2 * SSLv3/TLSv1 shared functions
4 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5 * SPDX-License-Identifier: Apache-2.0
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * This file is part of mbed TLS (https://tls.mbed.org)
22 * The SSL 3.0 specification was drafted by Netscape in 1996,
23 * and became an IETF standard in 1999.
25 * http://wp.netscape.com/eng/ssl3/
26 * http://www.ietf.org/rfc/rfc2246.txt
27 * http://www.ietf.org/rfc/rfc4346.txt
30 #if !defined(MBEDTLS_CONFIG_FILE)
31 #include "mbedtls/config.h"
33 #include MBEDTLS_CONFIG_FILE
36 #if defined(MBEDTLS_SSL_TLS_C)
38 #if defined(MBEDTLS_PLATFORM_C)
39 #include "mbedtls/platform.h"
42 #define mbedtls_calloc calloc
43 #define mbedtls_free free
46 #include "mbedtls/debug.h"
47 #include "mbedtls/ssl.h"
48 #include "mbedtls/ssl_internal.h"
52 #if defined(MBEDTLS_X509_CRT_PARSE_C)
53 #include "mbedtls/oid.h"
56 /* Implementation that should never be optimized out by the compiler */
57 static void mbedtls_zeroize( void *v, size_t n ) {
58 volatile unsigned char *p = v; while( n-- ) *p++ = 0;
61 /* Length of the "epoch" field in the record header */
62 static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
64 #if defined(MBEDTLS_SSL_PROTO_DTLS)
65 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
75 * Passing millisecs = 0 cancels a running timer.
77 static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
79 if( ssl->f_set_timer == NULL )
82 MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
83 ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
87 * Return -1 is timer is expired, 0 if it isn't.
89 static int ssl_check_timer( mbedtls_ssl_context *ssl )
91 if( ssl->f_get_timer == NULL )
94 if( ssl->f_get_timer( ssl->p_timer ) == 2 )
96 MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
103 #if defined(MBEDTLS_SSL_PROTO_DTLS)
105 * Double the retransmit timeout value, within the allowed range,
106 * returning -1 if the maximum value has already been reached.
108 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
110 uint32_t new_timeout;
112 if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
115 new_timeout = 2 * ssl->handshake->retransmit_timeout;
117 /* Avoid arithmetic overflow and range overflow */
118 if( new_timeout < ssl->handshake->retransmit_timeout ||
119 new_timeout > ssl->conf->hs_timeout_max )
121 new_timeout = ssl->conf->hs_timeout_max;
124 ssl->handshake->retransmit_timeout = new_timeout;
125 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
126 ssl->handshake->retransmit_timeout ) );
131 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
133 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
134 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
135 ssl->handshake->retransmit_timeout ) );
137 #endif /* MBEDTLS_SSL_PROTO_DTLS */
139 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
141 * Convert max_fragment_length codes to length.
144 * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
145 * } MaxFragmentLength;
146 * and we add 0 -> extension unused
148 static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] =
150 MBEDTLS_SSL_MAX_CONTENT_LEN, /* MBEDTLS_SSL_MAX_FRAG_LEN_NONE */
151 512, /* MBEDTLS_SSL_MAX_FRAG_LEN_512 */
152 1024, /* MBEDTLS_SSL_MAX_FRAG_LEN_1024 */
153 2048, /* MBEDTLS_SSL_MAX_FRAG_LEN_2048 */
154 4096, /* MBEDTLS_SSL_MAX_FRAG_LEN_4096 */
156 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
158 #if defined(MBEDTLS_SSL_CLI_C)
159 static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
161 mbedtls_ssl_session_free( dst );
162 memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
164 #if defined(MBEDTLS_X509_CRT_PARSE_C)
165 if( src->peer_cert != NULL )
169 dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
170 if( dst->peer_cert == NULL )
171 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
173 mbedtls_x509_crt_init( dst->peer_cert );
175 if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
176 src->peer_cert->raw.len ) ) != 0 )
178 mbedtls_free( dst->peer_cert );
179 dst->peer_cert = NULL;
183 #endif /* MBEDTLS_X509_CRT_PARSE_C */
185 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
186 if( src->ticket != NULL )
188 dst->ticket = mbedtls_calloc( 1, src->ticket_len );
189 if( dst->ticket == NULL )
190 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
192 memcpy( dst->ticket, src->ticket, src->ticket_len );
194 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
198 #endif /* MBEDTLS_SSL_CLI_C */
200 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
201 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
202 const unsigned char *key_enc, const unsigned char *key_dec,
204 const unsigned char *iv_enc, const unsigned char *iv_dec,
206 const unsigned char *mac_enc, const unsigned char *mac_dec,
207 size_t maclen ) = NULL;
208 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
209 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
210 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
211 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
212 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
213 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
216 * Key material generation
218 #if defined(MBEDTLS_SSL_PROTO_SSL3)
219 static int ssl3_prf( const unsigned char *secret, size_t slen,
221 const unsigned char *random, size_t rlen,
222 unsigned char *dstbuf, size_t dlen )
225 mbedtls_md5_context md5;
226 mbedtls_sha1_context sha1;
227 unsigned char padding[16];
228 unsigned char sha1sum[20];
231 mbedtls_md5_init( &md5 );
232 mbedtls_sha1_init( &sha1 );
237 * MD5( secret + SHA1( 'A' + secret + random ) ) +
238 * MD5( secret + SHA1( 'BB' + secret + random ) ) +
239 * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
242 for( i = 0; i < dlen / 16; i++ )
244 memset( padding, (unsigned char) ('A' + i), 1 + i );
246 mbedtls_sha1_starts( &sha1 );
247 mbedtls_sha1_update( &sha1, padding, 1 + i );
248 mbedtls_sha1_update( &sha1, secret, slen );
249 mbedtls_sha1_update( &sha1, random, rlen );
250 mbedtls_sha1_finish( &sha1, sha1sum );
252 mbedtls_md5_starts( &md5 );
253 mbedtls_md5_update( &md5, secret, slen );
254 mbedtls_md5_update( &md5, sha1sum, 20 );
255 mbedtls_md5_finish( &md5, dstbuf + i * 16 );
258 mbedtls_md5_free( &md5 );
259 mbedtls_sha1_free( &sha1 );
261 mbedtls_zeroize( padding, sizeof( padding ) );
262 mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
266 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
268 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
269 static int tls1_prf( const unsigned char *secret, size_t slen,
271 const unsigned char *random, size_t rlen,
272 unsigned char *dstbuf, size_t dlen )
276 const unsigned char *S1, *S2;
277 unsigned char tmp[128];
278 unsigned char h_i[20];
279 const mbedtls_md_info_t *md_info;
280 mbedtls_md_context_t md_ctx;
283 mbedtls_md_init( &md_ctx );
285 if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
286 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
288 hs = ( slen + 1 ) / 2;
290 S2 = secret + slen - hs;
292 nb = strlen( label );
293 memcpy( tmp + 20, label, nb );
294 memcpy( tmp + 20 + nb, random, rlen );
298 * First compute P_md5(secret,label+random)[0..dlen]
300 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
301 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
303 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
306 mbedtls_md_hmac_starts( &md_ctx, S1, hs );
307 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
308 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
310 for( i = 0; i < dlen; i += 16 )
312 mbedtls_md_hmac_reset ( &md_ctx );
313 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
314 mbedtls_md_hmac_finish( &md_ctx, h_i );
316 mbedtls_md_hmac_reset ( &md_ctx );
317 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
318 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
320 k = ( i + 16 > dlen ) ? dlen % 16 : 16;
322 for( j = 0; j < k; j++ )
323 dstbuf[i + j] = h_i[j];
326 mbedtls_md_free( &md_ctx );
329 * XOR out with P_sha1(secret,label+random)[0..dlen]
331 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
332 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
334 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
337 mbedtls_md_hmac_starts( &md_ctx, S2, hs );
338 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
339 mbedtls_md_hmac_finish( &md_ctx, tmp );
341 for( i = 0; i < dlen; i += 20 )
343 mbedtls_md_hmac_reset ( &md_ctx );
344 mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
345 mbedtls_md_hmac_finish( &md_ctx, h_i );
347 mbedtls_md_hmac_reset ( &md_ctx );
348 mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
349 mbedtls_md_hmac_finish( &md_ctx, tmp );
351 k = ( i + 20 > dlen ) ? dlen % 20 : 20;
353 for( j = 0; j < k; j++ )
354 dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
357 mbedtls_md_free( &md_ctx );
359 mbedtls_zeroize( tmp, sizeof( tmp ) );
360 mbedtls_zeroize( h_i, sizeof( h_i ) );
364 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
366 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
367 static int tls_prf_generic( mbedtls_md_type_t md_type,
368 const unsigned char *secret, size_t slen,
370 const unsigned char *random, size_t rlen,
371 unsigned char *dstbuf, size_t dlen )
374 size_t i, j, k, md_len;
375 unsigned char tmp[128];
376 unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
377 const mbedtls_md_info_t *md_info;
378 mbedtls_md_context_t md_ctx;
381 mbedtls_md_init( &md_ctx );
383 if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
384 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
386 md_len = mbedtls_md_get_size( md_info );
388 if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
389 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
391 nb = strlen( label );
392 memcpy( tmp + md_len, label, nb );
393 memcpy( tmp + md_len + nb, random, rlen );
397 * Compute P_<hash>(secret, label + random)[0..dlen]
399 if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
402 mbedtls_md_hmac_starts( &md_ctx, secret, slen );
403 mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
404 mbedtls_md_hmac_finish( &md_ctx, tmp );
406 for( i = 0; i < dlen; i += md_len )
408 mbedtls_md_hmac_reset ( &md_ctx );
409 mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
410 mbedtls_md_hmac_finish( &md_ctx, h_i );
412 mbedtls_md_hmac_reset ( &md_ctx );
413 mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
414 mbedtls_md_hmac_finish( &md_ctx, tmp );
416 k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
418 for( j = 0; j < k; j++ )
419 dstbuf[i + j] = h_i[j];
422 mbedtls_md_free( &md_ctx );
424 mbedtls_zeroize( tmp, sizeof( tmp ) );
425 mbedtls_zeroize( h_i, sizeof( h_i ) );
430 #if defined(MBEDTLS_SHA256_C)
431 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
433 const unsigned char *random, size_t rlen,
434 unsigned char *dstbuf, size_t dlen )
436 return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
437 label, random, rlen, dstbuf, dlen ) );
439 #endif /* MBEDTLS_SHA256_C */
441 #if defined(MBEDTLS_SHA512_C)
442 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
444 const unsigned char *random, size_t rlen,
445 unsigned char *dstbuf, size_t dlen )
447 return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
448 label, random, rlen, dstbuf, dlen ) );
450 #endif /* MBEDTLS_SHA512_C */
451 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
453 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
455 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
456 defined(MBEDTLS_SSL_PROTO_TLS1_1)
457 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
460 #if defined(MBEDTLS_SSL_PROTO_SSL3)
461 static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
462 static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
465 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
466 static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
467 static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
470 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
471 #if defined(MBEDTLS_SHA256_C)
472 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
473 static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
474 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
477 #if defined(MBEDTLS_SHA512_C)
478 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
479 static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
480 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
482 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
484 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
487 unsigned char tmp[64];
488 unsigned char keyblk[256];
491 unsigned char *mac_enc;
492 unsigned char *mac_dec;
494 const mbedtls_cipher_info_t *cipher_info;
495 const mbedtls_md_info_t *md_info;
497 mbedtls_ssl_session *session = ssl->session_negotiate;
498 mbedtls_ssl_transform *transform = ssl->transform_negotiate;
499 mbedtls_ssl_handshake_params *handshake = ssl->handshake;
501 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
503 cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
504 if( cipher_info == NULL )
506 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
507 transform->ciphersuite_info->cipher ) );
508 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
511 md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
512 if( md_info == NULL )
514 MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
515 transform->ciphersuite_info->mac ) );
516 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
520 * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
522 #if defined(MBEDTLS_SSL_PROTO_SSL3)
523 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
525 handshake->tls_prf = ssl3_prf;
526 handshake->calc_verify = ssl_calc_verify_ssl;
527 handshake->calc_finished = ssl_calc_finished_ssl;
531 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
532 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
534 handshake->tls_prf = tls1_prf;
535 handshake->calc_verify = ssl_calc_verify_tls;
536 handshake->calc_finished = ssl_calc_finished_tls;
540 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
541 #if defined(MBEDTLS_SHA512_C)
542 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
543 transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
545 handshake->tls_prf = tls_prf_sha384;
546 handshake->calc_verify = ssl_calc_verify_tls_sha384;
547 handshake->calc_finished = ssl_calc_finished_tls_sha384;
551 #if defined(MBEDTLS_SHA256_C)
552 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
554 handshake->tls_prf = tls_prf_sha256;
555 handshake->calc_verify = ssl_calc_verify_tls_sha256;
556 handshake->calc_finished = ssl_calc_finished_tls_sha256;
560 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
562 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
563 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
569 * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
570 * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
571 * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
574 * master = PRF( premaster, "master secret", randbytes )[0..47]
576 if( handshake->resume == 0 )
578 MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
581 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
582 if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
584 unsigned char session_hash[48];
587 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
589 ssl->handshake->calc_verify( ssl, session_hash );
591 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
592 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
594 #if defined(MBEDTLS_SHA512_C)
595 if( ssl->transform_negotiate->ciphersuite_info->mac ==
605 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
608 MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
610 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
611 "extended master secret",
612 session_hash, hash_len,
613 session->master, 48 );
616 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
623 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
625 handshake->randbytes, 64,
626 session->master, 48 );
629 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
633 mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) );
636 MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
639 * Swap the client and server random values.
641 memcpy( tmp, handshake->randbytes, 64 );
642 memcpy( handshake->randbytes, tmp + 32, 32 );
643 memcpy( handshake->randbytes + 32, tmp, 32 );
644 mbedtls_zeroize( tmp, sizeof( tmp ) );
649 * MD5( master + SHA1( 'A' + master + randbytes ) ) +
650 * MD5( master + SHA1( 'BB' + master + randbytes ) ) +
651 * MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
652 * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
656 * key block = PRF( master, "key expansion", randbytes )
658 ret = handshake->tls_prf( session->master, 48, "key expansion",
659 handshake->randbytes, 64, keyblk, 256 );
662 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
666 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
667 mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
668 MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
669 MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
670 MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
672 mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) );
675 * Determine the appropriate key, IV and MAC length.
678 transform->keylen = cipher_info->key_bitlen / 8;
680 if( cipher_info->mode == MBEDTLS_MODE_GCM ||
681 cipher_info->mode == MBEDTLS_MODE_CCM )
683 transform->maclen = 0;
685 transform->ivlen = 12;
686 transform->fixed_ivlen = 4;
688 /* Minimum length is expicit IV + tag */
689 transform->minlen = transform->ivlen - transform->fixed_ivlen
690 + ( transform->ciphersuite_info->flags &
691 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16 );
695 /* Initialize HMAC contexts */
696 if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
697 ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
699 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
704 transform->maclen = mbedtls_md_get_size( md_info );
706 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
708 * If HMAC is to be truncated, we shall keep the leftmost bytes,
709 * (rfc 6066 page 13 or rfc 2104 section 4),
710 * so we only need to adjust the length here.
712 if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
713 transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
714 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
717 transform->ivlen = cipher_info->iv_size;
720 if( cipher_info->mode == MBEDTLS_MODE_STREAM )
721 transform->minlen = transform->maclen;
725 * GenericBlockCipher:
726 * 1. if EtM is in use: one block plus MAC
727 * otherwise: * first multiple of blocklen greater than maclen
728 * 2. IV except for SSL3 and TLS 1.0
730 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
731 if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
733 transform->minlen = transform->maclen
734 + cipher_info->block_size;
739 transform->minlen = transform->maclen
740 + cipher_info->block_size
741 - transform->maclen % cipher_info->block_size;
744 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
745 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
746 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
747 ; /* No need to adjust minlen */
750 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
751 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
752 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
754 transform->minlen += transform->ivlen;
759 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
760 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
765 MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
766 transform->keylen, transform->minlen, transform->ivlen,
767 transform->maclen ) );
770 * Finally setup the cipher contexts, IVs and MAC secrets.
772 #if defined(MBEDTLS_SSL_CLI_C)
773 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
775 key1 = keyblk + transform->maclen * 2;
776 key2 = keyblk + transform->maclen * 2 + transform->keylen;
779 mac_dec = keyblk + transform->maclen;
782 * This is not used in TLS v1.1.
784 iv_copy_len = ( transform->fixed_ivlen ) ?
785 transform->fixed_ivlen : transform->ivlen;
786 memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
787 memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
791 #endif /* MBEDTLS_SSL_CLI_C */
792 #if defined(MBEDTLS_SSL_SRV_C)
793 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
795 key1 = keyblk + transform->maclen * 2 + transform->keylen;
796 key2 = keyblk + transform->maclen * 2;
798 mac_enc = keyblk + transform->maclen;
802 * This is not used in TLS v1.1.
804 iv_copy_len = ( transform->fixed_ivlen ) ?
805 transform->fixed_ivlen : transform->ivlen;
806 memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
807 memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
811 #endif /* MBEDTLS_SSL_SRV_C */
813 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
814 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
817 #if defined(MBEDTLS_SSL_PROTO_SSL3)
818 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
820 if( transform->maclen > sizeof transform->mac_enc )
822 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
823 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
826 memcpy( transform->mac_enc, mac_enc, transform->maclen );
827 memcpy( transform->mac_dec, mac_dec, transform->maclen );
830 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
831 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
832 defined(MBEDTLS_SSL_PROTO_TLS1_2)
833 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
835 mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
836 mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
841 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
842 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
845 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
846 if( mbedtls_ssl_hw_record_init != NULL )
850 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
852 if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
853 transform->iv_enc, transform->iv_dec,
856 transform->maclen ) ) != 0 )
858 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
859 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
862 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
864 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
865 if( ssl->conf->f_export_keys != NULL )
867 ssl->conf->f_export_keys( ssl->conf->p_export_keys,
868 session->master, keyblk,
869 transform->maclen, transform->keylen,
874 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
875 cipher_info ) ) != 0 )
877 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
881 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
882 cipher_info ) ) != 0 )
884 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
888 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
889 cipher_info->key_bitlen,
890 MBEDTLS_ENCRYPT ) ) != 0 )
892 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
896 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
897 cipher_info->key_bitlen,
898 MBEDTLS_DECRYPT ) ) != 0 )
900 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
904 #if defined(MBEDTLS_CIPHER_MODE_CBC)
905 if( cipher_info->mode == MBEDTLS_MODE_CBC )
907 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
908 MBEDTLS_PADDING_NONE ) ) != 0 )
910 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
914 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
915 MBEDTLS_PADDING_NONE ) ) != 0 )
917 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
921 #endif /* MBEDTLS_CIPHER_MODE_CBC */
923 mbedtls_zeroize( keyblk, sizeof( keyblk ) );
925 #if defined(MBEDTLS_ZLIB_SUPPORT)
926 // Initialize compression
928 if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
930 if( ssl->compress_buf == NULL )
932 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
933 ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN );
934 if( ssl->compress_buf == NULL )
936 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
937 MBEDTLS_SSL_BUFFER_LEN ) );
938 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
942 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
944 memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
945 memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
947 if( deflateInit( &transform->ctx_deflate,
948 Z_DEFAULT_COMPRESSION ) != Z_OK ||
949 inflateInit( &transform->ctx_inflate ) != Z_OK )
951 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
952 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
955 #endif /* MBEDTLS_ZLIB_SUPPORT */
957 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
962 #if defined(MBEDTLS_SSL_PROTO_SSL3)
963 void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
965 mbedtls_md5_context md5;
966 mbedtls_sha1_context sha1;
967 unsigned char pad_1[48];
968 unsigned char pad_2[48];
970 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
972 mbedtls_md5_init( &md5 );
973 mbedtls_sha1_init( &sha1 );
975 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
976 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
978 memset( pad_1, 0x36, 48 );
979 memset( pad_2, 0x5C, 48 );
981 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
982 mbedtls_md5_update( &md5, pad_1, 48 );
983 mbedtls_md5_finish( &md5, hash );
985 mbedtls_md5_starts( &md5 );
986 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
987 mbedtls_md5_update( &md5, pad_2, 48 );
988 mbedtls_md5_update( &md5, hash, 16 );
989 mbedtls_md5_finish( &md5, hash );
991 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
992 mbedtls_sha1_update( &sha1, pad_1, 40 );
993 mbedtls_sha1_finish( &sha1, hash + 16 );
995 mbedtls_sha1_starts( &sha1 );
996 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
997 mbedtls_sha1_update( &sha1, pad_2, 40 );
998 mbedtls_sha1_update( &sha1, hash + 16, 20 );
999 mbedtls_sha1_finish( &sha1, hash + 16 );
1001 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1002 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1004 mbedtls_md5_free( &md5 );
1005 mbedtls_sha1_free( &sha1 );
1009 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1011 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1012 void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
1014 mbedtls_md5_context md5;
1015 mbedtls_sha1_context sha1;
1017 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1019 mbedtls_md5_init( &md5 );
1020 mbedtls_sha1_init( &sha1 );
1022 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1023 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1025 mbedtls_md5_finish( &md5, hash );
1026 mbedtls_sha1_finish( &sha1, hash + 16 );
1028 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1029 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1031 mbedtls_md5_free( &md5 );
1032 mbedtls_sha1_free( &sha1 );
1036 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1038 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1039 #if defined(MBEDTLS_SHA256_C)
1040 void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
1042 mbedtls_sha256_context sha256;
1044 mbedtls_sha256_init( &sha256 );
1046 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1048 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1049 mbedtls_sha256_finish( &sha256, hash );
1051 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
1052 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1054 mbedtls_sha256_free( &sha256 );
1058 #endif /* MBEDTLS_SHA256_C */
1060 #if defined(MBEDTLS_SHA512_C)
1061 void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
1063 mbedtls_sha512_context sha512;
1065 mbedtls_sha512_init( &sha512 );
1067 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1069 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
1070 mbedtls_sha512_finish( &sha512, hash );
1072 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
1073 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1075 mbedtls_sha512_free( &sha512 );
1079 #endif /* MBEDTLS_SHA512_C */
1080 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1082 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1083 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1085 unsigned char *p = ssl->handshake->premaster;
1086 unsigned char *end = p + sizeof( ssl->handshake->premaster );
1087 const unsigned char *psk = ssl->conf->psk;
1088 size_t psk_len = ssl->conf->psk_len;
1090 /* If the psk callback was called, use its result */
1091 if( ssl->handshake->psk != NULL )
1093 psk = ssl->handshake->psk;
1094 psk_len = ssl->handshake->psk_len;
1099 * opaque other_secret<0..2^16-1>;
1100 * opaque psk<0..2^16-1>;
1102 * with "other_secret" depending on the particular key exchange
1104 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1105 if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1108 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1110 *(p++) = (unsigned char)( psk_len >> 8 );
1111 *(p++) = (unsigned char)( psk_len );
1113 if( end < p || (size_t)( end - p ) < psk_len )
1114 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1116 memset( p, 0, psk_len );
1120 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1121 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1122 if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
1125 * other_secret already set by the ClientKeyExchange message,
1126 * and is 48 bytes long
1133 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1134 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1135 if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
1140 /* Write length only when we know the actual value */
1141 if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
1142 p + 2, end - ( p + 2 ), &len,
1143 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1145 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1148 *(p++) = (unsigned char)( len >> 8 );
1149 *(p++) = (unsigned char)( len );
1152 MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
1155 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1156 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
1157 if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
1162 if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
1163 p + 2, end - ( p + 2 ),
1164 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1166 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1170 *(p++) = (unsigned char)( zlen >> 8 );
1171 *(p++) = (unsigned char)( zlen );
1174 MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
1177 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1179 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1180 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1183 /* opaque psk<0..2^16-1>; */
1185 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1187 *(p++) = (unsigned char)( psk_len >> 8 );
1188 *(p++) = (unsigned char)( psk_len );
1190 if( end < p || (size_t)( end - p ) < psk_len )
1191 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1193 memcpy( p, psk, psk_len );
1196 ssl->handshake->pmslen = p - ssl->handshake->premaster;
1200 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1202 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1204 * SSLv3.0 MAC functions
1206 static void ssl_mac( mbedtls_md_context_t *md_ctx, unsigned char *secret,
1207 unsigned char *buf, size_t len,
1208 unsigned char *ctr, int type )
1210 unsigned char header[11];
1211 unsigned char padding[48];
1213 int md_size = mbedtls_md_get_size( md_ctx->md_info );
1214 int md_type = mbedtls_md_get_type( md_ctx->md_info );
1216 /* Only MD5 and SHA-1 supported */
1217 if( md_type == MBEDTLS_MD_MD5 )
1222 memcpy( header, ctr, 8 );
1223 header[ 8] = (unsigned char) type;
1224 header[ 9] = (unsigned char)( len >> 8 );
1225 header[10] = (unsigned char)( len );
1227 memset( padding, 0x36, padlen );
1228 mbedtls_md_starts( md_ctx );
1229 mbedtls_md_update( md_ctx, secret, md_size );
1230 mbedtls_md_update( md_ctx, padding, padlen );
1231 mbedtls_md_update( md_ctx, header, 11 );
1232 mbedtls_md_update( md_ctx, buf, len );
1233 mbedtls_md_finish( md_ctx, buf + len );
1235 memset( padding, 0x5C, padlen );
1236 mbedtls_md_starts( md_ctx );
1237 mbedtls_md_update( md_ctx, secret, md_size );
1238 mbedtls_md_update( md_ctx, padding, padlen );
1239 mbedtls_md_update( md_ctx, buf + len, md_size );
1240 mbedtls_md_finish( md_ctx, buf + len );
1242 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1244 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
1245 ( defined(MBEDTLS_CIPHER_MODE_CBC) && \
1246 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) )
1247 #define SSL_SOME_MODES_USE_MAC
1250 /* The function below is only used in the Lucky 13 counter-measure in
1251 * ssl_decrypt_buf(). These are the defines that guard the call site. */
1252 #if defined(SSL_SOME_MODES_USE_MAC) && \
1253 ( defined(MBEDTLS_SSL_PROTO_TLS1) || \
1254 defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1255 defined(MBEDTLS_SSL_PROTO_TLS1_2) )
1256 /* This function makes sure every byte in the memory region is accessed
1257 * (in ascending addresses order) */
1258 static void ssl_read_memory( unsigned char *p, size_t len )
1260 unsigned char acc = 0;
1261 volatile unsigned char force;
1263 for( ; len != 0; p++, len-- )
1269 #endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
1272 * Encryption/decryption functions
1274 static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
1276 mbedtls_cipher_mode_t mode;
1279 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
1281 if( ssl->session_out == NULL || ssl->transform_out == NULL )
1283 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1284 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1287 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
1289 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
1290 ssl->out_msg, ssl->out_msglen );
1293 * Add MAC before if needed
1295 #if defined(SSL_SOME_MODES_USE_MAC)
1296 if( mode == MBEDTLS_MODE_STREAM ||
1297 ( mode == MBEDTLS_MODE_CBC
1298 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1299 && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
1303 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1304 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1306 ssl_mac( &ssl->transform_out->md_ctx_enc,
1307 ssl->transform_out->mac_enc,
1308 ssl->out_msg, ssl->out_msglen,
1309 ssl->out_ctr, ssl->out_msgtype );
1313 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1314 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1315 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
1317 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1319 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
1320 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
1321 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
1322 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1323 ssl->out_msg, ssl->out_msglen );
1324 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
1325 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1327 memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
1332 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1333 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1336 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
1337 ssl->out_msg + ssl->out_msglen,
1338 ssl->transform_out->maclen );
1340 ssl->out_msglen += ssl->transform_out->maclen;
1343 #endif /* AEAD not the only option */
1348 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1349 if( mode == MBEDTLS_MODE_STREAM )
1354 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1355 "including %d bytes of padding",
1356 ssl->out_msglen, 0 ) );
1358 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1359 ssl->transform_out->iv_enc,
1360 ssl->transform_out->ivlen,
1361 ssl->out_msg, ssl->out_msglen,
1362 ssl->out_msg, &olen ) ) != 0 )
1364 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1368 if( ssl->out_msglen != olen )
1370 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1371 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1375 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1376 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1377 if( mode == MBEDTLS_MODE_GCM ||
1378 mode == MBEDTLS_MODE_CCM )
1381 size_t enc_msglen, olen;
1382 unsigned char *enc_msg;
1383 unsigned char add_data[13];
1384 unsigned char taglen = ssl->transform_out->ciphersuite_info->flags &
1385 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1387 memcpy( add_data, ssl->out_ctr, 8 );
1388 add_data[8] = ssl->out_msgtype;
1389 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1390 ssl->conf->transport, add_data + 9 );
1391 add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
1392 add_data[12] = ssl->out_msglen & 0xFF;
1394 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1400 if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 )
1402 /* Reminder if we ever add an AEAD mode with a different size */
1403 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1404 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1407 memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1409 memcpy( ssl->out_iv, ssl->out_ctr, 8 );
1411 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv,
1412 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1415 * Fix pointer positions and message length with added IV
1417 enc_msg = ssl->out_msg;
1418 enc_msglen = ssl->out_msglen;
1419 ssl->out_msglen += ssl->transform_out->ivlen -
1420 ssl->transform_out->fixed_ivlen;
1422 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1423 "including %d bytes of padding",
1424 ssl->out_msglen, 0 ) );
1427 * Encrypt and authenticate
1429 if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc,
1430 ssl->transform_out->iv_enc,
1431 ssl->transform_out->ivlen,
1433 enc_msg, enc_msglen,
1435 enc_msg + enc_msglen, taglen ) ) != 0 )
1437 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
1441 if( olen != enc_msglen )
1443 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1444 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1447 ssl->out_msglen += taglen;
1450 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
1453 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1454 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1455 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1456 if( mode == MBEDTLS_MODE_CBC )
1459 unsigned char *enc_msg;
1460 size_t enc_msglen, padlen, olen = 0, i;
1462 padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
1463 ssl->transform_out->ivlen;
1464 if( padlen == ssl->transform_out->ivlen )
1467 for( i = 0; i <= padlen; i++ )
1468 ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
1470 ssl->out_msglen += padlen + 1;
1472 enc_msglen = ssl->out_msglen;
1473 enc_msg = ssl->out_msg;
1475 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1477 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
1478 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1480 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1485 ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
1486 ssl->transform_out->ivlen );
1490 memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
1491 ssl->transform_out->ivlen );
1494 * Fix pointer positions and message length with added IV
1496 enc_msg = ssl->out_msg;
1497 enc_msglen = ssl->out_msglen;
1498 ssl->out_msglen += ssl->transform_out->ivlen;
1500 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1502 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1503 "including %d bytes of IV and %d bytes of padding",
1504 ssl->out_msglen, ssl->transform_out->ivlen,
1507 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1508 ssl->transform_out->iv_enc,
1509 ssl->transform_out->ivlen,
1510 enc_msg, enc_msglen,
1511 enc_msg, &olen ) ) != 0 )
1513 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1517 if( enc_msglen != olen )
1519 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1520 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1523 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1524 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1527 * Save IV in SSL3 and TLS1
1529 memcpy( ssl->transform_out->iv_enc,
1530 ssl->transform_out->cipher_ctx_enc.iv,
1531 ssl->transform_out->ivlen );
1535 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1536 if( auth_done == 0 )
1539 * MAC(MAC_write_key, seq_num +
1540 * TLSCipherText.type +
1541 * TLSCipherText.version +
1542 * length_of( (IV +) ENC(...) ) +
1543 * IV + // except for TLS 1.0
1544 * ENC(content + padding + padding_length));
1546 unsigned char pseudo_hdr[13];
1548 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1550 memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
1551 memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
1552 pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
1553 pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
1555 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1557 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
1558 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1559 ssl->out_iv, ssl->out_msglen );
1560 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1561 ssl->out_iv + ssl->out_msglen );
1562 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1564 ssl->out_msglen += ssl->transform_out->maclen;
1567 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1570 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1571 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1573 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1574 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1577 /* Make extra sure authentication was performed, exactly once */
1578 if( auth_done != 1 )
1580 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1581 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1584 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1589 static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
1592 mbedtls_cipher_mode_t mode;
1594 #if defined(SSL_SOME_MODES_USE_MAC)
1595 size_t padlen = 0, correct = 1;
1598 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1600 if( ssl->session_in == NULL || ssl->transform_in == NULL )
1602 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1603 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1606 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
1608 if( ssl->in_msglen < ssl->transform_in->minlen )
1610 MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
1611 ssl->in_msglen, ssl->transform_in->minlen ) );
1612 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1615 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1616 if( mode == MBEDTLS_MODE_STREAM )
1623 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1624 ssl->transform_in->iv_dec,
1625 ssl->transform_in->ivlen,
1626 ssl->in_msg, ssl->in_msglen,
1627 ssl->in_msg, &olen ) ) != 0 )
1629 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1633 if( ssl->in_msglen != olen )
1635 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1636 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1640 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1641 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1642 if( mode == MBEDTLS_MODE_GCM ||
1643 mode == MBEDTLS_MODE_CCM )
1646 size_t dec_msglen, olen;
1647 unsigned char *dec_msg;
1648 unsigned char *dec_msg_result;
1649 unsigned char add_data[13];
1650 unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
1651 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1652 size_t explicit_iv_len = ssl->transform_in->ivlen -
1653 ssl->transform_in->fixed_ivlen;
1655 if( ssl->in_msglen < explicit_iv_len + taglen )
1657 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
1658 "+ taglen (%d)", ssl->in_msglen,
1659 explicit_iv_len, taglen ) );
1660 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1662 dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
1664 dec_msg = ssl->in_msg;
1665 dec_msg_result = ssl->in_msg;
1666 ssl->in_msglen = dec_msglen;
1668 memcpy( add_data, ssl->in_ctr, 8 );
1669 add_data[8] = ssl->in_msgtype;
1670 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1671 ssl->conf->transport, add_data + 9 );
1672 add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
1673 add_data[12] = ssl->in_msglen & 0xFF;
1675 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1678 memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
1680 ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
1682 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
1683 ssl->transform_in->ivlen );
1684 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
1687 * Decrypt and authenticate
1689 if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
1690 ssl->transform_in->iv_dec,
1691 ssl->transform_in->ivlen,
1693 dec_msg, dec_msglen,
1694 dec_msg_result, &olen,
1695 dec_msg + dec_msglen, taglen ) ) != 0 )
1697 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
1699 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
1700 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1706 if( olen != dec_msglen )
1708 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1709 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1713 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1714 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1715 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1716 if( mode == MBEDTLS_MODE_CBC )
1719 * Decrypt and check the padding
1722 unsigned char *dec_msg;
1723 unsigned char *dec_msg_result;
1729 * Check immediate ciphertext sanity
1731 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1732 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1733 minlen += ssl->transform_in->ivlen;
1736 if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
1737 ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
1739 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
1740 "+ 1 ) ( + expl IV )", ssl->in_msglen,
1741 ssl->transform_in->ivlen,
1742 ssl->transform_in->maclen ) );
1743 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1746 dec_msglen = ssl->in_msglen;
1747 dec_msg = ssl->in_msg;
1748 dec_msg_result = ssl->in_msg;
1751 * Authenticate before decrypt if enabled
1753 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1754 if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1756 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1757 unsigned char pseudo_hdr[13];
1759 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1761 dec_msglen -= ssl->transform_in->maclen;
1762 ssl->in_msglen -= ssl->transform_in->maclen;
1764 memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
1765 memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
1766 pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
1767 pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
1769 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1771 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
1772 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
1773 ssl->in_iv, ssl->in_msglen );
1774 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
1775 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1777 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
1778 ssl->transform_in->maclen );
1779 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
1780 ssl->transform_in->maclen );
1782 if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
1783 ssl->transform_in->maclen ) != 0 )
1785 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1787 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1791 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1794 * Check length sanity
1796 if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
1798 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
1799 ssl->in_msglen, ssl->transform_in->ivlen ) );
1800 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1803 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1805 * Initialize for prepended IV for block cipher in TLS v1.1 and up
1807 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1809 dec_msglen -= ssl->transform_in->ivlen;
1810 ssl->in_msglen -= ssl->transform_in->ivlen;
1812 for( i = 0; i < ssl->transform_in->ivlen; i++ )
1813 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
1815 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1817 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1818 ssl->transform_in->iv_dec,
1819 ssl->transform_in->ivlen,
1820 dec_msg, dec_msglen,
1821 dec_msg_result, &olen ) ) != 0 )
1823 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1827 if( dec_msglen != olen )
1829 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1830 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1833 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1834 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1837 * Save IV in SSL3 and TLS1
1839 memcpy( ssl->transform_in->iv_dec,
1840 ssl->transform_in->cipher_ctx_dec.iv,
1841 ssl->transform_in->ivlen );
1845 padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
1847 if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
1850 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1851 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
1852 ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
1858 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1859 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1861 if( padlen > ssl->transform_in->ivlen )
1863 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1864 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
1865 "should be no more than %d",
1866 padlen, ssl->transform_in->ivlen ) );
1872 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1873 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1874 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1875 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1878 * TLSv1+: always check the padding up to the first failure
1879 * and fake check up to 256 bytes of padding
1881 size_t pad_count = 0, real_count = 1;
1882 size_t padding_idx = ssl->in_msglen - padlen - 1;
1885 * Padding is guaranteed to be incorrect if:
1886 * 1. padlen >= ssl->in_msglen
1888 * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN +
1889 * ssl->transform_in->maclen
1891 * In both cases we reset padding_idx to a safe value (0) to
1892 * prevent out-of-buffer reads.
1894 correct &= ( ssl->in_msglen >= padlen + 1 );
1895 correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN +
1896 ssl->transform_in->maclen );
1898 padding_idx *= correct;
1900 for( i = 1; i <= 256; i++ )
1902 real_count &= ( i <= padlen );
1903 pad_count += real_count *
1904 ( ssl->in_msg[padding_idx + i] == padlen - 1 );
1907 correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
1909 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1910 if( padlen > 0 && correct == 0 )
1911 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
1913 padlen &= correct * 0x1FF;
1916 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1917 MBEDTLS_SSL_PROTO_TLS1_2 */
1919 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1920 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1923 ssl->in_msglen -= padlen;
1926 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1927 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1929 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1930 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1933 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
1934 ssl->in_msg, ssl->in_msglen );
1937 * Authenticate if not done yet.
1938 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1940 #if defined(SSL_SOME_MODES_USE_MAC)
1941 if( auth_done == 0 )
1943 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1945 ssl->in_msglen -= ssl->transform_in->maclen;
1947 ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
1948 ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
1950 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1951 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1953 ssl_mac( &ssl->transform_in->md_ctx_dec,
1954 ssl->transform_in->mac_dec,
1955 ssl->in_msg, ssl->in_msglen,
1956 ssl->in_ctr, ssl->in_msgtype );
1959 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1960 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1961 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1962 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1965 * Process MAC and always update for padlen afterwards to make
1966 * total time independent of padlen.
1968 * Known timing attacks:
1969 * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
1971 * To compensate for different timings for the MAC calculation
1972 * depending on how much padding was removed (which is determined
1973 * by padlen), process extra_run more blocks through the hash
1976 * The formula in the paper is
1977 * extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
1978 * where L1 is the size of the header plus the decrypted message
1979 * plus CBC padding and L2 is the size of the header plus the
1980 * decrypted message. This is for an underlying hash function
1981 * with 64-byte blocks.
1982 * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
1983 * correctly. We round down instead of up, so -56 is the correct
1984 * value for our calculations instead of -55.
1986 * Repeat the formula rather than defining a block_size variable.
1987 * This avoids requiring division by a variable at runtime
1988 * (which would be marginally less efficient and would require
1989 * linking an extra division function in some builds).
1991 size_t j, extra_run = 0;
1994 * The next two sizes are the minimum and maximum values of
1995 * in_msglen over all padlen values.
1997 * They're independent of padlen, since we previously did
1998 * in_msglen -= padlen.
2000 * Note that max_len + maclen is never more than the buffer
2001 * length, as we previously did in_msglen -= maclen too.
2003 const size_t max_len = ssl->in_msglen + padlen;
2004 const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
2006 switch( ssl->transform_in->ciphersuite_info->mac )
2008 #if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
2009 defined(MBEDTLS_SHA256_C)
2010 case MBEDTLS_MD_MD5:
2011 case MBEDTLS_MD_SHA1:
2012 case MBEDTLS_MD_SHA256:
2013 /* 8 bytes of message size, 64-byte compression blocks */
2014 extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
2015 ( 13 + ssl->in_msglen + 8 ) / 64;
2018 #if defined(MBEDTLS_SHA512_C)
2019 case MBEDTLS_MD_SHA384:
2020 /* 16 bytes of message size, 128-byte compression blocks */
2021 extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -
2022 ( 13 + ssl->in_msglen + 16 ) / 128;
2026 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2027 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2030 extra_run &= correct * 0xFF;
2032 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
2033 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
2034 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
2035 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
2037 /* Make sure we access everything even when padlen > 0. This
2038 * makes the synchronisation requirements for just-in-time
2039 * Prime+Probe attacks much tighter and hopefully impractical. */
2040 ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );
2041 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
2043 /* Call mbedtls_md_process at least once due to cache attacks
2044 * that observe whether md_process() was called of not */
2045 for( j = 0; j < extra_run + 1; j++ )
2046 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
2048 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
2050 /* Make sure we access all the memory that could contain the MAC,
2051 * before we check it in the next code block. This makes the
2052 * synchronisation requirements for just-in-time Prime+Probe
2053 * attacks much tighter and hopefully impractical. */
2054 ssl_read_memory( ssl->in_msg + min_len,
2055 max_len - min_len + ssl->transform_in->maclen );
2058 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2059 MBEDTLS_SSL_PROTO_TLS1_2 */
2061 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2062 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2065 #if defined(MBEDTLS_SSL_DEBUG_ALL)
2066 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
2067 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_msg + ssl->in_msglen,
2068 ssl->transform_in->maclen );
2071 if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,
2072 ssl->transform_in->maclen ) != 0 )
2074 #if defined(MBEDTLS_SSL_DEBUG_ALL)
2075 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
2082 * Finally check the correct flag
2085 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2087 #endif /* SSL_SOME_MODES_USE_MAC */
2089 /* Make extra sure authentication was performed, exactly once */
2090 if( auth_done != 1 )
2092 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2093 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2096 if( ssl->in_msglen == 0 )
2101 * Three or more empty messages may be a DoS attack
2102 * (excessive CPU consumption).
2104 if( ssl->nb_zero > 3 )
2106 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
2107 "messages, possible DoS attack" ) );
2108 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2114 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2115 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2117 ; /* in_ctr read from peer, not maintained internally */
2122 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2123 if( ++ssl->in_ctr[i - 1] != 0 )
2126 /* The loop goes to its end iff the counter is wrapping */
2127 if( i == ssl_ep_len( ssl ) )
2129 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
2130 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2134 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
2140 #undef MAC_PLAINTEXT
2141 #undef MAC_CIPHERTEXT
2143 #if defined(MBEDTLS_ZLIB_SUPPORT)
2145 * Compression/decompression functions
2147 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
2150 unsigned char *msg_post = ssl->out_msg;
2151 size_t len_pre = ssl->out_msglen;
2152 unsigned char *msg_pre = ssl->compress_buf;
2154 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
2159 memcpy( msg_pre, ssl->out_msg, len_pre );
2161 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
2162 ssl->out_msglen ) );
2164 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
2165 ssl->out_msg, ssl->out_msglen );
2167 ssl->transform_out->ctx_deflate.next_in = msg_pre;
2168 ssl->transform_out->ctx_deflate.avail_in = len_pre;
2169 ssl->transform_out->ctx_deflate.next_out = msg_post;
2170 ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN;
2172 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
2175 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
2176 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2179 ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN -
2180 ssl->transform_out->ctx_deflate.avail_out;
2182 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
2183 ssl->out_msglen ) );
2185 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
2186 ssl->out_msg, ssl->out_msglen );
2188 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
2193 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
2196 unsigned char *msg_post = ssl->in_msg;
2197 size_t len_pre = ssl->in_msglen;
2198 unsigned char *msg_pre = ssl->compress_buf;
2200 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
2205 memcpy( msg_pre, ssl->in_msg, len_pre );
2207 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
2210 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
2211 ssl->in_msg, ssl->in_msglen );
2213 ssl->transform_in->ctx_inflate.next_in = msg_pre;
2214 ssl->transform_in->ctx_inflate.avail_in = len_pre;
2215 ssl->transform_in->ctx_inflate.next_out = msg_post;
2216 ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN;
2218 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
2221 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
2222 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2225 ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN -
2226 ssl->transform_in->ctx_inflate.avail_out;
2228 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
2231 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
2232 ssl->in_msg, ssl->in_msglen );
2234 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
2238 #endif /* MBEDTLS_ZLIB_SUPPORT */
2240 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2241 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
2243 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2244 static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
2246 /* If renegotiation is not enforced, retransmit until we would reach max
2247 * timeout if we were using the usual handshake doubling scheme */
2248 if( ssl->conf->renego_max_records < 0 )
2250 uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2251 unsigned char doublings = 1;
2259 if( ++ssl->renego_records_seen > doublings )
2261 MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
2266 return( ssl_write_hello_request( ssl ) );
2269 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2272 * Fill the input message buffer by appending data to it.
2273 * The amount of data already fetched is in ssl->in_left.
2275 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2276 * available (from this read and/or a previous one). Otherwise, an error code
2277 * is returned (possibly EOF or WANT_READ).
2279 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2280 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2281 * since we always read a whole datagram at once.
2283 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2284 * they're done reading a record.
2286 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
2291 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2293 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2295 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2296 "or mbedtls_ssl_set_bio()" ) );
2297 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2300 if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2302 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2303 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2306 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2307 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2311 /* Just to be sure */
2312 if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
2314 MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
2315 "mbedtls_ssl_set_timer_cb() for DTLS" ) );
2316 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2320 * The point is, we need to always read a full datagram at once, so we
2321 * sometimes read more then requested, and handle the additional data.
2322 * It could be the rest of the current record (while fetching the
2323 * header) and/or some other records in the same datagram.
2327 * Move to the next record in the already read datagram if applicable
2329 if( ssl->next_record_offset != 0 )
2331 if( ssl->in_left < ssl->next_record_offset )
2333 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2334 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2337 ssl->in_left -= ssl->next_record_offset;
2339 if( ssl->in_left != 0 )
2341 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2342 ssl->next_record_offset ) );
2343 memmove( ssl->in_hdr,
2344 ssl->in_hdr + ssl->next_record_offset,
2348 ssl->next_record_offset = 0;
2351 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2352 ssl->in_left, nb_want ) );
2355 * Done if we already have enough data.
2357 if( nb_want <= ssl->in_left)
2359 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2364 * A record can't be split accross datagrams. If we need to read but
2365 * are not at the beginning of a new record, the caller did something
2368 if( ssl->in_left != 0 )
2370 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2371 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2375 * Don't even try to read if time's out already.
2376 * This avoids by-passing the timer when repeatedly receiving messages
2377 * that will end up being dropped.
2379 if( ssl_check_timer( ssl ) != 0 )
2380 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2383 len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
2385 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2386 timeout = ssl->handshake->retransmit_timeout;
2388 timeout = ssl->conf->read_timeout;
2390 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2392 if( ssl->f_recv_timeout != NULL )
2393 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2396 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2398 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2401 return( MBEDTLS_ERR_SSL_CONN_EOF );
2404 if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
2406 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2407 ssl_set_timer( ssl, 0 );
2409 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2411 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2413 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2414 return( MBEDTLS_ERR_SSL_TIMEOUT );
2417 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2419 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2423 return( MBEDTLS_ERR_SSL_WANT_READ );
2425 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2426 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2427 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
2429 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
2431 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
2435 return( MBEDTLS_ERR_SSL_WANT_READ );
2437 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2448 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2449 ssl->in_left, nb_want ) );
2451 while( ssl->in_left < nb_want )
2453 len = nb_want - ssl->in_left;
2455 if( ssl_check_timer( ssl ) != 0 )
2456 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2459 if( ssl->f_recv_timeout != NULL )
2461 ret = ssl->f_recv_timeout( ssl->p_bio,
2462 ssl->in_hdr + ssl->in_left, len,
2463 ssl->conf->read_timeout );
2467 ret = ssl->f_recv( ssl->p_bio,
2468 ssl->in_hdr + ssl->in_left, len );
2472 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2473 ssl->in_left, nb_want ) );
2474 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2477 return( MBEDTLS_ERR_SSL_CONN_EOF );
2482 ssl->in_left += ret;
2486 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2492 * Flush any data not yet written
2494 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
2497 unsigned char *buf, i;
2499 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2501 if( ssl->f_send == NULL )
2503 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2504 "or mbedtls_ssl_set_bio()" ) );
2505 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2508 /* Avoid incrementing counter if data is flushed */
2509 if( ssl->out_left == 0 )
2511 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2515 while( ssl->out_left > 0 )
2517 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2518 mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2520 buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) +
2521 ssl->out_msglen - ssl->out_left;
2522 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2524 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2529 ssl->out_left -= ret;
2532 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2533 if( ++ssl->out_ctr[i - 1] != 0 )
2536 /* The loop goes to its end iff the counter is wrapping */
2537 if( i == ssl_ep_len( ssl ) )
2539 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
2540 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2543 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2549 * Functions to handle the DTLS retransmission state machine
2551 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2553 * Append current handshake message to current outgoing flight
2555 static int ssl_flight_append( mbedtls_ssl_context *ssl )
2557 mbedtls_ssl_flight_item *msg;
2559 /* Allocate space for current message */
2560 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2562 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2563 sizeof( mbedtls_ssl_flight_item ) ) );
2564 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2567 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2569 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2570 mbedtls_free( msg );
2571 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2574 /* Copy current handshake message with headers */
2575 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2576 msg->len = ssl->out_msglen;
2577 msg->type = ssl->out_msgtype;
2580 /* Append to the current flight */
2581 if( ssl->handshake->flight == NULL )
2582 ssl->handshake->flight = msg;
2585 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2586 while( cur->next != NULL )
2595 * Free the current flight of handshake messages
2597 static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
2599 mbedtls_ssl_flight_item *cur = flight;
2600 mbedtls_ssl_flight_item *next;
2602 while( cur != NULL )
2606 mbedtls_free( cur->p );
2607 mbedtls_free( cur );
2613 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2614 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
2618 * Swap transform_out and out_ctr with the alternative ones
2620 static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
2622 mbedtls_ssl_transform *tmp_transform;
2623 unsigned char tmp_out_ctr[8];
2625 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2627 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2631 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2633 /* Swap transforms */
2634 tmp_transform = ssl->transform_out;
2635 ssl->transform_out = ssl->handshake->alt_transform_out;
2636 ssl->handshake->alt_transform_out = tmp_transform;
2638 /* Swap epoch + sequence_number */
2639 memcpy( tmp_out_ctr, ssl->out_ctr, 8 );
2640 memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 );
2641 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
2643 /* Adjust to the newly activated transform */
2644 if( ssl->transform_out != NULL &&
2645 ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
2647 ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen -
2648 ssl->transform_out->fixed_ivlen;
2651 ssl->out_msg = ssl->out_iv;
2653 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2654 if( mbedtls_ssl_hw_record_activate != NULL )
2656 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
2658 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
2659 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2666 * Retransmit the current flight of messages.
2668 * Need to remember the current message in case flush_output returns
2669 * WANT_WRITE, causing us to exit this function and come back later.
2670 * This function must be called until state is no longer SENDING.
2672 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
2674 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
2676 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
2678 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) );
2680 ssl->handshake->cur_msg = ssl->handshake->flight;
2681 ssl_swap_epochs( ssl );
2683 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2686 while( ssl->handshake->cur_msg != NULL )
2689 mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg;
2691 /* Swap epochs before sending Finished: we can't do it after
2692 * sending ChangeCipherSpec, in case write returns WANT_READ.
2693 * Must be done before copying, may change out_msg pointer */
2694 if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2695 cur->p[0] == MBEDTLS_SSL_HS_FINISHED )
2697 ssl_swap_epochs( ssl );
2700 memcpy( ssl->out_msg, cur->p, cur->len );
2701 ssl->out_msglen = cur->len;
2702 ssl->out_msgtype = cur->type;
2704 ssl->handshake->cur_msg = cur->next;
2706 MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 );
2708 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
2710 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
2715 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
2716 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2719 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2720 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2723 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
2729 * To be called when the last message of an incoming flight is received.
2731 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
2733 /* We won't need to resend that one any more */
2734 ssl_flight_free( ssl->handshake->flight );
2735 ssl->handshake->flight = NULL;
2736 ssl->handshake->cur_msg = NULL;
2738 /* The next incoming flight will start with this msg_seq */
2739 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2742 ssl_set_timer( ssl, 0 );
2744 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2745 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2747 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2750 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2754 * To be called when the last message of an outgoing flight is send.
2756 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
2758 ssl_reset_retransmit_timeout( ssl );
2759 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2761 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2762 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2764 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2767 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2769 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2772 * Record layer functions
2776 * Write current record.
2777 * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg.
2779 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl )
2781 int ret, done = 0, out_msg_type;
2782 size_t len = ssl->out_msglen;
2784 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
2786 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2787 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2788 ssl->handshake != NULL &&
2789 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
2791 ; /* Skip special handshake treatment when resending */
2795 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
2797 out_msg_type = ssl->out_msg[0];
2799 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST &&
2800 ssl->handshake == NULL )
2802 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2803 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2806 ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
2807 ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
2808 ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
2811 * DTLS has additional fields in the Handshake layer,
2812 * between the length field and the actual payload:
2813 * uint16 message_seq;
2814 * uint24 fragment_offset;
2815 * uint24 fragment_length;
2817 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2818 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2820 /* Make room for the additional DTLS fields */
2821 memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 );
2822 ssl->out_msglen += 8;
2825 /* Write message_seq and update it, except for HelloRequest */
2826 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2828 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
2829 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
2830 ++( ssl->handshake->out_msg_seq );
2834 ssl->out_msg[4] = 0;
2835 ssl->out_msg[5] = 0;
2838 /* We don't fragment, so frag_offset = 0 and frag_len = len */
2839 memset( ssl->out_msg + 6, 0x00, 3 );
2840 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
2842 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2844 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2845 ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
2848 /* Save handshake and CCS messages for resending */
2849 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2850 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2851 ssl->handshake != NULL &&
2852 ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING &&
2853 ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ||
2854 ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) )
2856 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
2858 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
2864 #if defined(MBEDTLS_ZLIB_SUPPORT)
2865 if( ssl->transform_out != NULL &&
2866 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
2868 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
2870 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
2874 len = ssl->out_msglen;
2876 #endif /*MBEDTLS_ZLIB_SUPPORT */
2878 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2879 if( mbedtls_ssl_hw_record_write != NULL )
2881 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
2883 ret = mbedtls_ssl_hw_record_write( ssl );
2884 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
2886 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
2887 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2893 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2896 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
2897 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2898 ssl->conf->transport, ssl->out_hdr + 1 );
2900 ssl->out_len[0] = (unsigned char)( len >> 8 );
2901 ssl->out_len[1] = (unsigned char)( len );
2903 if( ssl->transform_out != NULL )
2905 if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
2907 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
2911 len = ssl->out_msglen;
2912 ssl->out_len[0] = (unsigned char)( len >> 8 );
2913 ssl->out_len[1] = (unsigned char)( len );
2916 ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen;
2918 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
2919 "version = [%d:%d], msglen = %d",
2920 ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
2921 ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) );
2923 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
2924 ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen );
2927 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2929 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
2933 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
2938 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2940 * Mark bits in bitmask (used for DTLS HS reassembly)
2942 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
2944 unsigned int start_bits, end_bits;
2946 start_bits = 8 - ( offset % 8 );
2947 if( start_bits != 8 )
2949 size_t first_byte_idx = offset / 8;
2952 if( len <= start_bits )
2954 for( ; len != 0; len-- )
2955 mask[first_byte_idx] |= 1 << ( start_bits - len );
2957 /* Avoid potential issues with offset or len becoming invalid */
2961 offset += start_bits; /* Now offset % 8 == 0 */
2964 for( ; start_bits != 0; start_bits-- )
2965 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
2971 size_t last_byte_idx = ( offset + len ) / 8;
2973 len -= end_bits; /* Now len % 8 == 0 */
2975 for( ; end_bits != 0; end_bits-- )
2976 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
2979 memset( mask + offset / 8, 0xFF, len / 8 );
2983 * Check that bitmask is full
2985 static int ssl_bitmask_check( unsigned char *mask, size_t len )
2989 for( i = 0; i < len / 8; i++ )
2990 if( mask[i] != 0xFF )
2993 for( i = 0; i < len % 8; i++ )
2994 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
3001 * Reassemble fragmented DTLS handshake messages.
3003 * Use a temporary buffer for reassembly, divided in two parts:
3004 * - the first holds the reassembled message (including handshake header),
3005 * - the second holds a bitmask indicating which parts of the message
3006 * (excluding headers) have been received so far.
3008 static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )
3010 unsigned char *msg, *bitmask;
3011 size_t frag_len, frag_off;
3012 size_t msg_len = ssl->in_hslen - 12; /* Without headers */
3014 if( ssl->handshake == NULL )
3016 MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) );
3017 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3021 * For first fragment, check size and allocate buffer
3023 if( ssl->handshake->hs_msg == NULL )
3027 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
3030 if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3032 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) );
3033 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3036 /* The bitmask needs one bit per byte of message excluding header */
3037 alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 );
3039 ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len );
3040 if( ssl->handshake->hs_msg == NULL )
3042 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) );
3043 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
3046 /* Prepare final header: copy msg_type, length and message_seq,
3047 * then add standardised fragment_offset and fragment_length */
3048 memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 );
3049 memset( ssl->handshake->hs_msg + 6, 0, 3 );
3050 memcpy( ssl->handshake->hs_msg + 9,
3051 ssl->handshake->hs_msg + 1, 3 );
3055 /* Make sure msg_type and length are consistent */
3056 if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 )
3058 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) );
3059 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3063 msg = ssl->handshake->hs_msg + 12;
3064 bitmask = msg + msg_len;
3067 * Check and copy current fragment
3069 frag_off = ( ssl->in_msg[6] << 16 ) |
3070 ( ssl->in_msg[7] << 8 ) |
3072 frag_len = ( ssl->in_msg[9] << 16 ) |
3073 ( ssl->in_msg[10] << 8 ) |
3076 if( frag_off + frag_len > msg_len )
3078 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d",
3079 frag_off, frag_len, msg_len ) );
3080 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3083 if( frag_len + 12 > ssl->in_msglen )
3085 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d",
3086 frag_len, ssl->in_msglen ) );
3087 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3090 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
3091 frag_off, frag_len ) );
3093 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
3094 ssl_bitmask_set( bitmask, frag_off, frag_len );
3097 * Do we have the complete message by now?
3098 * If yes, finalize it, else ask to read the next record.
3100 if( ssl_bitmask_check( bitmask, msg_len ) != 0 )
3102 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) );
3103 return( MBEDTLS_ERR_SSL_WANT_READ );
3106 MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) );
3108 if( frag_len + 12 < ssl->in_msglen )
3111 * We'got more handshake messages in the same record.
3112 * This case is not handled now because no know implementation does
3113 * that and it's hard to test, so we prefer to fail cleanly for now.
3115 MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) );
3116 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3119 if( ssl->in_left > ssl->next_record_offset )
3122 * We've got more data in the buffer after the current record,
3123 * that we don't want to overwrite. Move it before writing the
3124 * reassembled message, and adjust in_left and next_record_offset.
3126 unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset;
3127 unsigned char *new_remain = ssl->in_msg + ssl->in_hslen;
3128 size_t remain_len = ssl->in_left - ssl->next_record_offset;
3130 /* First compute and check new lengths */
3131 ssl->next_record_offset = new_remain - ssl->in_hdr;
3132 ssl->in_left = ssl->next_record_offset + remain_len;
3134 if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN -
3135 (size_t)( ssl->in_hdr - ssl->in_buf ) )
3137 MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) );
3138 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3141 memmove( new_remain, cur_remain, remain_len );
3144 memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );
3146 mbedtls_free( ssl->handshake->hs_msg );
3147 ssl->handshake->hs_msg = NULL;
3149 MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message",
3150 ssl->in_msg, ssl->in_hslen );
3154 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3156 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
3158 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
3160 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
3162 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3165 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + (
3166 ( ssl->in_msg[1] << 16 ) |
3167 ( ssl->in_msg[2] << 8 ) |
3170 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
3171 " %d, type = %d, hslen = %d",
3172 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
3174 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3175 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3178 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
3180 /* ssl->handshake is NULL when receiving ClientHello for renego */
3181 if( ssl->handshake != NULL &&
3182 recv_msg_seq != ssl->handshake->in_msg_seq )
3184 /* Retransmit only on last message from previous flight, to avoid
3185 * too many retransmissions.
3186 * Besides, No sane server ever retransmits HelloVerifyRequest */
3187 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3188 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
3190 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
3191 "message_seq = %d, start_of_flight = %d",
3193 ssl->handshake->in_flight_start_seq ) );
3195 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3197 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
3203 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
3204 "message_seq = %d, expected = %d",
3206 ssl->handshake->in_msg_seq ) );
3209 return( MBEDTLS_ERR_SSL_WANT_READ );
3211 /* Wait until message completion to increment in_msg_seq */
3213 /* Reassemble if current message is fragmented or reassembly is
3214 * already in progress */
3215 if( ssl->in_msglen < ssl->in_hslen ||
3216 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
3217 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ||
3218 ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) )
3220 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
3222 if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 )
3224 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_reassemble_dtls_handshake", ret );
3230 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3231 /* With TLS we don't handle fragmentation (for now) */
3232 if( ssl->in_msglen < ssl->in_hslen )
3234 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
3235 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3241 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
3244 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
3245 ssl->handshake != NULL )
3247 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
3250 /* Handshake message is complete, increment counter */
3251 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3252 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3253 ssl->handshake != NULL )
3255 ssl->handshake->in_msg_seq++;
3261 * DTLS anti-replay: RFC 6347 4.1.2.6
3263 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3264 * Bit n is set iff record number in_window_top - n has been seen.
3266 * Usually, in_window_top is the last record number seen and the lsb of
3267 * in_window is set. The only exception is the initial state (record number 0
3270 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3271 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
3273 ssl->in_window_top = 0;
3277 static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
3279 return( ( (uint64_t) buf[0] << 40 ) |
3280 ( (uint64_t) buf[1] << 32 ) |
3281 ( (uint64_t) buf[2] << 24 ) |
3282 ( (uint64_t) buf[3] << 16 ) |
3283 ( (uint64_t) buf[4] << 8 ) |
3284 ( (uint64_t) buf[5] ) );
3288 * Return 0 if sequence number is acceptable, -1 otherwise
3290 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
3292 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3295 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3298 if( rec_seqnum > ssl->in_window_top )
3301 bit = ssl->in_window_top - rec_seqnum;
3306 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
3313 * Update replay window on new validated record
3315 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
3317 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3319 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3322 if( rec_seqnum > ssl->in_window_top )
3324 /* Update window_top and the contents of the window */
3325 uint64_t shift = rec_seqnum - ssl->in_window_top;
3331 ssl->in_window <<= shift;
3332 ssl->in_window |= 1;
3335 ssl->in_window_top = rec_seqnum;
3339 /* Mark that number as seen in the current window */
3340 uint64_t bit = ssl->in_window_top - rec_seqnum;
3342 if( bit < 64 ) /* Always true, but be extra sure */
3343 ssl->in_window |= (uint64_t) 1 << bit;
3346 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3348 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3349 /* Forward declaration */
3350 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
3353 * Without any SSL context, check if a datagram looks like a ClientHello with
3354 * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
3355 * Both input and output include full DTLS headers.
3357 * - if cookie is valid, return 0
3358 * - if ClientHello looks superficially valid but cookie is not,
3359 * fill obuf and set olen, then
3360 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3361 * - otherwise return a specific error code
3363 static int ssl_check_dtls_clihlo_cookie(
3364 mbedtls_ssl_cookie_write_t *f_cookie_write,
3365 mbedtls_ssl_cookie_check_t *f_cookie_check,
3367 const unsigned char *cli_id, size_t cli_id_len,
3368 const unsigned char *in, size_t in_len,
3369 unsigned char *obuf, size_t buf_len, size_t *olen )
3371 size_t sid_len, cookie_len;
3374 if( f_cookie_write == NULL || f_cookie_check == NULL )
3375 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3378 * Structure of ClientHello with record and handshake headers,
3379 * and expected values. We don't need to check a lot, more checks will be
3380 * done when actually parsing the ClientHello - skipping those checks
3381 * avoids code duplication and does not make cookie forging any easier.
3383 * 0-0 ContentType type; copied, must be handshake
3384 * 1-2 ProtocolVersion version; copied
3385 * 3-4 uint16 epoch; copied, must be 0
3386 * 5-10 uint48 sequence_number; copied
3387 * 11-12 uint16 length; (ignored)
3389 * 13-13 HandshakeType msg_type; (ignored)
3390 * 14-16 uint24 length; (ignored)
3391 * 17-18 uint16 message_seq; copied
3392 * 19-21 uint24 fragment_offset; copied, must be 0
3393 * 22-24 uint24 fragment_length; (ignored)
3395 * 25-26 ProtocolVersion client_version; (ignored)
3396 * 27-58 Random random; (ignored)
3397 * 59-xx SessionID session_id; 1 byte len + sid_len content
3398 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3401 * Minimum length is 61 bytes.
3404 in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
3405 in[3] != 0 || in[4] != 0 ||
3406 in[19] != 0 || in[20] != 0 || in[21] != 0 )
3408 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3412 if( sid_len > in_len - 61 )
3413 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3415 cookie_len = in[60 + sid_len];
3416 if( cookie_len > in_len - 60 )
3417 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3419 if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
3420 cli_id, cli_id_len ) == 0 )
3427 * If we get here, we've got an invalid cookie, let's prepare HVR.
3429 * 0-0 ContentType type; copied
3430 * 1-2 ProtocolVersion version; copied
3431 * 3-4 uint16 epoch; copied
3432 * 5-10 uint48 sequence_number; copied
3433 * 11-12 uint16 length; olen - 13
3435 * 13-13 HandshakeType msg_type; hello_verify_request
3436 * 14-16 uint24 length; olen - 25
3437 * 17-18 uint16 message_seq; copied
3438 * 19-21 uint24 fragment_offset; copied
3439 * 22-24 uint24 fragment_length; olen - 25
3441 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3442 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3444 * Minimum length is 28.
3447 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3449 /* Copy most fields and adapt others */
3450 memcpy( obuf, in, 25 );
3451 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3455 /* Generate and write actual cookie */
3457 if( f_cookie_write( p_cookie,
3458 &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
3460 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3465 /* Go back and fill length fields */
3466 obuf[27] = (unsigned char)( *olen - 28 );
3468 obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
3469 obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
3470 obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
3472 obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
3473 obuf[12] = (unsigned char)( ( *olen - 13 ) );
3475 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3479 * Handle possible client reconnect with the same UDP quadruplet
3480 * (RFC 6347 Section 4.2.8).
3482 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3483 * that looks like a ClientHello.
3485 * - if the input looks like a ClientHello without cookies,
3486 * send back HelloVerifyRequest, then
3487 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3488 * - if the input looks like a ClientHello with a valid cookie,
3489 * reset the session of the current context, and
3490 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3491 * - if anything goes wrong, return a specific error code
3493 * mbedtls_ssl_read_record() will ignore the record if anything else than
3494 * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
3495 * cannot not return 0.
3497 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
3502 ret = ssl_check_dtls_clihlo_cookie(
3503 ssl->conf->f_cookie_write,
3504 ssl->conf->f_cookie_check,
3505 ssl->conf->p_cookie,
3506 ssl->cli_id, ssl->cli_id_len,
3507 ssl->in_buf, ssl->in_left,
3508 ssl->out_buf, MBEDTLS_SSL_MAX_CONTENT_LEN, &len );
3510 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
3512 if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
3514 /* Dont check write errors as we can't do anything here.
3515 * If the error is permanent we'll catch it later,
3516 * if it's not, then hopefully it'll work next time. */
3517 (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
3519 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3524 /* Got a valid cookie, partially reset context */
3525 if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
3527 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
3531 return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
3536 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3540 * ProtocolVersion version;
3541 * uint16 epoch; // DTLS only
3542 * uint48 sequence_number; // DTLS only
3545 * Return 0 if header looks sane (and, for DTLS, the record is expected)
3546 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
3547 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
3549 * With DTLS, mbedtls_ssl_read_record() will:
3550 * 1. proceed with the record if this function returns 0
3551 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
3552 * 3. return CLIENT_RECONNECT if this function return that value
3553 * 4. drop the whole datagram if this function returns anything else.
3554 * Point 2 is needed when the peer is resending, and we have already received
3555 * the first record from a datagram but are still waiting for the others.
3557 static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
3560 int major_ver, minor_ver;
3562 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
3564 ssl->in_msgtype = ssl->in_hdr[0];
3565 ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
3566 mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
3568 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
3569 "version = [%d:%d], msglen = %d",
3571 major_ver, minor_ver, ssl->in_msglen ) );
3573 /* Check record type */
3574 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
3575 ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
3576 ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3577 ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
3579 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
3581 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
3582 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3583 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 )
3588 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3592 if( major_ver != ssl->major_ver )
3594 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
3595 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3598 if( minor_ver > ssl->conf->max_minor_ver )
3600 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
3601 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3604 /* Check length against the size of our buffer */
3605 if( ssl->in_msglen > MBEDTLS_SSL_BUFFER_LEN
3606 - (size_t)( ssl->in_msg - ssl->in_buf ) )
3608 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3609 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3612 /* Check length against bounds of the current transform and version */
3613 if( ssl->transform_in == NULL )
3615 if( ssl->in_msglen < 1 ||
3616 ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3618 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3619 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3624 if( ssl->in_msglen < ssl->transform_in->minlen )
3626 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3627 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3630 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3631 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
3632 ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN )
3634 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3635 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3638 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3639 defined(MBEDTLS_SSL_PROTO_TLS1_2)
3641 * TLS encrypted messages can have up to 256 bytes of padding
3643 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
3644 ssl->in_msglen > ssl->transform_in->minlen +
3645 MBEDTLS_SSL_MAX_CONTENT_LEN + 256 )
3647 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3648 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3654 * DTLS-related tests done last, because most of them may result in
3655 * silently dropping the record (but not the whole datagram), and we only
3656 * want to consider that after ensuring that the "basic" fields (type,
3657 * version, length) are sane.
3659 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3660 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3662 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
3664 /* Drop unexpected ChangeCipherSpec messages */
3665 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3666 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
3667 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
3669 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) );
3670 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3673 /* Drop unexpected ApplicationData records,
3674 * except at the beginning of renegotiations */
3675 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
3676 ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
3677 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3678 && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
3679 ssl->state == MBEDTLS_SSL_SERVER_HELLO )
3683 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
3684 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3687 /* Check epoch (and sequence number) with DTLS */
3688 if( rec_epoch != ssl->in_epoch )
3690 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
3691 "expected %d, received %d",
3692 ssl->in_epoch, rec_epoch ) );
3694 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3696 * Check for an epoch 0 ClientHello. We can't use in_msg here to
3697 * access the first byte of record content (handshake type), as we
3698 * have an active transform (possibly iv_len != 0), so use the
3699 * fact that the record header len is 13 instead.
3701 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3702 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3704 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3705 ssl->in_left > 13 &&
3706 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
3708 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
3709 "from the same port" ) );
3710 return( ssl_handle_possible_reconnect( ssl ) );
3713 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3714 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3717 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3718 /* Replay detection only works for the current epoch */
3719 if( rec_epoch == ssl->in_epoch &&
3720 mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
3722 MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
3723 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3727 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3733 * If applicable, decrypt (and decompress) record content
3735 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
3739 MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
3740 ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
3742 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3743 if( mbedtls_ssl_hw_record_read != NULL )
3745 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
3747 ret = mbedtls_ssl_hw_record_read( ssl );
3748 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
3750 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
3751 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3757 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3758 if( !done && ssl->transform_in != NULL )
3760 if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
3762 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
3766 MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
3767 ssl->in_msg, ssl->in_msglen );
3769 if( ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3771 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3772 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3776 #if defined(MBEDTLS_ZLIB_SUPPORT)
3777 if( ssl->transform_in != NULL &&
3778 ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
3780 if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
3782 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
3786 #endif /* MBEDTLS_ZLIB_SUPPORT */
3788 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3789 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3791 mbedtls_ssl_dtls_replay_update( ssl );
3798 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
3803 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
3804 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
3807 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl )
3811 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
3815 if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 )
3817 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret );
3821 ret = mbedtls_ssl_handle_message_type( ssl );
3823 } while( MBEDTLS_ERR_SSL_NON_FATAL == ret );
3827 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
3831 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
3833 mbedtls_ssl_update_handshake_status( ssl );
3836 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
3841 int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl )
3845 if( ssl->in_hslen != 0 && ssl->in_hslen < ssl->in_msglen )
3848 * Get next Handshake message in the current record
3850 ssl->in_msglen -= ssl->in_hslen;
3852 memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
3855 MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
3856 ssl->in_msg, ssl->in_msglen );
3864 * Read the record header and parse it
3866 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3870 if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
3872 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
3876 if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
3878 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3879 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3880 ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
3882 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
3884 /* Skip unexpected record (but not whole datagram) */
3885 ssl->next_record_offset = ssl->in_msglen
3886 + mbedtls_ssl_hdr_len( ssl );
3888 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
3893 /* Skip invalid record and the rest of the datagram */
3894 ssl->next_record_offset = 0;
3897 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
3901 /* Get next record */
3902 goto read_record_header;
3909 * Read and optionally decrypt the message contents
3911 if( ( ret = mbedtls_ssl_fetch_input( ssl,
3912 mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
3914 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
3918 /* Done reading this record, get ready for the next one */
3919 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3920 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3921 ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
3926 if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
3928 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3929 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3931 /* Silently discard invalid records */
3932 if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
3933 ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3935 /* Except when waiting for Finished as a bad mac here
3936 * probably means something went wrong in the handshake
3937 * (eg wrong psk used, mitm downgrade attempt, etc.) */
3938 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
3939 ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
3941 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
3942 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3944 mbedtls_ssl_send_alert_message( ssl,
3945 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3946 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
3952 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
3953 if( ssl->conf->badmac_limit != 0 &&
3954 ++ssl->badmac_seen >= ssl->conf->badmac_limit )
3956 MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
3957 return( MBEDTLS_ERR_SSL_INVALID_MAC );
3961 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
3962 goto read_record_header;
3970 /* Error out (and send alert) on invalid records */
3971 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
3972 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3974 mbedtls_ssl_send_alert_message( ssl,
3975 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3976 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
3984 * When we sent the last flight of the handshake, we MUST respond to a
3985 * retransmit of the peer's previous flight with a retransmit. (In
3986 * practice, only the Finished message will make it, other messages
3987 * including CCS use the old transform so they're dropped as invalid.)
3989 * If the record we received is not a handshake message, however, it
3990 * means the peer received our last flight so we can clean up
3993 * This check needs to be done before prepare_handshake() due to an edge
3994 * case: if the client immediately requests renegotiation, this
3995 * finishes the current handshake first, avoiding the new ClientHello
3996 * being mistaken for an ancient message in the current handshake.
3998 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3999 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4000 ssl->handshake != NULL &&
4001 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
4003 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4004 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
4006 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) );
4008 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
4010 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
4014 return( MBEDTLS_ERR_SSL_WANT_READ );
4018 ssl_handshake_wrapup_free_hs_transform( ssl );
4026 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
4031 * Handle particular types of records
4033 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
4035 if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
4041 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
4043 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
4044 ssl->in_msg[0], ssl->in_msg[1] ) );
4047 * Ignore non-fatal alerts, except close_notify and no_renegotiation
4049 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
4051 MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
4053 return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
4056 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4057 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
4059 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
4060 return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
4063 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
4064 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4065 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
4067 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4068 /* Will be handled when trying to parse ServerHello */
4073 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
4074 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
4075 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4076 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4077 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4079 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4080 /* Will be handled in mbedtls_ssl_parse_certificate() */
4083 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
4085 /* Silently ignore: fetch new message */
4086 return MBEDTLS_ERR_SSL_NON_FATAL;
4092 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
4096 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
4097 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4098 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
4106 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
4107 unsigned char level,
4108 unsigned char message )
4112 if( ssl == NULL || ssl->conf == NULL )
4113 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4115 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
4117 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4118 ssl->out_msglen = 2;
4119 ssl->out_msg[0] = level;
4120 ssl->out_msg[1] = message;
4122 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4124 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4128 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
4134 * Handshake functions
4136 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
4137 !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \
4138 !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
4139 !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
4140 !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
4141 !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
4142 !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
4143 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4145 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4147 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4149 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4150 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4151 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4152 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
4153 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
4155 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4160 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4161 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4164 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4166 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4168 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4170 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4171 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4172 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4173 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
4174 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
4176 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4181 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4182 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4185 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4187 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4189 const mbedtls_x509_crt *crt;
4190 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4192 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4194 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4195 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4196 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4197 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
4198 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
4200 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4205 #if defined(MBEDTLS_SSL_CLI_C)
4206 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
4208 if( ssl->client_auth == 0 )
4210 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4215 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4217 * If using SSLv3 and got no cert, send an Alert message
4218 * (otherwise an empty Certificate message will be sent).
4220 if( mbedtls_ssl_own_cert( ssl ) == NULL &&
4221 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4223 ssl->out_msglen = 2;
4224 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4225 ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
4226 ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
4228 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
4231 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4233 #endif /* MBEDTLS_SSL_CLI_C */
4234 #if defined(MBEDTLS_SSL_SRV_C)
4235 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
4237 if( mbedtls_ssl_own_cert( ssl ) == NULL )
4239 MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
4240 return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
4245 MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
4248 * 0 . 0 handshake type
4249 * 1 . 3 handshake length
4250 * 4 . 6 length of all certs
4251 * 7 . 9 length of cert. 1
4252 * 10 . n-1 peer certificate
4253 * n . n+2 length of cert. 2
4254 * n+3 . ... upper level cert, etc.
4257 crt = mbedtls_ssl_own_cert( ssl );
4259 while( crt != NULL )
4262 if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i )
4264 MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
4265 i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) );
4266 return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
4269 ssl->out_msg[i ] = (unsigned char)( n >> 16 );
4270 ssl->out_msg[i + 1] = (unsigned char)( n >> 8 );
4271 ssl->out_msg[i + 2] = (unsigned char)( n );
4273 i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
4274 i += n; crt = crt->next;
4277 ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 );
4278 ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 );
4279 ssl->out_msg[6] = (unsigned char)( ( i - 7 ) );
4281 ssl->out_msglen = i;
4282 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4283 ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE;
4285 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
4291 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4293 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4297 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
4302 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4304 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4306 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4307 int authmode = ssl->conf->authmode;
4309 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4311 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4312 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4313 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4314 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
4315 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
4317 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4322 #if defined(MBEDTLS_SSL_SRV_C)
4323 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4324 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
4326 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4331 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4332 if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
4333 authmode = ssl->handshake->sni_authmode;
4336 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4337 authmode == MBEDTLS_SSL_VERIFY_NONE )
4339 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
4340 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4346 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4348 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4354 #if defined(MBEDTLS_SSL_SRV_C)
4355 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4357 * Check if the client sent an empty certificate
4359 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4360 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4362 if( ssl->in_msglen == 2 &&
4363 ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT &&
4364 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4365 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4367 MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
4369 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4370 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4373 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4376 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4378 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
4379 defined(MBEDTLS_SSL_PROTO_TLS1_2)
4380 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4381 ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
4383 if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
4384 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4385 ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE &&
4386 memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
4388 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
4390 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4391 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4394 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4397 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
4398 MBEDTLS_SSL_PROTO_TLS1_2 */
4399 #endif /* MBEDTLS_SSL_SRV_C */
4401 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4403 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4404 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4407 if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
4408 ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
4410 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4411 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4414 i = mbedtls_ssl_hs_hdr_len( ssl );
4417 * Same message structure as in mbedtls_ssl_write_certificate()
4419 n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
4421 if( ssl->in_msg[i] != 0 ||
4422 ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
4424 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4425 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4428 /* In case we tried to reuse a session but it failed */
4429 if( ssl->session_negotiate->peer_cert != NULL )
4431 mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
4432 mbedtls_free( ssl->session_negotiate->peer_cert );
4435 if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
4436 sizeof( mbedtls_x509_crt ) ) ) == NULL )
4438 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
4439 sizeof( mbedtls_x509_crt ) ) );
4440 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4443 mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
4447 while( i < ssl->in_hslen )
4449 if( ssl->in_msg[i] != 0 )
4451 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4452 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4455 n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
4456 | (unsigned int) ssl->in_msg[i + 2];
4459 if( n < 128 || i + n > ssl->in_hslen )
4461 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4462 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4465 ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
4466 ssl->in_msg + i, n );
4467 if( 0 != ret && ( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND ) != ret )
4469 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
4476 MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
4479 * On client, make sure the server cert doesn't change during renego to
4480 * avoid "triple handshake" attack: https://secure-resumption.com/
4482 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
4483 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4484 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
4486 if( ssl->session->peer_cert == NULL )
4488 MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
4489 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4492 if( ssl->session->peer_cert->raw.len !=
4493 ssl->session_negotiate->peer_cert->raw.len ||
4494 memcmp( ssl->session->peer_cert->raw.p,
4495 ssl->session_negotiate->peer_cert->raw.p,
4496 ssl->session->peer_cert->raw.len ) != 0 )
4498 MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
4499 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4502 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
4504 if( authmode != MBEDTLS_SSL_VERIFY_NONE )
4506 mbedtls_x509_crt *ca_chain;
4507 mbedtls_x509_crl *ca_crl;
4509 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4510 if( ssl->handshake->sni_ca_chain != NULL )
4512 ca_chain = ssl->handshake->sni_ca_chain;
4513 ca_crl = ssl->handshake->sni_ca_crl;
4518 ca_chain = ssl->conf->ca_chain;
4519 ca_crl = ssl->conf->ca_crl;
4522 if( ca_chain == NULL )
4524 MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
4525 return( MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED );
4529 * Main check: verify certificate
4531 ret = mbedtls_x509_crt_verify_with_profile(
4532 ssl->session_negotiate->peer_cert,
4534 ssl->conf->cert_profile,
4536 &ssl->session_negotiate->verify_result,
4537 ssl->conf->f_vrfy, ssl->conf->p_vrfy );
4541 MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
4545 * Secondary checks: always done, but change 'ret' only if it was 0
4548 #if defined(MBEDTLS_ECP_C)
4550 const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
4552 /* If certificate uses an EC key, make sure the curve is OK */
4553 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
4554 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
4556 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
4558 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4561 #endif /* MBEDTLS_ECP_C */
4563 if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
4565 ! ssl->conf->endpoint,
4566 &ssl->session_negotiate->verify_result ) != 0 )
4568 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
4570 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4573 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4577 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
4581 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
4582 !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
4583 !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
4584 !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
4585 !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
4586 !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
4587 !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4589 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
4593 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
4595 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4596 ssl->out_msglen = 1;
4597 ssl->out_msg[0] = 1;
4601 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4603 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4607 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
4612 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
4616 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
4618 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4620 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4624 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
4626 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4627 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4630 if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
4632 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4633 return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
4637 * Switch to our negotiated transform and session parameters for inbound
4640 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
4641 ssl->transform_in = ssl->transform_negotiate;
4642 ssl->session_in = ssl->session_negotiate;
4644 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4645 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4647 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4648 ssl_dtls_replay_reset( ssl );
4651 /* Increment epoch */
4652 if( ++ssl->in_epoch == 0 )
4654 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
4655 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
4659 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4660 memset( ssl->in_ctr, 0, 8 );
4663 * Set the in_msg pointer to the correct location based on IV length
4665 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
4667 ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -
4668 ssl->transform_negotiate->fixed_ivlen;
4671 ssl->in_msg = ssl->in_iv;
4673 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
4674 if( mbedtls_ssl_hw_record_activate != NULL )
4676 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
4678 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
4679 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
4686 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
4691 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
4692 const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
4694 ((void) ciphersuite_info);
4696 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4697 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4698 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
4699 ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
4702 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4703 #if defined(MBEDTLS_SHA512_C)
4704 if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
4705 ssl->handshake->update_checksum = ssl_update_checksum_sha384;
4708 #if defined(MBEDTLS_SHA256_C)
4709 if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
4710 ssl->handshake->update_checksum = ssl_update_checksum_sha256;
4713 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4715 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4720 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
4722 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4723 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4724 mbedtls_md5_starts( &ssl->handshake->fin_md5 );
4725 mbedtls_sha1_starts( &ssl->handshake->fin_sha1 );
4727 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4728 #if defined(MBEDTLS_SHA256_C)
4729 mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 );
4731 #if defined(MBEDTLS_SHA512_C)
4732 mbedtls_sha512_starts( &ssl->handshake->fin_sha512, 1 );
4734 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4737 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
4738 const unsigned char *buf, size_t len )
4740 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4741 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4742 mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4743 mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4745 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4746 #if defined(MBEDTLS_SHA256_C)
4747 mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4749 #if defined(MBEDTLS_SHA512_C)
4750 mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4752 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4755 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4756 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4757 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
4758 const unsigned char *buf, size_t len )
4760 mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4761 mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4765 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4766 #if defined(MBEDTLS_SHA256_C)
4767 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
4768 const unsigned char *buf, size_t len )
4770 mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4774 #if defined(MBEDTLS_SHA512_C)
4775 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
4776 const unsigned char *buf, size_t len )
4778 mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4781 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4783 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4784 static void ssl_calc_finished_ssl(
4785 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4788 mbedtls_md5_context md5;
4789 mbedtls_sha1_context sha1;
4791 unsigned char padbuf[48];
4792 unsigned char md5sum[16];
4793 unsigned char sha1sum[20];
4795 mbedtls_ssl_session *session = ssl->session_negotiate;
4797 session = ssl->session;
4799 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) );
4801 mbedtls_md5_init( &md5 );
4802 mbedtls_sha1_init( &sha1 );
4804 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
4805 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
4810 * MD5( master + pad2 +
4811 * MD5( handshake + sender + master + pad1 ) )
4812 * + SHA1( master + pad2 +
4813 * SHA1( handshake + sender + master + pad1 ) )
4816 #if !defined(MBEDTLS_MD5_ALT)
4817 MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
4818 md5.state, sizeof( md5.state ) );
4821 #if !defined(MBEDTLS_SHA1_ALT)
4822 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
4823 sha1.state, sizeof( sha1.state ) );
4826 sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
4829 memset( padbuf, 0x36, 48 );
4831 mbedtls_md5_update( &md5, (const unsigned char *) sender, 4 );
4832 mbedtls_md5_update( &md5, session->master, 48 );
4833 mbedtls_md5_update( &md5, padbuf, 48 );
4834 mbedtls_md5_finish( &md5, md5sum );
4836 mbedtls_sha1_update( &sha1, (const unsigned char *) sender, 4 );
4837 mbedtls_sha1_update( &sha1, session->master, 48 );
4838 mbedtls_sha1_update( &sha1, padbuf, 40 );
4839 mbedtls_sha1_finish( &sha1, sha1sum );
4841 memset( padbuf, 0x5C, 48 );
4843 mbedtls_md5_starts( &md5 );
4844 mbedtls_md5_update( &md5, session->master, 48 );
4845 mbedtls_md5_update( &md5, padbuf, 48 );
4846 mbedtls_md5_update( &md5, md5sum, 16 );
4847 mbedtls_md5_finish( &md5, buf );
4849 mbedtls_sha1_starts( &sha1 );
4850 mbedtls_sha1_update( &sha1, session->master, 48 );
4851 mbedtls_sha1_update( &sha1, padbuf , 40 );
4852 mbedtls_sha1_update( &sha1, sha1sum, 20 );
4853 mbedtls_sha1_finish( &sha1, buf + 16 );
4855 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
4857 mbedtls_md5_free( &md5 );
4858 mbedtls_sha1_free( &sha1 );
4860 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
4861 mbedtls_zeroize( md5sum, sizeof( md5sum ) );
4862 mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
4864 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
4866 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4868 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
4869 static void ssl_calc_finished_tls(
4870 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4874 mbedtls_md5_context md5;
4875 mbedtls_sha1_context sha1;
4876 unsigned char padbuf[36];
4878 mbedtls_ssl_session *session = ssl->session_negotiate;
4880 session = ssl->session;
4882 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) );
4884 mbedtls_md5_init( &md5 );
4885 mbedtls_sha1_init( &sha1 );
4887 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
4888 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
4892 * hash = PRF( master, finished_label,
4893 * MD5( handshake ) + SHA1( handshake ) )[0..11]
4896 #if !defined(MBEDTLS_MD5_ALT)
4897 MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
4898 md5.state, sizeof( md5.state ) );
4901 #if !defined(MBEDTLS_SHA1_ALT)
4902 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
4903 sha1.state, sizeof( sha1.state ) );
4906 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
4908 : "server finished";
4910 mbedtls_md5_finish( &md5, padbuf );
4911 mbedtls_sha1_finish( &sha1, padbuf + 16 );
4913 ssl->handshake->tls_prf( session->master, 48, sender,
4914 padbuf, 36, buf, len );
4916 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
4918 mbedtls_md5_free( &md5 );
4919 mbedtls_sha1_free( &sha1 );
4921 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
4923 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
4925 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
4927 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4928 #if defined(MBEDTLS_SHA256_C)
4929 static void ssl_calc_finished_tls_sha256(
4930 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4934 mbedtls_sha256_context sha256;
4935 unsigned char padbuf[32];
4937 mbedtls_ssl_session *session = ssl->session_negotiate;
4939 session = ssl->session;
4941 mbedtls_sha256_init( &sha256 );
4943 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) );
4945 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
4949 * hash = PRF( master, finished_label,
4950 * Hash( handshake ) )[0.11]
4953 #if !defined(MBEDTLS_SHA256_ALT)
4954 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
4955 sha256.state, sizeof( sha256.state ) );
4958 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
4960 : "server finished";
4962 mbedtls_sha256_finish( &sha256, padbuf );
4964 ssl->handshake->tls_prf( session->master, 48, sender,
4965 padbuf, 32, buf, len );
4967 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
4969 mbedtls_sha256_free( &sha256 );
4971 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
4973 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
4975 #endif /* MBEDTLS_SHA256_C */
4977 #if defined(MBEDTLS_SHA512_C)
4978 static void ssl_calc_finished_tls_sha384(
4979 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4983 mbedtls_sha512_context sha512;
4984 unsigned char padbuf[48];
4986 mbedtls_ssl_session *session = ssl->session_negotiate;
4988 session = ssl->session;
4990 mbedtls_sha512_init( &sha512 );
4992 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) );
4994 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
4998 * hash = PRF( master, finished_label,
4999 * Hash( handshake ) )[0.11]
5002 #if !defined(MBEDTLS_SHA512_ALT)
5003 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
5004 sha512.state, sizeof( sha512.state ) );
5007 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5009 : "server finished";
5011 mbedtls_sha512_finish( &sha512, padbuf );
5013 ssl->handshake->tls_prf( session->master, 48, sender,
5014 padbuf, 48, buf, len );
5016 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5018 mbedtls_sha512_free( &sha512 );
5020 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
5022 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
5024 #endif /* MBEDTLS_SHA512_C */
5025 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5027 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
5029 MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
5032 * Free our handshake params
5034 mbedtls_ssl_handshake_free( ssl->handshake );
5035 mbedtls_free( ssl->handshake );
5036 ssl->handshake = NULL;
5039 * Free the previous transform and swith in the current one
5041 if( ssl->transform )
5043 mbedtls_ssl_transform_free( ssl->transform );
5044 mbedtls_free( ssl->transform );
5046 ssl->transform = ssl->transform_negotiate;
5047 ssl->transform_negotiate = NULL;
5049 MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
5052 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
5054 int resume = ssl->handshake->resume;
5056 MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
5058 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5059 if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
5061 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE;
5062 ssl->renego_records_seen = 0;
5067 * Free the previous session and switch in the current one
5071 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5072 /* RFC 7366 3.1: keep the EtM state */
5073 ssl->session_negotiate->encrypt_then_mac =
5074 ssl->session->encrypt_then_mac;
5077 mbedtls_ssl_session_free( ssl->session );
5078 mbedtls_free( ssl->session );
5080 ssl->session = ssl->session_negotiate;
5081 ssl->session_negotiate = NULL;
5086 if( ssl->conf->f_set_cache != NULL &&
5087 ssl->session->id_len != 0 &&
5090 if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
5091 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
5094 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5095 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5096 ssl->handshake->flight != NULL )
5098 /* Cancel handshake timer */
5099 ssl_set_timer( ssl, 0 );
5101 /* Keep last flight around in case we need to resend it:
5102 * we need the handshake and transform structures for that */
5103 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
5107 ssl_handshake_wrapup_free_hs_transform( ssl );
5111 MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
5114 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
5118 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
5121 * Set the out_msg pointer to the correct location based on IV length
5123 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
5125 ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -
5126 ssl->transform_negotiate->fixed_ivlen;
5129 ssl->out_msg = ssl->out_iv;
5131 ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
5134 * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
5135 * may define some other value. Currently (early 2016), no defined
5136 * ciphersuite does this (and this is unlikely to change as activity has
5137 * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
5139 hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
5141 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5142 ssl->verify_data_len = hash_len;
5143 memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
5146 ssl->out_msglen = 4 + hash_len;
5147 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5148 ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED;
5151 * In case of session resuming, invert the client and server
5152 * ChangeCipherSpec messages order.
5154 if( ssl->handshake->resume != 0 )
5156 #if defined(MBEDTLS_SSL_CLI_C)
5157 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5158 ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5160 #if defined(MBEDTLS_SSL_SRV_C)
5161 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5162 ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5169 * Switch to our negotiated transform and session parameters for outbound
5172 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
5174 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5175 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5179 /* Remember current epoch settings for resending */
5180 ssl->handshake->alt_transform_out = ssl->transform_out;
5181 memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 );
5183 /* Set sequence_number to zero */
5184 memset( ssl->out_ctr + 2, 0, 6 );
5186 /* Increment epoch */
5187 for( i = 2; i > 0; i-- )
5188 if( ++ssl->out_ctr[i - 1] != 0 )
5191 /* The loop goes to its end iff the counter is wrapping */
5194 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
5195 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
5199 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5200 memset( ssl->out_ctr, 0, 8 );
5202 ssl->transform_out = ssl->transform_negotiate;
5203 ssl->session_out = ssl->session_negotiate;
5205 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5206 if( mbedtls_ssl_hw_record_activate != NULL )
5208 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
5210 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
5211 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5216 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5217 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5218 mbedtls_ssl_send_flight_completed( ssl );
5221 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
5223 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5227 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
5232 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5233 #define SSL_MAX_HASH_LEN 36
5235 #define SSL_MAX_HASH_LEN 12
5238 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
5241 unsigned int hash_len;
5242 unsigned char buf[SSL_MAX_HASH_LEN];
5244 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
5246 ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
5248 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
5250 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5254 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
5256 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5257 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5260 /* There is currently no ciphersuite using another length with TLS 1.2 */
5261 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5262 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
5268 if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
5269 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
5271 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5272 return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5275 if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
5276 buf, hash_len ) != 0 )
5278 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5279 return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5282 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5283 ssl->verify_data_len = hash_len;
5284 memcpy( ssl->peer_verify_data, buf, hash_len );
5287 if( ssl->handshake->resume != 0 )
5289 #if defined(MBEDTLS_SSL_CLI_C)
5290 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5291 ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5293 #if defined(MBEDTLS_SSL_SRV_C)
5294 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5295 ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5301 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5302 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5303 mbedtls_ssl_recv_flight_completed( ssl );
5306 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
5311 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
5313 memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
5315 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5316 defined(MBEDTLS_SSL_PROTO_TLS1_1)
5317 mbedtls_md5_init( &handshake->fin_md5 );
5318 mbedtls_sha1_init( &handshake->fin_sha1 );
5319 mbedtls_md5_starts( &handshake->fin_md5 );
5320 mbedtls_sha1_starts( &handshake->fin_sha1 );
5322 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5323 #if defined(MBEDTLS_SHA256_C)
5324 mbedtls_sha256_init( &handshake->fin_sha256 );
5325 mbedtls_sha256_starts( &handshake->fin_sha256, 0 );
5327 #if defined(MBEDTLS_SHA512_C)
5328 mbedtls_sha512_init( &handshake->fin_sha512 );
5329 mbedtls_sha512_starts( &handshake->fin_sha512, 1 );
5331 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5333 handshake->update_checksum = ssl_update_checksum_start;
5334 handshake->sig_alg = MBEDTLS_SSL_HASH_SHA1;
5336 #if defined(MBEDTLS_DHM_C)
5337 mbedtls_dhm_init( &handshake->dhm_ctx );
5339 #if defined(MBEDTLS_ECDH_C)
5340 mbedtls_ecdh_init( &handshake->ecdh_ctx );
5342 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5343 mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
5344 #if defined(MBEDTLS_SSL_CLI_C)
5345 handshake->ecjpake_cache = NULL;
5346 handshake->ecjpake_cache_len = 0;
5350 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5351 handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
5355 static void ssl_transform_init( mbedtls_ssl_transform *transform )
5357 memset( transform, 0, sizeof(mbedtls_ssl_transform) );
5359 mbedtls_cipher_init( &transform->cipher_ctx_enc );
5360 mbedtls_cipher_init( &transform->cipher_ctx_dec );
5362 mbedtls_md_init( &transform->md_ctx_enc );
5363 mbedtls_md_init( &transform->md_ctx_dec );
5366 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
5368 memset( session, 0, sizeof(mbedtls_ssl_session) );
5371 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
5373 /* Clear old handshake information if present */
5374 if( ssl->transform_negotiate )
5375 mbedtls_ssl_transform_free( ssl->transform_negotiate );
5376 if( ssl->session_negotiate )
5377 mbedtls_ssl_session_free( ssl->session_negotiate );
5378 if( ssl->handshake )
5379 mbedtls_ssl_handshake_free( ssl->handshake );
5382 * Either the pointers are now NULL or cleared properly and can be freed.
5383 * Now allocate missing structures.
5385 if( ssl->transform_negotiate == NULL )
5387 ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
5390 if( ssl->session_negotiate == NULL )
5392 ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
5395 if( ssl->handshake == NULL )
5397 ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
5400 /* All pointers should exist and can be directly freed without issue */
5401 if( ssl->handshake == NULL ||
5402 ssl->transform_negotiate == NULL ||
5403 ssl->session_negotiate == NULL )
5405 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
5407 mbedtls_free( ssl->handshake );
5408 mbedtls_free( ssl->transform_negotiate );
5409 mbedtls_free( ssl->session_negotiate );
5411 ssl->handshake = NULL;
5412 ssl->transform_negotiate = NULL;
5413 ssl->session_negotiate = NULL;
5415 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5418 /* Initialize structures */
5419 mbedtls_ssl_session_init( ssl->session_negotiate );
5420 ssl_transform_init( ssl->transform_negotiate );
5421 ssl_handshake_params_init( ssl->handshake );
5423 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5424 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5426 ssl->handshake->alt_transform_out = ssl->transform_out;
5428 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5429 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
5431 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
5433 ssl_set_timer( ssl, 0 );
5440 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5441 /* Dummy cookie callbacks for defaults */
5442 static int ssl_cookie_write_dummy( void *ctx,
5443 unsigned char **p, unsigned char *end,
5444 const unsigned char *cli_id, size_t cli_id_len )
5450 ((void) cli_id_len);
5452 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5455 static int ssl_cookie_check_dummy( void *ctx,
5456 const unsigned char *cookie, size_t cookie_len,
5457 const unsigned char *cli_id, size_t cli_id_len )
5461 ((void) cookie_len);
5463 ((void) cli_id_len);
5465 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5467 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
5470 * Initialize an SSL context
5472 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
5474 memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
5478 * Setup an SSL context
5480 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
5481 const mbedtls_ssl_config *conf )
5484 const size_t len = MBEDTLS_SSL_BUFFER_LEN;
5489 * Prepare base structures
5491 if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL ||
5492 ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL )
5494 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) );
5495 mbedtls_free( ssl->in_buf );
5497 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5500 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5501 if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5503 ssl->out_hdr = ssl->out_buf;
5504 ssl->out_ctr = ssl->out_buf + 3;
5505 ssl->out_len = ssl->out_buf + 11;
5506 ssl->out_iv = ssl->out_buf + 13;
5507 ssl->out_msg = ssl->out_buf + 13;
5509 ssl->in_hdr = ssl->in_buf;
5510 ssl->in_ctr = ssl->in_buf + 3;
5511 ssl->in_len = ssl->in_buf + 11;
5512 ssl->in_iv = ssl->in_buf + 13;
5513 ssl->in_msg = ssl->in_buf + 13;
5518 ssl->out_ctr = ssl->out_buf;
5519 ssl->out_hdr = ssl->out_buf + 8;
5520 ssl->out_len = ssl->out_buf + 11;
5521 ssl->out_iv = ssl->out_buf + 13;
5522 ssl->out_msg = ssl->out_buf + 13;
5524 ssl->in_ctr = ssl->in_buf;
5525 ssl->in_hdr = ssl->in_buf + 8;
5526 ssl->in_len = ssl->in_buf + 11;
5527 ssl->in_iv = ssl->in_buf + 13;
5528 ssl->in_msg = ssl->in_buf + 13;
5531 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5538 * Reset an initialized and used SSL context for re-use while retaining
5539 * all application-set variables, function pointers and data.
5541 * If partial is non-zero, keep data in the input buffer and client ID.
5542 * (Use when a DTLS client reconnects from the same port.)
5544 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
5548 ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5550 /* Cancel any possibly running timer */
5551 ssl_set_timer( ssl, 0 );
5553 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5554 ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
5555 ssl->renego_records_seen = 0;
5557 ssl->verify_data_len = 0;
5558 memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5559 memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5561 ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
5563 ssl->in_offt = NULL;
5565 ssl->in_msg = ssl->in_buf + 13;
5566 ssl->in_msgtype = 0;
5570 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5571 ssl->next_record_offset = 0;
5574 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5575 ssl_dtls_replay_reset( ssl );
5580 ssl->record_read = 0;
5582 ssl->out_msg = ssl->out_buf + 13;
5583 ssl->out_msgtype = 0;
5584 ssl->out_msglen = 0;
5586 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
5587 if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
5588 ssl->split_done = 0;
5591 ssl->transform_in = NULL;
5592 ssl->transform_out = NULL;
5594 memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5596 memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5598 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5599 if( mbedtls_ssl_hw_record_reset != NULL )
5601 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
5602 if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
5604 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
5605 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5610 if( ssl->transform )
5612 mbedtls_ssl_transform_free( ssl->transform );
5613 mbedtls_free( ssl->transform );
5614 ssl->transform = NULL;
5619 mbedtls_ssl_session_free( ssl->session );
5620 mbedtls_free( ssl->session );
5621 ssl->session = NULL;
5624 #if defined(MBEDTLS_SSL_ALPN)
5625 ssl->alpn_chosen = NULL;
5628 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5631 mbedtls_free( ssl->cli_id );
5633 ssl->cli_id_len = 0;
5637 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5644 * Reset an initialized and used SSL context for re-use while retaining
5645 * all application-set variables, function pointers and data.
5647 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
5649 return( ssl_session_reset_int( ssl, 0 ) );
5655 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
5657 conf->endpoint = endpoint;
5660 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
5662 conf->transport = transport;
5665 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5666 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
5668 conf->anti_replay = mode;
5672 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
5673 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
5675 conf->badmac_limit = limit;
5679 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5680 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max )
5682 conf->hs_timeout_min = min;
5683 conf->hs_timeout_max = max;
5687 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
5689 conf->authmode = authmode;
5692 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5693 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
5694 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
5697 conf->f_vrfy = f_vrfy;
5698 conf->p_vrfy = p_vrfy;
5700 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5702 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
5703 int (*f_rng)(void *, unsigned char *, size_t),
5706 conf->f_rng = f_rng;
5707 conf->p_rng = p_rng;
5710 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
5711 void (*f_dbg)(void *, int, const char *, int, const char *),
5714 conf->f_dbg = f_dbg;
5715 conf->p_dbg = p_dbg;
5718 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
5720 mbedtls_ssl_send_t *f_send,
5721 mbedtls_ssl_recv_t *f_recv,
5722 mbedtls_ssl_recv_timeout_t *f_recv_timeout )
5725 ssl->f_send = f_send;
5726 ssl->f_recv = f_recv;
5727 ssl->f_recv_timeout = f_recv_timeout;
5730 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
5732 conf->read_timeout = timeout;
5735 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
5737 mbedtls_ssl_set_timer_t *f_set_timer,
5738 mbedtls_ssl_get_timer_t *f_get_timer )
5740 ssl->p_timer = p_timer;
5741 ssl->f_set_timer = f_set_timer;
5742 ssl->f_get_timer = f_get_timer;
5744 /* Make sure we start with no timer running */
5745 ssl_set_timer( ssl, 0 );
5748 #if defined(MBEDTLS_SSL_SRV_C)
5749 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
5751 int (*f_get_cache)(void *, mbedtls_ssl_session *),
5752 int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
5754 conf->p_cache = p_cache;
5755 conf->f_get_cache = f_get_cache;
5756 conf->f_set_cache = f_set_cache;
5758 #endif /* MBEDTLS_SSL_SRV_C */
5760 #if defined(MBEDTLS_SSL_CLI_C)
5761 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
5767 ssl->session_negotiate == NULL ||
5768 ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
5770 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5773 if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
5776 ssl->handshake->resume = 1;
5780 #endif /* MBEDTLS_SSL_CLI_C */
5782 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
5783 const int *ciphersuites )
5785 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
5786 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
5787 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
5788 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
5791 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
5792 const int *ciphersuites,
5793 int major, int minor )
5795 if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
5798 if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
5801 conf->ciphersuite_list[minor] = ciphersuites;
5804 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5805 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
5806 const mbedtls_x509_crt_profile *profile )
5808 conf->cert_profile = profile;
5811 /* Append a new keycert entry to a (possibly empty) list */
5812 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
5813 mbedtls_x509_crt *cert,
5814 mbedtls_pk_context *key )
5816 mbedtls_ssl_key_cert *new;
5818 new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
5820 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5826 /* Update head is the list was null, else add to the end */
5833 mbedtls_ssl_key_cert *cur = *head;
5834 while( cur->next != NULL )
5842 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
5843 mbedtls_x509_crt *own_cert,
5844 mbedtls_pk_context *pk_key )
5846 return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
5849 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
5850 mbedtls_x509_crt *ca_chain,
5851 mbedtls_x509_crl *ca_crl )
5853 conf->ca_chain = ca_chain;
5854 conf->ca_crl = ca_crl;
5856 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5858 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5859 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
5860 mbedtls_x509_crt *own_cert,
5861 mbedtls_pk_context *pk_key )
5863 return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
5864 own_cert, pk_key ) );
5867 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
5868 mbedtls_x509_crt *ca_chain,
5869 mbedtls_x509_crl *ca_crl )
5871 ssl->handshake->sni_ca_chain = ca_chain;
5872 ssl->handshake->sni_ca_crl = ca_crl;
5875 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
5878 ssl->handshake->sni_authmode = authmode;
5880 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
5882 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5884 * Set EC J-PAKE password for current handshake
5886 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
5887 const unsigned char *pw,
5890 mbedtls_ecjpake_role role;
5892 if( ssl->handshake == NULL || ssl->conf == NULL )
5893 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5895 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5896 role = MBEDTLS_ECJPAKE_SERVER;
5898 role = MBEDTLS_ECJPAKE_CLIENT;
5900 return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
5903 MBEDTLS_ECP_DP_SECP256R1,
5906 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
5908 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
5909 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
5910 const unsigned char *psk, size_t psk_len,
5911 const unsigned char *psk_identity, size_t psk_identity_len )
5913 if( psk == NULL || psk_identity == NULL )
5914 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5916 if( psk_len > MBEDTLS_PSK_MAX_LEN )
5917 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5919 /* Identity len will be encoded on two bytes */
5920 if( ( psk_identity_len >> 16 ) != 0 ||
5921 psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN )
5923 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5926 if( conf->psk != NULL || conf->psk_identity != NULL )
5928 mbedtls_free( conf->psk );
5929 mbedtls_free( conf->psk_identity );
5931 conf->psk_identity = NULL;
5934 if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
5935 ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
5937 mbedtls_free( conf->psk );
5938 mbedtls_free( conf->psk_identity );
5940 conf->psk_identity = NULL;
5941 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5944 conf->psk_len = psk_len;
5945 conf->psk_identity_len = psk_identity_len;
5947 memcpy( conf->psk, psk, conf->psk_len );
5948 memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
5953 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
5954 const unsigned char *psk, size_t psk_len )
5956 if( psk == NULL || ssl->handshake == NULL )
5957 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5959 if( psk_len > MBEDTLS_PSK_MAX_LEN )
5960 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5962 if( ssl->handshake->psk != NULL )
5963 mbedtls_free( ssl->handshake->psk );
5965 if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
5966 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5968 ssl->handshake->psk_len = psk_len;
5969 memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
5974 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
5975 int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
5979 conf->f_psk = f_psk;
5980 conf->p_psk = p_psk;
5982 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
5984 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
5985 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
5989 if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
5990 ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
5992 mbedtls_mpi_free( &conf->dhm_P );
5993 mbedtls_mpi_free( &conf->dhm_G );
6000 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
6004 if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
6005 ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
6007 mbedtls_mpi_free( &conf->dhm_P );
6008 mbedtls_mpi_free( &conf->dhm_G );
6014 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
6016 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
6018 * Set the minimum length for Diffie-Hellman parameters
6020 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
6021 unsigned int bitlen )
6023 conf->dhm_min_bitlen = bitlen;
6025 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
6027 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
6029 * Set allowed/preferred hashes for handshake signatures
6031 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
6034 conf->sig_hashes = hashes;
6038 #if defined(MBEDTLS_ECP_C)
6040 * Set the allowed elliptic curves
6042 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
6043 const mbedtls_ecp_group_id *curve_list )
6045 conf->curve_list = curve_list;
6049 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6050 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
6052 size_t hostname_len;
6054 if( hostname == NULL )
6055 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6057 hostname_len = strlen( hostname );
6059 if( hostname_len + 1 == 0 )
6060 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6062 if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
6063 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6065 ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
6067 if( ssl->hostname == NULL )
6068 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6070 memcpy( ssl->hostname, hostname, hostname_len );
6072 ssl->hostname[hostname_len] = '\0';
6078 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
6079 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
6080 int (*f_sni)(void *, mbedtls_ssl_context *,
6081 const unsigned char *, size_t),
6084 conf->f_sni = f_sni;
6085 conf->p_sni = p_sni;
6087 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6089 #if defined(MBEDTLS_SSL_ALPN)
6090 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
6092 size_t cur_len, tot_len;
6096 * "Empty strings MUST NOT be included and byte strings MUST NOT be
6097 * truncated". Check lengths now rather than later.
6100 for( p = protos; *p != NULL; p++ )
6102 cur_len = strlen( *p );
6105 if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
6106 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6109 conf->alpn_list = protos;
6114 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
6116 return( ssl->alpn_chosen );
6118 #endif /* MBEDTLS_SSL_ALPN */
6120 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
6122 conf->max_major_ver = major;
6123 conf->max_minor_ver = minor;
6126 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
6128 conf->min_major_ver = major;
6129 conf->min_minor_ver = minor;
6132 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
6133 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
6135 conf->fallback = fallback;
6139 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6140 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
6142 conf->encrypt_then_mac = etm;
6146 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6147 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
6149 conf->extended_ms = ems;
6153 #if defined(MBEDTLS_ARC4_C)
6154 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
6156 conf->arc4_disabled = arc4;
6160 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6161 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
6163 if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
6164 mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN )
6166 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6169 conf->mfl_code = mfl_code;
6173 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6175 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
6176 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
6178 conf->trunc_hmac = truncate;
6180 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
6182 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6183 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
6185 conf->cbc_record_splitting = split;
6189 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
6191 conf->allow_legacy_renegotiation = allow_legacy;
6194 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6195 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
6197 conf->disable_renegotiation = renegotiation;
6200 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
6202 conf->renego_max_records = max_records;
6205 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
6206 const unsigned char period[8] )
6208 memcpy( conf->renego_period, period, 8 );
6210 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6212 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
6213 #if defined(MBEDTLS_SSL_CLI_C)
6214 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
6216 conf->session_tickets = use_tickets;
6220 #if defined(MBEDTLS_SSL_SRV_C)
6221 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
6222 mbedtls_ssl_ticket_write_t *f_ticket_write,
6223 mbedtls_ssl_ticket_parse_t *f_ticket_parse,
6226 conf->f_ticket_write = f_ticket_write;
6227 conf->f_ticket_parse = f_ticket_parse;
6228 conf->p_ticket = p_ticket;
6231 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
6233 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
6234 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
6235 mbedtls_ssl_export_keys_t *f_export_keys,
6236 void *p_export_keys )
6238 conf->f_export_keys = f_export_keys;
6239 conf->p_export_keys = p_export_keys;
6246 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
6248 return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
6251 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
6253 if( ssl->session != NULL )
6254 return( ssl->session->verify_result );
6256 if( ssl->session_negotiate != NULL )
6257 return( ssl->session_negotiate->verify_result );
6259 return( 0xFFFFFFFF );
6262 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
6264 if( ssl == NULL || ssl->session == NULL )
6267 return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
6270 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
6272 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6273 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6275 switch( ssl->minor_ver )
6277 case MBEDTLS_SSL_MINOR_VERSION_2:
6278 return( "DTLSv1.0" );
6280 case MBEDTLS_SSL_MINOR_VERSION_3:
6281 return( "DTLSv1.2" );
6284 return( "unknown (DTLS)" );
6289 switch( ssl->minor_ver )
6291 case MBEDTLS_SSL_MINOR_VERSION_0:
6292 return( "SSLv3.0" );
6294 case MBEDTLS_SSL_MINOR_VERSION_1:
6295 return( "TLSv1.0" );
6297 case MBEDTLS_SSL_MINOR_VERSION_2:
6298 return( "TLSv1.1" );
6300 case MBEDTLS_SSL_MINOR_VERSION_3:
6301 return( "TLSv1.2" );
6304 return( "unknown" );
6308 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
6310 size_t transform_expansion;
6311 const mbedtls_ssl_transform *transform = ssl->transform_out;
6313 #if defined(MBEDTLS_ZLIB_SUPPORT)
6314 if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
6315 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
6318 if( transform == NULL )
6319 return( (int) mbedtls_ssl_hdr_len( ssl ) );
6321 switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
6323 case MBEDTLS_MODE_GCM:
6324 case MBEDTLS_MODE_CCM:
6325 case MBEDTLS_MODE_STREAM:
6326 transform_expansion = transform->minlen;
6329 case MBEDTLS_MODE_CBC:
6330 transform_expansion = transform->maclen
6331 + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc );
6335 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6336 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6339 return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
6342 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6343 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
6348 * Assume mfl_code is correct since it was checked when set
6350 max_len = mfl_code_to_length[ssl->conf->mfl_code];
6353 * Check if a smaller max length was negotiated
6355 if( ssl->session_out != NULL &&
6356 mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
6358 max_len = mfl_code_to_length[ssl->session_out->mfl_code];
6363 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6365 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6366 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
6368 if( ssl == NULL || ssl->session == NULL )
6371 return( ssl->session->peer_cert );
6373 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6375 #if defined(MBEDTLS_SSL_CLI_C)
6376 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
6380 ssl->session == NULL ||
6381 ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
6383 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6386 return( ssl_session_copy( dst, ssl->session ) );
6388 #endif /* MBEDTLS_SSL_CLI_C */
6391 * Perform a single step of the SSL handshake
6393 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
6395 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6397 if( ssl == NULL || ssl->conf == NULL )
6398 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6400 #if defined(MBEDTLS_SSL_CLI_C)
6401 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6402 ret = mbedtls_ssl_handshake_client_step( ssl );
6404 #if defined(MBEDTLS_SSL_SRV_C)
6405 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6406 ret = mbedtls_ssl_handshake_server_step( ssl );
6413 * Perform the SSL handshake
6415 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
6419 if( ssl == NULL || ssl->conf == NULL )
6420 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6422 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
6424 while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6426 ret = mbedtls_ssl_handshake_step( ssl );
6432 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
6437 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6438 #if defined(MBEDTLS_SSL_SRV_C)
6440 * Write HelloRequest to request renegotiation on server
6442 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
6446 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
6448 ssl->out_msglen = 4;
6449 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
6450 ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST;
6452 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6454 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6458 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
6462 #endif /* MBEDTLS_SSL_SRV_C */
6465 * Actually renegotiate current connection, triggered by either:
6466 * - any side: calling mbedtls_ssl_renegotiate(),
6467 * - client: receiving a HelloRequest during mbedtls_ssl_read(),
6468 * - server: receiving any handshake message on server during mbedtls_ssl_read() after
6469 * the initial handshake is completed.
6470 * If the handshake doesn't complete due to waiting for I/O, it will continue
6471 * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
6473 static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
6477 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
6479 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
6482 /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
6483 * the ServerHello will have message_seq = 1" */
6484 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6485 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6486 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6488 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6489 ssl->handshake->out_msg_seq = 1;
6491 ssl->handshake->in_msg_seq = 1;
6495 ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
6496 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
6498 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6500 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6504 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
6510 * Renegotiate current connection on client,
6511 * or request renegotiation on server
6513 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
6515 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6517 if( ssl == NULL || ssl->conf == NULL )
6518 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6520 #if defined(MBEDTLS_SSL_SRV_C)
6521 /* On server, just send the request */
6522 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6524 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6525 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6527 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6529 /* Did we already try/start sending HelloRequest? */
6530 if( ssl->out_left != 0 )
6531 return( mbedtls_ssl_flush_output( ssl ) );
6533 return( ssl_write_hello_request( ssl ) );
6535 #endif /* MBEDTLS_SSL_SRV_C */
6537 #if defined(MBEDTLS_SSL_CLI_C)
6539 * On client, either start the renegotiation process or,
6540 * if already in progress, continue the handshake
6542 if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
6544 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6545 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6547 if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
6549 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6555 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6557 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6561 #endif /* MBEDTLS_SSL_CLI_C */
6567 * Check record counters and renegotiate if they're above the limit.
6569 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
6571 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
6572 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
6573 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
6578 if( memcmp( ssl->in_ctr, ssl->conf->renego_period, 8 ) <= 0 &&
6579 memcmp( ssl->out_ctr, ssl->conf->renego_period, 8 ) <= 0 )
6584 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
6585 return( mbedtls_ssl_renegotiate( ssl ) );
6587 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6590 * Receive application data decrypted from the SSL layer
6592 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
6594 int ret, record_read = 0;
6597 if( ssl == NULL || ssl->conf == NULL )
6598 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6600 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
6602 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6603 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6605 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
6608 if( ssl->handshake != NULL &&
6609 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
6611 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
6617 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6618 if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
6620 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
6625 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6627 ret = mbedtls_ssl_handshake( ssl );
6628 if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
6634 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6639 if( ssl->in_offt == NULL )
6641 /* Start timer if not already running */
6642 if( ssl->f_get_timer != NULL &&
6643 ssl->f_get_timer( ssl->p_timer ) == -1 )
6645 ssl_set_timer( ssl, ssl->conf->read_timeout );
6650 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6652 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6655 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6660 if( ssl->in_msglen == 0 &&
6661 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
6664 * OpenSSL sends empty messages to randomize the IV
6666 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6668 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6671 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6676 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6677 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
6679 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
6681 #if defined(MBEDTLS_SSL_CLI_C)
6682 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
6683 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
6684 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
6686 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
6688 /* With DTLS, drop the packet (probably from last handshake) */
6689 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6690 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6691 return( MBEDTLS_ERR_SSL_WANT_READ );
6693 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6696 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6697 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
6699 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
6701 /* With DTLS, drop the packet (probably from last handshake) */
6702 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6703 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6704 return( MBEDTLS_ERR_SSL_WANT_READ );
6706 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6710 if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
6711 ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
6712 ssl->conf->allow_legacy_renegotiation ==
6713 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) )
6715 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
6717 #if defined(MBEDTLS_SSL_PROTO_SSL3)
6718 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
6721 * SSLv3 does not have a "no_renegotiation" alert
6723 if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
6727 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
6728 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
6729 defined(MBEDTLS_SSL_PROTO_TLS1_2)
6730 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
6732 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
6733 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6734 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
6740 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
6741 MBEDTLS_SSL_PROTO_TLS1_2 */
6743 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6744 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6749 /* DTLS clients need to know renego is server-initiated */
6750 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6751 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6752 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6754 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6757 ret = ssl_start_renegotiation( ssl );
6758 if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
6764 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6769 /* If a non-handshake record was read during renego, fallthrough,
6770 * else tell the user they should call mbedtls_ssl_read() again */
6772 return( MBEDTLS_ERR_SSL_WANT_READ );
6774 else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6777 if( ssl->conf->renego_max_records >= 0 )
6779 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
6781 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
6782 "but not honored by client" ) );
6783 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6787 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6789 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
6790 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
6792 MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
6793 return( MBEDTLS_ERR_SSL_WANT_READ );
6796 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
6798 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
6799 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6802 ssl->in_offt = ssl->in_msg;
6804 /* We're going to return something now, cancel timer,
6805 * except if handshake (renegotiation) is in progress */
6806 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
6807 ssl_set_timer( ssl, 0 );
6809 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6810 /* If we requested renego but received AppData, resend HelloRequest.
6811 * Do it now, after setting in_offt, to avoid taking this branch
6812 * again if ssl_write_hello_request() returns WANT_WRITE */
6813 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
6814 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6815 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6817 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
6819 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
6823 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
6827 n = ( len < ssl->in_msglen )
6828 ? len : ssl->in_msglen;
6830 memcpy( buf, ssl->in_offt, n );
6831 ssl->in_msglen -= n;
6833 if( ssl->in_msglen == 0 )
6834 /* all bytes consumed */
6835 ssl->in_offt = NULL;
6837 /* more data available */
6840 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
6846 * Send application data to be encrypted by the SSL layer,
6847 * taking care of max fragment length and buffer size
6849 static int ssl_write_real( mbedtls_ssl_context *ssl,
6850 const unsigned char *buf, size_t len )
6853 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6854 size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
6858 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6859 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6861 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
6862 "maximum fragment length: %d > %d",
6864 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6870 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6872 if( ssl->out_left != 0 )
6874 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
6876 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
6882 ssl->out_msglen = len;
6883 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
6884 memcpy( ssl->out_msg, buf, len );
6886 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6888 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6893 return( (int) len );
6897 * Write application data, doing 1/n-1 splitting if necessary.
6899 * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
6900 * then the caller will call us again with the same arguments, so
6901 * remember wether we already did the split or not.
6903 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6904 static int ssl_write_split( mbedtls_ssl_context *ssl,
6905 const unsigned char *buf, size_t len )
6909 if( ssl->conf->cbc_record_splitting ==
6910 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
6912 ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
6913 mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
6914 != MBEDTLS_MODE_CBC )
6916 return( ssl_write_real( ssl, buf, len ) );
6919 if( ssl->split_done == 0 )
6921 if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
6923 ssl->split_done = 1;
6926 if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
6928 ssl->split_done = 0;
6932 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
6935 * Write application data (public-facing wrapper)
6937 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
6941 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
6943 if( ssl == NULL || ssl->conf == NULL )
6944 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6946 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6947 if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
6949 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
6954 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6956 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6958 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6963 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6964 ret = ssl_write_split( ssl, buf, len );
6966 ret = ssl_write_real( ssl, buf, len );
6969 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
6975 * Notify the peer that the connection is being closed
6977 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
6981 if( ssl == NULL || ssl->conf == NULL )
6982 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6984 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
6986 if( ssl->out_left != 0 )
6987 return( mbedtls_ssl_flush_output( ssl ) );
6989 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
6991 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
6992 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6993 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
6995 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
7000 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
7005 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
7007 if( transform == NULL )
7010 #if defined(MBEDTLS_ZLIB_SUPPORT)
7011 deflateEnd( &transform->ctx_deflate );
7012 inflateEnd( &transform->ctx_inflate );
7015 mbedtls_cipher_free( &transform->cipher_ctx_enc );
7016 mbedtls_cipher_free( &transform->cipher_ctx_dec );
7018 mbedtls_md_free( &transform->md_ctx_enc );
7019 mbedtls_md_free( &transform->md_ctx_dec );
7021 mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
7024 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7025 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
7027 mbedtls_ssl_key_cert *cur = key_cert, *next;
7029 while( cur != NULL )
7032 mbedtls_free( cur );
7036 #endif /* MBEDTLS_X509_CRT_PARSE_C */
7038 void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake )
7040 if( handshake == NULL )
7043 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
7044 defined(MBEDTLS_SSL_PROTO_TLS1_1)
7045 mbedtls_md5_free( &handshake->fin_md5 );
7046 mbedtls_sha1_free( &handshake->fin_sha1 );
7048 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7049 #if defined(MBEDTLS_SHA256_C)
7050 mbedtls_sha256_free( &handshake->fin_sha256 );
7052 #if defined(MBEDTLS_SHA512_C)
7053 mbedtls_sha512_free( &handshake->fin_sha512 );
7055 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7057 #if defined(MBEDTLS_DHM_C)
7058 mbedtls_dhm_free( &handshake->dhm_ctx );
7060 #if defined(MBEDTLS_ECDH_C)
7061 mbedtls_ecdh_free( &handshake->ecdh_ctx );
7063 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7064 mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
7065 #if defined(MBEDTLS_SSL_CLI_C)
7066 mbedtls_free( handshake->ecjpake_cache );
7067 handshake->ecjpake_cache = NULL;
7068 handshake->ecjpake_cache_len = 0;
7072 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
7073 defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7074 /* explicit void pointer cast for buggy MS compiler */
7075 mbedtls_free( (void *) handshake->curves );
7078 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7079 if( handshake->psk != NULL )
7081 mbedtls_zeroize( handshake->psk, handshake->psk_len );
7082 mbedtls_free( handshake->psk );
7086 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
7087 defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7089 * Free only the linked list wrapper, not the keys themselves
7090 * since the belong to the SNI callback
7092 if( handshake->sni_key_cert != NULL )
7094 mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
7096 while( cur != NULL )
7099 mbedtls_free( cur );
7103 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
7105 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7106 mbedtls_free( handshake->verify_cookie );
7107 mbedtls_free( handshake->hs_msg );
7108 ssl_flight_free( handshake->flight );
7111 mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) );
7114 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
7116 if( session == NULL )
7119 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7120 if( session->peer_cert != NULL )
7122 mbedtls_x509_crt_free( session->peer_cert );
7123 mbedtls_free( session->peer_cert );
7127 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
7128 mbedtls_free( session->ticket );
7131 mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) );
7135 * Free an SSL context
7137 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
7142 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
7144 if( ssl->out_buf != NULL )
7146 mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN );
7147 mbedtls_free( ssl->out_buf );
7150 if( ssl->in_buf != NULL )
7152 mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN );
7153 mbedtls_free( ssl->in_buf );
7156 #if defined(MBEDTLS_ZLIB_SUPPORT)
7157 if( ssl->compress_buf != NULL )
7159 mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN );
7160 mbedtls_free( ssl->compress_buf );
7164 if( ssl->transform )
7166 mbedtls_ssl_transform_free( ssl->transform );
7167 mbedtls_free( ssl->transform );
7170 if( ssl->handshake )
7172 mbedtls_ssl_handshake_free( ssl->handshake );
7173 mbedtls_ssl_transform_free( ssl->transform_negotiate );
7174 mbedtls_ssl_session_free( ssl->session_negotiate );
7176 mbedtls_free( ssl->handshake );
7177 mbedtls_free( ssl->transform_negotiate );
7178 mbedtls_free( ssl->session_negotiate );
7183 mbedtls_ssl_session_free( ssl->session );
7184 mbedtls_free( ssl->session );
7187 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7188 if( ssl->hostname != NULL )
7190 mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
7191 mbedtls_free( ssl->hostname );
7195 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
7196 if( mbedtls_ssl_hw_record_finish != NULL )
7198 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
7199 mbedtls_ssl_hw_record_finish( ssl );
7203 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7204 mbedtls_free( ssl->cli_id );
7207 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
7209 /* Actually clear after last debug message */
7210 mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
7214 * Initialze mbedtls_ssl_config
7216 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
7218 memset( conf, 0, sizeof( mbedtls_ssl_config ) );
7221 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7222 static int ssl_preset_default_hashes[] = {
7223 #if defined(MBEDTLS_SHA512_C)
7227 #if defined(MBEDTLS_SHA256_C)
7231 #if defined(MBEDTLS_SHA1_C)
7238 static int ssl_preset_suiteb_ciphersuites[] = {
7239 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
7240 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
7244 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7245 static int ssl_preset_suiteb_hashes[] = {
7252 #if defined(MBEDTLS_ECP_C)
7253 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
7254 MBEDTLS_ECP_DP_SECP256R1,
7255 MBEDTLS_ECP_DP_SECP384R1,
7261 * Load default in mbedtls_ssl_config
7263 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
7264 int endpoint, int transport, int preset )
7266 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7270 /* Use the functions here so that they are covered in tests,
7271 * but otherwise access member directly for efficiency */
7272 mbedtls_ssl_conf_endpoint( conf, endpoint );
7273 mbedtls_ssl_conf_transport( conf, transport );
7276 * Things that are common to all presets
7278 #if defined(MBEDTLS_SSL_CLI_C)
7279 if( endpoint == MBEDTLS_SSL_IS_CLIENT )
7281 conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
7282 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
7283 conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
7288 #if defined(MBEDTLS_ARC4_C)
7289 conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
7292 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
7293 conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
7296 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
7297 conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
7300 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7301 conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
7304 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7305 conf->f_cookie_write = ssl_cookie_write_dummy;
7306 conf->f_cookie_check = ssl_cookie_check_dummy;
7309 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
7310 conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
7313 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7314 conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
7315 conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
7318 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7319 conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
7320 memset( conf->renego_period, 0xFF, 7 );
7321 conf->renego_period[7] = 0x00;
7324 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7325 if( endpoint == MBEDTLS_SSL_IS_SERVER )
7327 if( ( ret = mbedtls_ssl_conf_dh_param( conf,
7328 MBEDTLS_DHM_RFC5114_MODP_2048_P,
7329 MBEDTLS_DHM_RFC5114_MODP_2048_G ) ) != 0 )
7337 * Preset-specific defaults
7344 case MBEDTLS_SSL_PRESET_SUITEB:
7345 conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7346 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
7347 conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7348 conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7350 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7351 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7352 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7353 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7354 ssl_preset_suiteb_ciphersuites;
7356 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7357 conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
7360 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7361 conf->sig_hashes = ssl_preset_suiteb_hashes;
7364 #if defined(MBEDTLS_ECP_C)
7365 conf->curve_list = ssl_preset_suiteb_curves;
7373 conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7374 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */
7375 conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7376 conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7378 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7379 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7380 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
7383 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7384 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7385 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7386 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7387 mbedtls_ssl_list_ciphersuites();
7389 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7390 conf->cert_profile = &mbedtls_x509_crt_profile_default;
7393 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7394 conf->sig_hashes = ssl_preset_default_hashes;
7397 #if defined(MBEDTLS_ECP_C)
7398 conf->curve_list = mbedtls_ecp_grp_id_list();
7401 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
7402 conf->dhm_min_bitlen = 1024;
7410 * Free mbedtls_ssl_config
7412 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
7414 #if defined(MBEDTLS_DHM_C)
7415 mbedtls_mpi_free( &conf->dhm_P );
7416 mbedtls_mpi_free( &conf->dhm_G );
7419 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7420 if( conf->psk != NULL )
7422 mbedtls_zeroize( conf->psk, conf->psk_len );
7423 mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len );
7424 mbedtls_free( conf->psk );
7425 mbedtls_free( conf->psk_identity );
7427 conf->psk_identity_len = 0;
7431 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7432 ssl_key_cert_free( conf->key_cert );
7435 mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) );
7438 #if defined(MBEDTLS_PK_C) && \
7439 ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
7441 * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7443 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
7445 #if defined(MBEDTLS_RSA_C)
7446 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
7447 return( MBEDTLS_SSL_SIG_RSA );
7449 #if defined(MBEDTLS_ECDSA_C)
7450 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
7451 return( MBEDTLS_SSL_SIG_ECDSA );
7453 return( MBEDTLS_SSL_SIG_ANON );
7456 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
7460 #if defined(MBEDTLS_RSA_C)
7461 case MBEDTLS_SSL_SIG_RSA:
7462 return( MBEDTLS_PK_RSA );
7464 #if defined(MBEDTLS_ECDSA_C)
7465 case MBEDTLS_SSL_SIG_ECDSA:
7466 return( MBEDTLS_PK_ECDSA );
7469 return( MBEDTLS_PK_NONE );
7472 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7475 * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
7477 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
7481 #if defined(MBEDTLS_MD5_C)
7482 case MBEDTLS_SSL_HASH_MD5:
7483 return( MBEDTLS_MD_MD5 );
7485 #if defined(MBEDTLS_SHA1_C)
7486 case MBEDTLS_SSL_HASH_SHA1:
7487 return( MBEDTLS_MD_SHA1 );
7489 #if defined(MBEDTLS_SHA256_C)
7490 case MBEDTLS_SSL_HASH_SHA224:
7491 return( MBEDTLS_MD_SHA224 );
7492 case MBEDTLS_SSL_HASH_SHA256:
7493 return( MBEDTLS_MD_SHA256 );
7495 #if defined(MBEDTLS_SHA512_C)
7496 case MBEDTLS_SSL_HASH_SHA384:
7497 return( MBEDTLS_MD_SHA384 );
7498 case MBEDTLS_SSL_HASH_SHA512:
7499 return( MBEDTLS_MD_SHA512 );
7502 return( MBEDTLS_MD_NONE );
7507 * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
7509 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
7513 #if defined(MBEDTLS_MD5_C)
7514 case MBEDTLS_MD_MD5:
7515 return( MBEDTLS_SSL_HASH_MD5 );
7517 #if defined(MBEDTLS_SHA1_C)
7518 case MBEDTLS_MD_SHA1:
7519 return( MBEDTLS_SSL_HASH_SHA1 );
7521 #if defined(MBEDTLS_SHA256_C)
7522 case MBEDTLS_MD_SHA224:
7523 return( MBEDTLS_SSL_HASH_SHA224 );
7524 case MBEDTLS_MD_SHA256:
7525 return( MBEDTLS_SSL_HASH_SHA256 );
7527 #if defined(MBEDTLS_SHA512_C)
7528 case MBEDTLS_MD_SHA384:
7529 return( MBEDTLS_SSL_HASH_SHA384 );
7530 case MBEDTLS_MD_SHA512:
7531 return( MBEDTLS_SSL_HASH_SHA512 );
7534 return( MBEDTLS_SSL_HASH_NONE );
7538 #if defined(MBEDTLS_ECP_C)
7540 * Check if a curve proposed by the peer is in our list.
7541 * Return 0 if we're willing to use it, -1 otherwise.
7543 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
7545 const mbedtls_ecp_group_id *gid;
7547 if( ssl->conf->curve_list == NULL )
7550 for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
7551 if( *gid == grp_id )
7556 #endif /* MBEDTLS_ECP_C */
7558 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7560 * Check if a hash proposed by the peer is in our list.
7561 * Return 0 if we're willing to use it, -1 otherwise.
7563 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
7564 mbedtls_md_type_t md )
7568 if( ssl->conf->sig_hashes == NULL )
7571 for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
7572 if( *cur == (int) md )
7577 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
7579 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7580 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
7581 const mbedtls_ssl_ciphersuite_t *ciphersuite,
7586 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7589 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7590 const char *ext_oid;
7594 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \
7595 !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7597 ((void) cert_endpoint);
7601 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7602 if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7604 /* Server part of the key exchange */
7605 switch( ciphersuite->key_exchange )
7607 case MBEDTLS_KEY_EXCHANGE_RSA:
7608 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
7609 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
7612 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
7613 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
7614 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
7615 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7618 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
7619 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
7620 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
7623 /* Don't use default: we want warnings when adding new values */
7624 case MBEDTLS_KEY_EXCHANGE_NONE:
7625 case MBEDTLS_KEY_EXCHANGE_PSK:
7626 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
7627 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
7628 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
7629 case MBEDTLS_KEY_EXCHANGE_ECDH_ANON:
7635 /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
7636 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7639 if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
7641 *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
7645 ((void) ciphersuite);
7646 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
7648 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7649 if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7651 ext_oid = MBEDTLS_OID_SERVER_AUTH;
7652 ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
7656 ext_oid = MBEDTLS_OID_CLIENT_AUTH;
7657 ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
7660 if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
7662 *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
7665 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
7669 #endif /* MBEDTLS_X509_CRT_PARSE_C */
7672 * Convert version numbers to/from wire format
7673 * and, for DTLS, to/from TLS equivalent.
7675 * For TLS this is the identity.
7676 * For DTLS, use one complement (v -> 255 - v, and then map as follows:
7677 * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1)
7678 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
7680 void mbedtls_ssl_write_version( int major, int minor, int transport,
7681 unsigned char ver[2] )
7683 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7684 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7686 if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
7687 --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7689 ver[0] = (unsigned char)( 255 - ( major - 2 ) );
7690 ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
7697 ver[0] = (unsigned char) major;
7698 ver[1] = (unsigned char) minor;
7702 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
7703 const unsigned char ver[2] )
7705 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7706 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7708 *major = 255 - ver[0] + 2;
7709 *minor = 255 - ver[1] + 1;
7711 if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
7712 ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7724 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
7726 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7727 if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
7728 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7732 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
7733 #if defined(MBEDTLS_MD5_C)
7734 case MBEDTLS_SSL_HASH_MD5:
7735 ssl->handshake->calc_verify = ssl_calc_verify_tls;
7738 #if defined(MBEDTLS_SHA1_C)
7739 case MBEDTLS_SSL_HASH_SHA1:
7740 ssl->handshake->calc_verify = ssl_calc_verify_tls;
7743 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
7744 #if defined(MBEDTLS_SHA512_C)
7745 case MBEDTLS_SSL_HASH_SHA384:
7746 ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
7749 #if defined(MBEDTLS_SHA256_C)
7750 case MBEDTLS_SSL_HASH_SHA256:
7751 ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
7755 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7759 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
7763 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7764 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7767 #endif /* MBEDTLS_SSL_TLS_C */