[MBEDTLS] Update to v2.2.0. By Ismael Ferreras Morezuelas. CORE-10561
[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 defined(MBEDTLS_SSL_EXPORT_KEYS)
866 if( ssl->conf->f_export_keys != NULL )
867 {
868 ssl->conf->f_export_keys( ssl->conf->p_export_keys,
869 session->master, keyblk,
870 transform->maclen, transform->keylen,
871 iv_copy_len );
872 }
873 #endif
874
875 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
876 cipher_info ) ) != 0 )
877 {
878 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
879 return( ret );
880 }
881
882 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
883 cipher_info ) ) != 0 )
884 {
885 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
886 return( ret );
887 }
888
889 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
890 cipher_info->key_bitlen,
891 MBEDTLS_ENCRYPT ) ) != 0 )
892 {
893 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
894 return( ret );
895 }
896
897 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
898 cipher_info->key_bitlen,
899 MBEDTLS_DECRYPT ) ) != 0 )
900 {
901 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
902 return( ret );
903 }
904
905 #if defined(MBEDTLS_CIPHER_MODE_CBC)
906 if( cipher_info->mode == MBEDTLS_MODE_CBC )
907 {
908 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
909 MBEDTLS_PADDING_NONE ) ) != 0 )
910 {
911 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
912 return( ret );
913 }
914
915 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
916 MBEDTLS_PADDING_NONE ) ) != 0 )
917 {
918 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
919 return( ret );
920 }
921 }
922 #endif /* MBEDTLS_CIPHER_MODE_CBC */
923
924 mbedtls_zeroize( keyblk, sizeof( keyblk ) );
925
926 #if defined(MBEDTLS_ZLIB_SUPPORT)
927 // Initialize compression
928 //
929 if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
930 {
931 if( ssl->compress_buf == NULL )
932 {
933 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
934 ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN );
935 if( ssl->compress_buf == NULL )
936 {
937 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
938 MBEDTLS_SSL_BUFFER_LEN ) );
939 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
940 }
941 }
942
943 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
944
945 memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
946 memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
947
948 if( deflateInit( &transform->ctx_deflate,
949 Z_DEFAULT_COMPRESSION ) != Z_OK ||
950 inflateInit( &transform->ctx_inflate ) != Z_OK )
951 {
952 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
953 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
954 }
955 }
956 #endif /* MBEDTLS_ZLIB_SUPPORT */
957
958 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
959
960 return( 0 );
961 }
962
963 #if defined(MBEDTLS_SSL_PROTO_SSL3)
964 void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
965 {
966 mbedtls_md5_context md5;
967 mbedtls_sha1_context sha1;
968 unsigned char pad_1[48];
969 unsigned char pad_2[48];
970
971 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
972
973 mbedtls_md5_init( &md5 );
974 mbedtls_sha1_init( &sha1 );
975
976 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
977 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
978
979 memset( pad_1, 0x36, 48 );
980 memset( pad_2, 0x5C, 48 );
981
982 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
983 mbedtls_md5_update( &md5, pad_1, 48 );
984 mbedtls_md5_finish( &md5, hash );
985
986 mbedtls_md5_starts( &md5 );
987 mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 );
988 mbedtls_md5_update( &md5, pad_2, 48 );
989 mbedtls_md5_update( &md5, hash, 16 );
990 mbedtls_md5_finish( &md5, hash );
991
992 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
993 mbedtls_sha1_update( &sha1, pad_1, 40 );
994 mbedtls_sha1_finish( &sha1, hash + 16 );
995
996 mbedtls_sha1_starts( &sha1 );
997 mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 );
998 mbedtls_sha1_update( &sha1, pad_2, 40 );
999 mbedtls_sha1_update( &sha1, hash + 16, 20 );
1000 mbedtls_sha1_finish( &sha1, hash + 16 );
1001
1002 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1003 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1004
1005 mbedtls_md5_free( &md5 );
1006 mbedtls_sha1_free( &sha1 );
1007
1008 return;
1009 }
1010 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1011
1012 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1013 void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
1014 {
1015 mbedtls_md5_context md5;
1016 mbedtls_sha1_context sha1;
1017
1018 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1019
1020 mbedtls_md5_init( &md5 );
1021 mbedtls_sha1_init( &sha1 );
1022
1023 mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1024 mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1025
1026 mbedtls_md5_finish( &md5, hash );
1027 mbedtls_sha1_finish( &sha1, hash + 16 );
1028
1029 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1030 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1031
1032 mbedtls_md5_free( &md5 );
1033 mbedtls_sha1_free( &sha1 );
1034
1035 return;
1036 }
1037 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1038
1039 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1040 #if defined(MBEDTLS_SHA256_C)
1041 void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
1042 {
1043 mbedtls_sha256_context sha256;
1044
1045 mbedtls_sha256_init( &sha256 );
1046
1047 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1048
1049 mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1050 mbedtls_sha256_finish( &sha256, hash );
1051
1052 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
1053 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1054
1055 mbedtls_sha256_free( &sha256 );
1056
1057 return;
1058 }
1059 #endif /* MBEDTLS_SHA256_C */
1060
1061 #if defined(MBEDTLS_SHA512_C)
1062 void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
1063 {
1064 mbedtls_sha512_context sha512;
1065
1066 mbedtls_sha512_init( &sha512 );
1067
1068 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1069
1070 mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
1071 mbedtls_sha512_finish( &sha512, hash );
1072
1073 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
1074 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1075
1076 mbedtls_sha512_free( &sha512 );
1077
1078 return;
1079 }
1080 #endif /* MBEDTLS_SHA512_C */
1081 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1082
1083 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1084 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1085 {
1086 unsigned char *p = ssl->handshake->premaster;
1087 unsigned char *end = p + sizeof( ssl->handshake->premaster );
1088 const unsigned char *psk = ssl->conf->psk;
1089 size_t psk_len = ssl->conf->psk_len;
1090
1091 /* If the psk callback was called, use its result */
1092 if( ssl->handshake->psk != NULL )
1093 {
1094 psk = ssl->handshake->psk;
1095 psk_len = ssl->handshake->psk_len;
1096 }
1097
1098 /*
1099 * PMS = struct {
1100 * opaque other_secret<0..2^16-1>;
1101 * opaque psk<0..2^16-1>;
1102 * };
1103 * with "other_secret" depending on the particular key exchange
1104 */
1105 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1106 if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1107 {
1108 if( end - p < 2 )
1109 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1110
1111 *(p++) = (unsigned char)( psk_len >> 8 );
1112 *(p++) = (unsigned char)( psk_len );
1113
1114 if( end < p || (size_t)( end - p ) < psk_len )
1115 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1116
1117 memset( p, 0, psk_len );
1118 p += psk_len;
1119 }
1120 else
1121 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1122 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1123 if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
1124 {
1125 /*
1126 * other_secret already set by the ClientKeyExchange message,
1127 * and is 48 bytes long
1128 */
1129 *p++ = 0;
1130 *p++ = 48;
1131 p += 48;
1132 }
1133 else
1134 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1135 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1136 if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
1137 {
1138 int ret;
1139 size_t len;
1140
1141 /* Write length only when we know the actual value */
1142 if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
1143 p + 2, end - ( p + 2 ), &len,
1144 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1145 {
1146 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1147 return( ret );
1148 }
1149 *(p++) = (unsigned char)( len >> 8 );
1150 *(p++) = (unsigned char)( len );
1151 p += len;
1152
1153 MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
1154 }
1155 else
1156 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1157 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
1158 if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
1159 {
1160 int ret;
1161 size_t zlen;
1162
1163 if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
1164 p + 2, end - ( p + 2 ),
1165 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1166 {
1167 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1168 return( ret );
1169 }
1170
1171 *(p++) = (unsigned char)( zlen >> 8 );
1172 *(p++) = (unsigned char)( zlen );
1173 p += zlen;
1174
1175 MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
1176 }
1177 else
1178 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1179 {
1180 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1181 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1182 }
1183
1184 /* opaque psk<0..2^16-1>; */
1185 if( end - p < 2 )
1186 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1187
1188 *(p++) = (unsigned char)( psk_len >> 8 );
1189 *(p++) = (unsigned char)( psk_len );
1190
1191 if( end < p || (size_t)( end - p ) < psk_len )
1192 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1193
1194 memcpy( p, psk, psk_len );
1195 p += psk_len;
1196
1197 ssl->handshake->pmslen = p - ssl->handshake->premaster;
1198
1199 return( 0 );
1200 }
1201 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1202
1203 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1204 /*
1205 * SSLv3.0 MAC functions
1206 */
1207 static void ssl_mac( mbedtls_md_context_t *md_ctx, unsigned char *secret,
1208 unsigned char *buf, size_t len,
1209 unsigned char *ctr, int type )
1210 {
1211 unsigned char header[11];
1212 unsigned char padding[48];
1213 int padlen;
1214 int md_size = mbedtls_md_get_size( md_ctx->md_info );
1215 int md_type = mbedtls_md_get_type( md_ctx->md_info );
1216
1217 /* Only MD5 and SHA-1 supported */
1218 if( md_type == MBEDTLS_MD_MD5 )
1219 padlen = 48;
1220 else
1221 padlen = 40;
1222
1223 memcpy( header, ctr, 8 );
1224 header[ 8] = (unsigned char) type;
1225 header[ 9] = (unsigned char)( len >> 8 );
1226 header[10] = (unsigned char)( len );
1227
1228 memset( padding, 0x36, padlen );
1229 mbedtls_md_starts( md_ctx );
1230 mbedtls_md_update( md_ctx, secret, md_size );
1231 mbedtls_md_update( md_ctx, padding, padlen );
1232 mbedtls_md_update( md_ctx, header, 11 );
1233 mbedtls_md_update( md_ctx, buf, len );
1234 mbedtls_md_finish( md_ctx, buf + len );
1235
1236 memset( padding, 0x5C, padlen );
1237 mbedtls_md_starts( md_ctx );
1238 mbedtls_md_update( md_ctx, secret, md_size );
1239 mbedtls_md_update( md_ctx, padding, padlen );
1240 mbedtls_md_update( md_ctx, buf + len, md_size );
1241 mbedtls_md_finish( md_ctx, buf + len );
1242 }
1243 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1244
1245 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
1246 ( defined(MBEDTLS_CIPHER_MODE_CBC) && \
1247 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) )
1248 #define SSL_SOME_MODES_USE_MAC
1249 #endif
1250
1251 /*
1252 * Encryption/decryption functions
1253 */
1254 static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
1255 {
1256 mbedtls_cipher_mode_t mode;
1257 int auth_done = 0;
1258
1259 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
1260
1261 if( ssl->session_out == NULL || ssl->transform_out == NULL )
1262 {
1263 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1264 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1265 }
1266
1267 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
1268
1269 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
1270 ssl->out_msg, ssl->out_msglen );
1271
1272 /*
1273 * Add MAC before if needed
1274 */
1275 #if defined(SSL_SOME_MODES_USE_MAC)
1276 if( mode == MBEDTLS_MODE_STREAM ||
1277 ( mode == MBEDTLS_MODE_CBC
1278 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1279 && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
1280 #endif
1281 ) )
1282 {
1283 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1284 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1285 {
1286 ssl_mac( &ssl->transform_out->md_ctx_enc,
1287 ssl->transform_out->mac_enc,
1288 ssl->out_msg, ssl->out_msglen,
1289 ssl->out_ctr, ssl->out_msgtype );
1290 }
1291 else
1292 #endif
1293 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1294 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1295 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
1296 {
1297 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
1298 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
1299 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
1300 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1301 ssl->out_msg, ssl->out_msglen );
1302 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1303 ssl->out_msg + ssl->out_msglen );
1304 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1305 }
1306 else
1307 #endif
1308 {
1309 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1310 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1311 }
1312
1313 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
1314 ssl->out_msg + ssl->out_msglen,
1315 ssl->transform_out->maclen );
1316
1317 ssl->out_msglen += ssl->transform_out->maclen;
1318 auth_done++;
1319 }
1320 #endif /* AEAD not the only option */
1321
1322 /*
1323 * Encrypt
1324 */
1325 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1326 if( mode == MBEDTLS_MODE_STREAM )
1327 {
1328 int ret;
1329 size_t olen = 0;
1330
1331 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1332 "including %d bytes of padding",
1333 ssl->out_msglen, 0 ) );
1334
1335 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1336 ssl->transform_out->iv_enc,
1337 ssl->transform_out->ivlen,
1338 ssl->out_msg, ssl->out_msglen,
1339 ssl->out_msg, &olen ) ) != 0 )
1340 {
1341 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1342 return( ret );
1343 }
1344
1345 if( ssl->out_msglen != olen )
1346 {
1347 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1348 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1349 }
1350 }
1351 else
1352 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1353 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1354 if( mode == MBEDTLS_MODE_GCM ||
1355 mode == MBEDTLS_MODE_CCM )
1356 {
1357 int ret;
1358 size_t enc_msglen, olen;
1359 unsigned char *enc_msg;
1360 unsigned char add_data[13];
1361 unsigned char taglen = ssl->transform_out->ciphersuite_info->flags &
1362 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1363
1364 memcpy( add_data, ssl->out_ctr, 8 );
1365 add_data[8] = ssl->out_msgtype;
1366 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1367 ssl->conf->transport, add_data + 9 );
1368 add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
1369 add_data[12] = ssl->out_msglen & 0xFF;
1370
1371 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1372 add_data, 13 );
1373
1374 /*
1375 * Generate IV
1376 */
1377 #if defined(MBEDTLS_SSL_AEAD_RANDOM_IV)
1378 ret = ssl->conf->f_rng( ssl->conf->p_rng,
1379 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1380 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1381 if( ret != 0 )
1382 return( ret );
1383
1384 memcpy( ssl->out_iv,
1385 ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1386 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1387 #else
1388 if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 )
1389 {
1390 /* Reminder if we ever add an AEAD mode with a different size */
1391 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1392 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1393 }
1394
1395 memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
1396 ssl->out_ctr, 8 );
1397 memcpy( ssl->out_iv, ssl->out_ctr, 8 );
1398 #endif
1399
1400 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv,
1401 ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
1402
1403 /*
1404 * Fix pointer positions and message length with added IV
1405 */
1406 enc_msg = ssl->out_msg;
1407 enc_msglen = ssl->out_msglen;
1408 ssl->out_msglen += ssl->transform_out->ivlen -
1409 ssl->transform_out->fixed_ivlen;
1410
1411 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1412 "including %d bytes of padding",
1413 ssl->out_msglen, 0 ) );
1414
1415 /*
1416 * Encrypt and authenticate
1417 */
1418 if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc,
1419 ssl->transform_out->iv_enc,
1420 ssl->transform_out->ivlen,
1421 add_data, 13,
1422 enc_msg, enc_msglen,
1423 enc_msg, &olen,
1424 enc_msg + enc_msglen, taglen ) ) != 0 )
1425 {
1426 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
1427 return( ret );
1428 }
1429
1430 if( olen != enc_msglen )
1431 {
1432 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1433 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1434 }
1435
1436 ssl->out_msglen += taglen;
1437 auth_done++;
1438
1439 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
1440 }
1441 else
1442 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1443 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1444 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1445 if( mode == MBEDTLS_MODE_CBC )
1446 {
1447 int ret;
1448 unsigned char *enc_msg;
1449 size_t enc_msglen, padlen, olen = 0, i;
1450
1451 padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
1452 ssl->transform_out->ivlen;
1453 if( padlen == ssl->transform_out->ivlen )
1454 padlen = 0;
1455
1456 for( i = 0; i <= padlen; i++ )
1457 ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
1458
1459 ssl->out_msglen += padlen + 1;
1460
1461 enc_msglen = ssl->out_msglen;
1462 enc_msg = ssl->out_msg;
1463
1464 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1465 /*
1466 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
1467 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1468 */
1469 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1470 {
1471 /*
1472 * Generate IV
1473 */
1474 ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
1475 ssl->transform_out->ivlen );
1476 if( ret != 0 )
1477 return( ret );
1478
1479 memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
1480 ssl->transform_out->ivlen );
1481
1482 /*
1483 * Fix pointer positions and message length with added IV
1484 */
1485 enc_msg = ssl->out_msg;
1486 enc_msglen = ssl->out_msglen;
1487 ssl->out_msglen += ssl->transform_out->ivlen;
1488 }
1489 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1490
1491 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1492 "including %d bytes of IV and %d bytes of padding",
1493 ssl->out_msglen, ssl->transform_out->ivlen,
1494 padlen + 1 ) );
1495
1496 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
1497 ssl->transform_out->iv_enc,
1498 ssl->transform_out->ivlen,
1499 enc_msg, enc_msglen,
1500 enc_msg, &olen ) ) != 0 )
1501 {
1502 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1503 return( ret );
1504 }
1505
1506 if( enc_msglen != olen )
1507 {
1508 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1509 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1510 }
1511
1512 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1513 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1514 {
1515 /*
1516 * Save IV in SSL3 and TLS1
1517 */
1518 memcpy( ssl->transform_out->iv_enc,
1519 ssl->transform_out->cipher_ctx_enc.iv,
1520 ssl->transform_out->ivlen );
1521 }
1522 #endif
1523
1524 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1525 if( auth_done == 0 )
1526 {
1527 /*
1528 * MAC(MAC_write_key, seq_num +
1529 * TLSCipherText.type +
1530 * TLSCipherText.version +
1531 * length_of( (IV +) ENC(...) ) +
1532 * IV + // except for TLS 1.0
1533 * ENC(content + padding + padding_length));
1534 */
1535 unsigned char pseudo_hdr[13];
1536
1537 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1538
1539 memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
1540 memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
1541 pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
1542 pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
1543
1544 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1545
1546 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
1547 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
1548 ssl->out_iv, ssl->out_msglen );
1549 mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
1550 ssl->out_iv + ssl->out_msglen );
1551 mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
1552
1553 ssl->out_msglen += ssl->transform_out->maclen;
1554 auth_done++;
1555 }
1556 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1557 }
1558 else
1559 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1560 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1561 {
1562 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1563 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1564 }
1565
1566 /* Make extra sure authentication was performed, exactly once */
1567 if( auth_done != 1 )
1568 {
1569 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1570 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1571 }
1572
1573 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1574
1575 return( 0 );
1576 }
1577
1578 #define SSL_MAX_MAC_SIZE 48
1579
1580 static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
1581 {
1582 size_t i;
1583 mbedtls_cipher_mode_t mode;
1584 int auth_done = 0;
1585 #if defined(SSL_SOME_MODES_USE_MAC)
1586 size_t padlen = 0, correct = 1;
1587 #endif
1588
1589 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1590
1591 if( ssl->session_in == NULL || ssl->transform_in == NULL )
1592 {
1593 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1594 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1595 }
1596
1597 mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
1598
1599 if( ssl->in_msglen < ssl->transform_in->minlen )
1600 {
1601 MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
1602 ssl->in_msglen, ssl->transform_in->minlen ) );
1603 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1604 }
1605
1606 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1607 if( mode == MBEDTLS_MODE_STREAM )
1608 {
1609 int ret;
1610 size_t olen = 0;
1611
1612 padlen = 0;
1613
1614 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1615 ssl->transform_in->iv_dec,
1616 ssl->transform_in->ivlen,
1617 ssl->in_msg, ssl->in_msglen,
1618 ssl->in_msg, &olen ) ) != 0 )
1619 {
1620 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1621 return( ret );
1622 }
1623
1624 if( ssl->in_msglen != olen )
1625 {
1626 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1627 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1628 }
1629 }
1630 else
1631 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1632 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
1633 if( mode == MBEDTLS_MODE_GCM ||
1634 mode == MBEDTLS_MODE_CCM )
1635 {
1636 int ret;
1637 size_t dec_msglen, olen;
1638 unsigned char *dec_msg;
1639 unsigned char *dec_msg_result;
1640 unsigned char add_data[13];
1641 unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
1642 MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1643 size_t explicit_iv_len = ssl->transform_in->ivlen -
1644 ssl->transform_in->fixed_ivlen;
1645
1646 if( ssl->in_msglen < explicit_iv_len + taglen )
1647 {
1648 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
1649 "+ taglen (%d)", ssl->in_msglen,
1650 explicit_iv_len, taglen ) );
1651 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1652 }
1653 dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
1654
1655 dec_msg = ssl->in_msg;
1656 dec_msg_result = ssl->in_msg;
1657 ssl->in_msglen = dec_msglen;
1658
1659 memcpy( add_data, ssl->in_ctr, 8 );
1660 add_data[8] = ssl->in_msgtype;
1661 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
1662 ssl->conf->transport, add_data + 9 );
1663 add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
1664 add_data[12] = ssl->in_msglen & 0xFF;
1665
1666 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1667 add_data, 13 );
1668
1669 memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
1670 ssl->in_iv,
1671 ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
1672
1673 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
1674 ssl->transform_in->ivlen );
1675 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
1676
1677 /*
1678 * Decrypt and authenticate
1679 */
1680 if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
1681 ssl->transform_in->iv_dec,
1682 ssl->transform_in->ivlen,
1683 add_data, 13,
1684 dec_msg, dec_msglen,
1685 dec_msg_result, &olen,
1686 dec_msg + dec_msglen, taglen ) ) != 0 )
1687 {
1688 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
1689
1690 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
1691 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1692
1693 return( ret );
1694 }
1695 auth_done++;
1696
1697 if( olen != dec_msglen )
1698 {
1699 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1700 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1701 }
1702 }
1703 else
1704 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1705 #if defined(MBEDTLS_CIPHER_MODE_CBC) && \
1706 ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) )
1707 if( mode == MBEDTLS_MODE_CBC )
1708 {
1709 /*
1710 * Decrypt and check the padding
1711 */
1712 int ret;
1713 unsigned char *dec_msg;
1714 unsigned char *dec_msg_result;
1715 size_t dec_msglen;
1716 size_t minlen = 0;
1717 size_t olen = 0;
1718
1719 /*
1720 * Check immediate ciphertext sanity
1721 */
1722 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1723 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1724 minlen += ssl->transform_in->ivlen;
1725 #endif
1726
1727 if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
1728 ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
1729 {
1730 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
1731 "+ 1 ) ( + expl IV )", ssl->in_msglen,
1732 ssl->transform_in->ivlen,
1733 ssl->transform_in->maclen ) );
1734 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1735 }
1736
1737 dec_msglen = ssl->in_msglen;
1738 dec_msg = ssl->in_msg;
1739 dec_msg_result = ssl->in_msg;
1740
1741 /*
1742 * Authenticate before decrypt if enabled
1743 */
1744 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1745 if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1746 {
1747 unsigned char computed_mac[SSL_MAX_MAC_SIZE];
1748 unsigned char pseudo_hdr[13];
1749
1750 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1751
1752 dec_msglen -= ssl->transform_in->maclen;
1753 ssl->in_msglen -= ssl->transform_in->maclen;
1754
1755 memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
1756 memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
1757 pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
1758 pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
1759
1760 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1761
1762 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
1763 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
1764 ssl->in_iv, ssl->in_msglen );
1765 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac );
1766 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1767
1768 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
1769 ssl->transform_in->maclen );
1770 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", computed_mac,
1771 ssl->transform_in->maclen );
1772
1773 if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac,
1774 ssl->transform_in->maclen ) != 0 )
1775 {
1776 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1777
1778 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1779 }
1780 auth_done++;
1781 }
1782 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1783
1784 /*
1785 * Check length sanity
1786 */
1787 if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
1788 {
1789 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
1790 ssl->in_msglen, ssl->transform_in->ivlen ) );
1791 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1792 }
1793
1794 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1795 /*
1796 * Initialize for prepended IV for block cipher in TLS v1.1 and up
1797 */
1798 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1799 {
1800 dec_msglen -= ssl->transform_in->ivlen;
1801 ssl->in_msglen -= ssl->transform_in->ivlen;
1802
1803 for( i = 0; i < ssl->transform_in->ivlen; i++ )
1804 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
1805 }
1806 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1807
1808 if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
1809 ssl->transform_in->iv_dec,
1810 ssl->transform_in->ivlen,
1811 dec_msg, dec_msglen,
1812 dec_msg_result, &olen ) ) != 0 )
1813 {
1814 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1815 return( ret );
1816 }
1817
1818 if( dec_msglen != olen )
1819 {
1820 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1821 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1822 }
1823
1824 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1825 if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1826 {
1827 /*
1828 * Save IV in SSL3 and TLS1
1829 */
1830 memcpy( ssl->transform_in->iv_dec,
1831 ssl->transform_in->cipher_ctx_dec.iv,
1832 ssl->transform_in->ivlen );
1833 }
1834 #endif
1835
1836 padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
1837
1838 if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
1839 auth_done == 0 )
1840 {
1841 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1842 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
1843 ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
1844 #endif
1845 padlen = 0;
1846 correct = 0;
1847 }
1848
1849 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1850 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1851 {
1852 if( padlen > ssl->transform_in->ivlen )
1853 {
1854 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1855 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
1856 "should be no more than %d",
1857 padlen, ssl->transform_in->ivlen ) );
1858 #endif
1859 correct = 0;
1860 }
1861 }
1862 else
1863 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1864 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1865 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1866 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1867 {
1868 /*
1869 * TLSv1+: always check the padding up to the first failure
1870 * and fake check up to 256 bytes of padding
1871 */
1872 size_t pad_count = 0, real_count = 1;
1873 size_t padding_idx = ssl->in_msglen - padlen - 1;
1874
1875 /*
1876 * Padding is guaranteed to be incorrect if:
1877 * 1. padlen >= ssl->in_msglen
1878 *
1879 * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN +
1880 * ssl->transform_in->maclen
1881 *
1882 * In both cases we reset padding_idx to a safe value (0) to
1883 * prevent out-of-buffer reads.
1884 */
1885 correct &= ( ssl->in_msglen >= padlen + 1 );
1886 correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN +
1887 ssl->transform_in->maclen );
1888
1889 padding_idx *= correct;
1890
1891 for( i = 1; i <= 256; i++ )
1892 {
1893 real_count &= ( i <= padlen );
1894 pad_count += real_count *
1895 ( ssl->in_msg[padding_idx + i] == padlen - 1 );
1896 }
1897
1898 correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
1899
1900 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1901 if( padlen > 0 && correct == 0 )
1902 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
1903 #endif
1904 padlen &= correct * 0x1FF;
1905 }
1906 else
1907 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1908 MBEDTLS_SSL_PROTO_TLS1_2 */
1909 {
1910 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1911 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1912 }
1913
1914 ssl->in_msglen -= padlen;
1915 }
1916 else
1917 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
1918 ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */
1919 {
1920 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1921 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1922 }
1923
1924 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
1925 ssl->in_msg, ssl->in_msglen );
1926
1927 /*
1928 * Authenticate if not done yet.
1929 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1930 */
1931 #if defined(SSL_SOME_MODES_USE_MAC)
1932 if( auth_done == 0 )
1933 {
1934 unsigned char tmp[SSL_MAX_MAC_SIZE];
1935
1936 ssl->in_msglen -= ssl->transform_in->maclen;
1937
1938 ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
1939 ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
1940
1941 memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
1942
1943 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1944 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1945 {
1946 ssl_mac( &ssl->transform_in->md_ctx_dec,
1947 ssl->transform_in->mac_dec,
1948 ssl->in_msg, ssl->in_msglen,
1949 ssl->in_ctr, ssl->in_msgtype );
1950 }
1951 else
1952 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1953 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1954 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1955 if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1956 {
1957 /*
1958 * Process MAC and always update for padlen afterwards to make
1959 * total time independent of padlen
1960 *
1961 * extra_run compensates MAC check for padlen
1962 *
1963 * Known timing attacks:
1964 * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
1965 *
1966 * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
1967 * correctly. (We round down instead of up, so -56 is the correct
1968 * value for our calculations instead of -55)
1969 */
1970 size_t j, extra_run = 0;
1971 extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
1972 ( 13 + ssl->in_msglen + 8 ) / 64;
1973
1974 extra_run &= correct * 0xFF;
1975
1976 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
1977 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
1978 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
1979 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
1980 ssl->in_msglen );
1981 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec,
1982 ssl->in_msg + ssl->in_msglen );
1983 /* Call mbedtls_md_process at least once due to cache attacks */
1984 for( j = 0; j < extra_run + 1; j++ )
1985 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
1986
1987 mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
1988 }
1989 else
1990 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1991 MBEDTLS_SSL_PROTO_TLS1_2 */
1992 {
1993 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1994 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1995 }
1996
1997 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen );
1998 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
1999 ssl->transform_in->maclen );
2000
2001 if( mbedtls_ssl_safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen,
2002 ssl->transform_in->maclen ) != 0 )
2003 {
2004 #if defined(MBEDTLS_SSL_DEBUG_ALL)
2005 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
2006 #endif
2007 correct = 0;
2008 }
2009 auth_done++;
2010
2011 /*
2012 * Finally check the correct flag
2013 */
2014 if( correct == 0 )
2015 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2016 }
2017 #endif /* SSL_SOME_MODES_USE_MAC */
2018
2019 /* Make extra sure authentication was performed, exactly once */
2020 if( auth_done != 1 )
2021 {
2022 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2023 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2024 }
2025
2026 if( ssl->in_msglen == 0 )
2027 {
2028 ssl->nb_zero++;
2029
2030 /*
2031 * Three or more empty messages may be a DoS attack
2032 * (excessive CPU consumption).
2033 */
2034 if( ssl->nb_zero > 3 )
2035 {
2036 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
2037 "messages, possible DoS attack" ) );
2038 return( MBEDTLS_ERR_SSL_INVALID_MAC );
2039 }
2040 }
2041 else
2042 ssl->nb_zero = 0;
2043
2044 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2045 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2046 {
2047 ; /* in_ctr read from peer, not maintained internally */
2048 }
2049 else
2050 #endif
2051 {
2052 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2053 if( ++ssl->in_ctr[i - 1] != 0 )
2054 break;
2055
2056 /* The loop goes to its end iff the counter is wrapping */
2057 if( i == ssl_ep_len( ssl ) )
2058 {
2059 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
2060 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2061 }
2062 }
2063
2064 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
2065
2066 return( 0 );
2067 }
2068
2069 #undef MAC_NONE
2070 #undef MAC_PLAINTEXT
2071 #undef MAC_CIPHERTEXT
2072
2073 #if defined(MBEDTLS_ZLIB_SUPPORT)
2074 /*
2075 * Compression/decompression functions
2076 */
2077 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
2078 {
2079 int ret;
2080 unsigned char *msg_post = ssl->out_msg;
2081 size_t len_pre = ssl->out_msglen;
2082 unsigned char *msg_pre = ssl->compress_buf;
2083
2084 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
2085
2086 if( len_pre == 0 )
2087 return( 0 );
2088
2089 memcpy( msg_pre, ssl->out_msg, len_pre );
2090
2091 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
2092 ssl->out_msglen ) );
2093
2094 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
2095 ssl->out_msg, ssl->out_msglen );
2096
2097 ssl->transform_out->ctx_deflate.next_in = msg_pre;
2098 ssl->transform_out->ctx_deflate.avail_in = len_pre;
2099 ssl->transform_out->ctx_deflate.next_out = msg_post;
2100 ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN;
2101
2102 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
2103 if( ret != Z_OK )
2104 {
2105 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
2106 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2107 }
2108
2109 ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN -
2110 ssl->transform_out->ctx_deflate.avail_out;
2111
2112 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
2113 ssl->out_msglen ) );
2114
2115 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
2116 ssl->out_msg, ssl->out_msglen );
2117
2118 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
2119
2120 return( 0 );
2121 }
2122
2123 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
2124 {
2125 int ret;
2126 unsigned char *msg_post = ssl->in_msg;
2127 size_t len_pre = ssl->in_msglen;
2128 unsigned char *msg_pre = ssl->compress_buf;
2129
2130 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
2131
2132 if( len_pre == 0 )
2133 return( 0 );
2134
2135 memcpy( msg_pre, ssl->in_msg, len_pre );
2136
2137 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
2138 ssl->in_msglen ) );
2139
2140 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
2141 ssl->in_msg, ssl->in_msglen );
2142
2143 ssl->transform_in->ctx_inflate.next_in = msg_pre;
2144 ssl->transform_in->ctx_inflate.avail_in = len_pre;
2145 ssl->transform_in->ctx_inflate.next_out = msg_post;
2146 ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN;
2147
2148 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
2149 if( ret != Z_OK )
2150 {
2151 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
2152 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
2153 }
2154
2155 ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN -
2156 ssl->transform_in->ctx_inflate.avail_out;
2157
2158 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
2159 ssl->in_msglen ) );
2160
2161 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
2162 ssl->in_msg, ssl->in_msglen );
2163
2164 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
2165
2166 return( 0 );
2167 }
2168 #endif /* MBEDTLS_ZLIB_SUPPORT */
2169
2170 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2171 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
2172
2173 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2174 static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
2175 {
2176 /* If renegotiation is not enforced, retransmit until we would reach max
2177 * timeout if we were using the usual handshake doubling scheme */
2178 if( ssl->conf->renego_max_records < 0 )
2179 {
2180 uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2181 unsigned char doublings = 1;
2182
2183 while( ratio != 0 )
2184 {
2185 ++doublings;
2186 ratio >>= 1;
2187 }
2188
2189 if( ++ssl->renego_records_seen > doublings )
2190 {
2191 MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
2192 return( 0 );
2193 }
2194 }
2195
2196 return( ssl_write_hello_request( ssl ) );
2197 }
2198 #endif
2199 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2200
2201 /*
2202 * Fill the input message buffer by appending data to it.
2203 * The amount of data already fetched is in ssl->in_left.
2204 *
2205 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2206 * available (from this read and/or a previous one). Otherwise, an error code
2207 * is returned (possibly EOF or WANT_READ).
2208 *
2209 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2210 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2211 * since we always read a whole datagram at once.
2212 *
2213 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2214 * they're done reading a record.
2215 */
2216 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
2217 {
2218 int ret;
2219 size_t len;
2220
2221 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2222
2223 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2224 {
2225 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2226 "or mbedtls_ssl_set_bio()" ) );
2227 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2228 }
2229
2230 if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2231 {
2232 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2233 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2234 }
2235
2236 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2237 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2238 {
2239 uint32_t timeout;
2240
2241 /* Just to be sure */
2242 if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
2243 {
2244 MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
2245 "mbedtls_ssl_set_timer_cb() for DTLS" ) );
2246 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2247 }
2248
2249 /*
2250 * The point is, we need to always read a full datagram at once, so we
2251 * sometimes read more then requested, and handle the additional data.
2252 * It could be the rest of the current record (while fetching the
2253 * header) and/or some other records in the same datagram.
2254 */
2255
2256 /*
2257 * Move to the next record in the already read datagram if applicable
2258 */
2259 if( ssl->next_record_offset != 0 )
2260 {
2261 if( ssl->in_left < ssl->next_record_offset )
2262 {
2263 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2264 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2265 }
2266
2267 ssl->in_left -= ssl->next_record_offset;
2268
2269 if( ssl->in_left != 0 )
2270 {
2271 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2272 ssl->next_record_offset ) );
2273 memmove( ssl->in_hdr,
2274 ssl->in_hdr + ssl->next_record_offset,
2275 ssl->in_left );
2276 }
2277
2278 ssl->next_record_offset = 0;
2279 }
2280
2281 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2282 ssl->in_left, nb_want ) );
2283
2284 /*
2285 * Done if we already have enough data.
2286 */
2287 if( nb_want <= ssl->in_left)
2288 {
2289 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2290 return( 0 );
2291 }
2292
2293 /*
2294 * A record can't be split accross datagrams. If we need to read but
2295 * are not at the beginning of a new record, the caller did something
2296 * wrong.
2297 */
2298 if( ssl->in_left != 0 )
2299 {
2300 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2301 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2302 }
2303
2304 /*
2305 * Don't even try to read if time's out already.
2306 * This avoids by-passing the timer when repeatedly receiving messages
2307 * that will end up being dropped.
2308 */
2309 if( ssl_check_timer( ssl ) != 0 )
2310 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2311 else
2312 {
2313 len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
2314
2315 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2316 timeout = ssl->handshake->retransmit_timeout;
2317 else
2318 timeout = ssl->conf->read_timeout;
2319
2320 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2321
2322 if( ssl->f_recv_timeout != NULL )
2323 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2324 timeout );
2325 else
2326 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2327
2328 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2329
2330 if( ret == 0 )
2331 return( MBEDTLS_ERR_SSL_CONN_EOF );
2332 }
2333
2334 if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
2335 {
2336 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2337 ssl_set_timer( ssl, 0 );
2338
2339 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2340 {
2341 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2342 {
2343 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2344 return( MBEDTLS_ERR_SSL_TIMEOUT );
2345 }
2346
2347 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2348 {
2349 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2350 return( ret );
2351 }
2352
2353 return( MBEDTLS_ERR_SSL_WANT_READ );
2354 }
2355 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2356 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2357 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
2358 {
2359 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
2360 {
2361 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
2362 return( ret );
2363 }
2364
2365 return( MBEDTLS_ERR_SSL_WANT_READ );
2366 }
2367 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2368 }
2369
2370 if( ret < 0 )
2371 return( ret );
2372
2373 ssl->in_left = ret;
2374 }
2375 else
2376 #endif
2377 {
2378 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2379 ssl->in_left, nb_want ) );
2380
2381 while( ssl->in_left < nb_want )
2382 {
2383 len = nb_want - ssl->in_left;
2384
2385 if( ssl_check_timer( ssl ) != 0 )
2386 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2387 else
2388 {
2389 if( ssl->f_recv_timeout != NULL )
2390 {
2391 ret = ssl->f_recv_timeout( ssl->p_bio,
2392 ssl->in_hdr + ssl->in_left, len,
2393 ssl->conf->read_timeout );
2394 }
2395 else
2396 {
2397 ret = ssl->f_recv( ssl->p_bio,
2398 ssl->in_hdr + ssl->in_left, len );
2399 }
2400 }
2401
2402 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2403 ssl->in_left, nb_want ) );
2404 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2405
2406 if( ret == 0 )
2407 return( MBEDTLS_ERR_SSL_CONN_EOF );
2408
2409 if( ret < 0 )
2410 return( ret );
2411
2412 ssl->in_left += ret;
2413 }
2414 }
2415
2416 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2417
2418 return( 0 );
2419 }
2420
2421 /*
2422 * Flush any data not yet written
2423 */
2424 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
2425 {
2426 int ret;
2427 unsigned char *buf, i;
2428
2429 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2430
2431 if( ssl->f_send == NULL )
2432 {
2433 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2434 "or mbedtls_ssl_set_bio()" ) );
2435 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2436 }
2437
2438 /* Avoid incrementing counter if data is flushed */
2439 if( ssl->out_left == 0 )
2440 {
2441 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2442 return( 0 );
2443 }
2444
2445 while( ssl->out_left > 0 )
2446 {
2447 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2448 mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2449
2450 buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) +
2451 ssl->out_msglen - ssl->out_left;
2452 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2453
2454 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2455
2456 if( ret <= 0 )
2457 return( ret );
2458
2459 ssl->out_left -= ret;
2460 }
2461
2462 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2463 if( ++ssl->out_ctr[i - 1] != 0 )
2464 break;
2465
2466 /* The loop goes to its end iff the counter is wrapping */
2467 if( i == ssl_ep_len( ssl ) )
2468 {
2469 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
2470 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2471 }
2472
2473 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2474
2475 return( 0 );
2476 }
2477
2478 /*
2479 * Functions to handle the DTLS retransmission state machine
2480 */
2481 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2482 /*
2483 * Append current handshake message to current outgoing flight
2484 */
2485 static int ssl_flight_append( mbedtls_ssl_context *ssl )
2486 {
2487 mbedtls_ssl_flight_item *msg;
2488
2489 /* Allocate space for current message */
2490 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2491 {
2492 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2493 sizeof( mbedtls_ssl_flight_item ) ) );
2494 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2495 }
2496
2497 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2498 {
2499 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2500 mbedtls_free( msg );
2501 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2502 }
2503
2504 /* Copy current handshake message with headers */
2505 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2506 msg->len = ssl->out_msglen;
2507 msg->type = ssl->out_msgtype;
2508 msg->next = NULL;
2509
2510 /* Append to the current flight */
2511 if( ssl->handshake->flight == NULL )
2512 ssl->handshake->flight = msg;
2513 else
2514 {
2515 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2516 while( cur->next != NULL )
2517 cur = cur->next;
2518 cur->next = msg;
2519 }
2520
2521 return( 0 );
2522 }
2523
2524 /*
2525 * Free the current flight of handshake messages
2526 */
2527 static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
2528 {
2529 mbedtls_ssl_flight_item *cur = flight;
2530 mbedtls_ssl_flight_item *next;
2531
2532 while( cur != NULL )
2533 {
2534 next = cur->next;
2535
2536 mbedtls_free( cur->p );
2537 mbedtls_free( cur );
2538
2539 cur = next;
2540 }
2541 }
2542
2543 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2544 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
2545 #endif
2546
2547 /*
2548 * Swap transform_out and out_ctr with the alternative ones
2549 */
2550 static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
2551 {
2552 mbedtls_ssl_transform *tmp_transform;
2553 unsigned char tmp_out_ctr[8];
2554
2555 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2556 {
2557 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2558 return;
2559 }
2560
2561 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2562
2563 /* Swap transforms */
2564 tmp_transform = ssl->transform_out;
2565 ssl->transform_out = ssl->handshake->alt_transform_out;
2566 ssl->handshake->alt_transform_out = tmp_transform;
2567
2568 /* Swap epoch + sequence_number */
2569 memcpy( tmp_out_ctr, ssl->out_ctr, 8 );
2570 memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 );
2571 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
2572
2573 /* Adjust to the newly activated transform */
2574 if( ssl->transform_out != NULL &&
2575 ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
2576 {
2577 ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen -
2578 ssl->transform_out->fixed_ivlen;
2579 }
2580 else
2581 ssl->out_msg = ssl->out_iv;
2582
2583 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2584 if( mbedtls_ssl_hw_record_activate != NULL )
2585 {
2586 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
2587 {
2588 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
2589 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2590 }
2591 }
2592 #endif
2593 }
2594
2595 /*
2596 * Retransmit the current flight of messages.
2597 *
2598 * Need to remember the current message in case flush_output returns
2599 * WANT_WRITE, causing us to exit this function and come back later.
2600 * This function must be called until state is no longer SENDING.
2601 */
2602 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
2603 {
2604 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
2605
2606 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
2607 {
2608 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) );
2609
2610 ssl->handshake->cur_msg = ssl->handshake->flight;
2611 ssl_swap_epochs( ssl );
2612
2613 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2614 }
2615
2616 while( ssl->handshake->cur_msg != NULL )
2617 {
2618 int ret;
2619 mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg;
2620
2621 /* Swap epochs before sending Finished: we can't do it after
2622 * sending ChangeCipherSpec, in case write returns WANT_READ.
2623 * Must be done before copying, may change out_msg pointer */
2624 if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2625 cur->p[0] == MBEDTLS_SSL_HS_FINISHED )
2626 {
2627 ssl_swap_epochs( ssl );
2628 }
2629
2630 memcpy( ssl->out_msg, cur->p, cur->len );
2631 ssl->out_msglen = cur->len;
2632 ssl->out_msgtype = cur->type;
2633
2634 ssl->handshake->cur_msg = cur->next;
2635
2636 MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 );
2637
2638 if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
2639 {
2640 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
2641 return( ret );
2642 }
2643 }
2644
2645 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
2646 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2647 else
2648 {
2649 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2650 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2651 }
2652
2653 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
2654
2655 return( 0 );
2656 }
2657
2658 /*
2659 * To be called when the last message of an incoming flight is received.
2660 */
2661 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
2662 {
2663 /* We won't need to resend that one any more */
2664 ssl_flight_free( ssl->handshake->flight );
2665 ssl->handshake->flight = NULL;
2666 ssl->handshake->cur_msg = NULL;
2667
2668 /* The next incoming flight will start with this msg_seq */
2669 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2670
2671 /* Cancel timer */
2672 ssl_set_timer( ssl, 0 );
2673
2674 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2675 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2676 {
2677 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2678 }
2679 else
2680 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2681 }
2682
2683 /*
2684 * To be called when the last message of an outgoing flight is send.
2685 */
2686 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
2687 {
2688 ssl_reset_retransmit_timeout( ssl );
2689 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2690
2691 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2692 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2693 {
2694 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2695 }
2696 else
2697 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2698 }
2699 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2700
2701 /*
2702 * Record layer functions
2703 */
2704
2705 /*
2706 * Write current record.
2707 * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg.
2708 */
2709 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl )
2710 {
2711 int ret, done = 0;
2712 size_t len = ssl->out_msglen;
2713
2714 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
2715
2716 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2717 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2718 ssl->handshake != NULL &&
2719 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
2720 {
2721 ; /* Skip special handshake treatment when resending */
2722 }
2723 else
2724 #endif
2725 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
2726 {
2727 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST &&
2728 ssl->handshake == NULL )
2729 {
2730 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2731 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2732 }
2733
2734 ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
2735 ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
2736 ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
2737
2738 /*
2739 * DTLS has additional fields in the Handshake layer,
2740 * between the length field and the actual payload:
2741 * uint16 message_seq;
2742 * uint24 fragment_offset;
2743 * uint24 fragment_length;
2744 */
2745 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2746 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2747 {
2748 /* Make room for the additional DTLS fields */
2749 memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 );
2750 ssl->out_msglen += 8;
2751 len += 8;
2752
2753 /* Write message_seq and update it, except for HelloRequest */
2754 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST )
2755 {
2756 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
2757 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
2758 ++( ssl->handshake->out_msg_seq );
2759 }
2760 else
2761 {
2762 ssl->out_msg[4] = 0;
2763 ssl->out_msg[5] = 0;
2764 }
2765
2766 /* We don't fragment, so frag_offset = 0 and frag_len = len */
2767 memset( ssl->out_msg + 6, 0x00, 3 );
2768 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
2769 }
2770 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2771
2772 if( ssl->out_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST )
2773 ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
2774 }
2775
2776 /* Save handshake and CCS messages for resending */
2777 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2778 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2779 ssl->handshake != NULL &&
2780 ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING &&
2781 ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ||
2782 ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) )
2783 {
2784 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
2785 {
2786 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
2787 return( ret );
2788 }
2789 }
2790 #endif
2791
2792 #if defined(MBEDTLS_ZLIB_SUPPORT)
2793 if( ssl->transform_out != NULL &&
2794 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
2795 {
2796 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
2797 {
2798 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
2799 return( ret );
2800 }
2801
2802 len = ssl->out_msglen;
2803 }
2804 #endif /*MBEDTLS_ZLIB_SUPPORT */
2805
2806 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2807 if( mbedtls_ssl_hw_record_write != NULL )
2808 {
2809 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
2810
2811 ret = mbedtls_ssl_hw_record_write( ssl );
2812 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
2813 {
2814 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
2815 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2816 }
2817
2818 if( ret == 0 )
2819 done = 1;
2820 }
2821 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2822 if( !done )
2823 {
2824 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
2825 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2826 ssl->conf->transport, ssl->out_hdr + 1 );
2827
2828 ssl->out_len[0] = (unsigned char)( len >> 8 );
2829 ssl->out_len[1] = (unsigned char)( len );
2830
2831 if( ssl->transform_out != NULL )
2832 {
2833 if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
2834 {
2835 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
2836 return( ret );
2837 }
2838
2839 len = ssl->out_msglen;
2840 ssl->out_len[0] = (unsigned char)( len >> 8 );
2841 ssl->out_len[1] = (unsigned char)( len );
2842 }
2843
2844 ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen;
2845
2846 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
2847 "version = [%d:%d], msglen = %d",
2848 ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
2849 ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) );
2850
2851 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
2852 ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen );
2853 }
2854
2855 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2856 {
2857 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
2858 return( ret );
2859 }
2860
2861 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
2862
2863 return( 0 );
2864 }
2865
2866 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2867 /*
2868 * Mark bits in bitmask (used for DTLS HS reassembly)
2869 */
2870 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
2871 {
2872 unsigned int start_bits, end_bits;
2873
2874 start_bits = 8 - ( offset % 8 );
2875 if( start_bits != 8 )
2876 {
2877 size_t first_byte_idx = offset / 8;
2878
2879 /* Special case */
2880 if( len <= start_bits )
2881 {
2882 for( ; len != 0; len-- )
2883 mask[first_byte_idx] |= 1 << ( start_bits - len );
2884
2885 /* Avoid potential issues with offset or len becoming invalid */
2886 return;
2887 }
2888
2889 offset += start_bits; /* Now offset % 8 == 0 */
2890 len -= start_bits;
2891
2892 for( ; start_bits != 0; start_bits-- )
2893 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
2894 }
2895
2896 end_bits = len % 8;
2897 if( end_bits != 0 )
2898 {
2899 size_t last_byte_idx = ( offset + len ) / 8;
2900
2901 len -= end_bits; /* Now len % 8 == 0 */
2902
2903 for( ; end_bits != 0; end_bits-- )
2904 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
2905 }
2906
2907 memset( mask + offset / 8, 0xFF, len / 8 );
2908 }
2909
2910 /*
2911 * Check that bitmask is full
2912 */
2913 static int ssl_bitmask_check( unsigned char *mask, size_t len )
2914 {
2915 size_t i;
2916
2917 for( i = 0; i < len / 8; i++ )
2918 if( mask[i] != 0xFF )
2919 return( -1 );
2920
2921 for( i = 0; i < len % 8; i++ )
2922 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
2923 return( -1 );
2924
2925 return( 0 );
2926 }
2927
2928 /*
2929 * Reassemble fragmented DTLS handshake messages.
2930 *
2931 * Use a temporary buffer for reassembly, divided in two parts:
2932 * - the first holds the reassembled message (including handshake header),
2933 * - the second holds a bitmask indicating which parts of the message
2934 * (excluding headers) have been received so far.
2935 */
2936 static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )
2937 {
2938 unsigned char *msg, *bitmask;
2939 size_t frag_len, frag_off;
2940 size_t msg_len = ssl->in_hslen - 12; /* Without headers */
2941
2942 if( ssl->handshake == NULL )
2943 {
2944 MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) );
2945 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2946 }
2947
2948 /*
2949 * For first fragment, check size and allocate buffer
2950 */
2951 if( ssl->handshake->hs_msg == NULL )
2952 {
2953 size_t alloc_len;
2954
2955 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
2956 msg_len ) );
2957
2958 if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN )
2959 {
2960 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) );
2961 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2962 }
2963
2964 /* The bitmask needs one bit per byte of message excluding header */
2965 alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 );
2966
2967 ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len );
2968 if( ssl->handshake->hs_msg == NULL )
2969 {
2970 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) );
2971 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2972 }
2973
2974 /* Prepare final header: copy msg_type, length and message_seq,
2975 * then add standardised fragment_offset and fragment_length */
2976 memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 );
2977 memset( ssl->handshake->hs_msg + 6, 0, 3 );
2978 memcpy( ssl->handshake->hs_msg + 9,
2979 ssl->handshake->hs_msg + 1, 3 );
2980 }
2981 else
2982 {
2983 /* Make sure msg_type and length are consistent */
2984 if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 )
2985 {
2986 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) );
2987 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
2988 }
2989 }
2990
2991 msg = ssl->handshake->hs_msg + 12;
2992 bitmask = msg + msg_len;
2993
2994 /*
2995 * Check and copy current fragment
2996 */
2997 frag_off = ( ssl->in_msg[6] << 16 ) |
2998 ( ssl->in_msg[7] << 8 ) |
2999 ssl->in_msg[8];
3000 frag_len = ( ssl->in_msg[9] << 16 ) |
3001 ( ssl->in_msg[10] << 8 ) |
3002 ssl->in_msg[11];
3003
3004 if( frag_off + frag_len > msg_len )
3005 {
3006 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d",
3007 frag_off, frag_len, msg_len ) );
3008 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3009 }
3010
3011 if( frag_len + 12 > ssl->in_msglen )
3012 {
3013 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d",
3014 frag_len, ssl->in_msglen ) );
3015 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3016 }
3017
3018 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
3019 frag_off, frag_len ) );
3020
3021 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
3022 ssl_bitmask_set( bitmask, frag_off, frag_len );
3023
3024 /*
3025 * Do we have the complete message by now?
3026 * If yes, finalize it, else ask to read the next record.
3027 */
3028 if( ssl_bitmask_check( bitmask, msg_len ) != 0 )
3029 {
3030 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) );
3031 return( MBEDTLS_ERR_SSL_WANT_READ );
3032 }
3033
3034 MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) );
3035
3036 if( frag_len + 12 < ssl->in_msglen )
3037 {
3038 /*
3039 * We'got more handshake messages in the same record.
3040 * This case is not handled now because no know implementation does
3041 * that and it's hard to test, so we prefer to fail cleanly for now.
3042 */
3043 MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) );
3044 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3045 }
3046
3047 if( ssl->in_left > ssl->next_record_offset )
3048 {
3049 /*
3050 * We've got more data in the buffer after the current record,
3051 * that we don't want to overwrite. Move it before writing the
3052 * reassembled message, and adjust in_left and next_record_offset.
3053 */
3054 unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset;
3055 unsigned char *new_remain = ssl->in_msg + ssl->in_hslen;
3056 size_t remain_len = ssl->in_left - ssl->next_record_offset;
3057
3058 /* First compute and check new lengths */
3059 ssl->next_record_offset = new_remain - ssl->in_hdr;
3060 ssl->in_left = ssl->next_record_offset + remain_len;
3061
3062 if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN -
3063 (size_t)( ssl->in_hdr - ssl->in_buf ) )
3064 {
3065 MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) );
3066 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3067 }
3068
3069 memmove( new_remain, cur_remain, remain_len );
3070 }
3071
3072 memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );
3073
3074 mbedtls_free( ssl->handshake->hs_msg );
3075 ssl->handshake->hs_msg = NULL;
3076
3077 MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message",
3078 ssl->in_msg, ssl->in_hslen );
3079
3080 return( 0 );