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