9142be85662b40e718f7818cb893d660903aba3a
[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: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * This file is part of mbed TLS (https://tls.mbed.org)
20 */
21 /*
22 * The SSL 3.0 specification was drafted by Netscape in 1996,
23 * and became an IETF standard in 1999.
24 *
25 * http://wp.netscape.com/eng/ssl3/
26 * http://www.ietf.org/rfc/rfc2246.txt
27 * http://www.ietf.org/rfc/rfc4346.txt
28 */
29
30 #if !defined(MBEDTLS_CONFIG_FILE)
31 #include "mbedtls/config.h"
32 #else
33 #include MBEDTLS_CONFIG_FILE
34 #endif
35
36 #if defined(MBEDTLS_SSL_TLS_C)
37
38 #include "mbedtls/debug.h"
39 #include "mbedtls/ssl.h"
40 #include "mbedtls/ssl_internal.h"
41
42 #include <string.h>
43
44 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
45 defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
46 #include "mbedtls/oid.h"
47 #endif
48
49 #if defined(MBEDTLS_PLATFORM_C)
50 #include "mbedtls/platform.h"
51 #else
52 #include <stdlib.h>
53 #define mbedtls_calloc calloc
54 #define mbedtls_free free
55 #endif
56
57 /* Implementation that should never be optimized out by the compiler */
58 static void mbedtls_zeroize( void *v, size_t n ) {
59 volatile unsigned char *p = v; while( n-- ) *p++ = 0;
60 }
61
62 /* Length of the "epoch" field in the record header */
63 static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
64 {
65 #if defined(MBEDTLS_SSL_PROTO_DTLS)
66 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
67 return( 2 );
68 #else
69 ((void) ssl);
70 #endif
71 return( 0 );
72 }
73
74 /*
75 * Start a timer.
76 * Passing millisecs = 0 cancels a running timer.
77 */
78 static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
79 {
80 if( ssl->f_set_timer == NULL )
81 return;
82
83 MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
84 ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
85 }
86
87 /*
88 * Return -1 is timer is expired, 0 if it isn't.
89 */
90 static int ssl_check_timer( mbedtls_ssl_context *ssl )
91 {
92 if( ssl->f_get_timer == NULL )
93 return( 0 );
94
95 if( ssl->f_get_timer( ssl->p_timer ) == 2 )
96 {
97 MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
98 return( -1 );
99 }
100
101 return( 0 );
102 }
103
104 #if defined(MBEDTLS_SSL_PROTO_DTLS)
105 /*
106 * Double the retransmit timeout value, within the allowed range,
107 * returning -1 if the maximum value has already been reached.
108 */
109 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
110 {
111 uint32_t new_timeout;
112
113 if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
114 return( -1 );
115
116 new_timeout = 2 * ssl->handshake->retransmit_timeout;
117
118 /* Avoid arithmetic overflow and range overflow */
119 if( new_timeout < ssl->handshake->retransmit_timeout ||
120 new_timeout > ssl->conf->hs_timeout_max )
121 {
122 new_timeout = ssl->conf->hs_timeout_max;
123 }
124
125 ssl->handshake->retransmit_timeout = new_timeout;
126 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
127 ssl->handshake->retransmit_timeout ) );
128
129 return( 0 );
130 }
131
132 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
133 {
134 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
135 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
136 ssl->handshake->retransmit_timeout ) );
137 }
138 #endif /* MBEDTLS_SSL_PROTO_DTLS */
139
140 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
141 /*
142 * Convert max_fragment_length codes to length.
143 * RFC 6066 says:
144 * enum{
145 * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
146 * } MaxFragmentLength;
147 * and we add 0 -> extension unused
148 */
149 static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] =
150 {
151 MBEDTLS_SSL_MAX_CONTENT_LEN, /* MBEDTLS_SSL_MAX_FRAG_LEN_NONE */
152 512, /* MBEDTLS_SSL_MAX_FRAG_LEN_512 */
153 1024, /* MBEDTLS_SSL_MAX_FRAG_LEN_1024 */
154 2048, /* MBEDTLS_SSL_MAX_FRAG_LEN_2048 */
155 4096, /* MBEDTLS_SSL_MAX_FRAG_LEN_4096 */
156 };
157 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
158
159 #if defined(MBEDTLS_SSL_CLI_C)
160 static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
161 {
162 mbedtls_ssl_session_free( dst );
163 memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
164
165 #if defined(MBEDTLS_X509_CRT_PARSE_C)
166 if( src->peer_cert != NULL )
167 {
168 int ret;
169
170 dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
171 if( dst->peer_cert == NULL )
172 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
173
174 mbedtls_x509_crt_init( dst->peer_cert );
175
176 if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
177 src->peer_cert->raw.len ) ) != 0 )
178 {
179 mbedtls_free( dst->peer_cert );
180 dst->peer_cert = NULL;
181 return( ret );
182 }
183 }
184 #endif /* MBEDTLS_X509_CRT_PARSE_C */
185
186 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
187 if( src->ticket != NULL )
188 {
189 dst->ticket = mbedtls_calloc( 1, src->ticket_len );
190 if( dst->ticket == NULL )
191 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
192
193 memcpy( dst->ticket, src->ticket, src->ticket_len );
194 }
195 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
196
197 return( 0 );
198 }
199 #endif /* MBEDTLS_SSL_CLI_C */
200
201 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
202 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
203 const unsigned char *key_enc, const unsigned char *key_dec,
204 size_t keylen,
205 const unsigned char *iv_enc, const unsigned char *iv_dec,
206 size_t ivlen,
207 const unsigned char *mac_enc, const unsigned char *mac_dec,
208 size_t maclen ) = NULL;
209 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
210 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
211 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
212 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
213 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
214 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
215
216 /*
217 * Key material generation
218 */
219 #if defined(MBEDTLS_SSL_PROTO_SSL3)
220 static int ssl3_prf( const unsigned char *secret, size_t slen,
221 const char *label,
222 const unsigned char *random, size_t rlen,
223 unsigned char *dstbuf, size_t dlen )
224 {
225 size_t i;
226 mbedtls_md5_context md5;
227 mbedtls_sha1_context sha1;
228 unsigned char padding[16];
229 unsigned char sha1sum[20];
230 ((void)label);
231
232 mbedtls_md5_init( &md5 );
233 mbedtls_sha1_init( &sha1 );
234
235 /*
236 * SSLv3:
237 * block =
238 * MD5( secret + SHA1( 'A' + secret + random ) ) +
239 * MD5( secret + SHA1( 'BB' + secret + random ) ) +
240 * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
241 * ...
242 */
243 for( i = 0; i < dlen / 16; i++ )
244 {
245 memset( padding, (unsigned char) ('A' + i), 1 + i );
246
247 mbedtls_sha1_starts( &sha1 );
248 mbedtls_sha1_update( &sha1, padding, 1 + i );
249 mbedtls_sha1_update( &sha1, secret, slen );
250 mbedtls_sha1_update( &sha1, random, rlen );
251 mbedtls_sha1_finish( &sha1, sha1sum );
252
253 mbedtls_md5_starts( &md5 );
254 mbedtls_md5_update( &md5, secret, slen );
255 mbedtls_md5_update( &md5, sha1sum, 20 );
256 mbedtls_md5_finish( &md5, dstbuf + i * 16 );
257 }
258
259 mbedtls_md5_free( &md5 );
260 mbedtls_sha1_free( &sha1 );
261
262 mbedtls_zeroize( padding, sizeof( padding ) );
263 mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
264
265 return( 0 );
266 }
267 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
268
269 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
270 static int tls1_prf( const unsigned char *secret, size_t slen,
271 const char *label,
272 const unsigned char *random, size_t rlen,
273 unsigned char *dstbuf, size_t dlen )
274 {
275 size_t nb, hs;
276 size_t i, j, k;
277 const unsigned char *S1, *S2;
278 unsigned char tmp[128];
279 unsigned char h_i[20];
280 const mbedtls_md_info_t *md_info;
281 mbedtls_md_context_t md_ctx;
282 int ret;
283
284 mbedtls_md_init( &md_ctx );
285
286 if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
287 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
288
289 hs = ( slen + 1 ) / 2;
290 S1 = secret;
291 S2 = secret + slen - hs;
292
293 nb = strlen( label );
294 memcpy( tmp + 20, label, nb );
295 memcpy( tmp + 20 + nb, random, rlen );
296 nb += rlen;
297
298 /*
299 * First compute P_md5(secret,label+random)[0..dlen]
300 */
301 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
302 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
303
304 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
305 return( ret );
306
307 mbedtls_md_hmac_starts( &md_ctx, S1, hs );
308 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
309 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
310
311 for( i = 0; i < dlen; i += 16 )
312 {
313 mbedtls_md_hmac_reset ( &md_ctx );
314 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
315 mbedtls_md_hmac_finish( &md_ctx, h_i );
316
317 mbedtls_md_hmac_reset ( &md_ctx );
318 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
319 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
320
321 k = ( i + 16 > dlen ) ? dlen % 16 : 16;
322
323 for( j = 0; j < k; j++ )
324 dstbuf[i + j] = h_i[j];
325 }
326
327 mbedtls_md_free( &md_ctx );
328
329 /*
330 * XOR out with P_sha1(secret,label+random)[0..dlen]
331 */
332 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
333 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
334
335 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
336 return( ret );
337
338 mbedtls_md_hmac_starts( &md_ctx, S2, hs );
339 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
340 mbedtls_md_hmac_finish( &md_ctx, tmp );
341
342 for( i = 0; i < dlen; i += 20 )
343 {
344 mbedtls_md_hmac_reset ( &md_ctx );
345 mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
346 mbedtls_md_hmac_finish( &md_ctx, h_i );
347
348 mbedtls_md_hmac_reset ( &md_ctx );
349 mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
350 mbedtls_md_hmac_finish( &md_ctx, tmp );
351
352 k = ( i + 20 > dlen ) ? dlen % 20 : 20;
353
354 for( j = 0; j < k; j++ )
355 dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
356 }
357
358 mbedtls_md_free( &md_ctx );
359
360 mbedtls_zeroize( tmp, sizeof( tmp ) );
361 mbedtls_zeroize( h_i, sizeof( h_i ) );
362
363 return( 0 );
364 }
365 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
366
367 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
368 static int tls_prf_generic( mbedtls_md_type_t md_type,
369 const unsigned char *secret, size_t slen,
370 const char *label,
371 const unsigned char *random, size_t rlen,
372 unsigned char *dstbuf, size_t dlen )
373 {
374 size_t nb;
375 size_t i, j, k, md_len;
376 unsigned char tmp[128];
377 unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
378 const mbedtls_md_info_t *md_info;
379 mbedtls_md_context_t md_ctx;
380 int ret;
381
382 mbedtls_md_init( &md_ctx );
383
384 if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
385 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
386
387 md_len = mbedtls_md_get_size( md_info );
388
389 if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
390 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
391
392 nb = strlen( label );
393 memcpy( tmp + md_len, label, nb );
394 memcpy( tmp + md_len + nb, random, rlen );
395 nb += rlen;
396
397 /*
398 * Compute P_<hash>(secret, label + random)[0..dlen]
399 */
400 if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
401 return( ret );
402
403 mbedtls_md_hmac_starts( &md_ctx, secret, slen );
404 mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
405 mbedtls_md_hmac_finish( &md_ctx, tmp );
406
407 for( i = 0; i < dlen; i += md_len )
408 {
409 mbedtls_md_hmac_reset ( &md_ctx );
410 mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
411 mbedtls_md_hmac_finish( &md_ctx, h_i );
412
413 mbedtls_md_hmac_reset ( &md_ctx );
414 mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
415 mbedtls_md_hmac_finish( &md_ctx, tmp );
416
417 k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
418
419 for( j = 0; j < k; j++ )
420 dstbuf[i + j] = h_i[j];
421 }
422
423 mbedtls_md_free( &md_ctx );
424
425 mbedtls_zeroize( tmp, sizeof( tmp ) );
426 mbedtls_zeroize( h_i, sizeof( h_i ) );
427
428 return( 0 );
429 }
430
431 #if defined(MBEDTLS_SHA256_C)
432 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
433 const char *label,
434 const unsigned char *random, size_t rlen,
435 unsigned char *dstbuf, size_t dlen )
436 {
437 return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
438 label, random, rlen, dstbuf, dlen ) );
439 }
440 #endif /* MBEDTLS_SHA256_C */
441
442 #if defined(MBEDTLS_SHA512_C)
443 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
444 const char *label,
445 const unsigned char *random, size_t rlen,
446 unsigned char *dstbuf, size_t dlen )
447 {
448 return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
449 label, random, rlen, dstbuf, dlen ) );
450 }
451 #endif /* MBEDTLS_SHA512_C */
452 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
453
454 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
455
456 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
457 defined(MBEDTLS_SSL_PROTO_TLS1_1)
458 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
459 #endif
460
461 #if defined(MBEDTLS_SSL_PROTO_SSL3)
462 static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
463 static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
464 #endif
465
466 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
467 static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
468 static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
469 #endif
470
471 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
472 #if defined(MBEDTLS_SHA256_C)
473 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
474 static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
475 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
476 #endif
477
478 #if defined(MBEDTLS_SHA512_C)
479 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
480 static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
481 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
482 #endif
483 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
484
485 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
486 {
487 int ret = 0;
488 unsigned char tmp[64];
489 unsigned char keyblk[256];
490 unsigned char *key1;
491 unsigned char *key2;
492 unsigned char *mac_enc;
493 unsigned char *mac_dec;
494 size_t iv_copy_len;
495 const mbedtls_cipher_info_t *cipher_info;
496 const mbedtls_md_info_t *md_info;
497
498 mbedtls_ssl_session *session = ssl->session_negotiate;
499 mbedtls_ssl_transform *transform = ssl->transform_negotiate;
500 mbedtls_ssl_handshake_params *handshake = ssl->handshake;
501
502 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
503
504 cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
505 if( cipher_info == NULL )
506 {
507 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
508 transform->ciphersuite_info->cipher ) );
509 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
510 }
511
512 md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
513 if( md_info == NULL )
514 {
515 MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
516 transform->ciphersuite_info->mac ) );
517 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
518 }
519
520 /*
521 * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
522 */
523 #if defined(MBEDTLS_SSL_PROTO_SSL3)
524 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
525 {
526 handshake->tls_prf = ssl3_prf;
527 handshake->calc_verify = ssl_calc_verify_ssl;
528 handshake->calc_finished = ssl_calc_finished_ssl;
529 }
530 else
531 #endif
532 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
533 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
534 {
535 handshake->tls_prf = tls1_prf;
536 handshake->calc_verify = ssl_calc_verify_tls;
537 handshake->calc_finished = ssl_calc_finished_tls;
538 }
539 else
540 #endif
541 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
542 #if defined(MBEDTLS_SHA512_C)
543 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
544 transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
545 {
546 handshake->tls_prf = tls_prf_sha384;
547 handshake->calc_verify = ssl_calc_verify_tls_sha384;
548 handshake->calc_finished = ssl_calc_finished_tls_sha384;
549 }
550 else
551 #endif
552 #if defined(MBEDTLS_SHA256_C)
553 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
554 {
555 handshake->tls_prf = tls_prf_sha256;
556 handshake->calc_verify = ssl_calc_verify_tls_sha256;
557 handshake->calc_finished = ssl_calc_finished_tls_sha256;
558 }
559 else
560 #endif
561 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
562 {
563 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
564 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
565 }
566
567 /*
568 * SSLv3:
569 * master =
570 * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
571 * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
572 * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
573 *
574 * TLSv1+:
575 * master = PRF( premaster, "master secret", randbytes )[0..47]
576 */
577 if( handshake->resume == 0 )
578 {
579 MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
580 handshake->pmslen );
581
582 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
583 if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
584 {
585 unsigned char session_hash[48];
586 size_t hash_len;
587
588 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
589
590 ssl->handshake->calc_verify( ssl, session_hash );
591
592 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
593 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
594 {
595 #if defined(MBEDTLS_SHA512_C)
596 if( ssl->transform_negotiate->ciphersuite_info->mac ==
597 MBEDTLS_MD_SHA384 )
598 {
599 hash_len = 48;
600 }
601 else
602 #endif
603 hash_len = 32;
604 }
605 else
606 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
607 hash_len = 36;
608
609 MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
610
611 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
612 "extended master secret",
613 session_hash, hash_len,
614 session->master, 48 );
615 if( ret != 0 )
616 {
617 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
618 return( ret );
619 }
620
621 }
622 else
623 #endif
624 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
625 "master secret",
626 handshake->randbytes, 64,
627 session->master, 48 );
628 if( ret != 0 )
629 {
630 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
631 return( ret );
632 }
633
634 mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) );
635 }
636 else
637 MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
638
639 /*
640 * Swap the client and server random values.
641 */
642 memcpy( tmp, handshake->randbytes, 64 );
643 memcpy( handshake->randbytes, tmp + 32, 32 );
644 memcpy( handshake->randbytes + 32, tmp, 32 );
645 mbedtls_zeroize( tmp, sizeof( tmp ) );
646
647 /*
648 * SSLv3:
649 * key block =
650 * MD5( master + SHA1( 'A' + master + randbytes ) ) +
651 * MD5( master + SHA1( 'BB' + master + randbytes ) ) +
652 * MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
653 * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
654 * ...
655 *
656 * TLSv1:
657 * key block = PRF( master, "key expansion", randbytes )
658 */
659 ret = handshake->tls_prf( session->master, 48, "key expansion",
660 handshake->randbytes, 64, keyblk, 256 );
661 if( ret != 0 )
662 {
663 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
664 return( ret );
665 }
666
667 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
668 mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
669 MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
670 MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
671 MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
672
673 mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) );
674
675 /*
676 * Determine the appropriate key, IV and MAC length.
677 */
678
679 transform->keylen = cipher_info->key_bitlen / 8;
680
681 if( cipher_info->mode == MBEDTLS_MODE_GCM ||
682 cipher_info->mode == MBEDTLS_MODE_CCM )
683 {
684 transform->maclen = 0;
685
686 transform->ivlen = 12;
687 transform->fixed_ivlen = 4;
688
689 /* Minimum length is expicit IV + tag */
690 transform->minlen = transform->ivlen - transform->fixed_ivlen
691 + ( transform->ciphersuite_info->flags &
692 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16 );
693 }
694 else
695 {
696 /* Initialize HMAC contexts */
697 if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
698 ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
699 {
700 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
701 return( ret );
702 }
703
704 /* Get MAC length */
705 transform->maclen = mbedtls_md_get_size( md_info );
706
707 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
708 /*
709 * If HMAC is to be truncated, we shall keep the leftmost bytes,
710 * (rfc 6066 page 13 or rfc 2104 section 4),
711 * so we only need to adjust the length here.
712 */
713 if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
714 transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
715 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
716
717 /* IV length */
718 transform->ivlen = cipher_info->iv_size;
719
720 /* Minimum length */
721 if( cipher_info->mode == MBEDTLS_MODE_STREAM )
722 transform->minlen = transform->maclen;
723 else
724 {
725 /*
726 * GenericBlockCipher:
727 * 1. if EtM is in use: one block plus MAC
728 * otherwise: * first multiple of blocklen greater than maclen
729 * 2. IV except for SSL3 and TLS 1.0
730 */
731 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
732 if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
733 {
734 transform->minlen = transform->maclen
735 + cipher_info->block_size;
736 }
737 else
738 #endif
739 {
740 transform->minlen = transform->maclen
741 + cipher_info->block_size
742 - transform->maclen % cipher_info->block_size;
743 }
744
745 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
746 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
747 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
748 ; /* No need to adjust minlen */
749 else
750 #endif
751 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
752 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
753 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
754 {
755 transform->minlen += transform->ivlen;
756 }
757 else
758 #endif
759 {
760 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
761 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
762 }
763 }
764 }
765
766 MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
767 transform->keylen, transform->minlen, transform->ivlen,
768 transform->maclen ) );
769
770 /*
771 * Finally setup the cipher contexts, IVs and MAC secrets.
772 */
773 #if defined(MBEDTLS_SSL_CLI_C)
774 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
775 {
776 key1 = keyblk + transform->maclen * 2;
777 key2 = keyblk + transform->maclen * 2 + transform->keylen;
778
779 mac_enc = keyblk;
780 mac_dec = keyblk + transform->maclen;
781
782 /*
783 * This is not used in TLS v1.1.
784 */
785 iv_copy_len = ( transform->fixed_ivlen ) ?
786 transform->fixed_ivlen : transform->ivlen;
787 memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
788 memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
789 iv_copy_len );
790 }
791 else
792 #endif /* MBEDTLS_SSL_CLI_C */
793 #if defined(MBEDTLS_SSL_SRV_C)
794 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
795 {
796 key1 = keyblk + transform->maclen * 2 + transform->keylen;
797 key2 = keyblk + transform->maclen * 2;
798
799 mac_enc = keyblk + transform->maclen;
800 mac_dec = keyblk;
801
802 /*
803 * This is not used in TLS v1.1.
804 */
805 iv_copy_len = ( transform->fixed_ivlen ) ?
806 transform->fixed_ivlen : transform->ivlen;
807 memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
808 memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
809 iv_copy_len );
810 }
811 else
812 #endif /* MBEDTLS_SSL_SRV_C */
813 {
814 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
815 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
816 }
817
818 #if defined(MBEDTLS_SSL_PROTO_SSL3)
819 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
820 {
821 if( transform->maclen > sizeof transform->mac_enc )
822 {
823 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
824 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
825 }
826
827 memcpy( transform->mac_enc, mac_enc, transform->maclen );
828 memcpy( transform->mac_dec, mac_dec, transform->maclen );
829 }
830 else
831 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
832 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
833 defined(MBEDTLS_SSL_PROTO_TLS1_2)
834 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
835 {
836 mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
837 mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
838 }
839 else
840 #endif
841 {
842 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
843 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
844 }
845
846 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
847 if( mbedtls_ssl_hw_record_init != NULL )
848 {
849 int ret = 0;
850
851 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
852
853 if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
854 transform->iv_enc, transform->iv_dec,
855 iv_copy_len,
856 mac_enc, mac_dec,
857 transform->maclen ) ) != 0 )
858 {
859 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
860 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
861 }
862 }
863 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
864
865 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
866 cipher_info ) ) != 0 )
867 {
868 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
869 return( ret );
870 }
871
872 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
873 cipher_info ) ) != 0 )
874 {
875 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
876 return( ret );
877 }
878
879 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
880 cipher_info->key_bitlen,
881 MBEDTLS_ENCRYPT ) ) != 0 )
882 {
883 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
884 return( ret );
885 }
886
887 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
888 cipher_info->key_bitlen,
889 MBEDTLS_DECRYPT ) ) != 0 )
890 {
891 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
892 return( ret );
893 }
894
895 #if defined(MBEDTLS_CIPHER_MODE_CBC)
896 if( cipher_info->mode == MBEDTLS_MODE_CBC )
897 {
898 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
899 MBEDTLS_PADDING_NONE ) ) != 0 )
900 {
901 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
902 return( ret );
903 }
904
905 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
906 MBEDTLS_PADDING_NONE ) ) != 0 )
907 {
908 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
909 return( ret );
910 }
911 }
912 #endif /* MBEDTLS_CIPHER_MODE_CBC */
913
914 mbedtls_zeroize( keyblk, sizeof( keyblk ) );
915
916 #if defined(MBEDTLS_ZLIB_SUPPORT)
917 // Initialize compression
918 //
919 if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
920 {
921 if( ssl->compress_buf == NULL )
922 {
923 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
924 ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN );
925 if( ssl->compress_buf == NULL )
926 {
927 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
928 MBEDTLS_SSL_BUFFER_LEN ) );
929 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
930 }
931 }
932
933 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
934
935 memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
936 memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
937
938 if( deflateInit( &transform->ctx_deflate,
939 Z_DEFAULT_COMPRESSION ) != Z_OK ||
940 inflateInit( &transform->ctx_inflate ) != Z_OK )
941 {
942 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
943 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
944 }
945 }
946 #endif /* MBEDTLS_ZLIB_SUPPORT */
947
948 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
949
950 return( 0 );
951 }
952
953 #if defined(MBEDTLS_SSL_PROTO_SSL3)
954 void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
955 {
956 mbedtls_md5_context md5;
957 mbedtls_sha1_context sha1;
958 unsigned char pad_1[48];
959 unsigned char pad_2[48];
960
961 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
962
963 mbedtls_md5_init( &md5 );
964 mbedtls_sha1_init( &sha1 );
965
966 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
967 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
968
969 memset( pad_1, 0x36, 48 );
970 memset( pad_2, 0x5C, 48 );
971
972 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
973 mbedtls_md5_update( &md5, pad_1, 48 );
974 mbedtls_md5_finish( &md5, hash );
975
976 mbedtls_md5_starts( &md5 );
977 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
978 mbedtls_md5_update( &md5, pad_2, 48 );
979 mbedtls_md5_update( &md5, hash, 16 );
980 mbedtls_md5_finish( &md5, hash );
981
982 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
983 mbedtls_sha1_update( &sha1, pad_1, 40 );
984 mbedtls_sha1_finish( &sha1, hash + 16 );
985
986 mbedtls_sha1_starts( &sha1 );
987 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
988 mbedtls_sha1_update( &sha1, pad_2, 40 );
989 mbedtls_sha1_update( &sha1, hash + 16, 20 );
990 mbedtls_sha1_finish( &sha1, hash + 16 );
991
992 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
993 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
994
995 mbedtls_md5_free( &md5 );
996 mbedtls_sha1_free( &sha1 );
997
998 return;
999 }
1000 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1001
1002 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1003 void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
1004 {
1005 mbedtls_md5_context md5;
1006 mbedtls_sha1_context sha1;
1007
1008 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1009
1010 mbedtls_md5_init( &md5 );
1011 mbedtls_sha1_init( &sha1 );
1012
1013 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1014 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1015
1016 mbedtls_md5_finish( &md5, hash );
1017 mbedtls_sha1_finish( &sha1, hash + 16 );
1018
1019 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1020 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1021
1022 mbedtls_md5_free( &md5 );
1023 mbedtls_sha1_free( &sha1 );
1024
1025 return;
1026 }
1027 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1028
1029 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1030 #if defined(MBEDTLS_SHA256_C)
1031 void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
1032 {
1033 mbedtls_sha256_context sha256;
1034
1035 mbedtls_sha256_init( &sha256 );
1036
1037 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1038
1039 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1040 mbedtls_sha256_finish( &sha256, hash );
1041
1042 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
1043 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1044
1045 mbedtls_sha256_free( &sha256 );
1046
1047 return;
1048 }
1049 #endif /* MBEDTLS_SHA256_C */
1050
1051 #if defined(MBEDTLS_SHA512_C)
1052 void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
1053 {
1054 mbedtls_sha512_context sha512;
1055
1056 mbedtls_sha512_init( &sha512 );
1057
1058 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1059
1060 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
1061 mbedtls_sha512_finish( &sha512, hash );
1062
1063 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
1064 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1065
1066 mbedtls_sha512_free( &sha512 );
1067
1068 return;
1069 }
1070 #endif /* MBEDTLS_SHA512_C */
1071 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1072
1073 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1074 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1075 {
1076 unsigned char *p = ssl->handshake->premaster;
1077 unsigned char *end = p + sizeof( ssl->handshake->premaster );
1078 const unsigned char *psk = ssl->conf->psk;
1079 size_t psk_len = ssl->conf->psk_len;
1080
1081 /* If the psk callback was called, use its result */
1082 if( ssl->handshake->psk != NULL )
1083 {
1084 psk = ssl->handshake->psk;
1085 psk_len = ssl->handshake->psk_len;
1086 }
1087
1088 /*
1089 * PMS = struct {
1090 * opaque other_secret<0..2^16-1>;
1091 * opaque psk<0..2^16-1>;
1092 * };
1093 * with "other_secret" depending on the particular key exchange
1094 */
1095 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1096 if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1097 {
1098 if( end - p < 2 + (int) psk_len )
1099 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1100
1101 *(p++) = (unsigned char)( psk_len >> 8 );
1102 *(p++) = (unsigned char)( psk_len );
1103 p += psk_len;
1104 }
1105 else
1106 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1107 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1108 if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
1109 {
1110 /*
1111 * other_secret already set by the ClientKeyExchange message,
1112 * and is 48 bytes long
1113 */
1114 *p++ = 0;
1115 *p++ = 48;
1116 p += 48;
1117 }
1118 else
1119 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1120 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1121 if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
1122 {
1123 int ret;
1124 size_t len;
1125
1126 /* Write length only when we know the actual value */
1127 if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
1128 p + 2, end - ( p + 2 ), &len,
1129 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1130 {
1131 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1132 return( ret );
1133 }
1134 *(p++) = (unsigned char)( len >> 8 );
1135 *(p++) = (unsigned char)( len );
1136 p += len;
1137
1138 MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
1139 }
1140 else
1141 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1142 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
1143 if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
1144 {
1145 int ret;
1146 size_t zlen;
1147
1148 if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
1149 p + 2, end - ( p + 2 ),
1150 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1151 {
1152 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1153 return( ret );
1154 }
1155
1156 *(p++) = (unsigned char)( zlen >> 8 );
1157 *(p++) = (unsigned char)( zlen );
1158 p += zlen;
1159
1160 MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
1161 }
1162 else
1163 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1164 {
1165 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1166 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1167 }
1168
1169 /* opaque psk<0..2^16-1>; */
1170 if( end - p < 2 + (int) psk_len )
1171 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1172
1173 *(p++) = (unsigned char)( psk_len >> 8 );
1174 *(p++) = (unsigned char)( psk_len );
1175 memcpy( p, psk, psk_len );
1176 p += psk_len;
1177
1178 ssl->handshake->pmslen = p - ssl->handshake->premaster;
1179
1180 return( 0 );
1181 }
1182 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1183
1184 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1185 /*
1186 * SSLv3.0 MAC functions
1187 */
1188 static void ssl_mac( mbedtls_md_context_t *md_ctx, unsigned char *secret,
1189 unsigned char *buf, size_t len,
1190 unsigned char *ctr, int type )
1191 {
1192 unsigned char header[11];
1193 unsigned char padding[48];
1194 int padlen;
1195 int md_size = mbedtls_md_get_size( md_ctx->md_info );
1196 int md_type = mbedtls_md_get_type( md_ctx->md_info );
1197
1198 /* Only MD5 and SHA-1 supported */
1199 if( md_type == MBEDTLS_MD_MD5 )
1200 padlen = 48;
1201 else
1202 padlen = 40;
1203
1204 memcpy( header, ctr, 8 );
1205 header[ 8] = (unsigned char) type;
1206 header[ 9] = (unsigned char)( len >> 8 );
1207 header[10] = (unsigned char)( len );
1208
1209 memset( padding, 0x36, padlen );
1210 mbedtls_md_starts( md_ctx );
1211 mbedtls_md_update( md_ctx, secret, md_size );
1212 mbedtls_md_update( md_ctx, padding, padlen );
1213 mbedtls_md_update( md_ctx, header, 11 );
1214 mbedtls_md_update( md_ctx, buf, len );
1215 mbedtls_md_finish( md_ctx, buf + len );
1216
1217 memset( padding, 0x5C, padlen );
1218 mbedtls_md_starts( md_ctx );
1219 mbedtls_md_update( md_ctx, secret, md_size );
1220 mbedtls_md_update( md_ctx, padding, padlen );
1221 mbedtls_md_update( md_ctx, buf + len, md_size );
1222 mbedtls_md_finish( md_ctx, buf + len );
1223 }
1224 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1225
1226 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
1227 ( defined(MBEDTLS_CIPHER_MODE_CBC) && \
1228 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) )
1229 #define SSL_SOME_MODES_USE_MAC
1230 #endif
1231
1232 /*
1233 * Encryption/decryption functions
1234 */
1235 static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
1236 {
1237 mbedtls_cipher_mode_t mode;
1238 int auth_done = 0;
1239
1240 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
1241
1242 if( ssl->session_out == NULL || ssl->transform_out == NULL )
1243 {
1244 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1245 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1246 }
1247
1248 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
1249
1250 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
1251 ssl->out_msg, ssl->out_msglen );
1252
1253 /*
1254 * Add MAC before if needed
1255 */
1256 #if defined(SSL_SOME_MODES_USE_MAC)
1257 if( mode == MBEDTLS_MODE_STREAM ||
1258 ( mode == MBEDTLS_MODE_CBC
1259 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1260 && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
1261 #endif
1262 ) )
1263 {
1264 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1265 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1266 {
1267 ssl_mac( &ssl->transform_out->md_ctx_enc,
1268 ssl->transform_out->mac_enc,
1269 ssl->out_msg, ssl->out_msglen,
1270 ssl->out_ctr, ssl->out_msgtype );
1271 }
1272 else
1273 #endif
1274 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1275 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1276 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
1277 {
1278 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
1279 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
1280 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
1281 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1282 ssl->out_msg, ssl->out_msglen );
1283 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1284 ssl->out_msg + ssl->out_msglen );
1285 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1286 }
1287 else
1288 #endif
1289 {
1290 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1291 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1292 }
1293
1294 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
1295 ssl->out_msg + ssl->out_msglen,
1296 ssl->transform_out->maclen );
1297
1298 ssl->out_msglen += ssl->transform_out->maclen;
1299 auth_done++;
1300 }
1301 #endif /* AEAD not the only option */
1302
1303 /*
1304 * Encrypt
1305 */
1306 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1307 if( mode == MBEDTLS_MODE_STREAM )
1308 {
1309 int ret;
1310 size_t olen = 0;
1311
1312 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1313 "including %d bytes of padding",
1314 ssl->out_msglen, 0 ) );
1315
1316 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1317 ssl->transform_out->iv_enc,
1318 ssl->transform_out->ivlen,
1319 ssl->out_msg, ssl->out_msglen,
1320 ssl->out_msg, &olen ) ) != 0 )
1321 {
1322 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1323 return( ret );
1324 }
1325
1326 if( ssl->out_msglen != olen )
1327 {
1328 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1329 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1330 }
1331 }
1332 else
1333 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1334 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1335 if( mode == MBEDTLS_MODE_GCM ||
1336 mode == MBEDTLS_MODE_CCM )
1337 {
1338 int ret;
1339 size_t enc_msglen, olen;
1340 unsigned char *enc_msg;
1341 unsigned char add_data[13];
1342 unsigned char taglen = ssl->transform_out->ciphersuite_info->flags &
1343 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1344
1345 memcpy( add_data, ssl->out_ctr, 8 );
1346 add_data[8] = ssl->out_msgtype;
1347 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1348 ssl->conf->transport, add_data + 9 );
1349 add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
1350 add_data[12] = ssl->out_msglen & 0xFF;
1351
1352 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1353 add_data, 13 );
1354
1355 /*
1356 * Generate IV
1357 */
1358 #if defined(MBEDTLS_SSL_AEAD_RANDOM_IV)
1359 ret = ssl->conf->f_rng( ssl->conf->p_rng,
1360 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1361 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1362 if( ret != 0 )
1363 return( ret );
1364
1365 memcpy( ssl->out_iv,
1366 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1367 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1368 #else
1369 if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 )
1370 {
1371 /* Reminder if we ever add an AEAD mode with a different size */
1372 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1373 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1374 }
1375
1376 memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1377 ssl->out_ctr, 8 );
1378 memcpy( ssl->out_iv, ssl->out_ctr, 8 );
1379 #endif
1380
1381 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv,
1382 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1383
1384 /*
1385 * Fix pointer positions and message length with added IV
1386 */
1387 enc_msg = ssl->out_msg;
1388 enc_msglen = ssl->out_msglen;
1389 ssl->out_msglen += ssl->transform_out->ivlen -
1390 ssl->transform_out->fixed_ivlen;
1391
1392 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1393 "including %d bytes of padding",
1394 ssl->out_msglen, 0 ) );
1395
1396 /*
1397 * Encrypt and authenticate
1398 */
1399 if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc,
1400 ssl->transform_out->iv_enc,
1401 ssl->transform_out->ivlen,
1402 add_data, 13,
1403 enc_msg, enc_msglen,
1404 enc_msg, &olen,
1405 enc_msg + enc_msglen, taglen ) ) != 0 )
1406 {
1407 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
1408 return( ret );
1409 }
1410
1411 if( olen != enc_msglen )
1412 {
1413 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1414 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1415 }
1416
1417 ssl->out_msglen += taglen;
1418 auth_done++;
1419
1420 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
1421 }
1422 else
1423 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1424 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1425 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1426 if( mode == MBEDTLS_MODE_CBC )
1427 {
1428 int ret;
1429 unsigned char *enc_msg;
1430 size_t enc_msglen, padlen, olen = 0, i;
1431
1432 padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
1433 ssl->transform_out->ivlen;
1434 if( padlen == ssl->transform_out->ivlen )
1435 padlen = 0;
1436
1437 for( i = 0; i <= padlen; i++ )
1438 ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
1439
1440 ssl->out_msglen += padlen + 1;
1441
1442 enc_msglen = ssl->out_msglen;
1443 enc_msg = ssl->out_msg;
1444
1445 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1446 /*
1447 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
1448 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1449 */
1450 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1451 {
1452 /*
1453 * Generate IV
1454 */
1455 ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
1456 ssl->transform_out->ivlen );
1457 if( ret != 0 )
1458 return( ret );
1459
1460 memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
1461 ssl->transform_out->ivlen );
1462
1463 /*
1464 * Fix pointer positions and message length with added IV
1465 */
1466 enc_msg = ssl->out_msg;
1467 enc_msglen = ssl->out_msglen;
1468 ssl->out_msglen += ssl->transform_out->ivlen;
1469 }
1470 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1471
1472 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1473 "including %d bytes of IV and %d bytes of padding",
1474 ssl->out_msglen, ssl->transform_out->ivlen,
1475 padlen + 1 ) );
1476
1477 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1478 ssl->transform_out->iv_enc,
1479 ssl->transform_out->ivlen,
1480 enc_msg, enc_msglen,
1481 enc_msg, &olen ) ) != 0 )
1482 {
1483 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1484 return( ret );
1485 }
1486
1487 if( enc_msglen != olen )
1488 {
1489 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1490 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1491 }
1492
1493 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1494 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1495 {
1496 /*
1497 * Save IV in SSL3 and TLS1
1498 */
1499 memcpy( ssl->transform_out->iv_enc,
1500 ssl->transform_out->cipher_ctx_enc.iv,
1501 ssl->transform_out->ivlen );
1502 }
1503 #endif
1504
1505 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1506 if( auth_done == 0 )
1507 {
1508 /*
1509 * MAC(MAC_write_key, seq_num +
1510 * TLSCipherText.type +
1511 * TLSCipherText.version +
1512 * length_of( (IV +) ENC(...) ) +
1513 * IV + // except for TLS 1.0
1514 * ENC(content + padding + padding_length));
1515 */
1516 unsigned char pseudo_hdr[13];
1517
1518 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1519
1520 memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
1521 memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
1522 pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
1523 pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
1524
1525 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1526
1527 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
1528 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1529 ssl->out_iv, ssl->out_msglen );
1530 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1531 ssl->out_iv + ssl->out_msglen );
1532 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1533
1534 ssl->out_msglen += ssl->transform_out->maclen;
1535 auth_done++;
1536 }
1537 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1538 }
1539 else
1540 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1541 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1542 {
1543 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1544 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1545 }
1546
1547 /* Make extra sure authentication was performed, exactly once */
1548 if( auth_done != 1 )
1549 {
1550 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1551 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1552 }
1553
1554 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1555
1556 return( 0 );
1557 }
1558
1559 #define SSL_MAX_MAC_SIZE 48
1560
1561 static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
1562 {
1563 size_t i;
1564 mbedtls_cipher_mode_t mode;
1565 int auth_done = 0;
1566 #if defined(SSL_SOME_MODES_USE_MAC)
1567 size_t padlen = 0, correct = 1;
1568 #endif
1569
1570 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1571
1572 if( ssl->session_in == NULL || ssl->transform_in == NULL )
1573 {
1574 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1575 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1576 }
1577
1578 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
1579
1580 if( ssl->in_msglen < ssl->transform_in->minlen )
1581 {
1582 MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
1583 ssl->in_msglen, ssl->transform_in->minlen ) );
1584 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1585 }
1586
1587 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1588 if( mode == MBEDTLS_MODE_STREAM )
1589 {
1590 int ret;
1591 size_t olen = 0;
1592
1593 padlen = 0;
1594
1595 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1596 ssl->transform_in->iv_dec,
1597 ssl->transform_in->ivlen,
1598 ssl->in_msg, ssl->in_msglen,
1599 ssl->in_msg, &olen ) ) != 0 )
1600 {
1601 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1602 return( ret );
1603 }
1604
1605 if( ssl->in_msglen != olen )
1606 {
1607 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1608 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1609 }
1610 }
1611 else
1612 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1613 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1614 if( mode == MBEDTLS_MODE_GCM ||
1615 mode == MBEDTLS_MODE_CCM )
1616 {
1617 int ret;
1618 size_t dec_msglen, olen;
1619 unsigned char *dec_msg;
1620 unsigned char *dec_msg_result;
1621 unsigned char add_data[13];
1622 unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
1623 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1624 size_t explicit_iv_len = ssl->transform_in->ivlen -
1625 ssl->transform_in->fixed_ivlen;
1626
1627 if( ssl->in_msglen < explicit_iv_len + taglen )
1628 {
1629 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
1630 "+ taglen (%d)", ssl->in_msglen,
1631 explicit_iv_len, taglen ) );
1632 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1633 }
1634 dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
1635
1636 dec_msg = ssl->in_msg;
1637 dec_msg_result = ssl->in_msg;
1638 ssl->in_msglen = dec_msglen;
1639
1640 memcpy( add_data, ssl->in_ctr, 8 );
1641 add_data[8] = ssl->in_msgtype;
1642 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1643 ssl->conf->transport, add_data + 9 );
1644 add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
1645 add_data[12] = ssl->in_msglen & 0xFF;
1646
1647 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1648 add_data, 13 );
1649
1650 memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
1651 ssl->in_iv,
1652 ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
1653
1654 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
1655 ssl->transform_in->ivlen );
1656 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
1657
1658 /*
1659 * Decrypt and authenticate
1660 */
1661 if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
1662 ssl->transform_in->iv_dec,
1663 ssl->transform_in->ivlen,
1664 add_data, 13,
1665 dec_msg, dec_msglen,
1666 dec_msg_result, &olen,
1667 dec_msg + dec_msglen, taglen ) ) != 0 )
1668 {
1669 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
1670
1671 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
1672 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1673
1674 return( ret );
1675 }
1676 auth_done++;
1677
1678 if( olen != dec_msglen )
1679 {
1680 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1681 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1682 }
1683 }
1684 else
1685 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1686 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1687 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1688 if( mode == MBEDTLS_MODE_CBC )
1689 {
1690 /*
1691 * Decrypt and check the padding
1692 */
1693 int ret;
1694 unsigned char *dec_msg;
1695 unsigned char *dec_msg_result;
1696 size_t dec_msglen;
1697 size_t minlen = 0;
1698 size_t olen = 0;
1699
1700 /*
1701 * Check immediate ciphertext sanity
1702 */
1703 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1704 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1705 minlen += ssl->transform_in->ivlen;
1706 #endif
1707
1708 if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
1709 ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
1710 {
1711 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
1712 "+ 1 ) ( + expl IV )", ssl->in_msglen,
1713 ssl->transform_in->ivlen,
1714 ssl->transform_in->maclen ) );
1715 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1716 }
1717
1718 dec_msglen = ssl->in_msglen;
1719 dec_msg = ssl->in_msg;
1720 dec_msg_result = ssl->in_msg;
1721
1722 /*
1723 * Authenticate before decrypt if enabled
1724 */
1725 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1726 if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1727 {
1728 unsigned char computed_mac[SSL_MAX_MAC_SIZE];
1729 unsigned char pseudo_hdr[13];
1730
1731 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1732
1733 dec_msglen -= ssl->transform_in->maclen;
1734 ssl->in_msglen -= ssl->transform_in->maclen;
1735
1736 memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
1737 memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
1738 pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
1739 pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
1740
1741 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1742
1743 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
1744 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
1745 ssl->in_iv, ssl->in_msglen );
1746 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac );
1747 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1748
1749 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
1750 ssl->transform_in->maclen );
1751 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", computed_mac,
1752 ssl->transform_in->maclen );
1753
1754 if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac,
1755 ssl->transform_in->maclen ) != 0 )
1756 {
1757 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1758
1759 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1760 }
1761 auth_done++;
1762 }
1763 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1764
1765 /*
1766 * Check length sanity
1767 */
1768 if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
1769 {
1770 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
1771 ssl->in_msglen, ssl->transform_in->ivlen ) );
1772 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1773 }
1774
1775 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1776 /*
1777 * Initialize for prepended IV for block cipher in TLS v1.1 and up
1778 */
1779 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1780 {
1781 dec_msglen -= ssl->transform_in->ivlen;
1782 ssl->in_msglen -= ssl->transform_in->ivlen;
1783
1784 for( i = 0; i < ssl->transform_in->ivlen; i++ )
1785 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
1786 }
1787 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1788
1789 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1790 ssl->transform_in->iv_dec,
1791 ssl->transform_in->ivlen,
1792 dec_msg, dec_msglen,
1793 dec_msg_result, &olen ) ) != 0 )
1794 {
1795 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1796 return( ret );
1797 }
1798
1799 if( dec_msglen != olen )
1800 {
1801 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1802 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1803 }
1804
1805 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1806 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1807 {
1808 /*
1809 * Save IV in SSL3 and TLS1
1810 */
1811 memcpy( ssl->transform_in->iv_dec,
1812 ssl->transform_in->cipher_ctx_dec.iv,
1813 ssl->transform_in->ivlen );
1814 }
1815 #endif
1816
1817 padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
1818
1819 if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
1820 auth_done == 0 )
1821 {
1822 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1823 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
1824 ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
1825 #endif
1826 padlen = 0;
1827 correct = 0;
1828 }
1829
1830 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1831 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1832 {
1833 if( padlen > ssl->transform_in->ivlen )
1834 {
1835 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1836 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
1837 "should be no more than %d",
1838 padlen, ssl->transform_in->ivlen ) );
1839 #endif
1840 correct = 0;
1841 }
1842 }
1843 else
1844 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1845 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1846 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1847 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1848 {
1849 /*
1850 * TLSv1+: always check the padding up to the first failure
1851 * and fake check up to 256 bytes of padding
1852 */
1853 size_t pad_count = 0, real_count = 1;
1854 size_t padding_idx = ssl->in_msglen - padlen - 1;
1855
1856 /*
1857 * Padding is guaranteed to be incorrect if:
1858 * 1. padlen >= ssl->in_msglen
1859 *
1860 * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN +
1861 * ssl->transform_in->maclen
1862 *
1863 * In both cases we reset padding_idx to a safe value (0) to
1864 * prevent out-of-buffer reads.
1865 */
1866 correct &= ( ssl->in_msglen >= padlen + 1 );
1867 correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN +
1868 ssl->transform_in->maclen );
1869
1870 padding_idx *= correct;
1871
1872 for( i = 1; i <= 256; i++ )
1873 {
1874 real_count &= ( i <= padlen );
1875 pad_count += real_count *
1876 ( ssl->in_msg[padding_idx + i] == padlen - 1 );
1877 }
1878
1879 correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
1880
1881 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1882 if( padlen > 0 && correct == 0 )
1883 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
1884 #endif
1885 padlen &= correct * 0x1FF;
1886 }
1887 else
1888 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1889 MBEDTLS_SSL_PROTO_TLS1_2 */
1890 {
1891 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1892 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1893 }
1894
1895 ssl->in_msglen -= padlen;
1896 }
1897 else
1898 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1899 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1900 {
1901 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1902 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1903 }
1904
1905 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
1906 ssl->in_msg, ssl->in_msglen );
1907
1908 /*
1909 * Authenticate if not done yet.
1910 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1911 */
1912 #if defined(SSL_SOME_MODES_USE_MAC)
1913 if( auth_done == 0 )
1914 {
1915 unsigned char tmp[SSL_MAX_MAC_SIZE];
1916
1917 ssl->in_msglen -= ssl->transform_in->maclen;
1918
1919 ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
1920 ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
1921
1922 memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
1923
1924 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1925 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1926 {
1927 ssl_mac( &ssl->transform_in->md_ctx_dec,
1928 ssl->transform_in->mac_dec,
1929 ssl->in_msg, ssl->in_msglen,
1930 ssl->in_ctr, ssl->in_msgtype );
1931 }
1932 else
1933 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1934 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1935 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1936 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1937 {
1938 /*
1939 * Process MAC and always update for padlen afterwards to make
1940 * total time independent of padlen
1941 *
1942 * extra_run compensates MAC check for padlen
1943 *
1944 * Known timing attacks:
1945 * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
1946 *
1947 * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
1948 * correctly. (We round down instead of up, so -56 is the correct
1949 * value for our calculations instead of -55)
1950 */
1951 size_t j, extra_run = 0;
1952 extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
1953 ( 13 + ssl->in_msglen + 8 ) / 64;
1954
1955 extra_run &= correct * 0xFF;
1956
1957 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
1958 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
1959 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
1960 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
1961 ssl->in_msglen );
1962 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec,
1963 ssl->in_msg + ssl->in_msglen );
1964 /* Call mbedtls_md_process at least once due to cache attacks */
1965 for( j = 0; j < extra_run + 1; j++ )
1966 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
1967
1968 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1969 }
1970 else
1971 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1972 MBEDTLS_SSL_PROTO_TLS1_2 */
1973 {
1974 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1975 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1976 }
1977
1978 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen );
1979 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
1980 ssl->transform_in->maclen );
1981
1982 if( mbedtls_ssl_safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen,
1983 ssl->transform_in->maclen ) != 0 )
1984 {
1985 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1986 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1987 #endif
1988 correct = 0;
1989 }
1990 auth_done++;
1991
1992 /*
1993 * Finally check the correct flag
1994 */
1995 if( correct == 0 )
1996 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1997 }
1998 #endif /* SSL_SOME_MODES_USE_MAC */
1999
2000 /* Make extra sure authentication was performed, exactly once */
2001 if( auth_done != 1 )
2002 {
2003 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2004 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2005 }
2006
2007 if( ssl->in_msglen == 0 )
2008 {
2009 ssl->nb_zero++;
2010
2011 /*
2012 * Three or more empty messages may be a DoS attack
2013 * (excessive CPU consumption).
2014 */
2015 if( ssl->nb_zero > 3 )
2016 {
2017 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
2018 "messages, possible DoS attack" ) );
2019 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2020 }
2021 }
2022 else
2023 ssl->nb_zero = 0;
2024
2025 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2026 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2027 {
2028 ; /* in_ctr read from peer, not maintained internally */
2029 }
2030 else
2031 #endif
2032 {
2033 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2034 if( ++ssl->in_ctr[i - 1] != 0 )
2035 break;
2036
2037 /* The loop goes to its end iff the counter is wrapping */
2038 if( i == ssl_ep_len( ssl ) )
2039 {
2040 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
2041 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2042 }
2043 }
2044
2045 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
2046
2047 return( 0 );
2048 }
2049
2050 #undef MAC_NONE
2051 #undef MAC_PLAINTEXT
2052 #undef MAC_CIPHERTEXT
2053
2054 #if defined(MBEDTLS_ZLIB_SUPPORT)
2055 /*
2056 * Compression/decompression functions
2057 */
2058 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
2059 {
2060 int ret;
2061 unsigned char *msg_post = ssl->out_msg;
2062 size_t len_pre = ssl->out_msglen;
2063 unsigned char *msg_pre = ssl->compress_buf;
2064
2065 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
2066
2067 if( len_pre == 0 )
2068 return( 0 );
2069
2070 memcpy( msg_pre, ssl->out_msg, len_pre );
2071
2072 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
2073 ssl->out_msglen ) );
2074
2075 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
2076 ssl->out_msg, ssl->out_msglen );
2077
2078 ssl->transform_out->ctx_deflate.next_in = msg_pre;
2079 ssl->transform_out->ctx_deflate.avail_in = len_pre;
2080 ssl->transform_out->ctx_deflate.next_out = msg_post;
2081 ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN;
2082
2083 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
2084 if( ret != Z_OK )
2085 {
2086 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
2087 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2088 }
2089
2090 ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN -
2091 ssl->transform_out->ctx_deflate.avail_out;
2092
2093 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
2094 ssl->out_msglen ) );
2095
2096 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
2097 ssl->out_msg, ssl->out_msglen );
2098
2099 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
2100
2101 return( 0 );
2102 }
2103
2104 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
2105 {
2106 int ret;
2107 unsigned char *msg_post = ssl->in_msg;
2108 size_t len_pre = ssl->in_msglen;
2109 unsigned char *msg_pre = ssl->compress_buf;
2110
2111 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
2112
2113 if( len_pre == 0 )
2114 return( 0 );
2115
2116 memcpy( msg_pre, ssl->in_msg, len_pre );
2117
2118 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
2119 ssl->in_msglen ) );
2120
2121 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
2122 ssl->in_msg, ssl->in_msglen );
2123
2124 ssl->transform_in->ctx_inflate.next_in = msg_pre;
2125 ssl->transform_in->ctx_inflate.avail_in = len_pre;
2126 ssl->transform_in->ctx_inflate.next_out = msg_post;
2127 ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN;
2128
2129 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
2130 if( ret != Z_OK )
2131 {
2132 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
2133 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2134 }
2135
2136 ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN -
2137 ssl->transform_in->ctx_inflate.avail_out;
2138
2139 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
2140 ssl->in_msglen ) );
2141
2142 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
2143 ssl->in_msg, ssl->in_msglen );
2144
2145 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
2146
2147 return( 0 );
2148 }
2149 #endif /* MBEDTLS_ZLIB_SUPPORT */
2150
2151 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2152 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
2153
2154 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2155 static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
2156 {
2157 /* If renegotiation is not enforced, retransmit until we would reach max
2158 * timeout if we were using the usual handshake doubling scheme */
2159 if( ssl->conf->renego_max_records < 0 )
2160 {
2161 uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2162 unsigned char doublings = 1;
2163
2164 while( ratio != 0 )
2165 {
2166 ++doublings;
2167 ratio >>= 1;
2168 }
2169
2170 if( ++ssl->renego_records_seen > doublings )
2171 {
2172 MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
2173 return( 0 );
2174 }
2175 }
2176
2177 return( ssl_write_hello_request( ssl ) );
2178 }
2179 #endif
2180 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2181
2182 /*
2183 * Fill the input message buffer by appending data to it.
2184 * The amount of data already fetched is in ssl->in_left.
2185 *
2186 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2187 * available (from this read and/or a previous one). Otherwise, an error code
2188 * is returned (possibly EOF or WANT_READ).
2189 *
2190 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2191 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2192 * since we always read a whole datagram at once.
2193 *
2194 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2195 * they're done reading a record.
2196 */
2197 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
2198 {
2199 int ret;
2200 size_t len;
2201
2202 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2203
2204 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2205 {
2206 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2207 "or mbedtls_ssl_set_bio()" ) );
2208 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2209 }
2210
2211 if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2212 {
2213 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2214 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2215 }
2216
2217 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2218 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2219 {
2220 uint32_t timeout;
2221
2222 /* Just to be sure */
2223 if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
2224 {
2225 MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
2226 "mbedtls_ssl_set_timer_cb() for DTLS" ) );
2227 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2228 }
2229
2230 /*
2231 * The point is, we need to always read a full datagram at once, so we
2232 * sometimes read more then requested, and handle the additional data.
2233 * It could be the rest of the current record (while fetching the
2234 * header) and/or some other records in the same datagram.
2235 */
2236
2237 /*
2238 * Move to the next record in the already read datagram if applicable
2239 */
2240 if( ssl->next_record_offset != 0 )
2241 {
2242 if( ssl->in_left < ssl->next_record_offset )
2243 {
2244 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2245 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2246 }
2247
2248 ssl->in_left -= ssl->next_record_offset;
2249
2250 if( ssl->in_left != 0 )
2251 {
2252 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2253 ssl->next_record_offset ) );
2254 memmove( ssl->in_hdr,
2255 ssl->in_hdr + ssl->next_record_offset,
2256 ssl->in_left );
2257 }
2258
2259 ssl->next_record_offset = 0;
2260 }
2261
2262 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2263 ssl->in_left, nb_want ) );
2264
2265 /*
2266 * Done if we already have enough data.
2267 */
2268 if( nb_want <= ssl->in_left)
2269 {
2270 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2271 return( 0 );
2272 }
2273
2274 /*
2275 * A record can't be split accross datagrams. If we need to read but
2276 * are not at the beginning of a new record, the caller did something
2277 * wrong.
2278 */
2279 if( ssl->in_left != 0 )
2280 {
2281 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2282 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2283 }
2284
2285 /*
2286 * Don't even try to read if time's out already.
2287 * This avoids by-passing the timer when repeatedly receiving messages
2288 * that will end up being dropped.
2289 */
2290 if( ssl_check_timer( ssl ) != 0 )
2291 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2292 else
2293 {
2294 len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
2295
2296 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2297 timeout = ssl->handshake->retransmit_timeout;
2298 else
2299 timeout = ssl->conf->read_timeout;
2300
2301 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2302
2303 if( ssl->f_recv_timeout != NULL )
2304 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2305 timeout );
2306 else
2307 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2308
2309 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2310
2311 if( ret == 0 )
2312 return( MBEDTLS_ERR_SSL_CONN_EOF );
2313 }
2314
2315 if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
2316 {
2317 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2318 ssl_set_timer( ssl, 0 );
2319
2320 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2321 {
2322 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2323 {
2324 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2325 return( MBEDTLS_ERR_SSL_TIMEOUT );
2326 }
2327
2328 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2329 {
2330 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2331 return( ret );
2332 }
2333
2334 return( MBEDTLS_ERR_SSL_WANT_READ );
2335 }
2336 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2337 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2338 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
2339 {
2340 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
2341 {
2342 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
2343 return( ret );
2344 }
2345
2346 return( MBEDTLS_ERR_SSL_WANT_READ );
2347 }
2348 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2349 }
2350
2351 if( ret < 0 )
2352 return( ret );
2353
2354 ssl->in_left = ret;
2355 }
2356 else
2357 #endif
2358 {
2359 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2360 ssl->in_left, nb_want ) );
2361
2362 while( ssl->in_left < nb_want )
2363 {
2364 len = nb_want - ssl->in_left;
2365
2366 if( ssl_check_timer( ssl ) != 0 )
2367 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2368 else
2369 {
2370 if( ssl->f_recv_timeout != NULL )
2371 {
2372 ret = ssl->f_recv_timeout( ssl->p_bio,
2373 ssl->in_hdr + ssl->in_left, len,
2374 ssl->conf->read_timeout );
2375 }
2376 else
2377 {
2378 ret = ssl->f_recv( ssl->p_bio,
2379 ssl->in_hdr + ssl->in_left, len );
2380 }
2381 }
2382
2383 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2384 ssl->in_left, nb_want ) );
2385 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2386
2387 if( ret == 0 )
2388 return( MBEDTLS_ERR_SSL_CONN_EOF );
2389
2390 if( ret < 0 )
2391 return( ret );
2392
2393 ssl->in_left += ret;
2394 }
2395 }
2396
2397 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2398
2399 return( 0 );
2400 }
2401
2402 /*
2403 * Flush any data not yet written
2404 */
2405 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
2406 {
2407 int ret;
2408 unsigned char *buf, i;
2409
2410 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2411
2412 if( ssl->f_send == NULL )
2413 {
2414 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2415 "or mbedtls_ssl_set_bio()" ) );
2416 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2417 }
2418
2419 /* Avoid incrementing counter if data is flushed */
2420 if( ssl->out_left == 0 )
2421 {
2422 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2423 return( 0 );
2424 }
2425
2426 while( ssl->out_left > 0 )
2427 {
2428 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2429 mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2430
2431 buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) +
2432 ssl->out_msglen - ssl->out_left;
2433 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2434
2435 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2436
2437 if( ret <= 0 )
2438 return( ret );
2439
2440 ssl->out_left -= ret;
2441 }
2442
2443 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2444 if( ++ssl->out_ctr[i - 1] != 0 )
2445 break;
2446
2447 /* The loop goes to its end iff the counter is wrapping */
2448 if( i == ssl_ep_len( ssl ) )
2449 {
2450 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
2451 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2452 }
2453
2454 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2455
2456 return( 0 );
2457 }
2458
2459 /*
2460 * Functions to handle the DTLS retransmission state machine
2461 */
2462 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2463 /*
2464 * Append current handshake message to current outgoing flight
2465 */
2466 static int ssl_flight_append( mbedtls_ssl_context *ssl )
2467 {
2468 mbedtls_ssl_flight_item *msg;
2469
2470 /* Allocate space for current message */
2471 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2472 {
2473 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2474 sizeof( mbedtls_ssl_flight_item ) ) );
2475 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2476 }
2477
2478 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2479 {
2480 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2481 mbedtls_free( msg );
2482 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2483 }
2484
2485 /* Copy current handshake message with headers */
2486 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2487 msg->len = ssl->out_msglen;
2488 msg->type = ssl->out_msgtype;
2489 msg->next = NULL;
2490
2491 /* Append to the current flight */
2492 if( ssl->handshake->flight == NULL )
2493 ssl->handshake->flight = msg;
2494 else
2495 {
2496 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2497 while( cur->next != NULL )
2498 cur = cur->next;
2499 cur->next = msg;
2500 }
2501
2502 return( 0 );
2503 }
2504
2505 /*
2506 * Free the current flight of handshake messages
2507 */
2508 static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
2509 {
2510 mbedtls_ssl_flight_item *cur = flight;
2511 mbedtls_ssl_flight_item *next;
2512
2513 while( cur != NULL )
2514 {
2515 next = cur->next;
2516
2517 mbedtls_free( cur->p );
2518 mbedtls_free( cur );
2519
2520 cur = next;
2521 }
2522 }
2523
2524 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2525 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
2526 #endif
2527
2528 /*
2529 * Swap transform_out and out_ctr with the alternative ones
2530 */
2531 static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
2532 {
2533 mbedtls_ssl_transform *tmp_transform;
2534 unsigned char tmp_out_ctr[8];
2535
2536 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2537 {
2538 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2539 return;
2540 }
2541
2542 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2543
2544 /* Swap transforms */
2545 tmp_transform = ssl->transform_out;
2546 ssl->transform_out = ssl->handshake->alt_transform_out;
2547 ssl->handshake->alt_transform_out = tmp_transform;
2548
2549 /* Swap epoch + sequence_number */
2550 memcpy( tmp_out_ctr, ssl->out_ctr, 8 );
2551 memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 );
2552 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
2553
2554 /* Adjust to the newly activated transform */
2555 if( ssl->transform_out != NULL &&
2556 ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
2557 {
2558 ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen -
2559 ssl->transform_out->fixed_ivlen;
2560 }
2561 else
2562 ssl->out_msg = ssl->out_iv;
2563
2564 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2565 if( mbedtls_ssl_hw_record_activate != NULL )
2566 {
2567 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
2568 {
2569 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
2570 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2571 }
2572 }
2573 #endif
2574 }
2575
2576 /*
2577 * Retransmit the current flight of messages.
2578 *
2579 * Need to remember the current message in case flush_output returns
2580 * WANT_WRITE, causing us to exit this function and come back later.
2581 * This function must be called until state is no longer SENDING.
2582 */
2583 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
2584 {
2585 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
2586
2587 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
2588 {
2589 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) );
2590
2591 ssl->handshake->cur_msg = ssl->handshake->flight;
2592 ssl_swap_epochs( ssl );
2593
2594 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2595 }
2596
2597 while( ssl->handshake->cur_msg != NULL )
2598 {
2599 int ret;
2600 mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg;
2601
2602 /* Swap epochs before sending Finished: we can't do it after
2603 * sending ChangeCipherSpec, in case write returns WANT_READ.
2604 * Must be done before copying, may change out_msg pointer */
2605 if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2606 cur->p[0] == MBEDTLS_SSL_HS_FINISHED )
2607 {
2608 ssl_swap_epochs( ssl );
2609 }
2610
2611 memcpy( ssl->out_msg, cur->p, cur->len );
2612 ssl->out_msglen = cur->len;
2613 ssl->out_msgtype = cur->type;
2614
2615 ssl->handshake->cur_msg = cur->next;
2616
2617 MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 );
2618
2619 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
2620 {
2621 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
2622 return( ret );
2623 }
2624 }
2625
2626 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
2627 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2628 else
2629 {
2630 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2631 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2632 }
2633
2634 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
2635
2636 return( 0 );
2637 }
2638
2639 /*
2640 * To be called when the last message of an incoming flight is received.
2641 */
2642 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
2643 {
2644 /* We won't need to resend that one any more */
2645 ssl_flight_free( ssl->handshake->flight );
2646 ssl->handshake->flight = NULL;
2647 ssl->handshake->cur_msg = NULL;
2648
2649 /* The next incoming flight will start with this msg_seq */
2650 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2651
2652 /* Cancel timer */
2653 ssl_set_timer( ssl, 0 );
2654
2655 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2656 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2657 {
2658 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2659 }
2660 else
2661 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2662 }
2663
2664 /*
2665 * To be called when the last message of an outgoing flight is send.
2666 */
2667 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
2668 {
2669 ssl_reset_retransmit_timeout( ssl );
2670 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2671
2672 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2673 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2674 {
2675 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2676 }
2677 else
2678 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2679 }
2680 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2681
2682 /*
2683 * Record layer functions
2684 */
2685
2686 /*
2687 * Write current record.
2688 * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg.
2689 */
2690 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl )
2691 {
2692 int ret, done = 0;
2693 size_t len = ssl->out_msglen;
2694
2695 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
2696
2697 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2698 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2699 ssl->handshake != NULL &&
2700 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
2701 {
2702 ; /* Skip special handshake treatment when resending */
2703 }
2704 else
2705 #endif
2706 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
2707 {
2708 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST &&
2709 ssl->handshake == NULL )
2710 {
2711 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2712 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2713 }
2714
2715 ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
2716 ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
2717 ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
2718
2719 /*
2720 * DTLS has additional fields in the Handshake layer,
2721 * between the length field and the actual payload:
2722 * uint16 message_seq;
2723 * uint24 fragment_offset;
2724 * uint24 fragment_length;
2725 */
2726 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2727 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2728 {
2729 /* Make room for the additional DTLS fields */
2730 memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 );
2731 ssl->out_msglen += 8;
2732 len += 8;
2733
2734 /* Write message_seq and update it, except for HelloRequest */
2735 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST )
2736 {
2737 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
2738 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
2739 ++( ssl->handshake->out_msg_seq );
2740 }
2741 else
2742 {
2743 ssl->out_msg[4] = 0;
2744 ssl->out_msg[5] = 0;
2745 }
2746
2747 /* We don't fragment, so frag_offset = 0 and frag_len = len */
2748 memset( ssl->out_msg + 6, 0x00, 3 );
2749 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
2750 }
2751 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2752
2753 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST )
2754 ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
2755 }
2756
2757 /* Save handshake and CCS messages for resending */
2758 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2759 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2760 ssl->handshake != NULL &&
2761 ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING &&
2762 ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ||
2763 ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) )
2764 {
2765 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
2766 {
2767 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
2768 return( ret );
2769 }
2770 }
2771 #endif
2772
2773 #if defined(MBEDTLS_ZLIB_SUPPORT)
2774 if( ssl->transform_out != NULL &&
2775 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
2776 {
2777 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
2778 {
2779 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
2780 return( ret );
2781 }
2782
2783 len = ssl->out_msglen;
2784 }
2785 #endif /*MBEDTLS_ZLIB_SUPPORT */
2786
2787 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2788 if( mbedtls_ssl_hw_record_write != NULL )
2789 {
2790 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
2791
2792 ret = mbedtls_ssl_hw_record_write( ssl );
2793 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
2794 {
2795 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
2796 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2797 }
2798
2799 if( ret == 0 )
2800 done = 1;
2801 }
2802 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2803 if( !done )
2804 {
2805 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
2806 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2807 ssl->conf->transport, ssl->out_hdr + 1 );
2808
2809 ssl->out_len[0] = (unsigned char)( len >> 8 );
2810 ssl->out_len[1] = (unsigned char)( len );
2811
2812 if( ssl->transform_out != NULL )
2813 {
2814 if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
2815 {
2816 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
2817 return( ret );
2818 }
2819
2820 len = ssl->out_msglen;
2821 ssl->out_len[0] = (unsigned char)( len >> 8 );
2822 ssl->out_len[1] = (unsigned char)( len );
2823 }
2824
2825 ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen;
2826
2827 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
2828 "version = [%d:%d], msglen = %d",
2829 ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
2830 ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) );
2831
2832 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
2833 ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen );
2834 }
2835
2836 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2837 {
2838 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
2839 return( ret );
2840 }
2841
2842 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
2843
2844 return( 0 );
2845 }
2846
2847 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2848 /*
2849 * Mark bits in bitmask (used for DTLS HS reassembly)
2850 */
2851 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
2852 {
2853 unsigned int start_bits, end_bits;
2854
2855 start_bits = 8 - ( offset % 8 );
2856 if( start_bits != 8 )
2857 {
2858 size_t first_byte_idx = offset / 8;
2859
2860 /* Special case */
2861 if( len <= start_bits )
2862 {
2863 for( ; len != 0; len-- )
2864 mask[first_byte_idx] |= 1 << ( start_bits - len );
2865
2866 /* Avoid potential issues with offset or len becoming invalid */
2867 return;
2868 }
2869
2870 offset += start_bits; /* Now offset % 8 == 0 */
2871 len -= start_bits;
2872
2873 for( ; start_bits != 0; start_bits-- )
2874 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
2875 }
2876
2877 end_bits = len % 8;
2878 if( end_bits != 0 )
2879 {
2880 size_t last_byte_idx = ( offset + len ) / 8;
2881
2882 len -= end_bits; /* Now len % 8 == 0 */
2883
2884 for( ; end_bits != 0; end_bits-- )
2885 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
2886 }
2887
2888 memset( mask + offset / 8, 0xFF, len / 8 );
2889 }
2890
2891 /*
2892 * Check that bitmask is full
2893 */
2894 static int ssl_bitmask_check( unsigned char *mask, size_t len )
2895 {
2896 size_t i;
2897
2898 for( i = 0; i < len / 8; i++ )
2899 if( mask[i] != 0xFF )
2900 return( -1 );
2901
2902 for( i = 0; i < len % 8; i++ )
2903 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
2904 return( -1 );
2905
2906 return( 0 );
2907 }
2908
2909 /*
2910 * Reassemble fragmented DTLS handshake messages.
2911 *
2912 * Use a temporary buffer for reassembly, divided in two parts:
2913 * - the first holds the reassembled message (including handshake header),
2914 * - the second holds a bitmask indicating which parts of the message
2915 * (excluding headers) have been received so far.
2916 */
2917 static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )
2918 {
2919 unsigned char *msg, *bitmask;
2920 size_t frag_len, frag_off;
2921 size_t msg_len = ssl->in_hslen - 12; /* Without headers */
2922
2923 if( ssl->handshake == NULL )
2924 {
2925 MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) );
2926 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2927 }
2928
2929 /*
2930 * For first fragment, check size and allocate buffer
2931 */
2932 if( ssl->handshake->hs_msg == NULL )
2933 {
2934 size_t alloc_len;
2935
2936 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
2937 msg_len ) );
2938
2939 if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN )
2940 {
2941 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) );
2942 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2943 }
2944
2945 /* The bitmask needs one bit per byte of message excluding header */
2946 alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 );
2947
2948 ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len );
2949 if( ssl->handshake->hs_msg == NULL )
2950 {
2951 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) );
2952 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2953 }
2954
2955 /* Prepare final header: copy msg_type, length and message_seq,
2956 * then add standardised fragment_offset and fragment_length */
2957 memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 );
2958 memset( ssl->handshake->hs_msg + 6, 0, 3 );
2959 memcpy( ssl->handshake->hs_msg + 9,
2960 ssl->handshake->hs_msg + 1, 3 );
2961 }
2962 else
2963 {
2964 /* Make sure msg_type and length are consistent */
2965 if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 )
2966 {
2967 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) );
2968 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2969 }
2970 }
2971
2972 msg = ssl->handshake->hs_msg + 12;
2973 bitmask = msg + msg_len;
2974
2975 /*
2976 * Check and copy current fragment
2977 */
2978 frag_off = ( ssl->in_msg[6] << 16 ) |
2979 ( ssl->in_msg[7] << 8 ) |
2980 ssl->in_msg[8];
2981 frag_len = ( ssl->in_msg[9] << 16 ) |
2982 ( ssl->in_msg[10] << 8 ) |
2983 ssl->in_msg[11];
2984
2985 if( frag_off + frag_len > msg_len )
2986 {
2987 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d",
2988 frag_off, frag_len, msg_len ) );
2989 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2990 }
2991
2992 if( frag_len + 12 > ssl->in_msglen )
2993 {
2994 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d",
2995 frag_len, ssl->in_msglen ) );
2996 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2997 }
2998
2999 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
3000 frag_off, frag_len ) );
3001
3002 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
3003 ssl_bitmask_set( bitmask, frag_off, frag_len );
3004
3005 /*
3006 * Do we have the complete message by now?
3007 * If yes, finalize it, else ask to read the next record.
3008 */
3009 if( ssl_bitmask_check( bitmask, msg_len ) != 0 )
3010 {
3011 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) );
3012 return( MBEDTLS_ERR_SSL_WANT_READ );
3013 }
3014
3015 MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) );
3016
3017 if( frag_len + 12 < ssl->in_msglen )
3018 {
3019 /*
3020 * We'got more handshake messages in the same record.
3021 * This case is not handled now because no know implementation does
3022 * that and it's hard to test, so we prefer to fail cleanly for now.
3023 */
3024 MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) );
3025 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3026 }
3027
3028 if( ssl->in_left > ssl->next_record_offset )
3029 {
3030 /*
3031 * We've got more data in the buffer after the current record,
3032 * that we don't want to overwrite. Move it before writing the
3033 * reassembled message, and adjust in_left and next_record_offset.
3034 */
3035 unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset;
3036 unsigned char *new_remain = ssl->in_msg + ssl->in_hslen;
3037 size_t remain_len = ssl->in_left - ssl->next_record_offset;
3038
3039 /* First compute and check new lengths */
3040 ssl->next_record_offset = new_remain - ssl->in_hdr;
3041 ssl->in_left = ssl->next_record_offset + remain_len;
3042
3043 if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN -
3044 (size_t)( ssl->in_hdr - ssl->in_buf ) )
3045 {
3046 MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) );
3047 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3048 }
3049
3050 memmove( new_remain, cur_remain, remain_len );
3051 }
3052
3053 memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );
3054
3055 mbedtls_free( ssl->handshake->hs_msg );
3056 ssl->handshake->hs_msg = NULL;
3057
3058 MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message",
3059 ssl->in_msg, ssl->in_hslen );
3060
3061 return( 0 );
3062 }
3063 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3064
3065 static int ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
3066 {
3067 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
3068 {
3069 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
3070 ssl->in_msglen ) );
3071 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3072 }
3073
3074 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + (
3075 ( ssl->in_msg[1] << 16 ) |
3076 ( ssl->in_msg[2] << 8 ) |
3077 ssl->in_msg[3] );
3078
3079 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
3080 " %d, type = %d, hslen = %d",
3081 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
3082
3083 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3084 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3085 {
3086 int ret;
3087 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
3088
3089 /* ssl->handshake is NULL when receiving ClientHello for renego */
3090 if( ssl->handshake != NULL &&
3091 recv_msg_seq != ssl->handshake->in_msg_seq )
3092 {
3093 /* Retransmit only on last message from previous flight, to avoid
3094 * too many retransmissions.
3095 * Besides, No sane server ever retransmits HelloVerifyRequest */
3096 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3097 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
3098 {
3099 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
3100 "message_seq = %d, start_of_flight = %d",
3101 recv_msg_seq,
3102 ssl->handshake->in_flight_start_seq ) );
3103
3104 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3105 {
3106 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
3107 return( ret );
3108 }
3109 }
3110 else
3111 {
3112 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
3113 "message_seq = %d, expected = %d",
3114 recv_msg_seq,
3115 ssl->handshake->in_msg_seq ) );
3116 }
3117
3118 return( MBEDTLS_ERR_SSL_WANT_READ );
3119 }
3120 /* Wait until message completion to increment in_msg_seq */
3121
3122 /* Reassemble if current message is fragmented or reassembly is
3123 * already in progress */
3124 if( ssl->in_msglen < ssl->in_hslen ||
3125 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
3126 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ||
3127 ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) )
3128 {
3129 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
3130
3131 if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 )
3132 {
3133 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_reassemble_dtls_handshake", ret );
3134 return( ret );
3135 }
3136 }
3137 }
3138 else
3139 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3140 /* With TLS we don't handle fragmentation (for now) */
3141 if( ssl->in_msglen < ssl->in_hslen )
3142 {
3143 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
3144 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3145 }
3146
3147 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
3148 ssl->handshake != NULL )
3149 {
3150 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
3151 }
3152
3153 /* Handshake message is complete, increment counter */
3154 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3155 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3156 ssl->handshake != NULL )
3157 {
3158 ssl->handshake->in_msg_seq++;
3159 }
3160 #endif
3161
3162 return( 0 );
3163 }
3164
3165 /*
3166 * DTLS anti-replay: RFC 6347 4.1.2.6
3167 *
3168 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3169 * Bit n is set iff record number in_window_top - n has been seen.
3170 *
3171 * Usually, in_window_top is the last record number seen and the lsb of
3172 * in_window is set. The only exception is the initial state (record number 0
3173 * not seen yet).
3174 */
3175 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3176 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
3177 {
3178 ssl->in_window_top = 0;
3179 ssl->in_window = 0;
3180 }
3181
3182 static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
3183 {
3184 return( ( (uint64_t) buf[0] << 40 ) |
3185 ( (uint64_t) buf[1] << 32 ) |
3186 ( (uint64_t) buf[2] << 24 ) |
3187 ( (uint64_t) buf[3] << 16 ) |
3188 ( (uint64_t) buf[4] << 8 ) |
3189 ( (uint64_t) buf[5] ) );
3190 }
3191
3192 /*
3193 * Return 0 if sequence number is acceptable, -1 otherwise
3194 */
3195 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
3196 {
3197 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3198 uint64_t bit;
3199
3200 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3201 return( 0 );
3202
3203 if( rec_seqnum > ssl->in_window_top )
3204 return( 0 );
3205
3206 bit = ssl->in_window_top - rec_seqnum;
3207
3208 if( bit >= 64 )
3209 return( -1 );
3210
3211 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
3212 return( -1 );
3213
3214 return( 0 );
3215 }
3216
3217 /*
3218 * Update replay window on new validated record
3219 */
3220 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
3221 {
3222 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3223
3224 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3225 return;
3226
3227 if( rec_seqnum > ssl->in_window_top )
3228 {
3229 /* Update window_top and the contents of the window */
3230 uint64_t shift = rec_seqnum - ssl->in_window_top;
3231
3232 if( shift >= 64 )
3233 ssl->in_window = 1;
3234 else
3235 {
3236 ssl->in_window <<= shift;
3237 ssl->in_window |= 1;
3238 }
3239
3240 ssl->in_window_top = rec_seqnum;
3241 }
3242 else
3243 {
3244 /* Mark that number as seen in the current window */
3245 uint64_t bit = ssl->in_window_top - rec_seqnum;
3246
3247 if( bit < 64 ) /* Always true, but be extra sure */
3248 ssl->in_window |= (uint64_t) 1 << bit;
3249 }
3250 }
3251 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3252
3253 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3254 /* Forward declaration */
3255 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
3256
3257 /*
3258 * Without any SSL context, check if a datagram looks like a ClientHello with
3259 * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
3260 * Both input and output include full DTLS headers.
3261 *
3262 * - if cookie is valid, return 0
3263 * - if ClientHello looks superficially valid but cookie is not,
3264 * fill obuf and set olen, then
3265 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3266 * - otherwise return a specific error code
3267 */
3268 static int ssl_check_dtls_clihlo_cookie(
3269 mbedtls_ssl_cookie_write_t *f_cookie_write,
3270 mbedtls_ssl_cookie_check_t *f_cookie_check,
3271 void *p_cookie,
3272 const unsigned char *cli_id, size_t cli_id_len,
3273 const unsigned char *in, size_t in_len,
3274 unsigned char *obuf, size_t buf_len, size_t *olen )
3275 {
3276 size_t sid_len, cookie_len;
3277 unsigned char *p;
3278
3279 if( f_cookie_write == NULL || f_cookie_check == NULL )
3280 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3281
3282 /*
3283 * Structure of ClientHello with record and handshake headers,
3284 * and expected values. We don't need to check a lot, more checks will be
3285 * done when actually parsing the ClientHello - skipping those checks
3286 * avoids code duplication and does not make cookie forging any easier.
3287 *
3288 * 0-0 ContentType type; copied, must be handshake
3289 * 1-2 ProtocolVersion version; copied
3290 * 3-4 uint16 epoch; copied, must be 0
3291 * 5-10 uint48 sequence_number; copied
3292 * 11-12 uint16 length; (ignored)
3293 *
3294 * 13-13 HandshakeType msg_type; (ignored)
3295 * 14-16 uint24 length; (ignored)
3296 * 17-18 uint16 message_seq; copied
3297 * 19-21 uint24 fragment_offset; copied, must be 0
3298 * 22-24 uint24 fragment_length; (ignored)
3299 *
3300 * 25-26 ProtocolVersion client_version; (ignored)
3301 * 27-58 Random random; (ignored)
3302 * 59-xx SessionID session_id; 1 byte len + sid_len content
3303 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3304 * ...
3305 *
3306 * Minimum length is 61 bytes.
3307 */
3308 if( in_len < 61 ||
3309 in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
3310 in[3] != 0 || in[4] != 0 ||
3311 in[19] != 0 || in[20] != 0 || in[21] != 0 )
3312 {
3313 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3314 }
3315
3316 sid_len = in[59];
3317 if( sid_len > in_len - 61 )
3318 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3319
3320 cookie_len = in[60 + sid_len];
3321 if( cookie_len > in_len - 60 )
3322 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3323
3324 if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
3325 cli_id, cli_id_len ) == 0 )
3326 {
3327 /* Valid cookie */
3328 return( 0 );
3329 }
3330
3331 /*
3332 * If we get here, we've got an invalid cookie, let's prepare HVR.
3333 *
3334 * 0-0 ContentType type; copied
3335 * 1-2 ProtocolVersion version; copied
3336 * 3-4 uint16 epoch; copied
3337 * 5-10 uint48 sequence_number; copied
3338 * 11-12 uint16 length; olen - 13
3339 *
3340 * 13-13 HandshakeType msg_type; hello_verify_request
3341 * 14-16 uint24 length; olen - 25
3342 * 17-18 uint16 message_seq; copied
3343 * 19-21 uint24 fragment_offset; copied
3344 * 22-24 uint24 fragment_length; olen - 25
3345 *
3346 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3347 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3348 *
3349 * Minimum length is 28.
3350 */
3351 if( buf_len < 28 )
3352 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3353
3354 /* Copy most fields and adapt others */
3355 memcpy( obuf, in, 25 );
3356 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3357 obuf[25] = 0xfe;
3358 obuf[26] = 0xff;
3359
3360 /* Generate and write actual cookie */
3361 p = obuf + 28;
3362 if( f_cookie_write( p_cookie,
3363 &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
3364 {
3365 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3366 }
3367
3368 *olen = p - obuf;
3369
3370 /* Go back and fill length fields */
3371 obuf[27] = (unsigned char)( *olen - 28 );
3372
3373 obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
3374 obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
3375 obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
3376
3377 obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
3378 obuf[12] = (unsigned char)( ( *olen - 13 ) );
3379
3380 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3381 }
3382
3383 /*
3384 * Handle possible client reconnect with the same UDP quadruplet
3385 * (RFC 6347 Section 4.2.8).
3386 *
3387 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3388 * that looks like a ClientHello.
3389 *
3390 * - if the input looks like a ClientHello without cookies,
3391 * send back HelloVerifyRequest, then
3392 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3393 * - if the input looks like a ClientHello with a valid cookie,
3394 * reset the session of the current context, and
3395 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3396 * - if anything goes wrong, return a specific error code
3397 *
3398 * mbedtls_ssl_read_record() will ignore the record if anything else than
3399 * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
3400 * cannot not return 0.
3401 */
3402 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
3403 {
3404 int ret;
3405 size_t len;
3406
3407 ret = ssl_check_dtls_clihlo_cookie(
3408 ssl->conf->f_cookie_write,
3409 ssl->conf->f_cookie_check,
3410 ssl->conf->p_cookie,
3411 ssl->cli_id, ssl->cli_id_len,
3412 ssl->in_buf, ssl->in_left,
3413 ssl->out_buf, MBEDTLS_SSL_MAX_CONTENT_LEN, &len );
3414
3415 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
3416
3417 if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
3418 {
3419 /* Dont check write errors as we can't do anything here.
3420 * If the error is permanent we'll catch it later,
3421 * if it's not, then hopefully it'll work next time. */
3422 (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
3423
3424 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3425 }
3426
3427 if( ret == 0 )
3428 {
3429 /* Got a valid cookie, partially reset context */
3430 if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
3431 {
3432 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
3433 return( ret );
3434 }
3435
3436 return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
3437 }
3438
3439 return( ret );
3440 }
3441 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3442
3443 /*
3444 * ContentType type;
3445 * ProtocolVersion version;
3446 * uint16 epoch; // DTLS only
3447 * uint48 sequence_number; // DTLS only
3448 * uint16 length;
3449 */
3450 static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
3451 {
3452 int ret;
3453 int major_ver, minor_ver;
3454
3455 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
3456
3457 ssl->in_msgtype = ssl->in_hdr[0];
3458 ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
3459 mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
3460
3461 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
3462 "version = [%d:%d], msglen = %d",
3463 ssl->in_msgtype,
3464 major_ver, minor_ver, ssl->in_msglen ) );
3465
3466 /* Check record type */
3467 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
3468 ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
3469 ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3470 ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
3471 {
3472 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
3473
3474 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
3475 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3476 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 )
3477 {
3478 return( ret );
3479 }
3480
3481 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3482 }
3483
3484 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3485 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3486 {
3487 /* Drop unexpected ChangeCipherSpec messages */
3488 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3489 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
3490 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
3491 {
3492 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) );
3493 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3494 }
3495
3496 /* Drop unexpected ApplicationData records,
3497 * except at the beginning of renegotiations */
3498 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
3499 ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
3500 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3501 && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
3502 ssl->state == MBEDTLS_SSL_SERVER_HELLO )
3503 #endif
3504 )
3505 {
3506 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
3507 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3508 }
3509 }
3510 #endif
3511
3512 /* Check version */
3513 if( major_ver != ssl->major_ver )
3514 {
3515 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
3516 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3517 }
3518
3519 if( minor_ver > ssl->conf->max_minor_ver )
3520 {
3521 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
3522 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3523 }
3524
3525 /* Check epoch (and sequence number) with DTLS */
3526 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3527 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3528 {
3529 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
3530
3531 if( rec_epoch != ssl->in_epoch )
3532 {
3533 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
3534 "expected %d, received %d",
3535 ssl->in_epoch, rec_epoch ) );
3536
3537 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3538 /*
3539 * Check for an epoch 0 ClientHello. We can't use in_msg here to
3540 * access the first byte of record content (handshake type), as we
3541 * have an active transform (possibly iv_len != 0), so use the
3542 * fact that the record header len is 13 instead.
3543 */
3544 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3545 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3546 rec_epoch == 0 &&
3547 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3548 ssl->in_left > 13 &&
3549 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
3550 {
3551 MBEDTLS_SSL