blob: ee7c882aa5149103275101260485541ab93359f2 [file] [log] [blame]
Edison Aic6672fd2018-02-28 15:01:47 +08001// SPDX-License-Identifier: Apache-2.0
Jens Wiklander817466c2018-05-22 13:49:31 +02002/*
3 * SSLv3/TLSv1 shared functions
4 *
5 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
Jens Wiklander817466c2018-05-22 13:49:31 +02006 *
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
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
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.
18 *
19 * This file is part of mbed TLS (https://tls.mbed.org)
20 */
21/*
22 * The SSL 3.0 specification was drafted by Netscape in 1996,
23 * and became an IETF standard in 1999.
24 *
25 * http://wp.netscape.com/eng/ssl3/
26 * http://www.ietf.org/rfc/rfc2246.txt
27 * http://www.ietf.org/rfc/rfc4346.txt
28 */
29
30#if !defined(MBEDTLS_CONFIG_FILE)
31#include "mbedtls/config.h"
32#else
33#include MBEDTLS_CONFIG_FILE
34#endif
35
36#if defined(MBEDTLS_SSL_TLS_C)
37
38#if defined(MBEDTLS_PLATFORM_C)
39#include "mbedtls/platform.h"
40#else
41#include <stdlib.h>
42#define mbedtls_calloc calloc
43#define mbedtls_free free
44#endif
45
46#include "mbedtls/debug.h"
47#include "mbedtls/ssl.h"
48#include "mbedtls/ssl_internal.h"
49
50#include <string.h>
51
52#if defined(MBEDTLS_X509_CRT_PARSE_C)
53#include "mbedtls/oid.h"
54#endif
55
56/* Implementation that should never be optimized out by the compiler */
57static void mbedtls_zeroize( void *v, size_t n ) {
58 volatile unsigned char *p = v; while( n-- ) *p++ = 0;
59}
60
61/* Length of the "epoch" field in the record header */
62static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
63{
64#if defined(MBEDTLS_SSL_PROTO_DTLS)
65 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
66 return( 2 );
67#else
68 ((void) ssl);
69#endif
70 return( 0 );
71}
72
73/*
74 * Start a timer.
75 * Passing millisecs = 0 cancels a running timer.
76 */
77static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
78{
79 if( ssl->f_set_timer == NULL )
80 return;
81
82 MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
83 ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
84}
85
86/*
87 * Return -1 is timer is expired, 0 if it isn't.
88 */
89static int ssl_check_timer( mbedtls_ssl_context *ssl )
90{
91 if( ssl->f_get_timer == NULL )
92 return( 0 );
93
94 if( ssl->f_get_timer( ssl->p_timer ) == 2 )
95 {
96 MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
97 return( -1 );
98 }
99
100 return( 0 );
101}
102
103#if defined(MBEDTLS_SSL_PROTO_DTLS)
104/*
105 * Double the retransmit timeout value, within the allowed range,
106 * returning -1 if the maximum value has already been reached.
107 */
108static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
109{
110 uint32_t new_timeout;
111
112 if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
113 return( -1 );
114
115 new_timeout = 2 * ssl->handshake->retransmit_timeout;
116
117 /* Avoid arithmetic overflow and range overflow */
118 if( new_timeout < ssl->handshake->retransmit_timeout ||
119 new_timeout > ssl->conf->hs_timeout_max )
120 {
121 new_timeout = ssl->conf->hs_timeout_max;
122 }
123
124 ssl->handshake->retransmit_timeout = new_timeout;
125 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
126 ssl->handshake->retransmit_timeout ) );
127
128 return( 0 );
129}
130
131static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
132{
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 ) );
136}
137#endif /* MBEDTLS_SSL_PROTO_DTLS */
138
139#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
140/*
141 * Convert max_fragment_length codes to length.
142 * RFC 6066 says:
143 * enum{
144 * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
145 * } MaxFragmentLength;
146 * and we add 0 -> extension unused
147 */
148static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] =
149{
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 */
155};
156#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
157
158#if defined(MBEDTLS_SSL_CLI_C)
159static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
160{
161 mbedtls_ssl_session_free( dst );
162 memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
163
164#if defined(MBEDTLS_X509_CRT_PARSE_C)
165 if( src->peer_cert != NULL )
166 {
167 int ret;
168
169 dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
170 if( dst->peer_cert == NULL )
171 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
172
173 mbedtls_x509_crt_init( dst->peer_cert );
174
175 if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
176 src->peer_cert->raw.len ) ) != 0 )
177 {
178 mbedtls_free( dst->peer_cert );
179 dst->peer_cert = NULL;
180 return( ret );
181 }
182 }
183#endif /* MBEDTLS_X509_CRT_PARSE_C */
184
185#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
186 if( src->ticket != NULL )
187 {
188 dst->ticket = mbedtls_calloc( 1, src->ticket_len );
189 if( dst->ticket == NULL )
190 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
191
192 memcpy( dst->ticket, src->ticket, src->ticket_len );
193 }
194#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
195
196 return( 0 );
197}
198#endif /* MBEDTLS_SSL_CLI_C */
199
200#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
201int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
202 const unsigned char *key_enc, const unsigned char *key_dec,
203 size_t keylen,
204 const unsigned char *iv_enc, const unsigned char *iv_dec,
205 size_t ivlen,
206 const unsigned char *mac_enc, const unsigned char *mac_dec,
207 size_t maclen ) = NULL;
208int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
209int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
210int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
211int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
212int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
213#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
214
215/*
216 * Key material generation
217 */
218#if defined(MBEDTLS_SSL_PROTO_SSL3)
219static int ssl3_prf( const unsigned char *secret, size_t slen,
220 const char *label,
221 const unsigned char *random, size_t rlen,
222 unsigned char *dstbuf, size_t dlen )
223{
224 size_t i;
225 mbedtls_md5_context md5;
226 mbedtls_sha1_context sha1;
227 unsigned char padding[16];
228 unsigned char sha1sum[20];
229 ((void)label);
230
231 mbedtls_md5_init( &md5 );
232 mbedtls_sha1_init( &sha1 );
233
234 /*
235 * SSLv3:
236 * block =
237 * MD5( secret + SHA1( 'A' + secret + random ) ) +
238 * MD5( secret + SHA1( 'BB' + secret + random ) ) +
239 * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
240 * ...
241 */
242 for( i = 0; i < dlen / 16; i++ )
243 {
244 memset( padding, (unsigned char) ('A' + i), 1 + i );
245
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 );
251
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 );
256 }
257
258 mbedtls_md5_free( &md5 );
259 mbedtls_sha1_free( &sha1 );
260
261 mbedtls_zeroize( padding, sizeof( padding ) );
262 mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
263
264 return( 0 );
265}
266#endif /* MBEDTLS_SSL_PROTO_SSL3 */
267
268#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
269static int tls1_prf( const unsigned char *secret, size_t slen,
270 const char *label,
271 const unsigned char *random, size_t rlen,
272 unsigned char *dstbuf, size_t dlen )
273{
274 size_t nb, hs;
275 size_t i, j, k;
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;
281 int ret;
282
283 mbedtls_md_init( &md_ctx );
284
285 if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
286 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
287
288 hs = ( slen + 1 ) / 2;
289 S1 = secret;
290 S2 = secret + slen - hs;
291
292 nb = strlen( label );
293 memcpy( tmp + 20, label, nb );
294 memcpy( tmp + 20 + nb, random, rlen );
295 nb += rlen;
296
297 /*
298 * First compute P_md5(secret,label+random)[0..dlen]
299 */
300 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
301 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
302
303 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
304 return( ret );
305
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 );
309
310 for( i = 0; i < dlen; i += 16 )
311 {
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 );
315
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 );
319
320 k = ( i + 16 > dlen ) ? dlen % 16 : 16;
321
322 for( j = 0; j < k; j++ )
323 dstbuf[i + j] = h_i[j];
324 }
325
326 mbedtls_md_free( &md_ctx );
327
328 /*
329 * XOR out with P_sha1(secret,label+random)[0..dlen]
330 */
331 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
332 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
333
334 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
335 return( ret );
336
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 );
340
341 for( i = 0; i < dlen; i += 20 )
342 {
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 );
346
347 mbedtls_md_hmac_reset ( &md_ctx );
348 mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
349 mbedtls_md_hmac_finish( &md_ctx, tmp );
350
351 k = ( i + 20 > dlen ) ? dlen % 20 : 20;
352
353 for( j = 0; j < k; j++ )
354 dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
355 }
356
357 mbedtls_md_free( &md_ctx );
358
359 mbedtls_zeroize( tmp, sizeof( tmp ) );
360 mbedtls_zeroize( h_i, sizeof( h_i ) );
361
362 return( 0 );
363}
364#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
365
366#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
367static int tls_prf_generic( mbedtls_md_type_t md_type,
368 const unsigned char *secret, size_t slen,
369 const char *label,
370 const unsigned char *random, size_t rlen,
371 unsigned char *dstbuf, size_t dlen )
372{
373 size_t nb;
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;
379 int ret;
380
381 mbedtls_md_init( &md_ctx );
382
383 if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
384 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
385
386 md_len = mbedtls_md_get_size( md_info );
387
388 if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
389 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
390
391 nb = strlen( label );
392 memcpy( tmp + md_len, label, nb );
393 memcpy( tmp + md_len + nb, random, rlen );
394 nb += rlen;
395
396 /*
397 * Compute P_<hash>(secret, label + random)[0..dlen]
398 */
399 if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
400 return( ret );
401
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 );
405
406 for( i = 0; i < dlen; i += md_len )
407 {
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 );
411
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 );
415
416 k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
417
418 for( j = 0; j < k; j++ )
419 dstbuf[i + j] = h_i[j];
420 }
421
422 mbedtls_md_free( &md_ctx );
423
424 mbedtls_zeroize( tmp, sizeof( tmp ) );
425 mbedtls_zeroize( h_i, sizeof( h_i ) );
426
427 return( 0 );
428}
429
430#if defined(MBEDTLS_SHA256_C)
431static int tls_prf_sha256( const unsigned char *secret, size_t slen,
432 const char *label,
433 const unsigned char *random, size_t rlen,
434 unsigned char *dstbuf, size_t dlen )
435{
436 return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
437 label, random, rlen, dstbuf, dlen ) );
438}
439#endif /* MBEDTLS_SHA256_C */
440
441#if defined(MBEDTLS_SHA512_C)
442static int tls_prf_sha384( const unsigned char *secret, size_t slen,
443 const char *label,
444 const unsigned char *random, size_t rlen,
445 unsigned char *dstbuf, size_t dlen )
446{
447 return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
448 label, random, rlen, dstbuf, dlen ) );
449}
450#endif /* MBEDTLS_SHA512_C */
451#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
452
453static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
454
455#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
456 defined(MBEDTLS_SSL_PROTO_TLS1_1)
457static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
458#endif
459
460#if defined(MBEDTLS_SSL_PROTO_SSL3)
461static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
462static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
463#endif
464
465#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
466static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
467static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
468#endif
469
470#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
471#if defined(MBEDTLS_SHA256_C)
472static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
473static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
474static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
475#endif
476
477#if defined(MBEDTLS_SHA512_C)
478static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
479static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
480static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
481#endif
482#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
483
484int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
485{
486 int ret = 0;
487 unsigned char tmp[64];
488 unsigned char keyblk[256];
489 unsigned char *key1;
490 unsigned char *key2;
491 unsigned char *mac_enc;
492 unsigned char *mac_dec;
493 size_t iv_copy_len;
494 const mbedtls_cipher_info_t *cipher_info;
495 const mbedtls_md_info_t *md_info;
496
497 mbedtls_ssl_session *session = ssl->session_negotiate;
498 mbedtls_ssl_transform *transform = ssl->transform_negotiate;
499 mbedtls_ssl_handshake_params *handshake = ssl->handshake;
500
501 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
502
503 cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
504 if( cipher_info == NULL )
505 {
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 );
509 }
510
511 md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
512 if( md_info == NULL )
513 {
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 );
517 }
518
519 /*
520 * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
521 */
522#if defined(MBEDTLS_SSL_PROTO_SSL3)
523 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
524 {
525 handshake->tls_prf = ssl3_prf;
526 handshake->calc_verify = ssl_calc_verify_ssl;
527 handshake->calc_finished = ssl_calc_finished_ssl;
528 }
529 else
530#endif
531#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
532 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
533 {
534 handshake->tls_prf = tls1_prf;
535 handshake->calc_verify = ssl_calc_verify_tls;
536 handshake->calc_finished = ssl_calc_finished_tls;
537 }
538 else
539#endif
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 )
544 {
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;
548 }
549 else
550#endif
551#if defined(MBEDTLS_SHA256_C)
552 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
553 {
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;
557 }
558 else
559#endif
560#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
561 {
562 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
563 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
564 }
565
566 /*
567 * SSLv3:
568 * master =
569 * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
570 * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
571 * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
572 *
573 * TLSv1+:
574 * master = PRF( premaster, "master secret", randbytes )[0..47]
575 */
576 if( handshake->resume == 0 )
577 {
578 MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
579 handshake->pmslen );
580
581#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
582 if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
583 {
584 unsigned char session_hash[48];
585 size_t hash_len;
586
587 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
588
589 ssl->handshake->calc_verify( ssl, session_hash );
590
591#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
592 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
593 {
594#if defined(MBEDTLS_SHA512_C)
595 if( ssl->transform_negotiate->ciphersuite_info->mac ==
596 MBEDTLS_MD_SHA384 )
597 {
598 hash_len = 48;
599 }
600 else
601#endif
602 hash_len = 32;
603 }
604 else
605#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
606 hash_len = 36;
607
608 MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
609
610 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
611 "extended master secret",
612 session_hash, hash_len,
613 session->master, 48 );
614 if( ret != 0 )
615 {
616 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
617 return( ret );
618 }
619
620 }
621 else
622#endif
623 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
624 "master secret",
625 handshake->randbytes, 64,
626 session->master, 48 );
627 if( ret != 0 )
628 {
629 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
630 return( ret );
631 }
632
633 mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) );
634 }
635 else
636 MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
637
638 /*
639 * Swap the client and server random values.
640 */
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 ) );
645
646 /*
647 * SSLv3:
648 * key block =
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 ) ) +
653 * ...
654 *
655 * TLSv1:
656 * key block = PRF( master, "key expansion", randbytes )
657 */
658 ret = handshake->tls_prf( session->master, 48, "key expansion",
659 handshake->randbytes, 64, keyblk, 256 );
660 if( ret != 0 )
661 {
662 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
663 return( ret );
664 }
665
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 );
671
672 mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) );
673
674 /*
675 * Determine the appropriate key, IV and MAC length.
676 */
677
678 transform->keylen = cipher_info->key_bitlen / 8;
679
680 if( cipher_info->mode == MBEDTLS_MODE_GCM ||
681 cipher_info->mode == MBEDTLS_MODE_CCM )
682 {
683 transform->maclen = 0;
684
685 transform->ivlen = 12;
686 transform->fixed_ivlen = 4;
687
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 );
692 }
693 else
694 {
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 )
698 {
699 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
700 return( ret );
701 }
702
703 /* Get MAC length */
704 transform->maclen = mbedtls_md_get_size( md_info );
705
706#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
707 /*
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.
711 */
712 if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
713 transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
714#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
715
716 /* IV length */
717 transform->ivlen = cipher_info->iv_size;
718
719 /* Minimum length */
720 if( cipher_info->mode == MBEDTLS_MODE_STREAM )
721 transform->minlen = transform->maclen;
722 else
723 {
724 /*
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
729 */
730#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
731 if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
732 {
733 transform->minlen = transform->maclen
734 + cipher_info->block_size;
735 }
736 else
737#endif
738 {
739 transform->minlen = transform->maclen
740 + cipher_info->block_size
741 - transform->maclen % cipher_info->block_size;
742 }
743
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 */
748 else
749#endif
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 )
753 {
754 transform->minlen += transform->ivlen;
755 }
756 else
757#endif
758 {
759 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
760 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
761 }
762 }
763 }
764
765 MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
766 transform->keylen, transform->minlen, transform->ivlen,
767 transform->maclen ) );
768
769 /*
770 * Finally setup the cipher contexts, IVs and MAC secrets.
771 */
772#if defined(MBEDTLS_SSL_CLI_C)
773 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
774 {
775 key1 = keyblk + transform->maclen * 2;
776 key2 = keyblk + transform->maclen * 2 + transform->keylen;
777
778 mac_enc = keyblk;
779 mac_dec = keyblk + transform->maclen;
780
781 /*
782 * This is not used in TLS v1.1.
783 */
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,
788 iv_copy_len );
789 }
790 else
791#endif /* MBEDTLS_SSL_CLI_C */
792#if defined(MBEDTLS_SSL_SRV_C)
793 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
794 {
795 key1 = keyblk + transform->maclen * 2 + transform->keylen;
796 key2 = keyblk + transform->maclen * 2;
797
798 mac_enc = keyblk + transform->maclen;
799 mac_dec = keyblk;
800
801 /*
802 * This is not used in TLS v1.1.
803 */
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,
808 iv_copy_len );
809 }
810 else
811#endif /* MBEDTLS_SSL_SRV_C */
812 {
813 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
814 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
815 }
816
817#if defined(MBEDTLS_SSL_PROTO_SSL3)
818 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
819 {
820 if( transform->maclen > sizeof transform->mac_enc )
821 {
822 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
823 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
824 }
825
826 memcpy( transform->mac_enc, mac_enc, transform->maclen );
827 memcpy( transform->mac_dec, mac_dec, transform->maclen );
828 }
829 else
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 )
834 {
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 );
837 }
838 else
839#endif
840 {
841 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
842 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
843 }
844
845#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
846 if( mbedtls_ssl_hw_record_init != NULL )
847 {
848 int ret = 0;
849
850 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
851
852 if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
853 transform->iv_enc, transform->iv_dec,
854 iv_copy_len,
855 mac_enc, mac_dec,
856 transform->maclen ) ) != 0 )
857 {
858 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
859 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
860 }
861 }
862#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
863
864#if defined(MBEDTLS_SSL_EXPORT_KEYS)
865 if( ssl->conf->f_export_keys != NULL )
866 {
867 ssl->conf->f_export_keys( ssl->conf->p_export_keys,
868 session->master, keyblk,
869 transform->maclen, transform->keylen,
870 iv_copy_len );
871 }
872#endif
873
874 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
875 cipher_info ) ) != 0 )
876 {
877 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
878 return( ret );
879 }
880
881 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
882 cipher_info ) ) != 0 )
883 {
884 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
885 return( ret );
886 }
887
888 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
889 cipher_info->key_bitlen,
890 MBEDTLS_ENCRYPT ) ) != 0 )
891 {
892 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
893 return( ret );
894 }
895
896 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
897 cipher_info->key_bitlen,
898 MBEDTLS_DECRYPT ) ) != 0 )
899 {
900 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
901 return( ret );
902 }
903
904#if defined(MBEDTLS_CIPHER_MODE_CBC)
905 if( cipher_info->mode == MBEDTLS_MODE_CBC )
906 {
907 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
908 MBEDTLS_PADDING_NONE ) ) != 0 )
909 {
910 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
911 return( ret );
912 }
913
914 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
915 MBEDTLS_PADDING_NONE ) ) != 0 )
916 {
917 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
918 return( ret );
919 }
920 }
921#endif /* MBEDTLS_CIPHER_MODE_CBC */
922
923 mbedtls_zeroize( keyblk, sizeof( keyblk ) );
924
925#if defined(MBEDTLS_ZLIB_SUPPORT)
926 // Initialize compression
927 //
928 if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
929 {
930 if( ssl->compress_buf == NULL )
931 {
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 )
935 {
936 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
937 MBEDTLS_SSL_BUFFER_LEN ) );
938 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
939 }
940 }
941
942 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
943
944 memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
945 memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
946
947 if( deflateInit( &transform->ctx_deflate,
948 Z_DEFAULT_COMPRESSION ) != Z_OK ||
949 inflateInit( &transform->ctx_inflate ) != Z_OK )
950 {
951 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
952 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
953 }
954 }
955#endif /* MBEDTLS_ZLIB_SUPPORT */
956
957 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
958
959 return( 0 );
960}
961
962#if defined(MBEDTLS_SSL_PROTO_SSL3)
963void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
964{
965 mbedtls_md5_context md5;
966 mbedtls_sha1_context sha1;
967 unsigned char pad_1[48];
968 unsigned char pad_2[48];
969
970 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
971
972 mbedtls_md5_init( &md5 );
973 mbedtls_sha1_init( &sha1 );
974
975 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
976 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
977
978 memset( pad_1, 0x36, 48 );
979 memset( pad_2, 0x5C, 48 );
980
981 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
982 mbedtls_md5_update( &md5, pad_1, 48 );
983 mbedtls_md5_finish( &md5, hash );
984
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 );
990
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 );
994
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 );
1000
1001 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1002 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1003
1004 mbedtls_md5_free( &md5 );
1005 mbedtls_sha1_free( &sha1 );
1006
1007 return;
1008}
1009#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1010
1011#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1012void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
1013{
1014 mbedtls_md5_context md5;
1015 mbedtls_sha1_context sha1;
1016
1017 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1018
1019 mbedtls_md5_init( &md5 );
1020 mbedtls_sha1_init( &sha1 );
1021
1022 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1023 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1024
1025 mbedtls_md5_finish( &md5, hash );
1026 mbedtls_sha1_finish( &sha1, hash + 16 );
1027
1028 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1029 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1030
1031 mbedtls_md5_free( &md5 );
1032 mbedtls_sha1_free( &sha1 );
1033
1034 return;
1035}
1036#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1037
1038#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1039#if defined(MBEDTLS_SHA256_C)
1040void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
1041{
1042 mbedtls_sha256_context sha256;
1043
1044 mbedtls_sha256_init( &sha256 );
1045
1046 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1047
1048 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1049 mbedtls_sha256_finish( &sha256, hash );
1050
1051 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
1052 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1053
1054 mbedtls_sha256_free( &sha256 );
1055
1056 return;
1057}
1058#endif /* MBEDTLS_SHA256_C */
1059
1060#if defined(MBEDTLS_SHA512_C)
1061void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
1062{
1063 mbedtls_sha512_context sha512;
1064
1065 mbedtls_sha512_init( &sha512 );
1066
1067 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1068
1069 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
1070 mbedtls_sha512_finish( &sha512, hash );
1071
1072 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
1073 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1074
1075 mbedtls_sha512_free( &sha512 );
1076
1077 return;
1078}
1079#endif /* MBEDTLS_SHA512_C */
1080#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1081
1082#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1083int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1084{
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;
1089
1090 /* If the psk callback was called, use its result */
1091 if( ssl->handshake->psk != NULL )
1092 {
1093 psk = ssl->handshake->psk;
1094 psk_len = ssl->handshake->psk_len;
1095 }
1096
1097 /*
1098 * PMS = struct {
1099 * opaque other_secret<0..2^16-1>;
1100 * opaque psk<0..2^16-1>;
1101 * };
1102 * with "other_secret" depending on the particular key exchange
1103 */
1104#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1105 if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1106 {
1107 if( end - p < 2 )
1108 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1109
1110 *(p++) = (unsigned char)( psk_len >> 8 );
1111 *(p++) = (unsigned char)( psk_len );
1112
1113 if( end < p || (size_t)( end - p ) < psk_len )
1114 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1115
1116 memset( p, 0, psk_len );
1117 p += psk_len;
1118 }
1119 else
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 )
1123 {
1124 /*
1125 * other_secret already set by the ClientKeyExchange message,
1126 * and is 48 bytes long
1127 */
1128 *p++ = 0;
1129 *p++ = 48;
1130 p += 48;
1131 }
1132 else
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 )
1136 {
1137 int ret;
1138 size_t len;
1139
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 )
1144 {
1145 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1146 return( ret );
1147 }
1148 *(p++) = (unsigned char)( len >> 8 );
1149 *(p++) = (unsigned char)( len );
1150 p += len;
1151
1152 MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
1153 }
1154 else
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 )
1158 {
1159 int ret;
1160 size_t zlen;
1161
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 )
1165 {
1166 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1167 return( ret );
1168 }
1169
1170 *(p++) = (unsigned char)( zlen >> 8 );
1171 *(p++) = (unsigned char)( zlen );
1172 p += zlen;
1173
1174 MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
1175 }
1176 else
1177#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1178 {
1179 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1180 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1181 }
1182
1183 /* opaque psk<0..2^16-1>; */
1184 if( end - p < 2 )
1185 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1186
1187 *(p++) = (unsigned char)( psk_len >> 8 );
1188 *(p++) = (unsigned char)( psk_len );
1189
1190 if( end < p || (size_t)( end - p ) < psk_len )
1191 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1192
1193 memcpy( p, psk, psk_len );
1194 p += psk_len;
1195
1196 ssl->handshake->pmslen = p - ssl->handshake->premaster;
1197
1198 return( 0 );
1199}
1200#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1201
1202#if defined(MBEDTLS_SSL_PROTO_SSL3)
1203/*
1204 * SSLv3.0 MAC functions
1205 */
1206static 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 )
1209{
1210 unsigned char header[11];
1211 unsigned char padding[48];
1212 int padlen;
1213 int md_size = mbedtls_md_get_size( md_ctx->md_info );
1214 int md_type = mbedtls_md_get_type( md_ctx->md_info );
1215
1216 /* Only MD5 and SHA-1 supported */
1217 if( md_type == MBEDTLS_MD_MD5 )
1218 padlen = 48;
1219 else
1220 padlen = 40;
1221
1222 memcpy( header, ctr, 8 );
1223 header[ 8] = (unsigned char) type;
1224 header[ 9] = (unsigned char)( len >> 8 );
1225 header[10] = (unsigned char)( len );
1226
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 );
1234
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 );
1241}
1242#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1243
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
1248#endif
1249
1250/*
1251 * Encryption/decryption functions
1252 */
1253static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
1254{
1255 mbedtls_cipher_mode_t mode;
1256 int auth_done = 0;
1257
1258 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
1259
1260 if( ssl->session_out == NULL || ssl->transform_out == NULL )
1261 {
1262 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1263 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1264 }
1265
1266 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
1267
1268 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
1269 ssl->out_msg, ssl->out_msglen );
1270
1271 /*
1272 * Add MAC before if needed
1273 */
1274#if defined(SSL_SOME_MODES_USE_MAC)
1275 if( mode == MBEDTLS_MODE_STREAM ||
1276 ( mode == MBEDTLS_MODE_CBC
1277#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1278 && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
1279#endif
1280 ) )
1281 {
1282#if defined(MBEDTLS_SSL_PROTO_SSL3)
1283 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1284 {
1285 ssl_mac( &ssl->transform_out->md_ctx_enc,
1286 ssl->transform_out->mac_enc,
1287 ssl->out_msg, ssl->out_msglen,
1288 ssl->out_ctr, ssl->out_msgtype );
1289 }
1290 else
1291#endif
1292#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1293 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1294 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
1295 {
1296 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
1297 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
1298 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
1299 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1300 ssl->out_msg, ssl->out_msglen );
1301 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1302 ssl->out_msg + ssl->out_msglen );
1303 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1304 }
1305 else
1306#endif
1307 {
1308 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1309 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1310 }
1311
1312 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
1313 ssl->out_msg + ssl->out_msglen,
1314 ssl->transform_out->maclen );
1315
1316 ssl->out_msglen += ssl->transform_out->maclen;
1317 auth_done++;
1318 }
1319#endif /* AEAD not the only option */
1320
1321 /*
1322 * Encrypt
1323 */
1324#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1325 if( mode == MBEDTLS_MODE_STREAM )
1326 {
1327 int ret;
1328 size_t olen = 0;
1329
1330 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1331 "including %d bytes of padding",
1332 ssl->out_msglen, 0 ) );
1333
1334 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1335 ssl->transform_out->iv_enc,
1336 ssl->transform_out->ivlen,
1337 ssl->out_msg, ssl->out_msglen,
1338 ssl->out_msg, &olen ) ) != 0 )
1339 {
1340 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1341 return( ret );
1342 }
1343
1344 if( ssl->out_msglen != olen )
1345 {
1346 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1347 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1348 }
1349 }
1350 else
1351#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1352#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1353 if( mode == MBEDTLS_MODE_GCM ||
1354 mode == MBEDTLS_MODE_CCM )
1355 {
1356 int ret;
1357 size_t enc_msglen, olen;
1358 unsigned char *enc_msg;
1359 unsigned char add_data[13];
1360 unsigned char taglen = ssl->transform_out->ciphersuite_info->flags &
1361 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1362
1363 memcpy( add_data, ssl->out_ctr, 8 );
1364 add_data[8] = ssl->out_msgtype;
1365 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1366 ssl->conf->transport, add_data + 9 );
1367 add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
1368 add_data[12] = ssl->out_msglen & 0xFF;
1369
1370 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1371 add_data, 13 );
1372
1373 /*
1374 * Generate IV
1375 */
1376 if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 )
1377 {
1378 /* Reminder if we ever add an AEAD mode with a different size */
1379 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1380 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1381 }
1382
1383 memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1384 ssl->out_ctr, 8 );
1385 memcpy( ssl->out_iv, ssl->out_ctr, 8 );
1386
1387 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv,
1388 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1389
1390 /*
1391 * Fix pointer positions and message length with added IV
1392 */
1393 enc_msg = ssl->out_msg;
1394 enc_msglen = ssl->out_msglen;
1395 ssl->out_msglen += ssl->transform_out->ivlen -
1396 ssl->transform_out->fixed_ivlen;
1397
1398 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1399 "including %d bytes of padding",
1400 ssl->out_msglen, 0 ) );
1401
1402 /*
1403 * Encrypt and authenticate
1404 */
1405 if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc,
1406 ssl->transform_out->iv_enc,
1407 ssl->transform_out->ivlen,
1408 add_data, 13,
1409 enc_msg, enc_msglen,
1410 enc_msg, &olen,
1411 enc_msg + enc_msglen, taglen ) ) != 0 )
1412 {
1413 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
1414 return( ret );
1415 }
1416
1417 if( olen != enc_msglen )
1418 {
1419 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1420 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1421 }
1422
1423 ssl->out_msglen += taglen;
1424 auth_done++;
1425
1426 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
1427 }
1428 else
1429#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1430#if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1431 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1432 if( mode == MBEDTLS_MODE_CBC )
1433 {
1434 int ret;
1435 unsigned char *enc_msg;
1436 size_t enc_msglen, padlen, olen = 0, i;
1437
1438 padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
1439 ssl->transform_out->ivlen;
1440 if( padlen == ssl->transform_out->ivlen )
1441 padlen = 0;
1442
1443 for( i = 0; i <= padlen; i++ )
1444 ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
1445
1446 ssl->out_msglen += padlen + 1;
1447
1448 enc_msglen = ssl->out_msglen;
1449 enc_msg = ssl->out_msg;
1450
1451#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1452 /*
1453 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
1454 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1455 */
1456 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1457 {
1458 /*
1459 * Generate IV
1460 */
1461 ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
1462 ssl->transform_out->ivlen );
1463 if( ret != 0 )
1464 return( ret );
1465
1466 memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
1467 ssl->transform_out->ivlen );
1468
1469 /*
1470 * Fix pointer positions and message length with added IV
1471 */
1472 enc_msg = ssl->out_msg;
1473 enc_msglen = ssl->out_msglen;
1474 ssl->out_msglen += ssl->transform_out->ivlen;
1475 }
1476#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1477
1478 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1479 "including %d bytes of IV and %d bytes of padding",
1480 ssl->out_msglen, ssl->transform_out->ivlen,
1481 padlen + 1 ) );
1482
1483 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1484 ssl->transform_out->iv_enc,
1485 ssl->transform_out->ivlen,
1486 enc_msg, enc_msglen,
1487 enc_msg, &olen ) ) != 0 )
1488 {
1489 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1490 return( ret );
1491 }
1492
1493 if( enc_msglen != olen )
1494 {
1495 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1496 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1497 }
1498
1499#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1500 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1501 {
1502 /*
1503 * Save IV in SSL3 and TLS1
1504 */
1505 memcpy( ssl->transform_out->iv_enc,
1506 ssl->transform_out->cipher_ctx_enc.iv,
1507 ssl->transform_out->ivlen );
1508 }
1509#endif
1510
1511#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1512 if( auth_done == 0 )
1513 {
1514 /*
1515 * MAC(MAC_write_key, seq_num +
1516 * TLSCipherText.type +
1517 * TLSCipherText.version +
1518 * length_of( (IV +) ENC(...) ) +
1519 * IV + // except for TLS 1.0
1520 * ENC(content + padding + padding_length));
1521 */
1522 unsigned char pseudo_hdr[13];
1523
1524 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1525
1526 memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
1527 memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
1528 pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
1529 pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
1530
1531 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1532
1533 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
1534 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1535 ssl->out_iv, ssl->out_msglen );
1536 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1537 ssl->out_iv + ssl->out_msglen );
1538 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1539
1540 ssl->out_msglen += ssl->transform_out->maclen;
1541 auth_done++;
1542 }
1543#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1544 }
1545 else
1546#endif /* MBEDTLS_CIPHER_MODE_CBC &&
1547 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1548 {
1549 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1550 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1551 }
1552
1553 /* Make extra sure authentication was performed, exactly once */
1554 if( auth_done != 1 )
1555 {
1556 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1557 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1558 }
1559
1560 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1561
1562 return( 0 );
1563}
1564
1565#define SSL_MAX_MAC_SIZE 48
1566
1567static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
1568{
1569 size_t i;
1570 mbedtls_cipher_mode_t mode;
1571 int auth_done = 0;
1572#if defined(SSL_SOME_MODES_USE_MAC)
1573 size_t padlen = 0, correct = 1;
1574#endif
1575
1576 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1577
1578 if( ssl->session_in == NULL || ssl->transform_in == NULL )
1579 {
1580 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1581 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1582 }
1583
1584 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
1585
1586 if( ssl->in_msglen < ssl->transform_in->minlen )
1587 {
1588 MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
1589 ssl->in_msglen, ssl->transform_in->minlen ) );
1590 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1591 }
1592
1593#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1594 if( mode == MBEDTLS_MODE_STREAM )
1595 {
1596 int ret;
1597 size_t olen = 0;
1598
1599 padlen = 0;
1600
1601 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1602 ssl->transform_in->iv_dec,
1603 ssl->transform_in->ivlen,
1604 ssl->in_msg, ssl->in_msglen,
1605 ssl->in_msg, &olen ) ) != 0 )
1606 {
1607 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1608 return( ret );
1609 }
1610
1611 if( ssl->in_msglen != olen )
1612 {
1613 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1614 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1615 }
1616 }
1617 else
1618#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1619#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1620 if( mode == MBEDTLS_MODE_GCM ||
1621 mode == MBEDTLS_MODE_CCM )
1622 {
1623 int ret;
1624 size_t dec_msglen, olen;
1625 unsigned char *dec_msg;
1626 unsigned char *dec_msg_result;
1627 unsigned char add_data[13];
1628 unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
1629 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1630 size_t explicit_iv_len = ssl->transform_in->ivlen -
1631 ssl->transform_in->fixed_ivlen;
1632
1633 if( ssl->in_msglen < explicit_iv_len + taglen )
1634 {
1635 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
1636 "+ taglen (%d)", ssl->in_msglen,
1637 explicit_iv_len, taglen ) );
1638 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1639 }
1640 dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
1641
1642 dec_msg = ssl->in_msg;
1643 dec_msg_result = ssl->in_msg;
1644 ssl->in_msglen = dec_msglen;
1645
1646 memcpy( add_data, ssl->in_ctr, 8 );
1647 add_data[8] = ssl->in_msgtype;
1648 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1649 ssl->conf->transport, add_data + 9 );
1650 add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
1651 add_data[12] = ssl->in_msglen & 0xFF;
1652
1653 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1654 add_data, 13 );
1655
1656 memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
1657 ssl->in_iv,
1658 ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
1659
1660 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
1661 ssl->transform_in->ivlen );
1662 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
1663
1664 /*
1665 * Decrypt and authenticate
1666 */
1667 if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
1668 ssl->transform_in->iv_dec,
1669 ssl->transform_in->ivlen,
1670 add_data, 13,
1671 dec_msg, dec_msglen,
1672 dec_msg_result, &olen,
1673 dec_msg + dec_msglen, taglen ) ) != 0 )
1674 {
1675 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
1676
1677 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
1678 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1679
1680 return( ret );
1681 }
1682 auth_done++;
1683
1684 if( olen != dec_msglen )
1685 {
1686 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1687 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1688 }
1689 }
1690 else
1691#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1692#if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1693 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1694 if( mode == MBEDTLS_MODE_CBC )
1695 {
1696 /*
1697 * Decrypt and check the padding
1698 */
1699 int ret;
1700 unsigned char *dec_msg;
1701 unsigned char *dec_msg_result;
1702 size_t dec_msglen;
1703 size_t minlen = 0;
1704 size_t olen = 0;
1705
1706 /*
1707 * Check immediate ciphertext sanity
1708 */
1709#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1710 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1711 minlen += ssl->transform_in->ivlen;
1712#endif
1713
1714 if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
1715 ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
1716 {
1717 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
1718 "+ 1 ) ( + expl IV )", ssl->in_msglen,
1719 ssl->transform_in->ivlen,
1720 ssl->transform_in->maclen ) );
1721 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1722 }
1723
1724 dec_msglen = ssl->in_msglen;
1725 dec_msg = ssl->in_msg;
1726 dec_msg_result = ssl->in_msg;
1727
1728 /*
1729 * Authenticate before decrypt if enabled
1730 */
1731#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1732 if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1733 {
1734 unsigned char computed_mac[SSL_MAX_MAC_SIZE];
1735 unsigned char pseudo_hdr[13];
1736
1737 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1738
1739 dec_msglen -= ssl->transform_in->maclen;
1740 ssl->in_msglen -= ssl->transform_in->maclen;
1741
1742 memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
1743 memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
1744 pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
1745 pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
1746
1747 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1748
1749 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
1750 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
1751 ssl->in_iv, ssl->in_msglen );
1752 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac );
1753 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1754
1755 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
1756 ssl->transform_in->maclen );
1757 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", computed_mac,
1758 ssl->transform_in->maclen );
1759
1760 if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac,
1761 ssl->transform_in->maclen ) != 0 )
1762 {
1763 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1764
1765 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1766 }
1767 auth_done++;
1768 }
1769#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1770
1771 /*
1772 * Check length sanity
1773 */
1774 if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
1775 {
1776 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
1777 ssl->in_msglen, ssl->transform_in->ivlen ) );
1778 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1779 }
1780
1781#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1782 /*
1783 * Initialize for prepended IV for block cipher in TLS v1.1 and up
1784 */
1785 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1786 {
1787 dec_msglen -= ssl->transform_in->ivlen;
1788 ssl->in_msglen -= ssl->transform_in->ivlen;
1789
1790 for( i = 0; i < ssl->transform_in->ivlen; i++ )
1791 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
1792 }
1793#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1794
1795 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1796 ssl->transform_in->iv_dec,
1797 ssl->transform_in->ivlen,
1798 dec_msg, dec_msglen,
1799 dec_msg_result, &olen ) ) != 0 )
1800 {
1801 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1802 return( ret );
1803 }
1804
1805 if( dec_msglen != olen )
1806 {
1807 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1808 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1809 }
1810
1811#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1812 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1813 {
1814 /*
1815 * Save IV in SSL3 and TLS1
1816 */
1817 memcpy( ssl->transform_in->iv_dec,
1818 ssl->transform_in->cipher_ctx_dec.iv,
1819 ssl->transform_in->ivlen );
1820 }
1821#endif
1822
1823 padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
1824
1825 if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
1826 auth_done == 0 )
1827 {
1828#if defined(MBEDTLS_SSL_DEBUG_ALL)
1829 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
1830 ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
1831#endif
1832 padlen = 0;
1833 correct = 0;
1834 }
1835
1836#if defined(MBEDTLS_SSL_PROTO_SSL3)
1837 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1838 {
1839 if( padlen > ssl->transform_in->ivlen )
1840 {
1841#if defined(MBEDTLS_SSL_DEBUG_ALL)
1842 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
1843 "should be no more than %d",
1844 padlen, ssl->transform_in->ivlen ) );
1845#endif
1846 correct = 0;
1847 }
1848 }
1849 else
1850#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1851#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1852 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1853 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1854 {
1855 /*
1856 * TLSv1+: always check the padding up to the first failure
1857 * and fake check up to 256 bytes of padding
1858 */
1859 size_t pad_count = 0, real_count = 1;
1860 size_t padding_idx = ssl->in_msglen - padlen - 1;
1861
1862 /*
1863 * Padding is guaranteed to be incorrect if:
1864 * 1. padlen >= ssl->in_msglen
1865 *
1866 * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN +
1867 * ssl->transform_in->maclen
1868 *
1869 * In both cases we reset padding_idx to a safe value (0) to
1870 * prevent out-of-buffer reads.
1871 */
1872 correct &= ( ssl->in_msglen >= padlen + 1 );
1873 correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN +
1874 ssl->transform_in->maclen );
1875
1876 padding_idx *= correct;
1877
1878 for( i = 1; i <= 256; i++ )
1879 {
1880 real_count &= ( i <= padlen );
1881 pad_count += real_count *
1882 ( ssl->in_msg[padding_idx + i] == padlen - 1 );
1883 }
1884
1885 correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
1886
1887#if defined(MBEDTLS_SSL_DEBUG_ALL)
1888 if( padlen > 0 && correct == 0 )
1889 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
1890#endif
1891 padlen &= correct * 0x1FF;
1892 }
1893 else
1894#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1895 MBEDTLS_SSL_PROTO_TLS1_2 */
1896 {
1897 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1898 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1899 }
1900
1901 ssl->in_msglen -= padlen;
1902 }
1903 else
1904#endif /* MBEDTLS_CIPHER_MODE_CBC &&
1905 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1906 {
1907 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1908 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1909 }
1910
1911 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
1912 ssl->in_msg, ssl->in_msglen );
1913
1914 /*
1915 * Authenticate if not done yet.
1916 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1917 */
1918#if defined(SSL_SOME_MODES_USE_MAC)
1919 if( auth_done == 0 )
1920 {
1921 unsigned char tmp[SSL_MAX_MAC_SIZE];
1922
1923 ssl->in_msglen -= ssl->transform_in->maclen;
1924
1925 ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
1926 ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
1927
1928 memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
1929
1930#if defined(MBEDTLS_SSL_PROTO_SSL3)
1931 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1932 {
1933 ssl_mac( &ssl->transform_in->md_ctx_dec,
1934 ssl->transform_in->mac_dec,
1935 ssl->in_msg, ssl->in_msglen,
1936 ssl->in_ctr, ssl->in_msgtype );
1937 }
1938 else
1939#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1940#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1941 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1942 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1943 {
1944 /*
1945 * Process MAC and always update for padlen afterwards to make
1946 * total time independent of padlen
1947 *
1948 * extra_run compensates MAC check for padlen
1949 *
1950 * Known timing attacks:
1951 * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
1952 *
1953 * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
1954 * correctly. (We round down instead of up, so -56 is the correct
1955 * value for our calculations instead of -55)
1956 */
1957 size_t j, extra_run = 0;
1958 extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
1959 ( 13 + ssl->in_msglen + 8 ) / 64;
1960
1961 extra_run &= correct * 0xFF;
1962
1963 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
1964 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
1965 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
1966 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
1967 ssl->in_msglen );
1968 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec,
1969 ssl->in_msg + ssl->in_msglen );
1970 /* Call mbedtls_md_process at least once due to cache attacks */
1971 for( j = 0; j < extra_run + 1; j++ )
1972 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
1973
1974 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1975 }
1976 else
1977#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1978 MBEDTLS_SSL_PROTO_TLS1_2 */
1979 {
1980 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1981 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1982 }
1983
1984 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen );
1985 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
1986 ssl->transform_in->maclen );
1987
1988 if( mbedtls_ssl_safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen,
1989 ssl->transform_in->maclen ) != 0 )
1990 {
1991#if defined(MBEDTLS_SSL_DEBUG_ALL)
1992 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1993#endif
1994 correct = 0;
1995 }
1996 auth_done++;
1997
1998 /*
1999 * Finally check the correct flag
2000 */
2001 if( correct == 0 )
2002 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2003 }
2004#endif /* SSL_SOME_MODES_USE_MAC */
2005
2006 /* Make extra sure authentication was performed, exactly once */
2007 if( auth_done != 1 )
2008 {
2009 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2010 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2011 }
2012
2013 if( ssl->in_msglen == 0 )
2014 {
2015 ssl->nb_zero++;
2016
2017 /*
2018 * Three or more empty messages may be a DoS attack
2019 * (excessive CPU consumption).
2020 */
2021 if( ssl->nb_zero > 3 )
2022 {
2023 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
2024 "messages, possible DoS attack" ) );
2025 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2026 }
2027 }
2028 else
2029 ssl->nb_zero = 0;
2030
2031#if defined(MBEDTLS_SSL_PROTO_DTLS)
2032 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2033 {
2034 ; /* in_ctr read from peer, not maintained internally */
2035 }
2036 else
2037#endif
2038 {
2039 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2040 if( ++ssl->in_ctr[i - 1] != 0 )
2041 break;
2042
2043 /* The loop goes to its end iff the counter is wrapping */
2044 if( i == ssl_ep_len( ssl ) )
2045 {
2046 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
2047 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2048 }
2049 }
2050
2051 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
2052
2053 return( 0 );
2054}
2055
2056#undef MAC_NONE
2057#undef MAC_PLAINTEXT
2058#undef MAC_CIPHERTEXT
2059
2060#if defined(MBEDTLS_ZLIB_SUPPORT)
2061/*
2062 * Compression/decompression functions
2063 */
2064static int ssl_compress_buf( mbedtls_ssl_context *ssl )
2065{
2066 int ret;
2067 unsigned char *msg_post = ssl->out_msg;
2068 size_t len_pre = ssl->out_msglen;
2069 unsigned char *msg_pre = ssl->compress_buf;
2070
2071 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
2072
2073 if( len_pre == 0 )
2074 return( 0 );
2075
2076 memcpy( msg_pre, ssl->out_msg, len_pre );
2077
2078 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
2079 ssl->out_msglen ) );
2080
2081 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
2082 ssl->out_msg, ssl->out_msglen );
2083
2084 ssl->transform_out->ctx_deflate.next_in = msg_pre;
2085 ssl->transform_out->ctx_deflate.avail_in = len_pre;
2086 ssl->transform_out->ctx_deflate.next_out = msg_post;
2087 ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN;
2088
2089 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
2090 if( ret != Z_OK )
2091 {
2092 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
2093 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2094 }
2095
2096 ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN -
2097 ssl->transform_out->ctx_deflate.avail_out;
2098
2099 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
2100 ssl->out_msglen ) );
2101
2102 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
2103 ssl->out_msg, ssl->out_msglen );
2104
2105 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
2106
2107 return( 0 );
2108}
2109
2110static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
2111{
2112 int ret;
2113 unsigned char *msg_post = ssl->in_msg;
2114 size_t len_pre = ssl->in_msglen;
2115 unsigned char *msg_pre = ssl->compress_buf;
2116
2117 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
2118
2119 if( len_pre == 0 )
2120 return( 0 );
2121
2122 memcpy( msg_pre, ssl->in_msg, len_pre );
2123
2124 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
2125 ssl->in_msglen ) );
2126
2127 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
2128 ssl->in_msg, ssl->in_msglen );
2129
2130 ssl->transform_in->ctx_inflate.next_in = msg_pre;
2131 ssl->transform_in->ctx_inflate.avail_in = len_pre;
2132 ssl->transform_in->ctx_inflate.next_out = msg_post;
2133 ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN;
2134
2135 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
2136 if( ret != Z_OK )
2137 {
2138 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
2139 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2140 }
2141
2142 ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN -
2143 ssl->transform_in->ctx_inflate.avail_out;
2144
2145 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
2146 ssl->in_msglen ) );
2147
2148 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
2149 ssl->in_msg, ssl->in_msglen );
2150
2151 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
2152
2153 return( 0 );
2154}
2155#endif /* MBEDTLS_ZLIB_SUPPORT */
2156
2157#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2158static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
2159
2160#if defined(MBEDTLS_SSL_PROTO_DTLS)
2161static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
2162{
2163 /* If renegotiation is not enforced, retransmit until we would reach max
2164 * timeout if we were using the usual handshake doubling scheme */
2165 if( ssl->conf->renego_max_records < 0 )
2166 {
2167 uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2168 unsigned char doublings = 1;
2169
2170 while( ratio != 0 )
2171 {
2172 ++doublings;
2173 ratio >>= 1;
2174 }
2175
2176 if( ++ssl->renego_records_seen > doublings )
2177 {
2178 MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
2179 return( 0 );
2180 }
2181 }
2182
2183 return( ssl_write_hello_request( ssl ) );
2184}
2185#endif
2186#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2187
2188/*
2189 * Fill the input message buffer by appending data to it.
2190 * The amount of data already fetched is in ssl->in_left.
2191 *
2192 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2193 * available (from this read and/or a previous one). Otherwise, an error code
2194 * is returned (possibly EOF or WANT_READ).
2195 *
2196 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2197 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2198 * since we always read a whole datagram at once.
2199 *
2200 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2201 * they're done reading a record.
2202 */
2203int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
2204{
2205 int ret;
2206 size_t len;
2207
2208 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2209
2210 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2211 {
2212 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2213 "or mbedtls_ssl_set_bio()" ) );
2214 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2215 }
2216
2217 if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2218 {
2219 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2220 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2221 }
2222
2223#if defined(MBEDTLS_SSL_PROTO_DTLS)
2224 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2225 {
2226 uint32_t timeout;
2227
2228 /* Just to be sure */
2229 if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
2230 {
2231 MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
2232 "mbedtls_ssl_set_timer_cb() for DTLS" ) );
2233 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2234 }
2235
2236 /*
2237 * The point is, we need to always read a full datagram at once, so we
2238 * sometimes read more then requested, and handle the additional data.
2239 * It could be the rest of the current record (while fetching the
2240 * header) and/or some other records in the same datagram.
2241 */
2242
2243 /*
2244 * Move to the next record in the already read datagram if applicable
2245 */
2246 if( ssl->next_record_offset != 0 )
2247 {
2248 if( ssl->in_left < ssl->next_record_offset )
2249 {
2250 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2251 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2252 }
2253
2254 ssl->in_left -= ssl->next_record_offset;
2255
2256 if( ssl->in_left != 0 )
2257 {
2258 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2259 ssl->next_record_offset ) );
2260 memmove( ssl->in_hdr,
2261 ssl->in_hdr + ssl->next_record_offset,
2262 ssl->in_left );
2263 }
2264
2265 ssl->next_record_offset = 0;
2266 }
2267
2268 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2269 ssl->in_left, nb_want ) );
2270
2271 /*
2272 * Done if we already have enough data.
2273 */
2274 if( nb_want <= ssl->in_left)
2275 {
2276 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2277 return( 0 );
2278 }
2279
2280 /*
2281 * A record can't be split accross datagrams. If we need to read but
2282 * are not at the beginning of a new record, the caller did something
2283 * wrong.
2284 */
2285 if( ssl->in_left != 0 )
2286 {
2287 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2288 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2289 }
2290
2291 /*
2292 * Don't even try to read if time's out already.
2293 * This avoids by-passing the timer when repeatedly receiving messages
2294 * that will end up being dropped.
2295 */
2296 if( ssl_check_timer( ssl ) != 0 )
2297 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2298 else
2299 {
2300 len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
2301
2302 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2303 timeout = ssl->handshake->retransmit_timeout;
2304 else
2305 timeout = ssl->conf->read_timeout;
2306
2307 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2308
2309 if( ssl->f_recv_timeout != NULL )
2310 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2311 timeout );
2312 else
2313 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2314
2315 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2316
2317 if( ret == 0 )
2318 return( MBEDTLS_ERR_SSL_CONN_EOF );
2319 }
2320
2321 if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
2322 {
2323 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2324 ssl_set_timer( ssl, 0 );
2325
2326 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2327 {
2328 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2329 {
2330 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2331 return( MBEDTLS_ERR_SSL_TIMEOUT );
2332 }
2333
2334 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2335 {
2336 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2337 return( ret );
2338 }
2339
2340 return( MBEDTLS_ERR_SSL_WANT_READ );
2341 }
2342#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2343 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2344 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
2345 {
2346 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
2347 {
2348 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
2349 return( ret );
2350 }
2351
2352 return( MBEDTLS_ERR_SSL_WANT_READ );
2353 }
2354#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2355 }
2356
2357 if( ret < 0 )
2358 return( ret );
2359
2360 ssl->in_left = ret;
2361 }
2362 else
2363#endif
2364 {
2365 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2366 ssl->in_left, nb_want ) );
2367
2368 while( ssl->in_left < nb_want )
2369 {
2370 len = nb_want - ssl->in_left;
2371
2372 if( ssl_check_timer( ssl ) != 0 )
2373 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2374 else
2375 {
2376 if( ssl->f_recv_timeout != NULL )
2377 {
2378 ret = ssl->f_recv_timeout( ssl->p_bio,
2379 ssl->in_hdr + ssl->in_left, len,
2380 ssl->conf->read_timeout );
2381 }
2382 else
2383 {
2384 ret = ssl->f_recv( ssl->p_bio,
2385 ssl->in_hdr + ssl->in_left, len );
2386 }
2387 }
2388
2389 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2390 ssl->in_left, nb_want ) );
2391 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2392
2393 if( ret == 0 )
2394 return( MBEDTLS_ERR_SSL_CONN_EOF );
2395
2396 if( ret < 0 )
2397 return( ret );
2398
2399 ssl->in_left += ret;
2400 }
2401 }
2402
2403 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2404
2405 return( 0 );
2406}
2407
2408/*
2409 * Flush any data not yet written
2410 */
2411int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
2412{
2413 int ret;
2414 unsigned char *buf, i;
2415
2416 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2417
2418 if( ssl->f_send == NULL )
2419 {
2420 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2421 "or mbedtls_ssl_set_bio()" ) );
2422 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2423 }
2424
2425 /* Avoid incrementing counter if data is flushed */
2426 if( ssl->out_left == 0 )
2427 {
2428 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2429 return( 0 );
2430 }
2431
2432 while( ssl->out_left > 0 )
2433 {
2434 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2435 mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2436
2437 buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) +
2438 ssl->out_msglen - ssl->out_left;
2439 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2440
2441 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2442
2443 if( ret <= 0 )
2444 return( ret );
2445
2446 ssl->out_left -= ret;
2447 }
2448
2449 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2450 if( ++ssl->out_ctr[i - 1] != 0 )
2451 break;
2452
2453 /* The loop goes to its end iff the counter is wrapping */
2454 if( i == ssl_ep_len( ssl ) )
2455 {
2456 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
2457 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2458 }
2459
2460 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2461
2462 return( 0 );
2463}
2464
2465/*
2466 * Functions to handle the DTLS retransmission state machine
2467 */
2468#if defined(MBEDTLS_SSL_PROTO_DTLS)
2469/*
2470 * Append current handshake message to current outgoing flight
2471 */
2472static int ssl_flight_append( mbedtls_ssl_context *ssl )
2473{
2474 mbedtls_ssl_flight_item *msg;
2475
2476 /* Allocate space for current message */
2477 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2478 {
2479 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2480 sizeof( mbedtls_ssl_flight_item ) ) );
2481 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2482 }
2483
2484 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2485 {
2486 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2487 mbedtls_free( msg );
2488 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2489 }
2490
2491 /* Copy current handshake message with headers */
2492 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2493 msg->len = ssl->out_msglen;
2494 msg->type = ssl->out_msgtype;
2495 msg->next = NULL;
2496
2497 /* Append to the current flight */
2498 if( ssl->handshake->flight == NULL )
2499 ssl->handshake->flight = msg;
2500 else
2501 {
2502 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2503 while( cur->next != NULL )
2504 cur = cur->next;
2505 cur->next = msg;
2506 }
2507
2508 return( 0 );
2509}
2510
2511/*
2512 * Free the current flight of handshake messages
2513 */
2514static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
2515{
2516 mbedtls_ssl_flight_item *cur = flight;
2517 mbedtls_ssl_flight_item *next;
2518
2519 while( cur != NULL )
2520 {
2521 next = cur->next;
2522
2523 mbedtls_free( cur->p );
2524 mbedtls_free( cur );
2525
2526 cur = next;
2527 }
2528}
2529
2530#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2531static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
2532#endif
2533
2534/*
2535 * Swap transform_out and out_ctr with the alternative ones
2536 */
2537static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
2538{
2539 mbedtls_ssl_transform *tmp_transform;
2540 unsigned char tmp_out_ctr[8];
2541
2542 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2543 {
2544 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2545 return;
2546 }
2547
2548 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2549
2550 /* Swap transforms */
2551 tmp_transform = ssl->transform_out;
2552 ssl->transform_out = ssl->handshake->alt_transform_out;
2553 ssl->handshake->alt_transform_out = tmp_transform;
2554
2555 /* Swap epoch + sequence_number */
2556 memcpy( tmp_out_ctr, ssl->out_ctr, 8 );
2557 memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 );
2558 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
2559
2560 /* Adjust to the newly activated transform */
2561 if( ssl->transform_out != NULL &&
2562 ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
2563 {
2564 ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen -
2565 ssl->transform_out->fixed_ivlen;
2566 }
2567 else
2568 ssl->out_msg = ssl->out_iv;
2569
2570#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2571 if( mbedtls_ssl_hw_record_activate != NULL )
2572 {
2573 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
2574 {
2575 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
2576 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2577 }
2578 }
2579#endif
2580}
2581
2582/*
2583 * Retransmit the current flight of messages.
2584 *
2585 * Need to remember the current message in case flush_output returns
2586 * WANT_WRITE, causing us to exit this function and come back later.
2587 * This function must be called until state is no longer SENDING.
2588 */
2589int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
2590{
2591 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
2592
2593 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
2594 {
2595 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) );
2596
2597 ssl->handshake->cur_msg = ssl->handshake->flight;
2598 ssl_swap_epochs( ssl );
2599
2600 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2601 }
2602
2603 while( ssl->handshake->cur_msg != NULL )
2604 {
2605 int ret;
2606 mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg;
2607
2608 /* Swap epochs before sending Finished: we can't do it after
2609 * sending ChangeCipherSpec, in case write returns WANT_READ.
2610 * Must be done before copying, may change out_msg pointer */
2611 if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2612 cur->p[0] == MBEDTLS_SSL_HS_FINISHED )
2613 {
2614 ssl_swap_epochs( ssl );
2615 }
2616
2617 memcpy( ssl->out_msg, cur->p, cur->len );
2618 ssl->out_msglen = cur->len;
2619 ssl->out_msgtype = cur->type;
2620
2621 ssl->handshake->cur_msg = cur->next;
2622
2623 MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 );
2624
2625 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
2626 {
2627 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
2628 return( ret );
2629 }
2630 }
2631
2632 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
2633 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2634 else
2635 {
2636 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2637 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2638 }
2639
2640 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
2641
2642 return( 0 );
2643}
2644
2645/*
2646 * To be called when the last message of an incoming flight is received.
2647 */
2648void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
2649{
2650 /* We won't need to resend that one any more */
2651 ssl_flight_free( ssl->handshake->flight );
2652 ssl->handshake->flight = NULL;
2653 ssl->handshake->cur_msg = NULL;
2654
2655 /* The next incoming flight will start with this msg_seq */
2656 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2657
2658 /* Cancel timer */
2659 ssl_set_timer( ssl, 0 );
2660
2661 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2662 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2663 {
2664 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2665 }
2666 else
2667 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2668}
2669
2670/*
2671 * To be called when the last message of an outgoing flight is send.
2672 */
2673void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
2674{
2675 ssl_reset_retransmit_timeout( ssl );
2676 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2677
2678 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2679 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2680 {
2681 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2682 }
2683 else
2684 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2685}
2686#endif /* MBEDTLS_SSL_PROTO_DTLS */
2687
2688/*
2689 * Record layer functions
2690 */
2691
2692/*
2693 * Write current record.
2694 * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg.
2695 */
2696int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl )
2697{
2698 int ret, done = 0, out_msg_type;
2699 size_t len = ssl->out_msglen;
2700
2701 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
2702
2703#if defined(MBEDTLS_SSL_PROTO_DTLS)
2704 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2705 ssl->handshake != NULL &&
2706 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
2707 {
2708 ; /* Skip special handshake treatment when resending */
2709 }
2710 else
2711#endif
2712 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
2713 {
2714 out_msg_type = ssl->out_msg[0];
2715
2716 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST &&
2717 ssl->handshake == NULL )
2718 {
2719 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2720 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2721 }
2722
2723 ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
2724 ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
2725 ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
2726
2727 /*
2728 * DTLS has additional fields in the Handshake layer,
2729 * between the length field and the actual payload:
2730 * uint16 message_seq;
2731 * uint24 fragment_offset;
2732 * uint24 fragment_length;
2733 */
2734#if defined(MBEDTLS_SSL_PROTO_DTLS)
2735 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2736 {
2737 /* Make room for the additional DTLS fields */
2738 memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 );
2739 ssl->out_msglen += 8;
2740 len += 8;
2741
2742 /* Write message_seq and update it, except for HelloRequest */
2743 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2744 {
2745 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
2746 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
2747 ++( ssl->handshake->out_msg_seq );
2748 }
2749 else
2750 {
2751 ssl->out_msg[4] = 0;
2752 ssl->out_msg[5] = 0;
2753 }
2754
2755 /* We don't fragment, so frag_offset = 0 and frag_len = len */
2756 memset( ssl->out_msg + 6, 0x00, 3 );
2757 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
2758 }
2759#endif /* MBEDTLS_SSL_PROTO_DTLS */
2760
2761 if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2762 ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
2763 }
2764
2765 /* Save handshake and CCS messages for resending */
2766#if defined(MBEDTLS_SSL_PROTO_DTLS)
2767 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2768 ssl->handshake != NULL &&
2769 ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING &&
2770 ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ||
2771 ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) )
2772 {
2773 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
2774 {
2775 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
2776 return( ret );
2777 }
2778 }
2779#endif
2780
2781#if defined(MBEDTLS_ZLIB_SUPPORT)
2782 if( ssl->transform_out != NULL &&
2783 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
2784 {
2785 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
2786 {
2787 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
2788 return( ret );
2789 }
2790
2791 len = ssl->out_msglen;
2792 }
2793#endif /*MBEDTLS_ZLIB_SUPPORT */
2794
2795#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2796 if( mbedtls_ssl_hw_record_write != NULL )
2797 {
2798 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
2799
2800 ret = mbedtls_ssl_hw_record_write( ssl );
2801 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
2802 {
2803 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
2804 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2805 }
2806
2807 if( ret == 0 )
2808 done = 1;
2809 }
2810#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2811 if( !done )
2812 {
2813 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
2814 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2815 ssl->conf->transport, ssl->out_hdr + 1 );
2816
2817 ssl->out_len[0] = (unsigned char)( len >> 8 );
2818 ssl->out_len[1] = (unsigned char)( len );
2819
2820 if( ssl->transform_out != NULL )
2821 {
2822 if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
2823 {
2824 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
2825 return( ret );
2826 }
2827
2828 len = ssl->out_msglen;
2829 ssl->out_len[0] = (unsigned char)( len >> 8 );
2830 ssl->out_len[1] = (unsigned char)( len );
2831 }
2832
2833 ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen;
2834
2835 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
2836 "version = [%d:%d], msglen = %d",
2837 ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
2838 ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) );
2839
2840 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
2841 ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen );
2842 }
2843
2844 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2845 {
2846 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
2847 return( ret );
2848 }
2849
2850 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
2851
2852 return( 0 );
2853}
2854
2855#if defined(MBEDTLS_SSL_PROTO_DTLS)
2856/*
2857 * Mark bits in bitmask (used for DTLS HS reassembly)
2858 */
2859static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
2860{
2861 unsigned int start_bits, end_bits;
2862
2863 start_bits = 8 - ( offset % 8 );
2864 if( start_bits != 8 )
2865 {
2866 size_t first_byte_idx = offset / 8;
2867
2868 /* Special case */
2869 if( len <= start_bits )
2870 {
2871 for( ; len != 0; len-- )
2872 mask[first_byte_idx] |= 1 << ( start_bits - len );
2873
2874 /* Avoid potential issues with offset or len becoming invalid */
2875 return;
2876 }
2877
2878 offset += start_bits; /* Now offset % 8 == 0 */
2879 len -= start_bits;
2880
2881 for( ; start_bits != 0; start_bits-- )
2882 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
2883 }
2884
2885 end_bits = len % 8;
2886 if( end_bits != 0 )
2887 {
2888 size_t last_byte_idx = ( offset + len ) / 8;
2889
2890 len -= end_bits; /* Now len % 8 == 0 */
2891
2892 for( ; end_bits != 0; end_bits-- )
2893 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
2894 }
2895
2896 memset( mask + offset / 8, 0xFF, len / 8 );
2897}
2898
2899/*
2900 * Check that bitmask is full
2901 */
2902static int ssl_bitmask_check( unsigned char *mask, size_t len )
2903{
2904 size_t i;
2905
2906 for( i = 0; i < len / 8; i++ )
2907 if( mask[i] != 0xFF )
2908 return( -1 );
2909
2910 for( i = 0; i < len % 8; i++ )
2911 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
2912 return( -1 );
2913
2914 return( 0 );
2915}
2916
2917/*
2918 * Reassemble fragmented DTLS handshake messages.
2919 *
2920 * Use a temporary buffer for reassembly, divided in two parts:
2921 * - the first holds the reassembled message (including handshake header),
2922 * - the second holds a bitmask indicating which parts of the message
2923 * (excluding headers) have been received so far.
2924 */
2925static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )
2926{
2927 unsigned char *msg, *bitmask;
2928 size_t frag_len, frag_off;
2929 size_t msg_len = ssl->in_hslen - 12; /* Without headers */
2930
2931 if( ssl->handshake == NULL )
2932 {
2933 MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) );
2934 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2935 }
2936
2937 /*
2938 * For first fragment, check size and allocate buffer
2939 */
2940 if( ssl->handshake->hs_msg == NULL )
2941 {
2942 size_t alloc_len;
2943
2944 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
2945 msg_len ) );
2946
2947 if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN )
2948 {
2949 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) );
2950 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2951 }
2952
2953 /* The bitmask needs one bit per byte of message excluding header */
2954 alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 );
2955
2956 ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len );
2957 if( ssl->handshake->hs_msg == NULL )
2958 {
2959 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) );
2960 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2961 }
2962
2963 /* Prepare final header: copy msg_type, length and message_seq,
2964 * then add standardised fragment_offset and fragment_length */
2965 memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 );
2966 memset( ssl->handshake->hs_msg + 6, 0, 3 );
2967 memcpy( ssl->handshake->hs_msg + 9,
2968 ssl->handshake->hs_msg + 1, 3 );
2969 }
2970 else
2971 {
2972 /* Make sure msg_type and length are consistent */
2973 if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 )
2974 {
2975 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) );
2976 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2977 }
2978 }
2979
2980 msg = ssl->handshake->hs_msg + 12;
2981 bitmask = msg + msg_len;
2982
2983 /*
2984 * Check and copy current fragment
2985 */
2986 frag_off = ( ssl->in_msg[6] << 16 ) |
2987 ( ssl->in_msg[7] << 8 ) |
2988 ssl->in_msg[8];
2989 frag_len = ( ssl->in_msg[9] << 16 ) |
2990 ( ssl->in_msg[10] << 8 ) |
2991 ssl->in_msg[11];
2992
2993 if( frag_off + frag_len > msg_len )
2994 {
2995 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d",
2996 frag_off, frag_len, msg_len ) );
2997 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2998 }
2999
3000 if( frag_len + 12 > ssl->in_msglen )
3001 {
3002 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d",
3003 frag_len, ssl->in_msglen ) );
3004 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3005 }
3006
3007 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
3008 frag_off, frag_len ) );
3009
3010 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
3011 ssl_bitmask_set( bitmask, frag_off, frag_len );
3012
3013 /*
3014 * Do we have the complete message by now?
3015 * If yes, finalize it, else ask to read the next record.
3016 */
3017 if( ssl_bitmask_check( bitmask, msg_len ) != 0 )
3018 {
3019 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) );
3020 return( MBEDTLS_ERR_SSL_WANT_READ );
3021 }
3022
3023 MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) );
3024
3025 if( frag_len + 12 < ssl->in_msglen )
3026 {
3027 /*
3028 * We'got more handshake messages in the same record.
3029 * This case is not handled now because no know implementation does
3030 * that and it's hard to test, so we prefer to fail cleanly for now.
3031 */
3032 MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) );
3033 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3034 }
3035
3036 if( ssl->in_left > ssl->next_record_offset )
3037 {
3038 /*
3039 * We've got more data in the buffer after the current record,
3040 * that we don't want to overwrite. Move it before writing the
3041 * reassembled message, and adjust in_left and next_record_offset.
3042 */
3043 unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset;
3044 unsigned char *new_remain = ssl->in_msg + ssl->in_hslen;
3045 size_t remain_len = ssl->in_left - ssl->next_record_offset;
3046
3047 /* First compute and check new lengths */
3048 ssl->next_record_offset = new_remain - ssl->in_hdr;
3049 ssl->in_left = ssl->next_record_offset + remain_len;
3050
3051 if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN -
3052 (size_t)( ssl->in_hdr - ssl->in_buf ) )
3053 {
3054 MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) );
3055 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3056 }
3057
3058 memmove( new_remain, cur_remain, remain_len );
3059 }
3060
3061 memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );
3062
3063 mbedtls_free( ssl->handshake->hs_msg );
3064 ssl->handshake->hs_msg = NULL;
3065
3066 MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message",
3067 ssl->in_msg, ssl->in_hslen );
3068
3069 return( 0 );
3070}
3071#endif /* MBEDTLS_SSL_PROTO_DTLS */
3072
3073int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
3074{
3075 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
3076 {
3077 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
3078 ssl->in_msglen ) );
3079 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3080 }
3081
3082 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + (
3083 ( ssl->in_msg[1] << 16 ) |
3084 ( ssl->in_msg[2] << 8 ) |
3085 ssl->in_msg[3] );
3086
3087 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
3088 " %d, type = %d, hslen = %d",
3089 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
3090
3091#if defined(MBEDTLS_SSL_PROTO_DTLS)
3092 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3093 {
3094 int ret;
3095 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
3096
3097 /* ssl->handshake is NULL when receiving ClientHello for renego */
3098 if( ssl->handshake != NULL &&
3099 recv_msg_seq != ssl->handshake->in_msg_seq )
3100 {
3101 /* Retransmit only on last message from previous flight, to avoid
3102 * too many retransmissions.
3103 * Besides, No sane server ever retransmits HelloVerifyRequest */
3104 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3105 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
3106 {
3107 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
3108 "message_seq = %d, start_of_flight = %d",
3109 recv_msg_seq,
3110 ssl->handshake->in_flight_start_seq ) );
3111
3112 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3113 {
3114 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
3115 return( ret );
3116 }
3117 }
3118 else
3119 {
3120 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
3121 "message_seq = %d, expected = %d",
3122 recv_msg_seq,
3123 ssl->handshake->in_msg_seq ) );
3124 }
3125
3126 return( MBEDTLS_ERR_SSL_WANT_READ );
3127 }
3128 /* Wait until message completion to increment in_msg_seq */
3129
3130 /* Reassemble if current message is fragmented or reassembly is
3131 * already in progress */
3132 if( ssl->in_msglen < ssl->in_hslen ||
3133 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
3134 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ||
3135 ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) )
3136 {
3137 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
3138
3139 if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 )
3140 {
3141 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_reassemble_dtls_handshake", ret );
3142 return( ret );
3143 }
3144 }
3145 }
3146 else
3147#endif /* MBEDTLS_SSL_PROTO_DTLS */
3148 /* With TLS we don't handle fragmentation (for now) */
3149 if( ssl->in_msglen < ssl->in_hslen )
3150 {
3151 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
3152 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3153 }
3154
3155 return( 0 );
3156}
3157
3158void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
3159{
3160
3161 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
3162 ssl->handshake != NULL )
3163 {
3164 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
3165 }
3166
3167 /* Handshake message is complete, increment counter */
3168#if defined(MBEDTLS_SSL_PROTO_DTLS)
3169 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3170 ssl->handshake != NULL )
3171 {
3172 ssl->handshake->in_msg_seq++;
3173 }
3174#endif
3175}
3176
3177/*
3178 * DTLS anti-replay: RFC 6347 4.1.2.6
3179 *
3180 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3181 * Bit n is set iff record number in_window_top - n has been seen.
3182 *
3183 * Usually, in_window_top is the last record number seen and the lsb of
3184 * in_window is set. The only exception is the initial state (record number 0
3185 * not seen yet).
3186 */
3187#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3188static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
3189{
3190 ssl->in_window_top = 0;
3191 ssl->in_window = 0;
3192}
3193
3194static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
3195{
3196 return( ( (uint64_t) buf[0] << 40 ) |
3197 ( (uint64_t) buf[1] << 32 ) |
3198 ( (uint64_t) buf[2] << 24 ) |
3199 ( (uint64_t) buf[3] << 16 ) |
3200 ( (uint64_t) buf[4] << 8 ) |
3201 ( (uint64_t) buf[5] ) );
3202}
3203
3204/*
3205 * Return 0 if sequence number is acceptable, -1 otherwise
3206 */
3207int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
3208{
3209 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3210 uint64_t bit;
3211
3212 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3213 return( 0 );
3214
3215 if( rec_seqnum > ssl->in_window_top )
3216 return( 0 );
3217
3218 bit = ssl->in_window_top - rec_seqnum;
3219
3220 if( bit >= 64 )
3221 return( -1 );
3222
3223 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
3224 return( -1 );
3225
3226 return( 0 );
3227}
3228
3229/*
3230 * Update replay window on new validated record
3231 */
3232void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
3233{
3234 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3235
3236 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3237 return;
3238
3239 if( rec_seqnum > ssl->in_window_top )
3240 {
3241 /* Update window_top and the contents of the window */
3242 uint64_t shift = rec_seqnum - ssl->in_window_top;
3243
3244 if( shift >= 64 )
3245 ssl->in_window = 1;
3246 else
3247 {
3248 ssl->in_window <<= shift;
3249 ssl->in_window |= 1;
3250 }
3251
3252 ssl->in_window_top = rec_seqnum;
3253 }
3254 else
3255 {
3256 /* Mark that number as seen in the current window */
3257 uint64_t bit = ssl->in_window_top - rec_seqnum;
3258
3259 if( bit < 64 ) /* Always true, but be extra sure */
3260 ssl->in_window |= (uint64_t) 1 << bit;
3261 }
3262}
3263#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3264
3265#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3266/* Forward declaration */
3267static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
3268
3269/*
3270 * Without any SSL context, check if a datagram looks like a ClientHello with
3271 * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
3272 * Both input and output include full DTLS headers.
3273 *
3274 * - if cookie is valid, return 0
3275 * - if ClientHello looks superficially valid but cookie is not,
3276 * fill obuf and set olen, then
3277 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3278 * - otherwise return a specific error code
3279 */
3280static int ssl_check_dtls_clihlo_cookie(
3281 mbedtls_ssl_cookie_write_t *f_cookie_write,
3282 mbedtls_ssl_cookie_check_t *f_cookie_check,
3283 void *p_cookie,
3284 const unsigned char *cli_id, size_t cli_id_len,
3285 const unsigned char *in, size_t in_len,
3286 unsigned char *obuf, size_t buf_len, size_t *olen )
3287{
3288 size_t sid_len, cookie_len;
3289 unsigned char *p;
3290
3291 if( f_cookie_write == NULL || f_cookie_check == NULL )
3292 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3293
3294 /*
3295 * Structure of ClientHello with record and handshake headers,
3296 * and expected values. We don't need to check a lot, more checks will be
3297 * done when actually parsing the ClientHello - skipping those checks
3298 * avoids code duplication and does not make cookie forging any easier.
3299 *
3300 * 0-0 ContentType type; copied, must be handshake
3301 * 1-2 ProtocolVersion version; copied
3302 * 3-4 uint16 epoch; copied, must be 0
3303 * 5-10 uint48 sequence_number; copied
3304 * 11-12 uint16 length; (ignored)
3305 *
3306 * 13-13 HandshakeType msg_type; (ignored)
3307 * 14-16 uint24 length; (ignored)
3308 * 17-18 uint16 message_seq; copied
3309 * 19-21 uint24 fragment_offset; copied, must be 0
3310 * 22-24 uint24 fragment_length; (ignored)
3311 *
3312 * 25-26 ProtocolVersion client_version; (ignored)
3313 * 27-58 Random random; (ignored)
3314 * 59-xx SessionID session_id; 1 byte len + sid_len content
3315 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3316 * ...
3317 *
3318 * Minimum length is 61 bytes.
3319 */
3320 if( in_len < 61 ||
3321 in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
3322 in[3] != 0 || in[4] != 0 ||
3323 in[19] != 0 || in[20] != 0 || in[21] != 0 )
3324 {
3325 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3326 }
3327
3328 sid_len = in[59];
3329 if( sid_len > in_len - 61 )
3330 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3331
3332 cookie_len = in[60 + sid_len];
3333 if( cookie_len > in_len - 60 )
3334 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3335
3336 if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
3337 cli_id, cli_id_len ) == 0 )
3338 {
3339 /* Valid cookie */
3340 return( 0 );
3341 }
3342
3343 /*
3344 * If we get here, we've got an invalid cookie, let's prepare HVR.
3345 *
3346 * 0-0 ContentType type; copied
3347 * 1-2 ProtocolVersion version; copied
3348 * 3-4 uint16 epoch; copied
3349 * 5-10 uint48 sequence_number; copied
3350 * 11-12 uint16 length; olen - 13
3351 *
3352 * 13-13 HandshakeType msg_type; hello_verify_request
3353 * 14-16 uint24 length; olen - 25
3354 * 17-18 uint16 message_seq; copied
3355 * 19-21 uint24 fragment_offset; copied
3356 * 22-24 uint24 fragment_length; olen - 25
3357 *
3358 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3359 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3360 *
3361 * Minimum length is 28.
3362 */
3363 if( buf_len < 28 )
3364 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3365
3366 /* Copy most fields and adapt others */
3367 memcpy( obuf, in, 25 );
3368 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3369 obuf[25] = 0xfe;
3370 obuf[26] = 0xff;
3371
3372 /* Generate and write actual cookie */
3373 p = obuf + 28;
3374 if( f_cookie_write( p_cookie,
3375 &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
3376 {
3377 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3378 }
3379
3380 *olen = p - obuf;
3381
3382 /* Go back and fill length fields */
3383 obuf[27] = (unsigned char)( *olen - 28 );
3384
3385 obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
3386 obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
3387 obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
3388
3389 obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
3390 obuf[12] = (unsigned char)( ( *olen - 13 ) );
3391
3392 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3393}
3394
3395/*
3396 * Handle possible client reconnect with the same UDP quadruplet
3397 * (RFC 6347 Section 4.2.8).
3398 *
3399 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3400 * that looks like a ClientHello.
3401 *
3402 * - if the input looks like a ClientHello without cookies,
3403 * send back HelloVerifyRequest, then
3404 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3405 * - if the input looks like a ClientHello with a valid cookie,
3406 * reset the session of the current context, and
3407 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3408 * - if anything goes wrong, return a specific error code
3409 *
3410 * mbedtls_ssl_read_record() will ignore the record if anything else than
3411 * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
3412 * cannot not return 0.
3413 */
3414static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
3415{
3416 int ret;
3417 size_t len;
3418
3419 ret = ssl_check_dtls_clihlo_cookie(
3420 ssl->conf->f_cookie_write,
3421 ssl->conf->f_cookie_check,
3422 ssl->conf->p_cookie,
3423 ssl->cli_id, ssl->cli_id_len,
3424 ssl->in_buf, ssl->in_left,
3425 ssl->out_buf, MBEDTLS_SSL_MAX_CONTENT_LEN, &len );
3426
3427 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
3428
3429 if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
3430 {
3431 /* Don't check write errors as we can't do anything here.
3432 * If the error is permanent we'll catch it later,
3433 * if it's not, then hopefully it'll work next time. */
3434 (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
3435
3436 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3437 }
3438
3439 if( ret == 0 )
3440 {
3441 /* Got a valid cookie, partially reset context */
3442 if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
3443 {
3444 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
3445 return( ret );
3446 }
3447
3448 return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
3449 }
3450
3451 return( ret );
3452}
3453#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3454
3455/*
3456 * ContentType type;
3457 * ProtocolVersion version;
3458 * uint16 epoch; // DTLS only
3459 * uint48 sequence_number; // DTLS only
3460 * uint16 length;
3461 *
3462 * Return 0 if header looks sane (and, for DTLS, the record is expected)
3463 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
3464 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
3465 *
3466 * With DTLS, mbedtls_ssl_read_record() will:
3467 * 1. proceed with the record if this function returns 0
3468 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
3469 * 3. return CLIENT_RECONNECT if this function return that value
3470 * 4. drop the whole datagram if this function returns anything else.
3471 * Point 2 is needed when the peer is resending, and we have already received
3472 * the first record from a datagram but are still waiting for the others.
3473 */
3474static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
3475{
3476 int major_ver, minor_ver;
3477
3478 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
3479
3480 ssl->in_msgtype = ssl->in_hdr[0];
3481 ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
3482 mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
3483
3484 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
3485 "version = [%d:%d], msglen = %d",
3486 ssl->in_msgtype,
3487 major_ver, minor_ver, ssl->in_msglen ) );
3488
3489 /* Check record type */
3490 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
3491 ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
3492 ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3493 ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
3494 {
3495 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
3496 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3497 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3498 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3499 }
3500
3501 /* Check version */
3502 if( major_ver != ssl->major_ver )
3503 {
3504 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
3505 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3506 }
3507
3508 if( minor_ver > ssl->conf->max_minor_ver )
3509 {
3510 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
3511 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3512 }
3513
3514 /* Check length against the size of our buffer */
3515 if( ssl->in_msglen > MBEDTLS_SSL_BUFFER_LEN
3516 - (size_t)( ssl->in_msg - ssl->in_buf ) )
3517 {
3518 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3519 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3520 }
3521
3522 /* Check length against bounds of the current transform and version */
3523 if( ssl->transform_in == NULL )
3524 {
3525 if( ssl->in_msglen < 1 ||
3526 ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3527 {
3528 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3529 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3530 }
3531 }
3532 else
3533 {
3534 if( ssl->in_msglen < ssl->transform_in->minlen )
3535 {
3536 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3537 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3538 }
3539
3540#if defined(MBEDTLS_SSL_PROTO_SSL3)
3541 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
3542 ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN )
3543 {
3544 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3545 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3546 }
3547#endif
3548#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3549 defined(MBEDTLS_SSL_PROTO_TLS1_2)
3550 /*
3551 * TLS encrypted messages can have up to 256 bytes of padding
3552 */
3553 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
3554 ssl->in_msglen > ssl->transform_in->minlen +
3555 MBEDTLS_SSL_MAX_CONTENT_LEN + 256 )
3556 {
3557 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3558 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3559 }
3560#endif
3561 }
3562
3563 /*
3564 * DTLS-related tests done last, because most of them may result in
3565 * silently dropping the record (but not the whole datagram), and we only
3566 * want to consider that after ensuring that the "basic" fields (type,
3567 * version, length) are sane.
3568 */
3569#if defined(MBEDTLS_SSL_PROTO_DTLS)
3570 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3571 {
3572 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
3573
3574 /* Drop unexpected ChangeCipherSpec messages */
3575 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3576 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
3577 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
3578 {
3579 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) );
3580 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3581 }
3582
3583 /* Drop unexpected ApplicationData records,
3584 * except at the beginning of renegotiations */
3585 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
3586 ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
3587#if defined(MBEDTLS_SSL_RENEGOTIATION)
3588 && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
3589 ssl->state == MBEDTLS_SSL_SERVER_HELLO )
3590#endif
3591 )
3592 {
3593 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
3594 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3595 }
3596
3597 /* Check epoch (and sequence number) with DTLS */
3598 if( rec_epoch != ssl->in_epoch )
3599 {
3600 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
3601 "expected %d, received %d",
3602 ssl->in_epoch, rec_epoch ) );
3603
3604#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3605 /*
3606 * Check for an epoch 0 ClientHello. We can't use in_msg here to
3607 * access the first byte of record content (handshake type), as we
3608 * have an active transform (possibly iv_len != 0), so use the
3609 * fact that the record header len is 13 instead.
3610 */
3611 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3612 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3613 rec_epoch == 0 &&
3614 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3615 ssl->in_left > 13 &&
3616 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
3617 {
3618 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
3619 "from the same port" ) );
3620 return( ssl_handle_possible_reconnect( ssl ) );
3621 }
3622 else
3623#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3624 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3625 }
3626
3627#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3628 /* Replay detection only works for the current epoch */
3629 if( rec_epoch == ssl->in_epoch &&
3630 mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
3631 {
3632 MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
3633 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3634 }
3635#endif
3636 }
3637#endif /* MBEDTLS_SSL_PROTO_DTLS */
3638
3639 return( 0 );
3640}
3641
3642/*
3643 * If applicable, decrypt (and decompress) record content
3644 */
3645static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
3646{
3647 int ret, done = 0;
3648
3649 MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
3650 ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
3651
3652#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3653 if( mbedtls_ssl_hw_record_read != NULL )
3654 {
3655 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
3656
3657 ret = mbedtls_ssl_hw_record_read( ssl );
3658 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
3659 {
3660 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
3661 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3662 }
3663
3664 if( ret == 0 )
3665 done = 1;
3666 }
3667#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3668 if( !done && ssl->transform_in != NULL )
3669 {
3670 if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
3671 {
3672 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
3673 return( ret );
3674 }
3675
3676 MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
3677 ssl->in_msg, ssl->in_msglen );
3678
3679 if( ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3680 {
3681 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3682 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3683 }
3684 }
3685
3686#if defined(MBEDTLS_ZLIB_SUPPORT)
3687 if( ssl->transform_in != NULL &&
3688 ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
3689 {
3690 if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
3691 {
3692 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
3693 return( ret );
3694 }
3695 }
3696#endif /* MBEDTLS_ZLIB_SUPPORT */
3697
3698#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3699 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3700 {
3701 mbedtls_ssl_dtls_replay_update( ssl );
3702 }
3703#endif
3704
3705 return( 0 );
3706}
3707
3708static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
3709
3710/*
3711 * Read a record.
3712 *
3713 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
3714 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
3715 *
3716 */
3717int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl )
3718{
3719 int ret;
3720
3721 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
3722
3723 if( ssl->keep_current_message == 0 )
3724 {
3725 do {
3726
3727 if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 )
3728 {
3729 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret );
3730 return( ret );
3731 }
3732
3733 ret = mbedtls_ssl_handle_message_type( ssl );
3734
3735 } while( MBEDTLS_ERR_SSL_NON_FATAL == ret );
3736
3737 if( 0 != ret )
3738 {
3739 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret );
3740 return( ret );
3741 }
3742
3743 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
3744 {
3745 mbedtls_ssl_update_handshake_status( ssl );
3746 }
3747 }
3748 else
3749 {
3750 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= reuse previously read message" ) );
3751 ssl->keep_current_message = 0;
3752 }
3753
3754 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
3755
3756 return( 0 );
3757}
3758
3759int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl )
3760{
3761 int ret;
3762
3763 /*
3764 * Step A
3765 *
3766 * Consume last content-layer message and potentially
3767 * update in_msglen which keeps track of the contents'
3768 * consumption state.
3769 *
3770 * (1) Handshake messages:
3771 * Remove last handshake message, move content
3772 * and adapt in_msglen.
3773 *
3774 * (2) Alert messages:
3775 * Consume whole record content, in_msglen = 0.
3776 *
3777 * NOTE: This needs to be fixed, since like for
3778 * handshake messages it is allowed to have
3779 * multiple alerts witin a single record.
3780 * Internal reference IOTSSL-1321.
3781 *
3782 * (3) Change cipher spec:
3783 * Consume whole record content, in_msglen = 0.
3784 *
3785 * (4) Application data:
3786 * Don't do anything - the record layer provides
3787 * the application data as a stream transport
3788 * and consumes through mbedtls_ssl_read only.
3789 *
3790 */
3791
3792 /* Case (1): Handshake messages */
3793 if( ssl->in_hslen != 0 )
3794 {
3795 /* Hard assertion to be sure that no application data
3796 * is in flight, as corrupting ssl->in_msglen during
3797 * ssl->in_offt != NULL is fatal. */
3798 if( ssl->in_offt != NULL )
3799 {
3800 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3801 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3802 }
3803
3804 /*
3805 * Get next Handshake message in the current record
3806 */
3807
3808 /* Notes:
3809 * (1) in_hslen is *NOT* necessarily the size of the
3810 * current handshake content: If DTLS handshake
3811 * fragmentation is used, that's the fragment
3812 * size instead. Using the total handshake message
3813 * size here is FAULTY and should be changed at
3814 * some point. Internal reference IOTSSL-1414.
3815 * (2) While it doesn't seem to cause problems, one
3816 * has to be very careful not to assume that in_hslen
3817 * is always <= in_msglen in a sensible communication.
3818 * Again, it's wrong for DTLS handshake fragmentation.
3819 * The following check is therefore mandatory, and
3820 * should not be treated as a silently corrected assertion.
3821 * Additionally, ssl->in_hslen might be arbitrarily out of
3822 * bounds after handling a DTLS message with an unexpected
3823 * sequence number, see mbedtls_ssl_prepare_handshake_record.
3824 */
3825 if( ssl->in_hslen < ssl->in_msglen )
3826 {
3827 ssl->in_msglen -= ssl->in_hslen;
3828 memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
3829 ssl->in_msglen );
3830
3831 MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
3832 ssl->in_msg, ssl->in_msglen );
3833 }
3834 else
3835 {
3836 ssl->in_msglen = 0;
3837 }
3838
3839 ssl->in_hslen = 0;
3840 }
3841 /* Case (4): Application data */
3842 else if( ssl->in_offt != NULL )
3843 {
3844 return( 0 );
3845 }
3846 /* Everything else (CCS & Alerts) */
3847 else
3848 {
3849 ssl->in_msglen = 0;
3850 }
3851
3852 /*
3853 * Step B
3854 *
3855 * Fetch and decode new record if current one is fully consumed.
3856 *
3857 */
3858
3859 if( ssl->in_msglen > 0 )
3860 {
3861 /* There's something left to be processed in the current record. */
3862 return( 0 );
3863 }
3864
3865 /* Need to fetch a new record */
3866
3867#if defined(MBEDTLS_SSL_PROTO_DTLS)
3868read_record_header:
3869#endif
3870
3871 /* Current record either fully processed or to be discarded. */
3872
3873 if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
3874 {
3875 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
3876 return( ret );
3877 }
3878
3879 if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
3880 {
3881#if defined(MBEDTLS_SSL_PROTO_DTLS)
3882 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3883 ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
3884 {
3885 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
3886 {
3887 /* Skip unexpected record (but not whole datagram) */
3888 ssl->next_record_offset = ssl->in_msglen
3889 + mbedtls_ssl_hdr_len( ssl );
3890
3891 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
3892 "(header)" ) );
3893 }
3894 else
3895 {
3896 /* Skip invalid record and the rest of the datagram */
3897 ssl->next_record_offset = 0;
3898 ssl->in_left = 0;
3899
3900 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
3901 "(header)" ) );
3902 }
3903
3904 /* Get next record */
3905 goto read_record_header;
3906 }
3907#endif
3908 return( ret );
3909 }
3910
3911 /*
3912 * Read and optionally decrypt the message contents
3913 */
3914 if( ( ret = mbedtls_ssl_fetch_input( ssl,
3915 mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
3916 {
3917 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
3918 return( ret );
3919 }
3920
3921 /* Done reading this record, get ready for the next one */
3922#if defined(MBEDTLS_SSL_PROTO_DTLS)
3923 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3924 ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
3925 else
3926#endif
3927 ssl->in_left = 0;
3928
3929 if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
3930 {
3931#if defined(MBEDTLS_SSL_PROTO_DTLS)
3932 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3933 {
3934 /* Silently discard invalid records */
3935 if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
3936 ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3937 {
3938 /* Except when waiting for Finished as a bad mac here
3939 * probably means something went wrong in the handshake
3940 * (eg wrong psk used, mitm downgrade attempt, etc.) */
3941 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
3942 ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
3943 {
3944#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
3945 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3946 {
3947 mbedtls_ssl_send_alert_message( ssl,
3948 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3949 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
3950 }
3951#endif
3952 return( ret );
3953 }
3954
3955#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
3956 if( ssl->conf->badmac_limit != 0 &&
3957 ++ssl->badmac_seen >= ssl->conf->badmac_limit )
3958 {
3959 MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
3960 return( MBEDTLS_ERR_SSL_INVALID_MAC );
3961 }
3962#endif
3963
3964 /* As above, invalid records cause
3965 * dismissal of the whole datagram. */
3966
3967 ssl->next_record_offset = 0;
3968 ssl->in_left = 0;
3969
3970 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
3971 goto read_record_header;
3972 }
3973
3974 return( ret );
3975 }
3976 else
3977#endif
3978 {
3979 /* Error out (and send alert) on invalid records */
3980#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
3981 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
3982 {
3983 mbedtls_ssl_send_alert_message( ssl,
3984 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3985 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
3986 }
3987#endif
3988 return( ret );
3989 }
3990 }
3991
3992 /*
3993 * When we sent the last flight of the handshake, we MUST respond to a
3994 * retransmit of the peer's previous flight with a retransmit. (In
3995 * practice, only the Finished message will make it, other messages
3996 * including CCS use the old transform so they're dropped as invalid.)
3997 *
3998 * If the record we received is not a handshake message, however, it
3999 * means the peer received our last flight so we can clean up
4000 * handshake info.
4001 *
4002 * This check needs to be done before prepare_handshake() due to an edge
4003 * case: if the client immediately requests renegotiation, this
4004 * finishes the current handshake first, avoiding the new ClientHello
4005 * being mistaken for an ancient message in the current handshake.
4006 */
4007#if defined(MBEDTLS_SSL_PROTO_DTLS)
4008 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4009 ssl->handshake != NULL &&
4010 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
4011 {
4012 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4013 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
4014 {
4015 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) );
4016
4017 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
4018 {
4019 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
4020 return( ret );
4021 }
4022
4023 return( MBEDTLS_ERR_SSL_WANT_READ );
4024 }
4025 else
4026 {
4027 ssl_handshake_wrapup_free_hs_transform( ssl );
4028 }
4029 }
4030#endif
4031
4032 return( 0 );
4033}
4034
4035int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
4036{
4037 int ret;
4038
4039 /*
4040 * Handle particular types of records
4041 */
4042 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
4043 {
4044 if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
4045 {
4046 return( ret );
4047 }
4048 }
4049
4050 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
4051 {
4052 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
4053 ssl->in_msg[0], ssl->in_msg[1] ) );
4054
4055 /*
4056 * Ignore non-fatal alerts, except close_notify and no_renegotiation
4057 */
4058 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
4059 {
4060 MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
4061 ssl->in_msg[1] ) );
4062 return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
4063 }
4064
4065 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4066 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
4067 {
4068 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
4069 return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
4070 }
4071
4072#if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
4073 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4074 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
4075 {
4076 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4077 /* Will be handled when trying to parse ServerHello */
4078 return( 0 );
4079 }
4080#endif
4081
4082#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
4083 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
4084 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4085 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4086 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4087 {
4088 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4089 /* Will be handled in mbedtls_ssl_parse_certificate() */
4090 return( 0 );
4091 }
4092#endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
4093
4094 /* Silently ignore: fetch new message */
4095 return MBEDTLS_ERR_SSL_NON_FATAL;
4096 }
4097
4098 return( 0 );
4099}
4100
4101int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
4102{
4103 int ret;
4104
4105 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
4106 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4107 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
4108 {
4109 return( ret );
4110 }
4111
4112 return( 0 );
4113}
4114
4115int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
4116 unsigned char level,
4117 unsigned char message )
4118{
4119 int ret;
4120
4121 if( ssl == NULL || ssl->conf == NULL )
4122 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4123
4124 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
4125 MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
4126
4127 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4128 ssl->out_msglen = 2;
4129 ssl->out_msg[0] = level;
4130 ssl->out_msg[1] = message;
4131
4132 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4133 {
4134 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4135 return( ret );
4136 }
4137 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
4138
4139 return( 0 );
4140}
4141
4142/*
4143 * Handshake functions
4144 */
4145#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
4146 !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \
4147 !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
4148 !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
4149 !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
4150 !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
4151 !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
4152/* No certificate support -> dummy functions */
4153int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4154{
4155 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4156
4157 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4158
4159 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4160 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4161 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4162 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4163 {
4164 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4165 ssl->state++;
4166 return( 0 );
4167 }
4168
4169 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4170 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4171}
4172
4173int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4174{
4175 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4176
4177 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4178
4179 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4180 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4181 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4182 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4183 {
4184 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4185 ssl->state++;
4186 return( 0 );
4187 }
4188
4189 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4190 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4191}
4192
4193#else
4194/* Some certificate support -> implement write and parse */
4195
4196int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4197{
4198 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4199 size_t i, n;
4200 const mbedtls_x509_crt *crt;
4201 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4202
4203 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4204
4205 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4206 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4207 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4208 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4209 {
4210 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4211 ssl->state++;
4212 return( 0 );
4213 }
4214
4215#if defined(MBEDTLS_SSL_CLI_C)
4216 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
4217 {
4218 if( ssl->client_auth == 0 )
4219 {
4220 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4221 ssl->state++;
4222 return( 0 );
4223 }
4224
4225#if defined(MBEDTLS_SSL_PROTO_SSL3)
4226 /*
4227 * If using SSLv3 and got no cert, send an Alert message
4228 * (otherwise an empty Certificate message will be sent).
4229 */
4230 if( mbedtls_ssl_own_cert( ssl ) == NULL &&
4231 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4232 {
4233 ssl->out_msglen = 2;
4234 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4235 ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
4236 ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
4237
4238 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
4239 goto write_msg;
4240 }
4241#endif /* MBEDTLS_SSL_PROTO_SSL3 */
4242 }
4243#endif /* MBEDTLS_SSL_CLI_C */
4244#if defined(MBEDTLS_SSL_SRV_C)
4245 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
4246 {
4247 if( mbedtls_ssl_own_cert( ssl ) == NULL )
4248 {
4249 MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
4250 return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
4251 }
4252 }
4253#endif
4254
4255 MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
4256
4257 /*
4258 * 0 . 0 handshake type
4259 * 1 . 3 handshake length
4260 * 4 . 6 length of all certs
4261 * 7 . 9 length of cert. 1
4262 * 10 . n-1 peer certificate
4263 * n . n+2 length of cert. 2
4264 * n+3 . ... upper level cert, etc.
4265 */
4266 i = 7;
4267 crt = mbedtls_ssl_own_cert( ssl );
4268
4269 while( crt != NULL )
4270 {
4271 n = crt->raw.len;
4272 if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i )
4273 {
4274 MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
4275 i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) );
4276 return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
4277 }
4278
4279 ssl->out_msg[i ] = (unsigned char)( n >> 16 );
4280 ssl->out_msg[i + 1] = (unsigned char)( n >> 8 );
4281 ssl->out_msg[i + 2] = (unsigned char)( n );
4282
4283 i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
4284 i += n; crt = crt->next;
4285 }
4286
4287 ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 );
4288 ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 );
4289 ssl->out_msg[6] = (unsigned char)( ( i - 7 ) );
4290
4291 ssl->out_msglen = i;
4292 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4293 ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE;
4294
4295#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
4296write_msg:
4297#endif
4298
4299 ssl->state++;
4300
4301 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4302 {
4303 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4304 return( ret );
4305 }
4306
4307 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
4308
4309 return( ret );
4310}
4311
4312int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4313{
4314 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4315 size_t i, n;
4316 const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4317 int authmode = ssl->conf->authmode;
4318 uint8_t alert;
4319
4320 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4321
4322 if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4323 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4324 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4325 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4326 {
4327 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4328 ssl->state++;
4329 return( 0 );
4330 }
4331
4332#if defined(MBEDTLS_SSL_SRV_C)
4333 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4334 ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
4335 {
4336 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4337 ssl->state++;
4338 return( 0 );
4339 }
4340
4341#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4342 if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
4343 authmode = ssl->handshake->sni_authmode;
4344#endif
4345
4346 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4347 authmode == MBEDTLS_SSL_VERIFY_NONE )
4348 {
4349 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
4350 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4351 ssl->state++;
4352 return( 0 );
4353 }
4354#endif
4355
4356 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4357 {
4358 /* mbedtls_ssl_read_record may have sent an alert already. We
4359 let it decide whether to alert. */
4360 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4361 return( ret );
4362 }
4363
4364 ssl->state++;
4365
4366#if defined(MBEDTLS_SSL_SRV_C)
4367#if defined(MBEDTLS_SSL_PROTO_SSL3)
4368 /*
4369 * Check if the client sent an empty certificate
4370 */
4371 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4372 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4373 {
4374 if( ssl->in_msglen == 2 &&
4375 ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT &&
4376 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4377 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4378 {
4379 MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
4380
4381 /* The client was asked for a certificate but didn't send
4382 one. The client should know what's going on, so we
4383 don't send an alert. */
4384 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4385 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4386 return( 0 );
4387 else
4388 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4389 }
4390 }
4391#endif /* MBEDTLS_SSL_PROTO_SSL3 */
4392
4393#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
4394 defined(MBEDTLS_SSL_PROTO_TLS1_2)
4395 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4396 ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
4397 {
4398 if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
4399 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4400 ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE &&
4401 memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
4402 {
4403 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
4404
4405 /* The client was asked for a certificate but didn't send
4406 one. The client should know what's going on, so we
4407 don't send an alert. */
4408 ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4409 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4410 return( 0 );
4411 else
4412 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4413 }
4414 }
4415#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
4416 MBEDTLS_SSL_PROTO_TLS1_2 */
4417#endif /* MBEDTLS_SSL_SRV_C */
4418
4419 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4420 {
4421 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4422 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4423 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
4424 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4425 }
4426
4427 if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
4428 ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
4429 {
4430 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4431 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4432 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4433 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4434 }
4435
4436 i = mbedtls_ssl_hs_hdr_len( ssl );
4437
4438 /*
4439 * Same message structure as in mbedtls_ssl_write_certificate()
4440 */
4441 n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
4442
4443 if( ssl->in_msg[i] != 0 ||
4444 ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
4445 {
4446 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4447 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4448 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4449 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4450 }
4451
4452 /* In case we tried to reuse a session but it failed */
4453 if( ssl->session_negotiate->peer_cert != NULL )
4454 {
4455 mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
4456 mbedtls_free( ssl->session_negotiate->peer_cert );
4457 }
4458
4459 if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
4460 sizeof( mbedtls_x509_crt ) ) ) == NULL )
4461 {
4462 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
4463 sizeof( mbedtls_x509_crt ) ) );
4464 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4465 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
4466 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4467 }
4468
4469 mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
4470
4471 i += 3;
4472
4473 while( i < ssl->in_hslen )
4474 {
4475 if( ssl->in_msg[i] != 0 )
4476 {
4477 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4478 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4479 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4480 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4481 }
4482
4483 n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
4484 | (unsigned int) ssl->in_msg[i + 2];
4485 i += 3;
4486
4487 if( n < 128 || i + n > ssl->in_hslen )
4488 {
4489 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4490 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4491 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4492 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4493 }
4494
4495 ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
4496 ssl->in_msg + i, n );
4497 switch( ret )
4498 {
4499 case 0: /*ok*/
4500 case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
4501 /* Ignore certificate with an unknown algorithm: maybe a
4502 prior certificate was already trusted. */
4503 break;
4504
4505 case MBEDTLS_ERR_X509_ALLOC_FAILED:
4506 alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
4507 goto crt_parse_der_failed;
4508
4509 case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
4510 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4511 goto crt_parse_der_failed;
4512
4513 default:
4514 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
4515 crt_parse_der_failed:
4516 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
4517 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
4518 return( ret );
4519 }
4520
4521 i += n;
4522 }
4523
4524 MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
4525
4526 /*
4527 * On client, make sure the server cert doesn't change during renego to
4528 * avoid "triple handshake" attack: https://secure-resumption.com/
4529 */
4530#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
4531 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4532 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
4533 {
4534 if( ssl->session->peer_cert == NULL )
4535 {
4536 MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
4537 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4538 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
4539 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4540 }
4541
4542 if( ssl->session->peer_cert->raw.len !=
4543 ssl->session_negotiate->peer_cert->raw.len ||
4544 memcmp( ssl->session->peer_cert->raw.p,
4545 ssl->session_negotiate->peer_cert->raw.p,
4546 ssl->session->peer_cert->raw.len ) != 0 )
4547 {
4548 MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
4549 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4550 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
4551 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4552 }
4553 }
4554#endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
4555
4556 if( authmode != MBEDTLS_SSL_VERIFY_NONE )
4557 {
4558 mbedtls_x509_crt *ca_chain;
4559 mbedtls_x509_crl *ca_crl;
4560
4561#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4562 if( ssl->handshake->sni_ca_chain != NULL )
4563 {
4564 ca_chain = ssl->handshake->sni_ca_chain;
4565 ca_crl = ssl->handshake->sni_ca_crl;
4566 }
4567 else
4568#endif
4569 {
4570 ca_chain = ssl->conf->ca_chain;
4571 ca_crl = ssl->conf->ca_crl;
4572 }
4573
4574 /*
4575 * Main check: verify certificate
4576 */
4577 ret = mbedtls_x509_crt_verify_with_profile(
4578 ssl->session_negotiate->peer_cert,
4579 ca_chain, ca_crl,
4580 ssl->conf->cert_profile,
4581 ssl->hostname,
4582 &ssl->session_negotiate->verify_result,
4583 ssl->conf->f_vrfy, ssl->conf->p_vrfy );
4584
4585 if( ret != 0 )
4586 {
4587 MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
4588 }
4589
4590 /*
4591 * Secondary checks: always done, but change 'ret' only if it was 0
4592 */
4593
4594#if defined(MBEDTLS_ECP_C)
4595 {
4596 const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
4597
4598 /* If certificate uses an EC key, make sure the curve is OK */
4599 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
4600 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
4601 {
4602 ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
4603
4604 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
4605 if( ret == 0 )
4606 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4607 }
4608 }
4609#endif /* MBEDTLS_ECP_C */
4610
4611 if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
4612 ciphersuite_info,
4613 ! ssl->conf->endpoint,
4614 &ssl->session_negotiate->verify_result ) != 0 )
4615 {
4616 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
4617 if( ret == 0 )
4618 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4619 }
4620
4621 /* mbedtls_x509_crt_verify_with_profile is supposed to report a
4622 * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
4623 * with details encoded in the verification flags. All other kinds
4624 * of error codes, including those from the user provided f_vrfy
4625 * functions, are treated as fatal and lead to a failure of
4626 * ssl_parse_certificate even if verification was optional. */
4627 if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
4628 ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
4629 ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
4630 {
4631 ret = 0;
4632 }
4633
4634 if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
4635 {
4636 MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
4637 ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
4638 }
4639
4640 if( ret != 0 )
4641 {
4642 /* The certificate may have been rejected for several reasons.
4643 Pick one and send the corresponding alert. Which alert to send
4644 may be a subject of debate in some cases. */
4645 if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
4646 alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
4647 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
4648 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
4649 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
4650 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4651 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
4652 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4653 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
4654 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4655 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
4656 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4657 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
4658 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4659 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
4660 alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
4661 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
4662 alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
4663 else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
4664 alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
4665 else
4666 alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
4667 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4668 alert );
4669 }
4670
4671#if defined(MBEDTLS_DEBUG_C)
4672 if( ssl->session_negotiate->verify_result != 0 )
4673 {
4674 MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
4675 ssl->session_negotiate->verify_result ) );
4676 }
4677 else
4678 {
4679 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
4680 }
4681#endif /* MBEDTLS_DEBUG_C */
4682 }
4683
4684 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
4685
4686 return( ret );
4687}
4688#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
4689 !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
4690 !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
4691 !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
4692 !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
4693 !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
4694 !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4695
4696int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
4697{
4698 int ret;
4699
4700 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
4701
4702 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4703 ssl->out_msglen = 1;
4704 ssl->out_msg[0] = 1;
4705
4706 ssl->state++;
4707
4708 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4709 {
4710 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4711 return( ret );
4712 }
4713
4714 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
4715
4716 return( 0 );
4717}
4718
4719int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
4720{
4721 int ret;
4722
4723 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
4724
4725 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4726 {
4727 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4728 return( ret );
4729 }
4730
4731 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
4732 {
4733 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4734 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4735 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
4736 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4737 }
4738
4739 if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
4740 {
4741 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4742 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4743 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4744 return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
4745 }
4746
4747 /*
4748 * Switch to our negotiated transform and session parameters for inbound
4749 * data.
4750 */
4751 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
4752 ssl->transform_in = ssl->transform_negotiate;
4753 ssl->session_in = ssl->session_negotiate;
4754
4755#if defined(MBEDTLS_SSL_PROTO_DTLS)
4756 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4757 {
4758#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4759 ssl_dtls_replay_reset( ssl );
4760#endif
4761
4762 /* Increment epoch */
4763 if( ++ssl->in_epoch == 0 )
4764 {
4765 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
4766 /* This is highly unlikely to happen for legitimate reasons, so
4767 treat it as an attack and don't send an alert. */
4768 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
4769 }
4770 }
4771 else
4772#endif /* MBEDTLS_SSL_PROTO_DTLS */
4773 memset( ssl->in_ctr, 0, 8 );
4774
4775 /*
4776 * Set the in_msg pointer to the correct location based on IV length
4777 */
4778 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
4779 {
4780 ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -
4781 ssl->transform_negotiate->fixed_ivlen;
4782 }
4783 else
4784 ssl->in_msg = ssl->in_iv;
4785
4786#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
4787 if( mbedtls_ssl_hw_record_activate != NULL )
4788 {
4789 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
4790 {
4791 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
4792 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4793 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
4794 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
4795 }
4796 }
4797#endif
4798
4799 ssl->state++;
4800
4801 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
4802
4803 return( 0 );
4804}
4805
4806void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
4807 const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
4808{
4809 ((void) ciphersuite_info);
4810
4811#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4812 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4813 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
4814 ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
4815 else
4816#endif
4817#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4818#if defined(MBEDTLS_SHA512_C)
4819 if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
4820 ssl->handshake->update_checksum = ssl_update_checksum_sha384;
4821 else
4822#endif
4823#if defined(MBEDTLS_SHA256_C)
4824 if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
4825 ssl->handshake->update_checksum = ssl_update_checksum_sha256;
4826 else
4827#endif
4828#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4829 {
4830 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4831 return;
4832 }
4833}
4834
4835void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
4836{
4837#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4838 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4839 mbedtls_md5_starts( &ssl->handshake->fin_md5 );
4840 mbedtls_sha1_starts( &ssl->handshake->fin_sha1 );
4841#endif
4842#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4843#if defined(MBEDTLS_SHA256_C)
4844 mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 );
4845#endif
4846#if defined(MBEDTLS_SHA512_C)
4847 mbedtls_sha512_starts( &ssl->handshake->fin_sha512, 1 );
4848#endif
4849#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4850}
4851
4852static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
4853 const unsigned char *buf, size_t len )
4854{
4855#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4856 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4857 mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4858 mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4859#endif
4860#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4861#if defined(MBEDTLS_SHA256_C)
4862 mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4863#endif
4864#if defined(MBEDTLS_SHA512_C)
4865 mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4866#endif
4867#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4868}
4869
4870#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4871 defined(MBEDTLS_SSL_PROTO_TLS1_1)
4872static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
4873 const unsigned char *buf, size_t len )
4874{
4875 mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4876 mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4877}
4878#endif
4879
4880#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4881#if defined(MBEDTLS_SHA256_C)
4882static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
4883 const unsigned char *buf, size_t len )
4884{
4885 mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4886}
4887#endif
4888
4889#if defined(MBEDTLS_SHA512_C)
4890static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
4891 const unsigned char *buf, size_t len )
4892{
4893 mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4894}
4895#endif
4896#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4897
4898#if defined(MBEDTLS_SSL_PROTO_SSL3)
4899static void ssl_calc_finished_ssl(
4900 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4901{
4902 const char *sender;
4903 mbedtls_md5_context md5;
4904 mbedtls_sha1_context sha1;
4905
4906 unsigned char padbuf[48];
4907 unsigned char md5sum[16];
4908 unsigned char sha1sum[20];
4909
4910 mbedtls_ssl_session *session = ssl->session_negotiate;
4911 if( !session )
4912 session = ssl->session;
4913
4914 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) );
4915
4916 mbedtls_md5_init( &md5 );
4917 mbedtls_sha1_init( &sha1 );
4918
4919 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
4920 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
4921
4922 /*
4923 * SSLv3:
4924 * hash =
4925 * MD5( master + pad2 +
4926 * MD5( handshake + sender + master + pad1 ) )
4927 * + SHA1( master + pad2 +
4928 * SHA1( handshake + sender + master + pad1 ) )
4929 */
4930
4931#if !defined(MBEDTLS_MD5_ALT)
4932 MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
4933 md5.state, sizeof( md5.state ) );
4934#endif
4935
4936#if !defined(MBEDTLS_SHA1_ALT)
4937 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
4938 sha1.state, sizeof( sha1.state ) );
4939#endif
4940
4941 sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
4942 : "SRVR";
4943
4944 memset( padbuf, 0x36, 48 );
4945
4946 mbedtls_md5_update( &md5, (const unsigned char *) sender, 4 );
4947 mbedtls_md5_update( &md5, session->master, 48 );
4948 mbedtls_md5_update( &md5, padbuf, 48 );
4949 mbedtls_md5_finish( &md5, md5sum );
4950
4951 mbedtls_sha1_update( &sha1, (const unsigned char *) sender, 4 );
4952 mbedtls_sha1_update( &sha1, session->master, 48 );
4953 mbedtls_sha1_update( &sha1, padbuf, 40 );
4954 mbedtls_sha1_finish( &sha1, sha1sum );
4955
4956 memset( padbuf, 0x5C, 48 );
4957
4958 mbedtls_md5_starts( &md5 );
4959 mbedtls_md5_update( &md5, session->master, 48 );
4960 mbedtls_md5_update( &md5, padbuf, 48 );
4961 mbedtls_md5_update( &md5, md5sum, 16 );
4962 mbedtls_md5_finish( &md5, buf );
4963
4964 mbedtls_sha1_starts( &sha1 );
4965 mbedtls_sha1_update( &sha1, session->master, 48 );
4966 mbedtls_sha1_update( &sha1, padbuf , 40 );
4967 mbedtls_sha1_update( &sha1, sha1sum, 20 );
4968 mbedtls_sha1_finish( &sha1, buf + 16 );
4969
4970 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
4971
4972 mbedtls_md5_free( &md5 );
4973 mbedtls_sha1_free( &sha1 );
4974
4975 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
4976 mbedtls_zeroize( md5sum, sizeof( md5sum ) );
4977 mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
4978
4979 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
4980}
4981#endif /* MBEDTLS_SSL_PROTO_SSL3 */
4982
4983#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
4984static void ssl_calc_finished_tls(
4985 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4986{
4987 int len = 12;
4988 const char *sender;
4989 mbedtls_md5_context md5;
4990 mbedtls_sha1_context sha1;
4991 unsigned char padbuf[36];
4992
4993 mbedtls_ssl_session *session = ssl->session_negotiate;
4994 if( !session )
4995 session = ssl->session;
4996
4997 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) );
4998
4999 mbedtls_md5_init( &md5 );
5000 mbedtls_sha1_init( &sha1 );
5001
5002 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
5003 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
5004
5005 /*
5006 * TLSv1:
5007 * hash = PRF( master, finished_label,
5008 * MD5( handshake ) + SHA1( handshake ) )[0..11]
5009 */
5010
5011#if !defined(MBEDTLS_MD5_ALT)
5012 MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
5013 md5.state, sizeof( md5.state ) );
5014#endif
5015
5016#if !defined(MBEDTLS_SHA1_ALT)
5017 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
5018 sha1.state, sizeof( sha1.state ) );
5019#endif
5020
5021 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5022 ? "client finished"
5023 : "server finished";
5024
5025 mbedtls_md5_finish( &md5, padbuf );
5026 mbedtls_sha1_finish( &sha1, padbuf + 16 );
5027
5028 ssl->handshake->tls_prf( session->master, 48, sender,
5029 padbuf, 36, buf, len );
5030
5031 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5032
5033 mbedtls_md5_free( &md5 );
5034 mbedtls_sha1_free( &sha1 );
5035
5036 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
5037
5038 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
5039}
5040#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
5041
5042#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5043#if defined(MBEDTLS_SHA256_C)
5044static void ssl_calc_finished_tls_sha256(
5045 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5046{
5047 int len = 12;
5048 const char *sender;
5049 mbedtls_sha256_context sha256;
5050 unsigned char padbuf[32];
5051
5052 mbedtls_ssl_session *session = ssl->session_negotiate;
5053 if( !session )
5054 session = ssl->session;
5055
5056 mbedtls_sha256_init( &sha256 );
5057
5058 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) );
5059
5060 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
5061
5062 /*
5063 * TLSv1.2:
5064 * hash = PRF( master, finished_label,
5065 * Hash( handshake ) )[0.11]
5066 */
5067
5068#if !defined(MBEDTLS_SHA256_ALT)
5069 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
5070 sha256.state, sizeof( sha256.state ) );
5071#endif
5072
5073 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5074 ? "client finished"
5075 : "server finished";
5076
5077 mbedtls_sha256_finish( &sha256, padbuf );
5078
5079 ssl->handshake->tls_prf( session->master, 48, sender,
5080 padbuf, 32, buf, len );
5081
5082 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5083
5084 mbedtls_sha256_free( &sha256 );
5085
5086 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
5087
5088 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
5089}
5090#endif /* MBEDTLS_SHA256_C */
5091
5092#if defined(MBEDTLS_SHA512_C)
5093static void ssl_calc_finished_tls_sha384(
5094 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5095{
5096 int len = 12;
5097 const char *sender;
5098 mbedtls_sha512_context sha512;
5099 unsigned char padbuf[48];
5100
5101 mbedtls_ssl_session *session = ssl->session_negotiate;
5102 if( !session )
5103 session = ssl->session;
5104
5105 mbedtls_sha512_init( &sha512 );
5106
5107 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) );
5108
5109 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
5110
5111 /*
5112 * TLSv1.2:
5113 * hash = PRF( master, finished_label,
5114 * Hash( handshake ) )[0.11]
5115 */
5116
5117#if !defined(MBEDTLS_SHA512_ALT)
5118 MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
5119 sha512.state, sizeof( sha512.state ) );
5120#endif
5121
5122 sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5123 ? "client finished"
5124 : "server finished";
5125
5126 mbedtls_sha512_finish( &sha512, padbuf );
5127
5128 ssl->handshake->tls_prf( session->master, 48, sender,
5129 padbuf, 48, buf, len );
5130
5131 MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5132
5133 mbedtls_sha512_free( &sha512 );
5134
5135 mbedtls_zeroize( padbuf, sizeof( padbuf ) );
5136
5137 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
5138}
5139#endif /* MBEDTLS_SHA512_C */
5140#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5141
5142static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
5143{
5144 MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
5145
5146 /*
5147 * Free our handshake params
5148 */
5149 mbedtls_ssl_handshake_free( ssl->handshake );
5150 mbedtls_free( ssl->handshake );
5151 ssl->handshake = NULL;
5152
5153 /*
5154 * Free the previous transform and swith in the current one
5155 */
5156 if( ssl->transform )
5157 {
5158 mbedtls_ssl_transform_free( ssl->transform );
5159 mbedtls_free( ssl->transform );
5160 }
5161 ssl->transform = ssl->transform_negotiate;
5162 ssl->transform_negotiate = NULL;
5163
5164 MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
5165}
5166
5167void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
5168{
5169 int resume = ssl->handshake->resume;
5170
5171 MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
5172
5173#if defined(MBEDTLS_SSL_RENEGOTIATION)
5174 if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
5175 {
5176 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE;
5177 ssl->renego_records_seen = 0;
5178 }
5179#endif
5180
5181 /*
5182 * Free the previous session and switch in the current one
5183 */
5184 if( ssl->session )
5185 {
5186#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5187 /* RFC 7366 3.1: keep the EtM state */
5188 ssl->session_negotiate->encrypt_then_mac =
5189 ssl->session->encrypt_then_mac;
5190#endif
5191
5192 mbedtls_ssl_session_free( ssl->session );
5193 mbedtls_free( ssl->session );
5194 }
5195 ssl->session = ssl->session_negotiate;
5196 ssl->session_negotiate = NULL;
5197
5198 /*
5199 * Add cache entry
5200 */
5201 if( ssl->conf->f_set_cache != NULL &&
5202 ssl->session->id_len != 0 &&
5203 resume == 0 )
5204 {
5205 if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
5206 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
5207 }
5208
5209#if defined(MBEDTLS_SSL_PROTO_DTLS)
5210 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5211 ssl->handshake->flight != NULL )
5212 {
5213 /* Cancel handshake timer */
5214 ssl_set_timer( ssl, 0 );
5215
5216 /* Keep last flight around in case we need to resend it:
5217 * we need the handshake and transform structures for that */
5218 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
5219 }
5220 else
5221#endif
5222 ssl_handshake_wrapup_free_hs_transform( ssl );
5223
5224 ssl->state++;
5225
5226 MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
5227}
5228
5229int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
5230{
5231 int ret, hash_len;
5232
5233 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
5234
5235 /*
5236 * Set the out_msg pointer to the correct location based on IV length
5237 */
5238 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
5239 {
5240 ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -
5241 ssl->transform_negotiate->fixed_ivlen;
5242 }
5243 else
5244 ssl->out_msg = ssl->out_iv;
5245
5246 ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
5247
5248 /*
5249 * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
5250 * may define some other value. Currently (early 2016), no defined
5251 * ciphersuite does this (and this is unlikely to change as activity has
5252 * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
5253 */
5254 hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
5255
5256#if defined(MBEDTLS_SSL_RENEGOTIATION)
5257 ssl->verify_data_len = hash_len;
5258 memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
5259#endif
5260
5261 ssl->out_msglen = 4 + hash_len;
5262 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5263 ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED;
5264
5265 /*
5266 * In case of session resuming, invert the client and server
5267 * ChangeCipherSpec messages order.
5268 */
5269 if( ssl->handshake->resume != 0 )
5270 {
5271#if defined(MBEDTLS_SSL_CLI_C)
5272 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5273 ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5274#endif
5275#if defined(MBEDTLS_SSL_SRV_C)
5276 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5277 ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5278#endif
5279 }
5280 else
5281 ssl->state++;
5282
5283 /*
5284 * Switch to our negotiated transform and session parameters for outbound
5285 * data.
5286 */
5287 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
5288
5289#if defined(MBEDTLS_SSL_PROTO_DTLS)
5290 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5291 {
5292 unsigned char i;
5293
5294 /* Remember current epoch settings for resending */
5295 ssl->handshake->alt_transform_out = ssl->transform_out;
5296 memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 );
5297
5298 /* Set sequence_number to zero */
5299 memset( ssl->out_ctr + 2, 0, 6 );
5300
5301 /* Increment epoch */
5302 for( i = 2; i > 0; i-- )
5303 if( ++ssl->out_ctr[i - 1] != 0 )
5304 break;
5305
5306 /* The loop goes to its end iff the counter is wrapping */
5307 if( i == 0 )
5308 {
5309 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
5310 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
5311 }
5312 }
5313 else
5314#endif /* MBEDTLS_SSL_PROTO_DTLS */
5315 memset( ssl->out_ctr, 0, 8 );
5316
5317 ssl->transform_out = ssl->transform_negotiate;
5318 ssl->session_out = ssl->session_negotiate;
5319
5320#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5321 if( mbedtls_ssl_hw_record_activate != NULL )
5322 {
5323 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
5324 {
5325 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
5326 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5327 }
5328 }
5329#endif
5330
5331#if defined(MBEDTLS_SSL_PROTO_DTLS)
5332 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5333 mbedtls_ssl_send_flight_completed( ssl );
5334#endif
5335
5336 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
5337 {
5338 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5339 return( ret );
5340 }
5341
5342 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
5343
5344 return( 0 );
5345}
5346
5347#if defined(MBEDTLS_SSL_PROTO_SSL3)
5348#define SSL_MAX_HASH_LEN 36
5349#else
5350#define SSL_MAX_HASH_LEN 12
5351#endif
5352
5353int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
5354{
5355 int ret;
5356 unsigned int hash_len;
5357 unsigned char buf[SSL_MAX_HASH_LEN];
5358
5359 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
5360
5361 ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
5362
5363 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
5364 {
5365 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5366 return( ret );
5367 }
5368
5369 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
5370 {
5371 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5372 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5373 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
5374 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5375 }
5376
5377 /* There is currently no ciphersuite using another length with TLS 1.2 */
5378#if defined(MBEDTLS_SSL_PROTO_SSL3)
5379 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
5380 hash_len = 36;
5381 else
5382#endif
5383 hash_len = 12;
5384
5385 if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
5386 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
5387 {
5388 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5389 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5390 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
5391 return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5392 }
5393
5394 if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
5395 buf, hash_len ) != 0 )
5396 {
5397 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5398 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5399 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
5400 return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5401 }
5402
5403#if defined(MBEDTLS_SSL_RENEGOTIATION)
5404 ssl->verify_data_len = hash_len;
5405 memcpy( ssl->peer_verify_data, buf, hash_len );
5406#endif
5407
5408 if( ssl->handshake->resume != 0 )
5409 {
5410#if defined(MBEDTLS_SSL_CLI_C)
5411 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5412 ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5413#endif
5414#if defined(MBEDTLS_SSL_SRV_C)
5415 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5416 ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5417#endif
5418 }
5419 else
5420 ssl->state++;
5421
5422#if defined(MBEDTLS_SSL_PROTO_DTLS)
5423 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5424 mbedtls_ssl_recv_flight_completed( ssl );
5425#endif
5426
5427 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
5428
5429 return( 0 );
5430}
5431
5432static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
5433{
5434 memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
5435
5436#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5437 defined(MBEDTLS_SSL_PROTO_TLS1_1)
5438 mbedtls_md5_init( &handshake->fin_md5 );
5439 mbedtls_sha1_init( &handshake->fin_sha1 );
5440 mbedtls_md5_starts( &handshake->fin_md5 );
5441 mbedtls_sha1_starts( &handshake->fin_sha1 );
5442#endif
5443#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5444#if defined(MBEDTLS_SHA256_C)
5445 mbedtls_sha256_init( &handshake->fin_sha256 );
5446 mbedtls_sha256_starts( &handshake->fin_sha256, 0 );
5447#endif
5448#if defined(MBEDTLS_SHA512_C)
5449 mbedtls_sha512_init( &handshake->fin_sha512 );
5450 mbedtls_sha512_starts( &handshake->fin_sha512, 1 );
5451#endif
5452#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5453
5454 handshake->update_checksum = ssl_update_checksum_start;
5455
5456#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
5457 defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
5458 mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
5459#endif
5460
5461#if defined(MBEDTLS_DHM_C)
5462 mbedtls_dhm_init( &handshake->dhm_ctx );
5463#endif
5464#if defined(MBEDTLS_ECDH_C)
5465 mbedtls_ecdh_init( &handshake->ecdh_ctx );
5466#endif
5467#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5468 mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
5469#if defined(MBEDTLS_SSL_CLI_C)
5470 handshake->ecjpake_cache = NULL;
5471 handshake->ecjpake_cache_len = 0;
5472#endif
5473#endif
5474
5475#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5476 handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
5477#endif
5478}
5479
5480static void ssl_transform_init( mbedtls_ssl_transform *transform )
5481{
5482 memset( transform, 0, sizeof(mbedtls_ssl_transform) );
5483
5484 mbedtls_cipher_init( &transform->cipher_ctx_enc );
5485 mbedtls_cipher_init( &transform->cipher_ctx_dec );
5486
5487 mbedtls_md_init( &transform->md_ctx_enc );
5488 mbedtls_md_init( &transform->md_ctx_dec );
5489}
5490
5491void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
5492{
5493 memset( session, 0, sizeof(mbedtls_ssl_session) );
5494}
5495
5496static int ssl_handshake_init( mbedtls_ssl_context *ssl )
5497{
5498 /* Clear old handshake information if present */
5499 if( ssl->transform_negotiate )
5500 mbedtls_ssl_transform_free( ssl->transform_negotiate );
5501 if( ssl->session_negotiate )
5502 mbedtls_ssl_session_free( ssl->session_negotiate );
5503 if( ssl->handshake )
5504 mbedtls_ssl_handshake_free( ssl->handshake );
5505
5506 /*
5507 * Either the pointers are now NULL or cleared properly and can be freed.
5508 * Now allocate missing structures.
5509 */
5510 if( ssl->transform_negotiate == NULL )
5511 {
5512 ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
5513 }
5514
5515 if( ssl->session_negotiate == NULL )
5516 {
5517 ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
5518 }
5519
5520 if( ssl->handshake == NULL )
5521 {
5522 ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
5523 }
5524
5525 /* All pointers should exist and can be directly freed without issue */
5526 if( ssl->handshake == NULL ||
5527 ssl->transform_negotiate == NULL ||
5528 ssl->session_negotiate == NULL )
5529 {
5530 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
5531
5532 mbedtls_free( ssl->handshake );
5533 mbedtls_free( ssl->transform_negotiate );
5534 mbedtls_free( ssl->session_negotiate );
5535
5536 ssl->handshake = NULL;
5537 ssl->transform_negotiate = NULL;
5538 ssl->session_negotiate = NULL;
5539
5540 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5541 }
5542
5543 /* Initialize structures */
5544 mbedtls_ssl_session_init( ssl->session_negotiate );
5545 ssl_transform_init( ssl->transform_negotiate );
5546 ssl_handshake_params_init( ssl->handshake );
5547
5548#if defined(MBEDTLS_SSL_PROTO_DTLS)
5549 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5550 {
5551 ssl->handshake->alt_transform_out = ssl->transform_out;
5552
5553 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5554 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
5555 else
5556 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
5557
5558 ssl_set_timer( ssl, 0 );
5559 }
5560#endif
5561
5562 return( 0 );
5563}
5564
5565#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5566/* Dummy cookie callbacks for defaults */
5567static int ssl_cookie_write_dummy( void *ctx,
5568 unsigned char **p, unsigned char *end,
5569 const unsigned char *cli_id, size_t cli_id_len )
5570{
5571 ((void) ctx);
5572 ((void) p);
5573 ((void) end);
5574 ((void) cli_id);
5575 ((void) cli_id_len);
5576
5577 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5578}
5579
5580static int ssl_cookie_check_dummy( void *ctx,
5581 const unsigned char *cookie, size_t cookie_len,
5582 const unsigned char *cli_id, size_t cli_id_len )
5583{
5584 ((void) ctx);
5585 ((void) cookie);
5586 ((void) cookie_len);
5587 ((void) cli_id);
5588 ((void) cli_id_len);
5589
5590 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5591}
5592#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
5593
5594/*
5595 * Initialize an SSL context
5596 */
5597void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
5598{
5599 memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
5600}
5601
5602/*
5603 * Setup an SSL context
5604 */
5605int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
5606 const mbedtls_ssl_config *conf )
5607{
5608 int ret;
5609 const size_t len = MBEDTLS_SSL_BUFFER_LEN;
5610
5611 ssl->conf = conf;
5612
5613 /*
5614 * Prepare base structures
5615 */
5616 if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL ||
5617 ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL )
5618 {
5619 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) );
5620 mbedtls_free( ssl->in_buf );
5621 ssl->in_buf = NULL;
5622 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5623 }
5624
5625#if defined(MBEDTLS_SSL_PROTO_DTLS)
5626 if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5627 {
5628 ssl->out_hdr = ssl->out_buf;
5629 ssl->out_ctr = ssl->out_buf + 3;
5630 ssl->out_len = ssl->out_buf + 11;
5631 ssl->out_iv = ssl->out_buf + 13;
5632 ssl->out_msg = ssl->out_buf + 13;
5633
5634 ssl->in_hdr = ssl->in_buf;
5635 ssl->in_ctr = ssl->in_buf + 3;
5636 ssl->in_len = ssl->in_buf + 11;
5637 ssl->in_iv = ssl->in_buf + 13;
5638 ssl->in_msg = ssl->in_buf + 13;
5639 }
5640 else
5641#endif
5642 {
5643 ssl->out_ctr = ssl->out_buf;
5644 ssl->out_hdr = ssl->out_buf + 8;
5645 ssl->out_len = ssl->out_buf + 11;
5646 ssl->out_iv = ssl->out_buf + 13;
5647 ssl->out_msg = ssl->out_buf + 13;
5648
5649 ssl->in_ctr = ssl->in_buf;
5650 ssl->in_hdr = ssl->in_buf + 8;
5651 ssl->in_len = ssl->in_buf + 11;
5652 ssl->in_iv = ssl->in_buf + 13;
5653 ssl->in_msg = ssl->in_buf + 13;
5654 }
5655
5656 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5657 return( ret );
5658
5659 return( 0 );
5660}
5661
5662/*
5663 * Reset an initialized and used SSL context for re-use while retaining
5664 * all application-set variables, function pointers and data.
5665 *
5666 * If partial is non-zero, keep data in the input buffer and client ID.
5667 * (Use when a DTLS client reconnects from the same port.)
5668 */
5669static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
5670{
5671 int ret;
5672
5673 ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5674
5675 /* Cancel any possibly running timer */
5676 ssl_set_timer( ssl, 0 );
5677
5678#if defined(MBEDTLS_SSL_RENEGOTIATION)
5679 ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
5680 ssl->renego_records_seen = 0;
5681
5682 ssl->verify_data_len = 0;
5683 memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5684 memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5685#endif
5686 ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
5687
5688 ssl->in_offt = NULL;
5689
5690 ssl->in_msg = ssl->in_buf + 13;
5691 ssl->in_msgtype = 0;
5692 ssl->in_msglen = 0;
5693 if( partial == 0 )
5694 ssl->in_left = 0;
5695#if defined(MBEDTLS_SSL_PROTO_DTLS)
5696 ssl->next_record_offset = 0;
5697 ssl->in_epoch = 0;
5698#endif
5699#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5700 ssl_dtls_replay_reset( ssl );
5701#endif
5702
5703 ssl->in_hslen = 0;
5704 ssl->nb_zero = 0;
5705
5706 ssl->keep_current_message = 0;
5707
5708 ssl->out_msg = ssl->out_buf + 13;
5709 ssl->out_msgtype = 0;
5710 ssl->out_msglen = 0;
5711 ssl->out_left = 0;
5712#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
5713 if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
5714 ssl->split_done = 0;
5715#endif
5716
5717 ssl->transform_in = NULL;
5718 ssl->transform_out = NULL;
5719
5720 memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5721 if( partial == 0 )
5722 memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5723
5724#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5725 if( mbedtls_ssl_hw_record_reset != NULL )
5726 {
5727 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
5728 if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
5729 {
5730 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
5731 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5732 }
5733 }
5734#endif
5735
5736 if( ssl->transform )
5737 {
5738 mbedtls_ssl_transform_free( ssl->transform );
5739 mbedtls_free( ssl->transform );
5740 ssl->transform = NULL;
5741 }
5742
5743 if( ssl->session )
5744 {
5745 mbedtls_ssl_session_free( ssl->session );
5746 mbedtls_free( ssl->session );
5747 ssl->session = NULL;
5748 }
5749
5750#if defined(MBEDTLS_SSL_ALPN)
5751 ssl->alpn_chosen = NULL;
5752#endif
5753
5754#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5755 if( partial == 0 )
5756 {
5757 mbedtls_free( ssl->cli_id );
5758 ssl->cli_id = NULL;
5759 ssl->cli_id_len = 0;
5760 }
5761#endif
5762
5763 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5764 return( ret );
5765
5766 return( 0 );
5767}
5768
5769/*
5770 * Reset an initialized and used SSL context for re-use while retaining
5771 * all application-set variables, function pointers and data.
5772 */
5773int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
5774{
5775 return( ssl_session_reset_int( ssl, 0 ) );
5776}
5777
5778/*
5779 * SSL set accessors
5780 */
5781void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
5782{
5783 conf->endpoint = endpoint;
5784}
5785
5786void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
5787{
5788 conf->transport = transport;
5789}
5790
5791#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5792void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
5793{
5794 conf->anti_replay = mode;
5795}
5796#endif
5797
5798#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
5799void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
5800{
5801 conf->badmac_limit = limit;
5802}
5803#endif
5804
5805#if defined(MBEDTLS_SSL_PROTO_DTLS)
5806void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max )
5807{
5808 conf->hs_timeout_min = min;
5809 conf->hs_timeout_max = max;
5810}
5811#endif
5812
5813void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
5814{
5815 conf->authmode = authmode;
5816}
5817
5818#if defined(MBEDTLS_X509_CRT_PARSE_C)
5819void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
5820 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
5821 void *p_vrfy )
5822{
5823 conf->f_vrfy = f_vrfy;
5824 conf->p_vrfy = p_vrfy;
5825}
5826#endif /* MBEDTLS_X509_CRT_PARSE_C */
5827
5828void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
5829 int (*f_rng)(void *, unsigned char *, size_t),
5830 void *p_rng )
5831{
5832 conf->f_rng = f_rng;
5833 conf->p_rng = p_rng;
5834}
5835
5836void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
5837 void (*f_dbg)(void *, int, const char *, int, const char *),
5838 void *p_dbg )
5839{
5840 conf->f_dbg = f_dbg;
5841 conf->p_dbg = p_dbg;
5842}
5843
5844void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
5845 void *p_bio,
5846 mbedtls_ssl_send_t *f_send,
5847 mbedtls_ssl_recv_t *f_recv,
5848 mbedtls_ssl_recv_timeout_t *f_recv_timeout )
5849{
5850 ssl->p_bio = p_bio;
5851 ssl->f_send = f_send;
5852 ssl->f_recv = f_recv;
5853 ssl->f_recv_timeout = f_recv_timeout;
5854}
5855
5856void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
5857{
5858 conf->read_timeout = timeout;
5859}
5860
5861void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
5862 void *p_timer,
5863 mbedtls_ssl_set_timer_t *f_set_timer,
5864 mbedtls_ssl_get_timer_t *f_get_timer )
5865{
5866 ssl->p_timer = p_timer;
5867 ssl->f_set_timer = f_set_timer;
5868 ssl->f_get_timer = f_get_timer;
5869
5870 /* Make sure we start with no timer running */
5871 ssl_set_timer( ssl, 0 );
5872}
5873
5874#if defined(MBEDTLS_SSL_SRV_C)
5875void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
5876 void *p_cache,
5877 int (*f_get_cache)(void *, mbedtls_ssl_session *),
5878 int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
5879{
5880 conf->p_cache = p_cache;
5881 conf->f_get_cache = f_get_cache;
5882 conf->f_set_cache = f_set_cache;
5883}
5884#endif /* MBEDTLS_SSL_SRV_C */
5885
5886#if defined(MBEDTLS_SSL_CLI_C)
5887int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
5888{
5889 int ret;
5890
5891 if( ssl == NULL ||
5892 session == NULL ||
5893 ssl->session_negotiate == NULL ||
5894 ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
5895 {
5896 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5897 }
5898
5899 if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
5900 return( ret );
5901
5902 ssl->handshake->resume = 1;
5903
5904 return( 0 );
5905}
5906#endif /* MBEDTLS_SSL_CLI_C */
5907
5908void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
5909 const int *ciphersuites )
5910{
5911 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
5912 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
5913 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
5914 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
5915}
5916
5917void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
5918 const int *ciphersuites,
5919 int major, int minor )
5920{
5921 if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
5922 return;
5923
5924 if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
5925 return;
5926
5927 conf->ciphersuite_list[minor] = ciphersuites;
5928}
5929
5930#if defined(MBEDTLS_X509_CRT_PARSE_C)
5931void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
5932 const mbedtls_x509_crt_profile *profile )
5933{
5934 conf->cert_profile = profile;
5935}
5936
5937/* Append a new keycert entry to a (possibly empty) list */
5938static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
5939 mbedtls_x509_crt *cert,
5940 mbedtls_pk_context *key )
5941{
5942 mbedtls_ssl_key_cert *new;
5943
5944 new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
5945 if( new == NULL )
5946 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5947
5948 new->cert = cert;
5949 new->key = key;
5950 new->next = NULL;
5951
5952 /* Update head is the list was null, else add to the end */
5953 if( *head == NULL )
5954 {
5955 *head = new;
5956 }
5957 else
5958 {
5959 mbedtls_ssl_key_cert *cur = *head;
5960 while( cur->next != NULL )
5961 cur = cur->next;
5962 cur->next = new;
5963 }
5964
5965 return( 0 );
5966}
5967
5968int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
5969 mbedtls_x509_crt *own_cert,
5970 mbedtls_pk_context *pk_key )
5971{
5972 return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
5973}
5974
5975void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
5976 mbedtls_x509_crt *ca_chain,
5977 mbedtls_x509_crl *ca_crl )
5978{
5979 conf->ca_chain = ca_chain;
5980 conf->ca_crl = ca_crl;
5981}
5982#endif /* MBEDTLS_X509_CRT_PARSE_C */
5983
5984#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5985int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
5986 mbedtls_x509_crt *own_cert,
5987 mbedtls_pk_context *pk_key )
5988{
5989 return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
5990 own_cert, pk_key ) );
5991}
5992
5993void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
5994 mbedtls_x509_crt *ca_chain,
5995 mbedtls_x509_crl *ca_crl )
5996{
5997 ssl->handshake->sni_ca_chain = ca_chain;
5998 ssl->handshake->sni_ca_crl = ca_crl;
5999}
6000
6001void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
6002 int authmode )
6003{
6004 ssl->handshake->sni_authmode = authmode;
6005}
6006#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6007
6008#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6009/*
6010 * Set EC J-PAKE password for current handshake
6011 */
6012int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
6013 const unsigned char *pw,
6014 size_t pw_len )
6015{
6016 mbedtls_ecjpake_role role;
6017
6018 if( ssl->handshake == NULL || ssl->conf == NULL )
6019 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6020
6021 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6022 role = MBEDTLS_ECJPAKE_SERVER;
6023 else
6024 role = MBEDTLS_ECJPAKE_CLIENT;
6025
6026 return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
6027 role,
6028 MBEDTLS_MD_SHA256,
6029 MBEDTLS_ECP_DP_SECP256R1,
6030 pw, pw_len ) );
6031}
6032#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
6033
6034#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
6035int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
6036 const unsigned char *psk, size_t psk_len,
6037 const unsigned char *psk_identity, size_t psk_identity_len )
6038{
6039 if( psk == NULL || psk_identity == NULL )
6040 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6041
6042 if( psk_len > MBEDTLS_PSK_MAX_LEN )
6043 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6044
6045 /* Identity len will be encoded on two bytes */
6046 if( ( psk_identity_len >> 16 ) != 0 ||
6047 psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN )
6048 {
6049 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6050 }
6051
6052 if( conf->psk != NULL || conf->psk_identity != NULL )
6053 {
6054 mbedtls_free( conf->psk );
6055 mbedtls_free( conf->psk_identity );
6056 conf->psk = NULL;
6057 conf->psk_identity = NULL;
6058 }
6059
6060 if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
6061 ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
6062 {
6063 mbedtls_free( conf->psk );
6064 mbedtls_free( conf->psk_identity );
6065 conf->psk = NULL;
6066 conf->psk_identity = NULL;
6067 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6068 }
6069
6070 conf->psk_len = psk_len;
6071 conf->psk_identity_len = psk_identity_len;
6072
6073 memcpy( conf->psk, psk, conf->psk_len );
6074 memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
6075
6076 return( 0 );
6077}
6078
6079int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
6080 const unsigned char *psk, size_t psk_len )
6081{
6082 if( psk == NULL || ssl->handshake == NULL )
6083 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6084
6085 if( psk_len > MBEDTLS_PSK_MAX_LEN )
6086 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6087
6088 if( ssl->handshake->psk != NULL )
6089 mbedtls_free( ssl->handshake->psk );
6090
6091 if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
6092 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6093
6094 ssl->handshake->psk_len = psk_len;
6095 memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
6096
6097 return( 0 );
6098}
6099
6100void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
6101 int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
6102 size_t),
6103 void *p_psk )
6104{
6105 conf->f_psk = f_psk;
6106 conf->p_psk = p_psk;
6107}
6108#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
6109
6110#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6111int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
6112{
6113 int ret;
6114
6115 if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
6116 ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
6117 {
6118 mbedtls_mpi_free( &conf->dhm_P );
6119 mbedtls_mpi_free( &conf->dhm_G );
6120 return( ret );
6121 }
6122
6123 return( 0 );
6124}
6125
6126int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
6127{
6128 int ret;
6129
6130 if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
6131 ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
6132 {
6133 mbedtls_mpi_free( &conf->dhm_P );
6134 mbedtls_mpi_free( &conf->dhm_G );
6135 return( ret );
6136 }
6137
6138 return( 0 );
6139}
6140#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
6141
6142#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
6143/*
6144 * Set the minimum length for Diffie-Hellman parameters
6145 */
6146void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
6147 unsigned int bitlen )
6148{
6149 conf->dhm_min_bitlen = bitlen;
6150}
6151#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
6152
6153#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
6154/*
6155 * Set allowed/preferred hashes for handshake signatures
6156 */
6157void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
6158 const int *hashes )
6159{
6160 conf->sig_hashes = hashes;
6161}
6162#endif
6163
6164#if defined(MBEDTLS_ECP_C)
6165/*
6166 * Set the allowed elliptic curves
6167 */
6168void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
6169 const mbedtls_ecp_group_id *curve_list )
6170{
6171 conf->curve_list = curve_list;
6172}
6173#endif
6174
6175#if defined(MBEDTLS_X509_CRT_PARSE_C)
6176int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
6177{
6178 size_t hostname_len;
6179
6180 if( hostname == NULL )
6181 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6182
6183 hostname_len = strlen( hostname );
6184
6185 if( hostname_len + 1 == 0 )
6186 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6187
6188 if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
6189 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6190
6191 ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
6192
6193 if( ssl->hostname == NULL )
6194 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6195
6196 memcpy( ssl->hostname, hostname, hostname_len );
6197
6198 ssl->hostname[hostname_len] = '\0';
6199
6200 return( 0 );
6201}
6202#endif
6203
6204#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
6205void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
6206 int (*f_sni)(void *, mbedtls_ssl_context *,
6207 const unsigned char *, size_t),
6208 void *p_sni )
6209{
6210 conf->f_sni = f_sni;
6211 conf->p_sni = p_sni;
6212}
6213#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6214
6215#if defined(MBEDTLS_SSL_ALPN)
6216int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
6217{
6218 size_t cur_len, tot_len;
6219 const char **p;
6220
6221 /*
6222 * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
6223 * MUST NOT be truncated."
6224 * We check lengths now rather than later.
6225 */
6226 tot_len = 0;
6227 for( p = protos; *p != NULL; p++ )
6228 {
6229 cur_len = strlen( *p );
6230 tot_len += cur_len;
6231
6232 if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
6233 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6234 }
6235
6236 conf->alpn_list = protos;
6237
6238 return( 0 );
6239}
6240
6241const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
6242{
6243 return( ssl->alpn_chosen );
6244}
6245#endif /* MBEDTLS_SSL_ALPN */
6246
6247void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
6248{
6249 conf->max_major_ver = major;
6250 conf->max_minor_ver = minor;
6251}
6252
6253void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
6254{
6255 conf->min_major_ver = major;
6256 conf->min_minor_ver = minor;
6257}
6258
6259#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
6260void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
6261{
6262 conf->fallback = fallback;
6263}
6264#endif
6265
6266#if defined(MBEDTLS_SSL_SRV_C)
6267void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
6268 char cert_req_ca_list )
6269{
6270 conf->cert_req_ca_list = cert_req_ca_list;
6271}
6272#endif
6273
6274#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6275void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
6276{
6277 conf->encrypt_then_mac = etm;
6278}
6279#endif
6280
6281#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6282void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
6283{
6284 conf->extended_ms = ems;
6285}
6286#endif
6287
6288#if defined(MBEDTLS_ARC4_C)
6289void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
6290{
6291 conf->arc4_disabled = arc4;
6292}
6293#endif
6294
6295#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6296int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
6297{
6298 if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
6299 mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN )
6300 {
6301 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6302 }
6303
6304 conf->mfl_code = mfl_code;
6305
6306 return( 0 );
6307}
6308#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6309
6310#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
6311void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
6312{
6313 conf->trunc_hmac = truncate;
6314}
6315#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
6316
6317#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6318void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
6319{
6320 conf->cbc_record_splitting = split;
6321}
6322#endif
6323
6324void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
6325{
6326 conf->allow_legacy_renegotiation = allow_legacy;
6327}
6328
6329#if defined(MBEDTLS_SSL_RENEGOTIATION)
6330void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
6331{
6332 conf->disable_renegotiation = renegotiation;
6333}
6334
6335void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
6336{
6337 conf->renego_max_records = max_records;
6338}
6339
6340void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
6341 const unsigned char period[8] )
6342{
6343 memcpy( conf->renego_period, period, 8 );
6344}
6345#endif /* MBEDTLS_SSL_RENEGOTIATION */
6346
6347#if defined(MBEDTLS_SSL_SESSION_TICKETS)
6348#if defined(MBEDTLS_SSL_CLI_C)
6349void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
6350{
6351 conf->session_tickets = use_tickets;
6352}
6353#endif
6354
6355#if defined(MBEDTLS_SSL_SRV_C)
6356void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
6357 mbedtls_ssl_ticket_write_t *f_ticket_write,
6358 mbedtls_ssl_ticket_parse_t *f_ticket_parse,
6359 void *p_ticket )
6360{
6361 conf->f_ticket_write = f_ticket_write;
6362 conf->f_ticket_parse = f_ticket_parse;
6363 conf->p_ticket = p_ticket;
6364}
6365#endif
6366#endif /* MBEDTLS_SSL_SESSION_TICKETS */
6367
6368#if defined(MBEDTLS_SSL_EXPORT_KEYS)
6369void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
6370 mbedtls_ssl_export_keys_t *f_export_keys,
6371 void *p_export_keys )
6372{
6373 conf->f_export_keys = f_export_keys;
6374 conf->p_export_keys = p_export_keys;
6375}
6376#endif
6377
6378/*
6379 * SSL get accessors
6380 */
6381size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
6382{
6383 return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
6384}
6385
6386uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
6387{
6388 if( ssl->session != NULL )
6389 return( ssl->session->verify_result );
6390
6391 if( ssl->session_negotiate != NULL )
6392 return( ssl->session_negotiate->verify_result );
6393
6394 return( 0xFFFFFFFF );
6395}
6396
6397const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
6398{
6399 if( ssl == NULL || ssl->session == NULL )
6400 return( NULL );
6401
6402 return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
6403}
6404
6405const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
6406{
6407#if defined(MBEDTLS_SSL_PROTO_DTLS)
6408 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6409 {
6410 switch( ssl->minor_ver )
6411 {
6412 case MBEDTLS_SSL_MINOR_VERSION_2:
6413 return( "DTLSv1.0" );
6414
6415 case MBEDTLS_SSL_MINOR_VERSION_3:
6416 return( "DTLSv1.2" );
6417
6418 default:
6419 return( "unknown (DTLS)" );
6420 }
6421 }
6422#endif
6423
6424 switch( ssl->minor_ver )
6425 {
6426 case MBEDTLS_SSL_MINOR_VERSION_0:
6427 return( "SSLv3.0" );
6428
6429 case MBEDTLS_SSL_MINOR_VERSION_1:
6430 return( "TLSv1.0" );
6431
6432 case MBEDTLS_SSL_MINOR_VERSION_2:
6433 return( "TLSv1.1" );
6434
6435 case MBEDTLS_SSL_MINOR_VERSION_3:
6436 return( "TLSv1.2" );
6437
6438 default:
6439 return( "unknown" );
6440 }
6441}
6442
6443int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
6444{
6445 size_t transform_expansion;
6446 const mbedtls_ssl_transform *transform = ssl->transform_out;
6447
6448#if defined(MBEDTLS_ZLIB_SUPPORT)
6449 if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
6450 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
6451#endif
6452
6453 if( transform == NULL )
6454 return( (int) mbedtls_ssl_hdr_len( ssl ) );
6455
6456 switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
6457 {
6458 case MBEDTLS_MODE_GCM:
6459 case MBEDTLS_MODE_CCM:
6460 case MBEDTLS_MODE_STREAM:
6461 transform_expansion = transform->minlen;
6462 break;
6463
6464 case MBEDTLS_MODE_CBC:
6465 transform_expansion = transform->maclen
6466 + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc );
6467 break;
6468
6469 default:
6470 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6471 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6472 }
6473
6474 return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
6475}
6476
6477#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6478size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
6479{
6480 size_t max_len;
6481
6482 /*
6483 * Assume mfl_code is correct since it was checked when set
6484 */
6485 max_len = mfl_code_to_length[ssl->conf->mfl_code];
6486
6487 /*
6488 * Check if a smaller max length was negotiated
6489 */
6490 if( ssl->session_out != NULL &&
6491 mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
6492 {
6493 max_len = mfl_code_to_length[ssl->session_out->mfl_code];
6494 }
6495
6496 return max_len;
6497}
6498#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6499
6500#if defined(MBEDTLS_X509_CRT_PARSE_C)
6501const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
6502{
6503 if( ssl == NULL || ssl->session == NULL )
6504 return( NULL );
6505
6506 return( ssl->session->peer_cert );
6507}
6508#endif /* MBEDTLS_X509_CRT_PARSE_C */
6509
6510#if defined(MBEDTLS_SSL_CLI_C)
6511int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
6512{
6513 if( ssl == NULL ||
6514 dst == NULL ||
6515 ssl->session == NULL ||
6516 ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
6517 {
6518 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6519 }
6520
6521 return( ssl_session_copy( dst, ssl->session ) );
6522}
6523#endif /* MBEDTLS_SSL_CLI_C */
6524
6525/*
6526 * Perform a single step of the SSL handshake
6527 */
6528int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
6529{
6530 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6531
6532 if( ssl == NULL || ssl->conf == NULL )
6533 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6534
6535#if defined(MBEDTLS_SSL_CLI_C)
6536 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6537 ret = mbedtls_ssl_handshake_client_step( ssl );
6538#endif
6539#if defined(MBEDTLS_SSL_SRV_C)
6540 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6541 ret = mbedtls_ssl_handshake_server_step( ssl );
6542#endif
6543
6544 return( ret );
6545}
6546
6547/*
6548 * Perform the SSL handshake
6549 */
6550int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
6551{
6552 int ret = 0;
6553
6554 if( ssl == NULL || ssl->conf == NULL )
6555 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6556
6557 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
6558
6559 while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6560 {
6561 ret = mbedtls_ssl_handshake_step( ssl );
6562
6563 if( ret != 0 )
6564 break;
6565 }
6566
6567 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
6568
6569 return( ret );
6570}
6571
6572#if defined(MBEDTLS_SSL_RENEGOTIATION)
6573#if defined(MBEDTLS_SSL_SRV_C)
6574/*
6575 * Write HelloRequest to request renegotiation on server
6576 */
6577static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
6578{
6579 int ret;
6580
6581 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
6582
6583 ssl->out_msglen = 4;
6584 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
6585 ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST;
6586
6587 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6588 {
6589 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6590 return( ret );
6591 }
6592
6593 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
6594
6595 return( 0 );
6596}
6597#endif /* MBEDTLS_SSL_SRV_C */
6598
6599/*
6600 * Actually renegotiate current connection, triggered by either:
6601 * - any side: calling mbedtls_ssl_renegotiate(),
6602 * - client: receiving a HelloRequest during mbedtls_ssl_read(),
6603 * - server: receiving any handshake message on server during mbedtls_ssl_read() after
6604 * the initial handshake is completed.
6605 * If the handshake doesn't complete due to waiting for I/O, it will continue
6606 * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
6607 */
6608static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
6609{
6610 int ret;
6611
6612 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
6613
6614 if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
6615 return( ret );
6616
6617 /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
6618 * the ServerHello will have message_seq = 1" */
6619#if defined(MBEDTLS_SSL_PROTO_DTLS)
6620 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6621 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6622 {
6623 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6624 ssl->handshake->out_msg_seq = 1;
6625 else
6626 ssl->handshake->in_msg_seq = 1;
6627 }
6628#endif
6629
6630 ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
6631 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
6632
6633 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6634 {
6635 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6636 return( ret );
6637 }
6638
6639 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
6640
6641 return( 0 );
6642}
6643
6644/*
6645 * Renegotiate current connection on client,
6646 * or request renegotiation on server
6647 */
6648int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
6649{
6650 int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6651
6652 if( ssl == NULL || ssl->conf == NULL )
6653 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6654
6655#if defined(MBEDTLS_SSL_SRV_C)
6656 /* On server, just send the request */
6657 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6658 {
6659 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6660 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6661
6662 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6663
6664 /* Did we already try/start sending HelloRequest? */
6665 if( ssl->out_left != 0 )
6666 return( mbedtls_ssl_flush_output( ssl ) );
6667
6668 return( ssl_write_hello_request( ssl ) );
6669 }
6670#endif /* MBEDTLS_SSL_SRV_C */
6671
6672#if defined(MBEDTLS_SSL_CLI_C)
6673 /*
6674 * On client, either start the renegotiation process or,
6675 * if already in progress, continue the handshake
6676 */
6677 if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
6678 {
6679 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6680 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6681
6682 if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
6683 {
6684 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6685 return( ret );
6686 }
6687 }
6688 else
6689 {
6690 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6691 {
6692 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6693 return( ret );
6694 }
6695 }
6696#endif /* MBEDTLS_SSL_CLI_C */
6697
6698 return( ret );
6699}
6700
6701/*
6702 * Check record counters and renegotiate if they're above the limit.
6703 */
6704static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
6705{
6706 size_t ep_len = ssl_ep_len( ssl );
6707 int in_ctr_cmp;
6708 int out_ctr_cmp;
6709
6710 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
6711 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
6712 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
6713 {
6714 return( 0 );
6715 }
6716
6717 in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
6718 ssl->conf->renego_period + ep_len, 8 - ep_len );
6719 out_ctr_cmp = memcmp( ssl->out_ctr + ep_len,
6720 ssl->conf->renego_period + ep_len, 8 - ep_len );
6721
6722 if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
6723 {
6724 return( 0 );
6725 }
6726
6727 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
6728 return( mbedtls_ssl_renegotiate( ssl ) );
6729}
6730#endif /* MBEDTLS_SSL_RENEGOTIATION */
6731
6732/*
6733 * Receive application data decrypted from the SSL layer
6734 */
6735int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
6736{
6737 int ret;
6738 size_t n;
6739
6740 if( ssl == NULL || ssl->conf == NULL )
6741 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6742
6743 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
6744
6745#if defined(MBEDTLS_SSL_PROTO_DTLS)
6746 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6747 {
6748 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
6749 return( ret );
6750
6751 if( ssl->handshake != NULL &&
6752 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
6753 {
6754 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
6755 return( ret );
6756 }
6757 }
6758#endif
6759
6760 /*
6761 * Check if renegotiation is necessary and/or handshake is
6762 * in process. If yes, perform/continue, and fall through
6763 * if an unexpected packet is received while the client
6764 * is waiting for the ServerHello.
6765 *
6766 * (There is no equivalent to the last condition on
6767 * the server-side as it is not treated as within
6768 * a handshake while waiting for the ClientHello
6769 * after a renegotiation request.)
6770 */
6771
6772#if defined(MBEDTLS_SSL_RENEGOTIATION)
6773 ret = ssl_check_ctr_renegotiate( ssl );
6774 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
6775 ret != 0 )
6776 {
6777 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
6778 return( ret );
6779 }
6780#endif
6781
6782 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6783 {
6784 ret = mbedtls_ssl_handshake( ssl );
6785 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
6786 ret != 0 )
6787 {
6788 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6789 return( ret );
6790 }
6791 }
6792
6793 /*
6794 * TODO
6795 *
6796 * The logic should be streamlined here:
6797 *
6798 * Instead of
6799 *
6800 * - Manually checking whether ssl->in_offt is NULL
6801 * - Fetching a new record if yes
6802 * - Setting ssl->in_offt if one finds an application record
6803 * - Resetting keep_current_message after handling the application data
6804 *
6805 * one should
6806 *
6807 * - Adapt read_record to set ssl->in_offt automatically
6808 * when a new application data record is processed.
6809 * - Always call mbedtls_ssl_read_record here.
6810 *
6811 * This way, the logic of ssl_read would be much clearer:
6812 *
6813 * (1) Always call record layer and see what kind of record is on
6814 * and have it ready for consumption (in particular, in_offt
6815 * properly set for application data records).
6816 * (2) If it's application data (either freshly fetched
6817 * or something already being partially processed),
6818 * serve the read request from it.
6819 * (3) If it's something different from application data,
6820 * handle it accordingly, e.g. potentially start a
6821 * renegotiation.
6822 *
6823 * This will also remove the need to manually reset
6824 * ssl->keep_current_message = 0 below.
6825 *
6826 */
6827
6828 if( ssl->in_offt == NULL )
6829 {
6830 /* Start timer if not already running */
6831 if( ssl->f_get_timer != NULL &&
6832 ssl->f_get_timer( ssl->p_timer ) == -1 )
6833 {
6834 ssl_set_timer( ssl, ssl->conf->read_timeout );
6835 }
6836
6837 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6838 {
6839 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6840 return( 0 );
6841
6842 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6843 return( ret );
6844 }
6845
6846 if( ssl->in_msglen == 0 &&
6847 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
6848 {
6849 /*
6850 * OpenSSL sends empty messages to randomize the IV
6851 */
6852 if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6853 {
6854 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6855 return( 0 );
6856
6857 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6858 return( ret );
6859 }
6860 }
6861
6862#if defined(MBEDTLS_SSL_RENEGOTIATION)
6863 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
6864 {
6865 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
6866
6867 /*
6868 * - For client-side, expect SERVER_HELLO_REQUEST.
6869 * - For server-side, expect CLIENT_HELLO.
6870 * - Fail (TLS) or silently drop record (DTLS) in other cases.
6871 */
6872
6873#if defined(MBEDTLS_SSL_CLI_C)
6874 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
6875 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
6876 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
6877 {
6878 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
6879
6880 /* With DTLS, drop the packet (probably from last handshake) */
6881#if defined(MBEDTLS_SSL_PROTO_DTLS)
6882 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6883 return( MBEDTLS_ERR_SSL_WANT_READ );
6884#endif
6885 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6886 }
6887#endif /* MBEDTLS_SSL_CLI_C */
6888
6889#if defined(MBEDTLS_SSL_SRV_C)
6890 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6891 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
6892 {
6893 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
6894
6895 /* With DTLS, drop the packet (probably from last handshake) */
6896#if defined(MBEDTLS_SSL_PROTO_DTLS)
6897 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6898 return( MBEDTLS_ERR_SSL_WANT_READ );
6899#endif
6900 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6901 }
6902#endif /* MBEDTLS_SSL_SRV_C */
6903
6904 /* Determine whether renegotiation attempt should be accepted */
6905
6906 if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
6907 ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
6908 ssl->conf->allow_legacy_renegotiation ==
6909 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) )
6910 {
6911 /*
6912 * Refuse renegotiation
6913 */
6914
6915 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
6916
6917#if defined(MBEDTLS_SSL_PROTO_SSL3)
6918 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
6919 {
6920 /* SSLv3 does not have a "no_renegotiation" warning, so
6921 we send a fatal alert and abort the connection. */
6922 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6923 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
6924 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6925 }
6926 else
6927#endif /* MBEDTLS_SSL_PROTO_SSL3 */
6928#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
6929 defined(MBEDTLS_SSL_PROTO_TLS1_2)
6930 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
6931 {
6932 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
6933 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6934 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
6935 {
6936 return( ret );
6937 }
6938 }
6939 else
6940#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
6941 MBEDTLS_SSL_PROTO_TLS1_2 */
6942 {
6943 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6944 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6945 }
6946 }
6947 else
6948 {
6949 /*
6950 * Accept renegotiation request
6951 */
6952
6953 /* DTLS clients need to know renego is server-initiated */
6954#if defined(MBEDTLS_SSL_PROTO_DTLS)
6955 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6956 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6957 {
6958 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6959 }
6960#endif
6961 ret = ssl_start_renegotiation( ssl );
6962 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
6963 ret != 0 )
6964 {
6965 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6966 return( ret );
6967 }
6968 }
6969
6970 return( MBEDTLS_ERR_SSL_WANT_READ );
6971 }
6972 else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6973 {
6974 if( ssl->conf->renego_max_records >= 0 )
6975 {
6976 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
6977 {
6978 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
6979 "but not honored by client" ) );
6980 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6981 }
6982 }
6983 }
6984#endif /* MBEDTLS_SSL_RENEGOTIATION */
6985
6986 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
6987 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
6988 {
6989 MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
6990 return( MBEDTLS_ERR_SSL_WANT_READ );
6991 }
6992
6993 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
6994 {
6995 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
6996 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6997 }
6998
6999 ssl->in_offt = ssl->in_msg;
7000
7001 /* We're going to return something now, cancel timer,
7002 * except if handshake (renegotiation) is in progress */
7003 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
7004 ssl_set_timer( ssl, 0 );
7005
7006#if defined(MBEDTLS_SSL_PROTO_DTLS)
7007 /* If we requested renego but received AppData, resend HelloRequest.
7008 * Do it now, after setting in_offt, to avoid taking this branch
7009 * again if ssl_write_hello_request() returns WANT_WRITE */
7010#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
7011 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
7012 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
7013 {
7014 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
7015 {
7016 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
7017 return( ret );
7018 }
7019 }
7020#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
7021#endif /* MBEDTLS_SSL_PROTO_DTLS */
7022 }
7023
7024 n = ( len < ssl->in_msglen )
7025 ? len : ssl->in_msglen;
7026
7027 memcpy( buf, ssl->in_offt, n );
7028 ssl->in_msglen -= n;
7029
7030 if( ssl->in_msglen == 0 )
7031 {
7032 /* all bytes consumed */
7033 ssl->in_offt = NULL;
7034 ssl->keep_current_message = 0;
7035 }
7036 else
7037 {
7038 /* more data available */
7039 ssl->in_offt += n;
7040 }
7041
7042 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
7043
7044 return( (int) n );
7045}
7046
7047/*
7048 * Send application data to be encrypted by the SSL layer,
7049 * taking care of max fragment length and buffer size
7050 */
7051static int ssl_write_real( mbedtls_ssl_context *ssl,
7052 const unsigned char *buf, size_t len )
7053{
7054 int ret;
7055#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
7056 size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
7057
7058 if( len > max_len )
7059 {
7060#if defined(MBEDTLS_SSL_PROTO_DTLS)
7061 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7062 {
7063 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
7064 "maximum fragment length: %d > %d",
7065 len, max_len ) );
7066 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7067 }
7068 else
7069#endif
7070 len = max_len;
7071 }
7072#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
7073
7074 if( ssl->out_left != 0 )
7075 {
7076 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
7077 {
7078 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
7079 return( ret );
7080 }
7081 }
7082 else
7083 {
7084 ssl->out_msglen = len;
7085 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
7086 memcpy( ssl->out_msg, buf, len );
7087
7088 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
7089 {
7090 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
7091 return( ret );
7092 }
7093 }
7094
7095 return( (int) len );
7096}
7097
7098/*
7099 * Write application data, doing 1/n-1 splitting if necessary.
7100 *
7101 * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
7102 * then the caller will call us again with the same arguments, so
7103 * remember wether we already did the split or not.
7104 */
7105#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7106static int ssl_write_split( mbedtls_ssl_context *ssl,
7107 const unsigned char *buf, size_t len )
7108{
7109 int ret;
7110
7111 if( ssl->conf->cbc_record_splitting ==
7112 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
7113 len <= 1 ||
7114 ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
7115 mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
7116 != MBEDTLS_MODE_CBC )
7117 {
7118 return( ssl_write_real( ssl, buf, len ) );
7119 }
7120
7121 if( ssl->split_done == 0 )
7122 {
7123 if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
7124 return( ret );
7125 ssl->split_done = 1;
7126 }
7127
7128 if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
7129 return( ret );
7130 ssl->split_done = 0;
7131
7132 return( ret + 1 );
7133}
7134#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
7135
7136/*
7137 * Write application data (public-facing wrapper)
7138 */
7139int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
7140{
7141 int ret;
7142
7143 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
7144
7145 if( ssl == NULL || ssl->conf == NULL )
7146 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7147
7148#if defined(MBEDTLS_SSL_RENEGOTIATION)
7149 if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
7150 {
7151 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
7152 return( ret );
7153 }
7154#endif
7155
7156 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
7157 {
7158 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
7159 {
7160 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
7161 return( ret );
7162 }
7163 }
7164
7165#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7166 ret = ssl_write_split( ssl, buf, len );
7167#else
7168 ret = ssl_write_real( ssl, buf, len );
7169#endif
7170
7171 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
7172
7173 return( ret );
7174}
7175
7176/*
7177 * Notify the peer that the connection is being closed
7178 */
7179int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
7180{
7181 int ret;
7182
7183 if( ssl == NULL || ssl->conf == NULL )
7184 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7185
7186 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
7187
7188 if( ssl->out_left != 0 )
7189 return( mbedtls_ssl_flush_output( ssl ) );
7190
7191 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
7192 {
7193 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
7194 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
7195 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
7196 {
7197 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
7198 return( ret );
7199 }
7200 }
7201
7202 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
7203
7204 return( 0 );
7205}
7206
7207void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
7208{
7209 if( transform == NULL )
7210 return;
7211
7212#if defined(MBEDTLS_ZLIB_SUPPORT)
7213 deflateEnd( &transform->ctx_deflate );
7214 inflateEnd( &transform->ctx_inflate );
7215#endif
7216
7217 mbedtls_cipher_free( &transform->cipher_ctx_enc );
7218 mbedtls_cipher_free( &transform->cipher_ctx_dec );
7219
7220 mbedtls_md_free( &transform->md_ctx_enc );
7221 mbedtls_md_free( &transform->md_ctx_dec );
7222
7223 mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
7224}
7225
7226#if defined(MBEDTLS_X509_CRT_PARSE_C)
7227static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
7228{
7229 mbedtls_ssl_key_cert *cur = key_cert, *next;
7230
7231 while( cur != NULL )
7232 {
7233 next = cur->next;
7234 mbedtls_free( cur );
7235 cur = next;
7236 }
7237}
7238#endif /* MBEDTLS_X509_CRT_PARSE_C */
7239
7240void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake )
7241{
7242 if( handshake == NULL )
7243 return;
7244
7245#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
7246 defined(MBEDTLS_SSL_PROTO_TLS1_1)
7247 mbedtls_md5_free( &handshake->fin_md5 );
7248 mbedtls_sha1_free( &handshake->fin_sha1 );
7249#endif
7250#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7251#if defined(MBEDTLS_SHA256_C)
7252 mbedtls_sha256_free( &handshake->fin_sha256 );
7253#endif
7254#if defined(MBEDTLS_SHA512_C)
7255 mbedtls_sha512_free( &handshake->fin_sha512 );
7256#endif
7257#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7258
7259#if defined(MBEDTLS_DHM_C)
7260 mbedtls_dhm_free( &handshake->dhm_ctx );
7261#endif
7262#if defined(MBEDTLS_ECDH_C)
7263 mbedtls_ecdh_free( &handshake->ecdh_ctx );
7264#endif
7265#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7266 mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
7267#if defined(MBEDTLS_SSL_CLI_C)
7268 mbedtls_free( handshake->ecjpake_cache );
7269 handshake->ecjpake_cache = NULL;
7270 handshake->ecjpake_cache_len = 0;
7271#endif
7272#endif
7273
7274#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
7275 defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7276 /* explicit void pointer cast for buggy MS compiler */
7277 mbedtls_free( (void *) handshake->curves );
7278#endif
7279
7280#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7281 if( handshake->psk != NULL )
7282 {
7283 mbedtls_zeroize( handshake->psk, handshake->psk_len );
7284 mbedtls_free( handshake->psk );
7285 }
7286#endif
7287
7288#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
7289 defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7290 /*
7291 * Free only the linked list wrapper, not the keys themselves
7292 * since the belong to the SNI callback
7293 */
7294 if( handshake->sni_key_cert != NULL )
7295 {
7296 mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
7297
7298 while( cur != NULL )
7299 {
7300 next = cur->next;
7301 mbedtls_free( cur );
7302 cur = next;
7303 }
7304 }
7305#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
7306
7307#if defined(MBEDTLS_SSL_PROTO_DTLS)
7308 mbedtls_free( handshake->verify_cookie );
7309 mbedtls_free( handshake->hs_msg );
7310 ssl_flight_free( handshake->flight );
7311#endif
7312
7313 mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) );
7314}
7315
7316void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
7317{
7318 if( session == NULL )
7319 return;
7320
7321#if defined(MBEDTLS_X509_CRT_PARSE_C)
7322 if( session->peer_cert != NULL )
7323 {
7324 mbedtls_x509_crt_free( session->peer_cert );
7325 mbedtls_free( session->peer_cert );
7326 }
7327#endif
7328
7329#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
7330 mbedtls_free( session->ticket );
7331#endif
7332
7333 mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) );
7334}
7335
7336/*
7337 * Free an SSL context
7338 */
7339void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
7340{
7341 if( ssl == NULL )
7342 return;
7343
7344 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
7345
7346 if( ssl->out_buf != NULL )
7347 {
7348 mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN );
7349 mbedtls_free( ssl->out_buf );
7350 }
7351
7352 if( ssl->in_buf != NULL )
7353 {
7354 mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN );
7355 mbedtls_free( ssl->in_buf );
7356 }
7357
7358#if defined(MBEDTLS_ZLIB_SUPPORT)
7359 if( ssl->compress_buf != NULL )
7360 {
7361 mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN );
7362 mbedtls_free( ssl->compress_buf );
7363 }
7364#endif
7365
7366 if( ssl->transform )
7367 {
7368 mbedtls_ssl_transform_free( ssl->transform );
7369 mbedtls_free( ssl->transform );
7370 }
7371
7372 if( ssl->handshake )
7373 {
7374 mbedtls_ssl_handshake_free( ssl->handshake );
7375 mbedtls_ssl_transform_free( ssl->transform_negotiate );
7376 mbedtls_ssl_session_free( ssl->session_negotiate );
7377
7378 mbedtls_free( ssl->handshake );
7379 mbedtls_free( ssl->transform_negotiate );
7380 mbedtls_free( ssl->session_negotiate );
7381 }
7382
7383 if( ssl->session )
7384 {
7385 mbedtls_ssl_session_free( ssl->session );
7386 mbedtls_free( ssl->session );
7387 }
7388
7389#if defined(MBEDTLS_X509_CRT_PARSE_C)
7390 if( ssl->hostname != NULL )
7391 {
7392 mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
7393 mbedtls_free( ssl->hostname );
7394 }
7395#endif
7396
7397#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
7398 if( mbedtls_ssl_hw_record_finish != NULL )
7399 {
7400 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
7401 mbedtls_ssl_hw_record_finish( ssl );
7402 }
7403#endif
7404
7405#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7406 mbedtls_free( ssl->cli_id );
7407#endif
7408
7409 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
7410
7411 /* Actually clear after last debug message */
7412 mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
7413}
7414
7415/*
7416 * Initialze mbedtls_ssl_config
7417 */
7418void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
7419{
7420 memset( conf, 0, sizeof( mbedtls_ssl_config ) );
7421}
7422
7423#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7424static int ssl_preset_default_hashes[] = {
7425#if defined(MBEDTLS_SHA512_C)
7426 MBEDTLS_MD_SHA512,
7427 MBEDTLS_MD_SHA384,
7428#endif
7429#if defined(MBEDTLS_SHA256_C)
7430 MBEDTLS_MD_SHA256,
7431 MBEDTLS_MD_SHA224,
7432#endif
7433#if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
7434 MBEDTLS_MD_SHA1,
7435#endif
7436 MBEDTLS_MD_NONE
7437};
7438#endif
7439
7440static int ssl_preset_suiteb_ciphersuites[] = {
7441 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
7442 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
7443 0
7444};
7445
7446#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7447static int ssl_preset_suiteb_hashes[] = {
7448 MBEDTLS_MD_SHA256,
7449 MBEDTLS_MD_SHA384,
7450 MBEDTLS_MD_NONE
7451};
7452#endif
7453
7454#if defined(MBEDTLS_ECP_C)
7455static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
7456 MBEDTLS_ECP_DP_SECP256R1,
7457 MBEDTLS_ECP_DP_SECP384R1,
7458 MBEDTLS_ECP_DP_NONE
7459};
7460#endif
7461
7462/*
7463 * Load default in mbedtls_ssl_config
7464 */
7465int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
7466 int endpoint, int transport, int preset )
7467{
7468#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7469 int ret;
7470#endif
7471
7472 /* Use the functions here so that they are covered in tests,
7473 * but otherwise access member directly for efficiency */
7474 mbedtls_ssl_conf_endpoint( conf, endpoint );
7475 mbedtls_ssl_conf_transport( conf, transport );
7476
7477 /*
7478 * Things that are common to all presets
7479 */
7480#if defined(MBEDTLS_SSL_CLI_C)
7481 if( endpoint == MBEDTLS_SSL_IS_CLIENT )
7482 {
7483 conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
7484#if defined(MBEDTLS_SSL_SESSION_TICKETS)
7485 conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
7486#endif
7487 }
7488#endif
7489
7490#if defined(MBEDTLS_ARC4_C)
7491 conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
7492#endif
7493
7494#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
7495 conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
7496#endif
7497
7498#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
7499 conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
7500#endif
7501
7502#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7503 conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
7504#endif
7505
7506#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7507 conf->f_cookie_write = ssl_cookie_write_dummy;
7508 conf->f_cookie_check = ssl_cookie_check_dummy;
7509#endif
7510
7511#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
7512 conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
7513#endif
7514
7515#if defined(MBEDTLS_SSL_SRV_C)
7516 conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
7517#endif
7518
7519#if defined(MBEDTLS_SSL_PROTO_DTLS)
7520 conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
7521 conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
7522#endif
7523
7524#if defined(MBEDTLS_SSL_RENEGOTIATION)
7525 conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
7526 memset( conf->renego_period, 0x00, 2 );
7527 memset( conf->renego_period + 2, 0xFF, 6 );
7528#endif
7529
7530#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7531 if( endpoint == MBEDTLS_SSL_IS_SERVER )
7532 {
7533 if( ( ret = mbedtls_ssl_conf_dh_param( conf,
7534 MBEDTLS_DHM_RFC5114_MODP_2048_P,
7535 MBEDTLS_DHM_RFC5114_MODP_2048_G ) ) != 0 )
7536 {
7537 return( ret );
7538 }
7539 }
7540#endif
7541
7542 /*
7543 * Preset-specific defaults
7544 */
7545 switch( preset )
7546 {
7547 /*
7548 * NSA Suite B
7549 */
7550 case MBEDTLS_SSL_PRESET_SUITEB:
7551 conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7552 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
7553 conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7554 conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7555
7556 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7557 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7558 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7559 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7560 ssl_preset_suiteb_ciphersuites;
7561
7562#if defined(MBEDTLS_X509_CRT_PARSE_C)
7563 conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
7564#endif
7565
7566#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7567 conf->sig_hashes = ssl_preset_suiteb_hashes;
7568#endif
7569
7570#if defined(MBEDTLS_ECP_C)
7571 conf->curve_list = ssl_preset_suiteb_curves;
7572#endif
7573 break;
7574
7575 /*
7576 * Default
7577 */
7578 default:
7579 conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7580 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */
7581 conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7582 conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7583
7584#if defined(MBEDTLS_SSL_PROTO_DTLS)
7585 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7586 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
7587#endif
7588
7589 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7590 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7591 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7592 conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7593 mbedtls_ssl_list_ciphersuites();
7594
7595#if defined(MBEDTLS_X509_CRT_PARSE_C)
7596 conf->cert_profile = &mbedtls_x509_crt_profile_default;
7597#endif
7598
7599#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7600 conf->sig_hashes = ssl_preset_default_hashes;
7601#endif
7602
7603#if defined(MBEDTLS_ECP_C)
7604 conf->curve_list = mbedtls_ecp_grp_id_list();
7605#endif
7606
7607#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
7608 conf->dhm_min_bitlen = 1024;
7609#endif
7610 }
7611
7612 return( 0 );
7613}
7614
7615/*
7616 * Free mbedtls_ssl_config
7617 */
7618void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
7619{
7620#if defined(MBEDTLS_DHM_C)
7621 mbedtls_mpi_free( &conf->dhm_P );
7622 mbedtls_mpi_free( &conf->dhm_G );
7623#endif
7624
7625#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7626 if( conf->psk != NULL )
7627 {
7628 mbedtls_zeroize( conf->psk, conf->psk_len );
7629 mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len );
7630 mbedtls_free( conf->psk );
7631 mbedtls_free( conf->psk_identity );
7632 conf->psk_len = 0;
7633 conf->psk_identity_len = 0;
7634 }
7635#endif
7636
7637#if defined(MBEDTLS_X509_CRT_PARSE_C)
7638 ssl_key_cert_free( conf->key_cert );
7639#endif
7640
7641 mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) );
7642}
7643
7644#if defined(MBEDTLS_PK_C) && \
7645 ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
7646/*
7647 * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7648 */
7649unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
7650{
7651#if defined(MBEDTLS_RSA_C)
7652 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
7653 return( MBEDTLS_SSL_SIG_RSA );
7654#endif
7655#if defined(MBEDTLS_ECDSA_C)
7656 if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
7657 return( MBEDTLS_SSL_SIG_ECDSA );
7658#endif
7659 return( MBEDTLS_SSL_SIG_ANON );
7660}
7661
7662unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
7663{
7664 switch( type ) {
7665 case MBEDTLS_PK_RSA:
7666 return( MBEDTLS_SSL_SIG_RSA );
7667 case MBEDTLS_PK_ECDSA:
7668 case MBEDTLS_PK_ECKEY:
7669 return( MBEDTLS_SSL_SIG_ECDSA );
7670 default:
7671 return( MBEDTLS_SSL_SIG_ANON );
7672 }
7673}
7674
7675mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
7676{
7677 switch( sig )
7678 {
7679#if defined(MBEDTLS_RSA_C)
7680 case MBEDTLS_SSL_SIG_RSA:
7681 return( MBEDTLS_PK_RSA );
7682#endif
7683#if defined(MBEDTLS_ECDSA_C)
7684 case MBEDTLS_SSL_SIG_ECDSA:
7685 return( MBEDTLS_PK_ECDSA );
7686#endif
7687 default:
7688 return( MBEDTLS_PK_NONE );
7689 }
7690}
7691#endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7692
7693#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
7694 defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7695
7696/* Find an entry in a signature-hash set matching a given hash algorithm. */
7697mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
7698 mbedtls_pk_type_t sig_alg )
7699{
7700 switch( sig_alg )
7701 {
7702 case MBEDTLS_PK_RSA:
7703 return( set->rsa );
7704 case MBEDTLS_PK_ECDSA:
7705 return( set->ecdsa );
7706 default:
7707 return( MBEDTLS_MD_NONE );
7708 }
7709}
7710
7711/* Add a signature-hash-pair to a signature-hash set */
7712void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
7713 mbedtls_pk_type_t sig_alg,
7714 mbedtls_md_type_t md_alg )
7715{
7716 switch( sig_alg )
7717 {
7718 case MBEDTLS_PK_RSA:
7719 if( set->rsa == MBEDTLS_MD_NONE )
7720 set->rsa = md_alg;
7721 break;
7722
7723 case MBEDTLS_PK_ECDSA:
7724 if( set->ecdsa == MBEDTLS_MD_NONE )
7725 set->ecdsa = md_alg;
7726 break;
7727
7728 default:
7729 break;
7730 }
7731}
7732
7733/* Allow exactly one hash algorithm for each signature. */
7734void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
7735 mbedtls_md_type_t md_alg )
7736{
7737 set->rsa = md_alg;
7738 set->ecdsa = md_alg;
7739}
7740
7741#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
7742 MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
7743
7744/*
7745 * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
7746 */
7747mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
7748{
7749 switch( hash )
7750 {
7751#if defined(MBEDTLS_MD5_C)
7752 case MBEDTLS_SSL_HASH_MD5:
7753 return( MBEDTLS_MD_MD5 );
7754#endif
7755#if defined(MBEDTLS_SHA1_C)
7756 case MBEDTLS_SSL_HASH_SHA1:
7757 return( MBEDTLS_MD_SHA1 );
7758#endif
7759#if defined(MBEDTLS_SHA256_C)
7760 case MBEDTLS_SSL_HASH_SHA224:
7761 return( MBEDTLS_MD_SHA224 );
7762 case MBEDTLS_SSL_HASH_SHA256:
7763 return( MBEDTLS_MD_SHA256 );
7764#endif
7765#if defined(MBEDTLS_SHA512_C)
7766 case MBEDTLS_SSL_HASH_SHA384:
7767 return( MBEDTLS_MD_SHA384 );
7768 case MBEDTLS_SSL_HASH_SHA512:
7769 return( MBEDTLS_MD_SHA512 );
7770#endif
7771 default:
7772 return( MBEDTLS_MD_NONE );
7773 }
7774}
7775
7776/*
7777 * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
7778 */
7779unsigned char mbedtls_ssl_hash_from_md_alg( int md )
7780{
7781 switch( md )
7782 {
7783#if defined(MBEDTLS_MD5_C)
7784 case MBEDTLS_MD_MD5:
7785 return( MBEDTLS_SSL_HASH_MD5 );
7786#endif
7787#if defined(MBEDTLS_SHA1_C)
7788 case MBEDTLS_MD_SHA1:
7789 return( MBEDTLS_SSL_HASH_SHA1 );
7790#endif
7791#if defined(MBEDTLS_SHA256_C)
7792 case MBEDTLS_MD_SHA224:
7793 return( MBEDTLS_SSL_HASH_SHA224 );
7794 case MBEDTLS_MD_SHA256:
7795 return( MBEDTLS_SSL_HASH_SHA256 );
7796#endif
7797#if defined(MBEDTLS_SHA512_C)
7798 case MBEDTLS_MD_SHA384:
7799 return( MBEDTLS_SSL_HASH_SHA384 );
7800 case MBEDTLS_MD_SHA512:
7801 return( MBEDTLS_SSL_HASH_SHA512 );
7802#endif
7803 default:
7804 return( MBEDTLS_SSL_HASH_NONE );
7805 }
7806}
7807
7808#if defined(MBEDTLS_ECP_C)
7809/*
7810 * Check if a curve proposed by the peer is in our list.
7811 * Return 0 if we're willing to use it, -1 otherwise.
7812 */
7813int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
7814{
7815 const mbedtls_ecp_group_id *gid;
7816
7817 if( ssl->conf->curve_list == NULL )
7818 return( -1 );
7819
7820 for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
7821 if( *gid == grp_id )
7822 return( 0 );
7823
7824 return( -1 );
7825}
7826#endif /* MBEDTLS_ECP_C */
7827
7828#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7829/*
7830 * Check if a hash proposed by the peer is in our list.
7831 * Return 0 if we're willing to use it, -1 otherwise.
7832 */
7833int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
7834 mbedtls_md_type_t md )
7835{
7836 const int *cur;
7837
7838 if( ssl->conf->sig_hashes == NULL )
7839 return( -1 );
7840
7841 for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
7842 if( *cur == (int) md )
7843 return( 0 );
7844
7845 return( -1 );
7846}
7847#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
7848
7849#if defined(MBEDTLS_X509_CRT_PARSE_C)
7850int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
7851 const mbedtls_ssl_ciphersuite_t *ciphersuite,
7852 int cert_endpoint,
7853 uint32_t *flags )
7854{
7855 int ret = 0;
7856#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7857 int usage = 0;
7858#endif
7859#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7860 const char *ext_oid;
7861 size_t ext_len;
7862#endif
7863
7864#if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \
7865 !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7866 ((void) cert);
7867 ((void) cert_endpoint);
7868 ((void) flags);
7869#endif
7870
7871#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7872 if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7873 {
7874 /* Server part of the key exchange */
7875 switch( ciphersuite->key_exchange )
7876 {
7877 case MBEDTLS_KEY_EXCHANGE_RSA:
7878 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
7879 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
7880 break;
7881
7882 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
7883 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
7884 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
7885 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7886 break;
7887
7888 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
7889 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
7890 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
7891 break;
7892
7893 /* Don't use default: we want warnings when adding new values */
7894 case MBEDTLS_KEY_EXCHANGE_NONE:
7895 case MBEDTLS_KEY_EXCHANGE_PSK:
7896 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
7897 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
7898 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
7899 usage = 0;
7900 }
7901 }
7902 else
7903 {
7904 /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
7905 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7906 }
7907
7908 if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
7909 {
7910 *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
7911 ret = -1;
7912 }
7913#else
7914 ((void) ciphersuite);
7915#endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
7916
7917#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7918 if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7919 {
7920 ext_oid = MBEDTLS_OID_SERVER_AUTH;
7921 ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
7922 }
7923 else
7924 {
7925 ext_oid = MBEDTLS_OID_CLIENT_AUTH;
7926 ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
7927 }
7928
7929 if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
7930 {
7931 *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
7932 ret = -1;
7933 }
7934#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
7935
7936 return( ret );
7937}
7938#endif /* MBEDTLS_X509_CRT_PARSE_C */
7939
7940/*
7941 * Convert version numbers to/from wire format
7942 * and, for DTLS, to/from TLS equivalent.
7943 *
7944 * For TLS this is the identity.
7945 * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
7946 * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1)
7947 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
7948 */
7949void mbedtls_ssl_write_version( int major, int minor, int transport,
7950 unsigned char ver[2] )
7951{
7952#if defined(MBEDTLS_SSL_PROTO_DTLS)
7953 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7954 {
7955 if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
7956 --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7957
7958 ver[0] = (unsigned char)( 255 - ( major - 2 ) );
7959 ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
7960 }
7961 else
7962#else
7963 ((void) transport);
7964#endif
7965 {
7966 ver[0] = (unsigned char) major;
7967 ver[1] = (unsigned char) minor;
7968 }
7969}
7970
7971void mbedtls_ssl_read_version( int *major, int *minor, int transport,
7972 const unsigned char ver[2] )
7973{
7974#if defined(MBEDTLS_SSL_PROTO_DTLS)
7975 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7976 {
7977 *major = 255 - ver[0] + 2;
7978 *minor = 255 - ver[1] + 1;
7979
7980 if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
7981 ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7982 }
7983 else
7984#else
7985 ((void) transport);
7986#endif
7987 {
7988 *major = ver[0];
7989 *minor = ver[1];
7990 }
7991}
7992
7993int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
7994{
7995#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7996 if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
7997 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7998
7999 switch( md )
8000 {
8001#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
8002#if defined(MBEDTLS_MD5_C)
8003 case MBEDTLS_SSL_HASH_MD5:
8004 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8005#endif
8006#if defined(MBEDTLS_SHA1_C)
8007 case MBEDTLS_SSL_HASH_SHA1:
8008 ssl->handshake->calc_verify = ssl_calc_verify_tls;
8009 break;
8010#endif
8011#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
8012#if defined(MBEDTLS_SHA512_C)
8013 case MBEDTLS_SSL_HASH_SHA384:
8014 ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
8015 break;
8016#endif
8017#if defined(MBEDTLS_SHA256_C)
8018 case MBEDTLS_SSL_HASH_SHA256:
8019 ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
8020 break;
8021#endif
8022 default:
8023 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8024 }
8025
8026 return 0;
8027#else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
8028 (void) ssl;
8029 (void) md;
8030
8031 return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8032#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
8033}
8034
8035#endif /* MBEDTLS_SSL_TLS_C */