1 /*
2 * Generic SSL/TLS messaging layer functions
3 * (record layer + retransmission state machine)
4 *
5 * Copyright The Mbed TLS Contributors
6 * SPDX-License-Identifier: Apache-2.0
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may
9 * not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20 /*
21 * The SSL 3.0 specification was drafted by Netscape in 1996,
22 * and became an IETF standard in 1999.
23 *
24 * http://wp.netscape.com/eng/ssl3/
25 * http://www.ietf.org/rfc/rfc2246.txt
26 * http://www.ietf.org/rfc/rfc4346.txt
27 */
28
29 #include "common.h"
30
31 #if defined(MBEDTLS_SSL_TLS_C)
32
33 #if defined(MBEDTLS_PLATFORM_C)
34 #include "mbedtls/platform.h"
35 #else
36 #include <stdlib.h>
37 #define mbedtls_calloc calloc
38 #define mbedtls_free free
39 #endif
40
41 #include "mbedtls/ssl.h"
42 #include "mbedtls/ssl_internal.h"
43 #include "mbedtls/debug.h"
44 #include "mbedtls/error.h"
45 #include "mbedtls/platform_util.h"
46 #include "mbedtls/version.h"
47
48 #include "ssl_invasive.h"
49
50 #include <string.h>
51
52 #if defined(MBEDTLS_USE_PSA_CRYPTO)
53 #include "mbedtls/psa_util.h"
54 #include "psa/crypto.h"
55 #endif
56
57 #if defined(MBEDTLS_X509_CRT_PARSE_C)
58 #include "mbedtls/oid.h"
59 #endif
60
61 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
62
63 /*
64 * Start a timer.
65 * Passing millisecs = 0 cancels a running timer.
66 */
mbedtls_ssl_set_timer(mbedtls_ssl_context * ssl,uint32_t millisecs)67 void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
68 {
69 if( ssl->f_set_timer == NULL )
70 return;
71
72 MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
73 ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
74 }
75
76 /*
77 * Return -1 is timer is expired, 0 if it isn't.
78 */
mbedtls_ssl_check_timer(mbedtls_ssl_context * ssl)79 int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl )
80 {
81 if( ssl->f_get_timer == NULL )
82 return( 0 );
83
84 if( ssl->f_get_timer( ssl->p_timer ) == 2 )
85 {
86 MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
87 return( -1 );
88 }
89
90 return( 0 );
91 }
92
93 #if defined(MBEDTLS_SSL_RECORD_CHECKING)
94 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl,
95 unsigned char *buf,
96 size_t len,
97 mbedtls_record *rec );
98
mbedtls_ssl_check_record(mbedtls_ssl_context const * ssl,unsigned char * buf,size_t buflen)99 int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl,
100 unsigned char *buf,
101 size_t buflen )
102 {
103 int ret = 0;
104 MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) );
105 MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen );
106
107 /* We don't support record checking in TLS because
108 * (a) there doesn't seem to be a usecase for it, and
109 * (b) In SSLv3 and TLS 1.0, CBC record decryption has state
110 * and we'd need to backup the transform here.
111 */
112 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
113 {
114 ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
115 goto exit;
116 }
117 #if defined(MBEDTLS_SSL_PROTO_DTLS)
118 else
119 {
120 mbedtls_record rec;
121
122 ret = ssl_parse_record_header( ssl, buf, buflen, &rec );
123 if( ret != 0 )
124 {
125 MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret );
126 goto exit;
127 }
128
129 if( ssl->transform_in != NULL )
130 {
131 ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec );
132 if( ret != 0 )
133 {
134 MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret );
135 goto exit;
136 }
137 }
138 }
139 #endif /* MBEDTLS_SSL_PROTO_DTLS */
140
141 exit:
142 /* On success, we have decrypted the buffer in-place, so make
143 * sure we don't leak any plaintext data. */
144 mbedtls_platform_zeroize( buf, buflen );
145
146 /* For the purpose of this API, treat messages with unexpected CID
147 * as well as such from future epochs as unexpected. */
148 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
149 ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
150 {
151 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
152 }
153
154 MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) );
155 return( ret );
156 }
157 #endif /* MBEDTLS_SSL_RECORD_CHECKING */
158
159 #define SSL_DONT_FORCE_FLUSH 0
160 #define SSL_FORCE_FLUSH 1
161
162 #if defined(MBEDTLS_SSL_PROTO_DTLS)
163
164 /* Forward declarations for functions related to message buffering. */
165 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
166 uint8_t slot );
167 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
168 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
169 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
170 static int ssl_buffer_message( mbedtls_ssl_context *ssl );
171 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl,
172 mbedtls_record const *rec );
173 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
174
ssl_get_maximum_datagram_size(mbedtls_ssl_context const * ssl)175 static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
176 {
177 size_t mtu = mbedtls_ssl_get_current_mtu( ssl );
178 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
179 size_t out_buf_len = ssl->out_buf_len;
180 #else
181 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
182 #endif
183
184 if( mtu != 0 && mtu < out_buf_len )
185 return( mtu );
186
187 return( out_buf_len );
188 }
189
ssl_get_remaining_space_in_datagram(mbedtls_ssl_context const * ssl)190 static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
191 {
192 size_t const bytes_written = ssl->out_left;
193 size_t const mtu = ssl_get_maximum_datagram_size( ssl );
194
195 /* Double-check that the write-index hasn't gone
196 * past what we can transmit in a single datagram. */
197 if( bytes_written > mtu )
198 {
199 /* Should never happen... */
200 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
201 }
202
203 return( (int) ( mtu - bytes_written ) );
204 }
205
ssl_get_remaining_payload_in_datagram(mbedtls_ssl_context const * ssl)206 static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
207 {
208 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
209 size_t remaining, expansion;
210 size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
211
212 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
213 const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl );
214
215 if( max_len > mfl )
216 max_len = mfl;
217
218 /* By the standard (RFC 6066 Sect. 4), the MFL extension
219 * only limits the maximum record payload size, so in theory
220 * we would be allowed to pack multiple records of payload size
221 * MFL into a single datagram. However, this would mean that there's
222 * no way to explicitly communicate MTU restrictions to the peer.
223 *
224 * The following reduction of max_len makes sure that we never
225 * write datagrams larger than MFL + Record Expansion Overhead.
226 */
227 if( max_len <= ssl->out_left )
228 return( 0 );
229
230 max_len -= ssl->out_left;
231 #endif
232
233 ret = ssl_get_remaining_space_in_datagram( ssl );
234 if( ret < 0 )
235 return( ret );
236 remaining = (size_t) ret;
237
238 ret = mbedtls_ssl_get_record_expansion( ssl );
239 if( ret < 0 )
240 return( ret );
241 expansion = (size_t) ret;
242
243 if( remaining <= expansion )
244 return( 0 );
245
246 remaining -= expansion;
247 if( remaining >= max_len )
248 remaining = max_len;
249
250 return( (int) remaining );
251 }
252
253 /*
254 * Double the retransmit timeout value, within the allowed range,
255 * returning -1 if the maximum value has already been reached.
256 */
ssl_double_retransmit_timeout(mbedtls_ssl_context * ssl)257 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
258 {
259 uint32_t new_timeout;
260
261 if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
262 return( -1 );
263
264 /* Implement the final paragraph of RFC 6347 section 4.1.1.1
265 * in the following way: after the initial transmission and a first
266 * retransmission, back off to a temporary estimated MTU of 508 bytes.
267 * This value is guaranteed to be deliverable (if not guaranteed to be
268 * delivered) of any compliant IPv4 (and IPv6) network, and should work
269 * on most non-IP stacks too. */
270 if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
271 {
272 ssl->handshake->mtu = 508;
273 MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
274 }
275
276 new_timeout = 2 * ssl->handshake->retransmit_timeout;
277
278 /* Avoid arithmetic overflow and range overflow */
279 if( new_timeout < ssl->handshake->retransmit_timeout ||
280 new_timeout > ssl->conf->hs_timeout_max )
281 {
282 new_timeout = ssl->conf->hs_timeout_max;
283 }
284
285 ssl->handshake->retransmit_timeout = new_timeout;
286 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
287 ssl->handshake->retransmit_timeout ) );
288
289 return( 0 );
290 }
291
ssl_reset_retransmit_timeout(mbedtls_ssl_context * ssl)292 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
293 {
294 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
295 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
296 ssl->handshake->retransmit_timeout ) );
297 }
298 #endif /* MBEDTLS_SSL_PROTO_DTLS */
299
300 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
301 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
302 const unsigned char *key_enc, const unsigned char *key_dec,
303 size_t keylen,
304 const unsigned char *iv_enc, const unsigned char *iv_dec,
305 size_t ivlen,
306 const unsigned char *mac_enc, const unsigned char *mac_dec,
307 size_t maclen ) = NULL;
308 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
309 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
310 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
311 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
312 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
313 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
314
315 /*
316 * Encryption/decryption functions
317 */
318
319 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \
320 defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
321
ssl_compute_padding_length(size_t len,size_t granularity)322 static size_t ssl_compute_padding_length( size_t len,
323 size_t granularity )
324 {
325 return( ( granularity - ( len + 1 ) % granularity ) % granularity );
326 }
327
328 /* This functions transforms a (D)TLS plaintext fragment and a record content
329 * type into an instance of the (D)TLSInnerPlaintext structure. This is used
330 * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect
331 * a record's content type.
332 *
333 * struct {
334 * opaque content[DTLSPlaintext.length];
335 * ContentType real_type;
336 * uint8 zeros[length_of_padding];
337 * } (D)TLSInnerPlaintext;
338 *
339 * Input:
340 * - `content`: The beginning of the buffer holding the
341 * plaintext to be wrapped.
342 * - `*content_size`: The length of the plaintext in Bytes.
343 * - `max_len`: The number of Bytes available starting from
344 * `content`. This must be `>= *content_size`.
345 * - `rec_type`: The desired record content type.
346 *
347 * Output:
348 * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure.
349 * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure.
350 *
351 * Returns:
352 * - `0` on success.
353 * - A negative error code if `max_len` didn't offer enough space
354 * for the expansion.
355 */
ssl_build_inner_plaintext(unsigned char * content,size_t * content_size,size_t remaining,uint8_t rec_type,size_t pad)356 static int ssl_build_inner_plaintext( unsigned char *content,
357 size_t *content_size,
358 size_t remaining,
359 uint8_t rec_type,
360 size_t pad )
361 {
362 size_t len = *content_size;
363
364 /* Write real content type */
365 if( remaining == 0 )
366 return( -1 );
367 content[ len ] = rec_type;
368 len++;
369 remaining--;
370
371 if( remaining < pad )
372 return( -1 );
373 memset( content + len, 0, pad );
374 len += pad;
375 remaining -= pad;
376
377 *content_size = len;
378 return( 0 );
379 }
380
381 /* This function parses a (D)TLSInnerPlaintext structure.
382 * See ssl_build_inner_plaintext() for details. */
ssl_parse_inner_plaintext(unsigned char const * content,size_t * content_size,uint8_t * rec_type)383 static int ssl_parse_inner_plaintext( unsigned char const *content,
384 size_t *content_size,
385 uint8_t *rec_type )
386 {
387 size_t remaining = *content_size;
388
389 /* Determine length of padding by skipping zeroes from the back. */
390 do
391 {
392 if( remaining == 0 )
393 return( -1 );
394 remaining--;
395 } while( content[ remaining ] == 0 );
396
397 *content_size = remaining;
398 *rec_type = content[ remaining ];
399
400 return( 0 );
401 }
402 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID ||
403 MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
404
405 /* `add_data` must have size 13 Bytes if the CID extension is disabled,
406 * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */
ssl_extract_add_data_from_record(unsigned char * add_data,size_t * add_data_len,mbedtls_record * rec,unsigned minor_ver)407 static void ssl_extract_add_data_from_record( unsigned char* add_data,
408 size_t *add_data_len,
409 mbedtls_record *rec,
410 unsigned minor_ver )
411 {
412 /* Quoting RFC 5246 (TLS 1.2):
413 *
414 * additional_data = seq_num + TLSCompressed.type +
415 * TLSCompressed.version + TLSCompressed.length;
416 *
417 * For the CID extension, this is extended as follows
418 * (quoting draft-ietf-tls-dtls-connection-id-05,
419 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05):
420 *
421 * additional_data = seq_num + DTLSPlaintext.type +
422 * DTLSPlaintext.version +
423 * cid +
424 * cid_length +
425 * length_of_DTLSInnerPlaintext;
426 *
427 * For TLS 1.3, the record sequence number is dropped from the AAD
428 * and encoded within the nonce of the AEAD operation instead.
429 */
430
431 unsigned char *cur = add_data;
432
433 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
434 if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 )
435 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
436 {
437 ((void) minor_ver);
438 memcpy( cur, rec->ctr, sizeof( rec->ctr ) );
439 cur += sizeof( rec->ctr );
440 }
441
442 *cur = rec->type;
443 cur++;
444
445 memcpy( cur, rec->ver, sizeof( rec->ver ) );
446 cur += sizeof( rec->ver );
447
448 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
449 if( rec->cid_len != 0 )
450 {
451 memcpy( cur, rec->cid, rec->cid_len );
452 cur += rec->cid_len;
453
454 *cur = rec->cid_len;
455 cur++;
456
457 cur[0] = ( rec->data_len >> 8 ) & 0xFF;
458 cur[1] = ( rec->data_len >> 0 ) & 0xFF;
459 cur += 2;
460 }
461 else
462 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
463 {
464 cur[0] = ( rec->data_len >> 8 ) & 0xFF;
465 cur[1] = ( rec->data_len >> 0 ) & 0xFF;
466 cur += 2;
467 }
468
469 *add_data_len = cur - add_data;
470 }
471
472 #if defined(MBEDTLS_SSL_PROTO_SSL3)
473
474 #define SSL3_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */
475
476 /*
477 * SSLv3.0 MAC functions
478 */
ssl_mac(mbedtls_md_context_t * md_ctx,const unsigned char * secret,const unsigned char * buf,size_t len,const unsigned char * ctr,int type,unsigned char out[SSL3_MAC_MAX_BYTES])479 static void ssl_mac( mbedtls_md_context_t *md_ctx,
480 const unsigned char *secret,
481 const unsigned char *buf, size_t len,
482 const unsigned char *ctr, int type,
483 unsigned char out[SSL3_MAC_MAX_BYTES] )
484 {
485 unsigned char header[11];
486 unsigned char padding[48];
487 int padlen;
488 int md_size = mbedtls_md_get_size( md_ctx->md_info );
489 int md_type = mbedtls_md_get_type( md_ctx->md_info );
490
491 /* Only MD5 and SHA-1 supported */
492 if( md_type == MBEDTLS_MD_MD5 )
493 padlen = 48;
494 else
495 padlen = 40;
496
497 memcpy( header, ctr, 8 );
498 header[ 8] = (unsigned char) type;
499 header[ 9] = (unsigned char)( len >> 8 );
500 header[10] = (unsigned char)( len );
501
502 memset( padding, 0x36, padlen );
503 mbedtls_md_starts( md_ctx );
504 mbedtls_md_update( md_ctx, secret, md_size );
505 mbedtls_md_update( md_ctx, padding, padlen );
506 mbedtls_md_update( md_ctx, header, 11 );
507 mbedtls_md_update( md_ctx, buf, len );
508 mbedtls_md_finish( md_ctx, out );
509
510 memset( padding, 0x5C, padlen );
511 mbedtls_md_starts( md_ctx );
512 mbedtls_md_update( md_ctx, secret, md_size );
513 mbedtls_md_update( md_ctx, padding, padlen );
514 mbedtls_md_update( md_ctx, out, md_size );
515 mbedtls_md_finish( md_ctx, out );
516 }
517 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
518
519 #if defined(MBEDTLS_GCM_C) || \
520 defined(MBEDTLS_CCM_C) || \
521 defined(MBEDTLS_CHACHAPOLY_C)
ssl_transform_aead_dynamic_iv_is_explicit(mbedtls_ssl_transform const * transform)522 static int ssl_transform_aead_dynamic_iv_is_explicit(
523 mbedtls_ssl_transform const *transform )
524 {
525 return( transform->ivlen != transform->fixed_ivlen );
526 }
527
528 /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV )
529 *
530 * Concretely, this occurs in two variants:
531 *
532 * a) Fixed and dynamic IV lengths add up to total IV length, giving
533 * IV = fixed_iv || dynamic_iv
534 *
535 * This variant is used in TLS 1.2 when used with GCM or CCM.
536 *
537 * b) Fixed IV lengths matches total IV length, giving
538 * IV = fixed_iv XOR ( 0 || dynamic_iv )
539 *
540 * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly.
541 *
542 * See also the documentation of mbedtls_ssl_transform.
543 *
544 * This function has the precondition that
545 *
546 * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len )
547 *
548 * which has to be ensured by the caller. If this precondition
549 * violated, the behavior of this function is undefined.
550 */
ssl_build_record_nonce(unsigned char * dst_iv,size_t dst_iv_len,unsigned char const * fixed_iv,size_t fixed_iv_len,unsigned char const * dynamic_iv,size_t dynamic_iv_len)551 static void ssl_build_record_nonce( unsigned char *dst_iv,
552 size_t dst_iv_len,
553 unsigned char const *fixed_iv,
554 size_t fixed_iv_len,
555 unsigned char const *dynamic_iv,
556 size_t dynamic_iv_len )
557 {
558 size_t i;
559
560 /* Start with Fixed IV || 0 */
561 memset( dst_iv, 0, dst_iv_len );
562 memcpy( dst_iv, fixed_iv, fixed_iv_len );
563
564 dst_iv += dst_iv_len - dynamic_iv_len;
565 for( i = 0; i < dynamic_iv_len; i++ )
566 dst_iv[i] ^= dynamic_iv[i];
567 }
568 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
569
mbedtls_ssl_encrypt_buf(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform,mbedtls_record * rec,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)570 int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
571 mbedtls_ssl_transform *transform,
572 mbedtls_record *rec,
573 int (*f_rng)(void *, unsigned char *, size_t),
574 void *p_rng )
575 {
576 mbedtls_cipher_mode_t mode;
577 int auth_done = 0;
578 unsigned char * data;
579 unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ];
580 size_t add_data_len;
581 size_t post_avail;
582
583 /* The SSL context is only used for debugging purposes! */
584 #if !defined(MBEDTLS_DEBUG_C)
585 ssl = NULL; /* make sure we don't use it except for debug */
586 ((void) ssl);
587 #endif
588
589 /* The PRNG is used for dynamic IV generation that's used
590 * for CBC transformations in TLS 1.1 and TLS 1.2. */
591 #if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
592 ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) )
593 ((void) f_rng);
594 ((void) p_rng);
595 #endif
596
597 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
598
599 if( transform == NULL )
600 {
601 MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) );
602 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
603 }
604 if( rec == NULL
605 || rec->buf == NULL
606 || rec->buf_len < rec->data_offset
607 || rec->buf_len - rec->data_offset < rec->data_len
608 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
609 || rec->cid_len != 0
610 #endif
611 )
612 {
613 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) );
614 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
615 }
616
617 data = rec->buf + rec->data_offset;
618 post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
619 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
620 data, rec->data_len );
621
622 mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc );
623
624 if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
625 {
626 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %u too large, maximum %d",
627 (unsigned) rec->data_len,
628 MBEDTLS_SSL_OUT_CONTENT_LEN ) );
629 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
630 }
631
632 /* The following two code paths implement the (D)TLSInnerPlaintext
633 * structure present in TLS 1.3 and DTLS 1.2 + CID.
634 *
635 * See ssl_build_inner_plaintext() for more information.
636 *
637 * Note that this changes `rec->data_len`, and hence
638 * `post_avail` needs to be recalculated afterwards.
639 *
640 * Note also that the two code paths cannot occur simultaneously
641 * since they apply to different versions of the protocol. There
642 * is hence no risk of double-addition of the inner plaintext.
643 */
644 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
645 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 )
646 {
647 size_t padding =
648 ssl_compute_padding_length( rec->data_len,
649 MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY );
650 if( ssl_build_inner_plaintext( data,
651 &rec->data_len,
652 post_avail,
653 rec->type,
654 padding ) != 0 )
655 {
656 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
657 }
658
659 rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA;
660 }
661 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
662
663 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
664 /*
665 * Add CID information
666 */
667 rec->cid_len = transform->out_cid_len;
668 memcpy( rec->cid, transform->out_cid, transform->out_cid_len );
669 MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len );
670
671 if( rec->cid_len != 0 )
672 {
673 size_t padding =
674 ssl_compute_padding_length( rec->data_len,
675 MBEDTLS_SSL_CID_PADDING_GRANULARITY );
676 /*
677 * Wrap plaintext into DTLSInnerPlaintext structure.
678 * See ssl_build_inner_plaintext() for more information.
679 *
680 * Note that this changes `rec->data_len`, and hence
681 * `post_avail` needs to be recalculated afterwards.
682 */
683 if( ssl_build_inner_plaintext( data,
684 &rec->data_len,
685 post_avail,
686 rec->type,
687 padding ) != 0 )
688 {
689 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
690 }
691
692 rec->type = MBEDTLS_SSL_MSG_CID;
693 }
694 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
695
696 post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
697
698 /*
699 * Add MAC before if needed
700 */
701 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
702 if( mode == MBEDTLS_MODE_STREAM ||
703 ( mode == MBEDTLS_MODE_CBC
704 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
705 && transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
706 #endif
707 ) )
708 {
709 if( post_avail < transform->maclen )
710 {
711 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
712 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
713 }
714
715 #if defined(MBEDTLS_SSL_PROTO_SSL3)
716 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
717 {
718 unsigned char mac[SSL3_MAC_MAX_BYTES];
719 ssl_mac( &transform->md_ctx_enc, transform->mac_enc,
720 data, rec->data_len, rec->ctr, rec->type, mac );
721 memcpy( data + rec->data_len, mac, transform->maclen );
722 }
723 else
724 #endif
725 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
726 defined(MBEDTLS_SSL_PROTO_TLS1_2)
727 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
728 {
729 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
730
731 ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
732 transform->minor_ver );
733
734 mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data,
735 add_data_len );
736 mbedtls_md_hmac_update( &transform->md_ctx_enc,
737 data, rec->data_len );
738 mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac );
739 mbedtls_md_hmac_reset( &transform->md_ctx_enc );
740
741 memcpy( data + rec->data_len, mac, transform->maclen );
742 }
743 else
744 #endif
745 {
746 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
747 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
748 }
749
750 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len,
751 transform->maclen );
752
753 rec->data_len += transform->maclen;
754 post_avail -= transform->maclen;
755 auth_done++;
756 }
757 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
758
759 /*
760 * Encrypt
761 */
762 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
763 if( mode == MBEDTLS_MODE_STREAM )
764 {
765 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
766 size_t olen;
767 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
768 "including %d bytes of padding",
769 rec->data_len, 0 ) );
770
771 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
772 transform->iv_enc, transform->ivlen,
773 data, rec->data_len,
774 data, &olen ) ) != 0 )
775 {
776 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
777 return( ret );
778 }
779
780 if( rec->data_len != olen )
781 {
782 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
783 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
784 }
785 }
786 else
787 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
788
789 #if defined(MBEDTLS_GCM_C) || \
790 defined(MBEDTLS_CCM_C) || \
791 defined(MBEDTLS_CHACHAPOLY_C)
792 if( mode == MBEDTLS_MODE_GCM ||
793 mode == MBEDTLS_MODE_CCM ||
794 mode == MBEDTLS_MODE_CHACHAPOLY )
795 {
796 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
797 unsigned char iv[12];
798 unsigned char *dynamic_iv;
799 size_t dynamic_iv_len;
800 int dynamic_iv_is_explicit =
801 ssl_transform_aead_dynamic_iv_is_explicit( transform );
802
803 /* Check that there's space for the authentication tag. */
804 if( post_avail < transform->taglen )
805 {
806 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
807 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
808 }
809
810 /*
811 * Build nonce for AEAD encryption.
812 *
813 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
814 * part of the IV is prepended to the ciphertext and
815 * can be chosen freely - in particular, it need not
816 * agree with the record sequence number.
817 * However, since ChaChaPoly as well as all AEAD modes
818 * in TLS 1.3 use the record sequence number as the
819 * dynamic part of the nonce, we uniformly use the
820 * record sequence number here in all cases.
821 */
822 dynamic_iv = rec->ctr;
823 dynamic_iv_len = sizeof( rec->ctr );
824
825 ssl_build_record_nonce( iv, sizeof( iv ),
826 transform->iv_enc,
827 transform->fixed_ivlen,
828 dynamic_iv,
829 dynamic_iv_len );
830
831 /*
832 * Build additional data for AEAD encryption.
833 * This depends on the TLS version.
834 */
835 ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
836 transform->minor_ver );
837
838 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
839 iv, transform->ivlen );
840 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
841 dynamic_iv,
842 dynamic_iv_is_explicit ? dynamic_iv_len : 0 );
843 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
844 add_data, add_data_len );
845 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
846 "including 0 bytes of padding",
847 rec->data_len ) );
848
849 /*
850 * Encrypt and authenticate
851 */
852
853 if( ( ret = mbedtls_cipher_auth_encrypt_ext( &transform->cipher_ctx_enc,
854 iv, transform->ivlen,
855 add_data, add_data_len,
856 data, rec->data_len, /* src */
857 data, rec->buf_len - (data - rec->buf), /* dst */
858 &rec->data_len,
859 transform->taglen ) ) != 0 )
860 {
861 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
862 return( ret );
863 }
864 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag",
865 data + rec->data_len - transform->taglen,
866 transform->taglen );
867 /* Account for authentication tag. */
868 post_avail -= transform->taglen;
869
870 /*
871 * Prefix record content with dynamic IV in case it is explicit.
872 */
873 if( dynamic_iv_is_explicit != 0 )
874 {
875 if( rec->data_offset < dynamic_iv_len )
876 {
877 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
878 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
879 }
880
881 memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len );
882 rec->data_offset -= dynamic_iv_len;
883 rec->data_len += dynamic_iv_len;
884 }
885
886 auth_done++;
887 }
888 else
889 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
890 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
891 if( mode == MBEDTLS_MODE_CBC )
892 {
893 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
894 size_t padlen, i;
895 size_t olen;
896
897 /* Currently we're always using minimal padding
898 * (up to 255 bytes would be allowed). */
899 padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen;
900 if( padlen == transform->ivlen )
901 padlen = 0;
902
903 /* Check there's enough space in the buffer for the padding. */
904 if( post_avail < padlen + 1 )
905 {
906 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
907 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
908 }
909
910 for( i = 0; i <= padlen; i++ )
911 data[rec->data_len + i] = (unsigned char) padlen;
912
913 rec->data_len += padlen + 1;
914 post_avail -= padlen + 1;
915
916 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
917 /*
918 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
919 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
920 */
921 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
922 {
923 if( f_rng == NULL )
924 {
925 MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) );
926 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
927 }
928
929 if( rec->data_offset < transform->ivlen )
930 {
931 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
932 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
933 }
934
935 /*
936 * Generate IV
937 */
938 ret = f_rng( p_rng, transform->iv_enc, transform->ivlen );
939 if( ret != 0 )
940 return( ret );
941
942 memcpy( data - transform->ivlen, transform->iv_enc,
943 transform->ivlen );
944
945 }
946 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
947
948 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
949 "including %d bytes of IV and %d bytes of padding",
950 rec->data_len, transform->ivlen,
951 padlen + 1 ) );
952
953 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
954 transform->iv_enc,
955 transform->ivlen,
956 data, rec->data_len,
957 data, &olen ) ) != 0 )
958 {
959 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
960 return( ret );
961 }
962
963 if( rec->data_len != olen )
964 {
965 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
966 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
967 }
968
969 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
970 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
971 {
972 /*
973 * Save IV in SSL3 and TLS1
974 */
975 memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv,
976 transform->ivlen );
977 }
978 else
979 #endif
980 {
981 data -= transform->ivlen;
982 rec->data_offset -= transform->ivlen;
983 rec->data_len += transform->ivlen;
984 }
985
986 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
987 if( auth_done == 0 )
988 {
989 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
990
991 /*
992 * MAC(MAC_write_key, seq_num +
993 * TLSCipherText.type +
994 * TLSCipherText.version +
995 * length_of( (IV +) ENC(...) ) +
996 * IV + // except for TLS 1.0
997 * ENC(content + padding + padding_length));
998 */
999
1000 if( post_avail < transform->maclen)
1001 {
1002 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
1003 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
1004 }
1005
1006 ssl_extract_add_data_from_record( add_data, &add_data_len,
1007 rec, transform->minor_ver );
1008
1009 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1010 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data,
1011 add_data_len );
1012
1013 mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data,
1014 add_data_len );
1015 mbedtls_md_hmac_update( &transform->md_ctx_enc,
1016 data, rec->data_len );
1017 mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac );
1018 mbedtls_md_hmac_reset( &transform->md_ctx_enc );
1019
1020 memcpy( data + rec->data_len, mac, transform->maclen );
1021
1022 rec->data_len += transform->maclen;
1023 post_avail -= transform->maclen;
1024 auth_done++;
1025 }
1026 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1027 }
1028 else
1029 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
1030 {
1031 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1032 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1033 }
1034
1035 /* Make extra sure authentication was performed, exactly once */
1036 if( auth_done != 1 )
1037 {
1038 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1039 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1040 }
1041
1042 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1043
1044 return( 0 );
1045 }
1046
1047 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
1048 /*
1049 * Turn a bit into a mask:
1050 * - if bit == 1, return the all-bits 1 mask, aka (size_t) -1
1051 * - if bit == 0, return the all-bits 0 mask, aka 0
1052 *
1053 * This function can be used to write constant-time code by replacing branches
1054 * with bit operations using masks.
1055 *
1056 * This function is implemented without using comparison operators, as those
1057 * might be translated to branches by some compilers on some platforms.
1058 */
mbedtls_ssl_cf_mask_from_bit(size_t bit)1059 static size_t mbedtls_ssl_cf_mask_from_bit( size_t bit )
1060 {
1061 /* MSVC has a warning about unary minus on unsigned integer types,
1062 * but this is well-defined and precisely what we want to do here. */
1063 #if defined(_MSC_VER)
1064 #pragma warning( push )
1065 #pragma warning( disable : 4146 )
1066 #endif
1067 return -bit;
1068 #if defined(_MSC_VER)
1069 #pragma warning( pop )
1070 #endif
1071 }
1072
1073 /*
1074 * Constant-flow mask generation for "less than" comparison:
1075 * - if x < y, return all bits 1, that is (size_t) -1
1076 * - otherwise, return all bits 0, that is 0
1077 *
1078 * This function can be used to write constant-time code by replacing branches
1079 * with bit operations using masks.
1080 *
1081 * This function is implemented without using comparison operators, as those
1082 * might be translated to branches by some compilers on some platforms.
1083 */
mbedtls_ssl_cf_mask_lt(size_t x,size_t y)1084 static size_t mbedtls_ssl_cf_mask_lt( size_t x, size_t y )
1085 {
1086 /* This has the most significant bit set if and only if x < y */
1087 const size_t sub = x - y;
1088
1089 /* sub1 = (x < y) ? 1 : 0 */
1090 const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
1091
1092 /* mask = (x < y) ? 0xff... : 0x00... */
1093 const size_t mask = mbedtls_ssl_cf_mask_from_bit( sub1 );
1094
1095 return( mask );
1096 }
1097
1098 /*
1099 * Constant-flow mask generation for "greater or equal" comparison:
1100 * - if x >= y, return all bits 1, that is (size_t) -1
1101 * - otherwise, return all bits 0, that is 0
1102 *
1103 * This function can be used to write constant-time code by replacing branches
1104 * with bit operations using masks.
1105 *
1106 * This function is implemented without using comparison operators, as those
1107 * might be translated to branches by some compilers on some platforms.
1108 */
mbedtls_ssl_cf_mask_ge(size_t x,size_t y)1109 static size_t mbedtls_ssl_cf_mask_ge( size_t x, size_t y )
1110 {
1111 return( ~mbedtls_ssl_cf_mask_lt( x, y ) );
1112 }
1113
1114 /*
1115 * Constant-flow boolean "equal" comparison:
1116 * return x == y
1117 *
1118 * This function can be used to write constant-time code by replacing branches
1119 * with bit operations - it can be used in conjunction with
1120 * mbedtls_ssl_cf_mask_from_bit().
1121 *
1122 * This function is implemented without using comparison operators, as those
1123 * might be translated to branches by some compilers on some platforms.
1124 */
mbedtls_ssl_cf_bool_eq(size_t x,size_t y)1125 static size_t mbedtls_ssl_cf_bool_eq( size_t x, size_t y )
1126 {
1127 /* diff = 0 if x == y, non-zero otherwise */
1128 const size_t diff = x ^ y;
1129
1130 /* MSVC has a warning about unary minus on unsigned integer types,
1131 * but this is well-defined and precisely what we want to do here. */
1132 #if defined(_MSC_VER)
1133 #pragma warning( push )
1134 #pragma warning( disable : 4146 )
1135 #endif
1136
1137 /* diff_msb's most significant bit is equal to x != y */
1138 const size_t diff_msb = ( diff | -diff );
1139
1140 #if defined(_MSC_VER)
1141 #pragma warning( pop )
1142 #endif
1143
1144 /* diff1 = (x != y) ? 1 : 0 */
1145 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
1146
1147 return( 1 ^ diff1 );
1148 }
1149
1150 /*
1151 * Constant-flow conditional memcpy:
1152 * - if c1 == c2, equivalent to memcpy(dst, src, len),
1153 * - otherwise, a no-op,
1154 * but with execution flow independent of the values of c1 and c2.
1155 *
1156 * This function is implemented without using comparison operators, as those
1157 * might be translated to branches by some compilers on some platforms.
1158 */
mbedtls_ssl_cf_memcpy_if_eq(unsigned char * dst,const unsigned char * src,size_t len,size_t c1,size_t c2)1159 static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst,
1160 const unsigned char *src,
1161 size_t len,
1162 size_t c1, size_t c2 )
1163 {
1164 /* mask = c1 == c2 ? 0xff : 0x00 */
1165 const size_t equal = mbedtls_ssl_cf_bool_eq( c1, c2 );
1166 const unsigned char mask = (unsigned char) mbedtls_ssl_cf_mask_from_bit( equal );
1167
1168 /* dst[i] = c1 == c2 ? src[i] : dst[i] */
1169 for( size_t i = 0; i < len; i++ )
1170 dst[i] = ( src[i] & mask ) | ( dst[i] & ~mask );
1171 }
1172
1173 /*
1174 * Compute HMAC of variable-length data with constant flow.
1175 *
1176 * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
1177 * (Otherwise, computation of block_size needs to be adapted.)
1178 */
mbedtls_ssl_cf_hmac(mbedtls_md_context_t * ctx,const unsigned char * add_data,size_t add_data_len,const unsigned char * data,size_t data_len_secret,size_t min_data_len,size_t max_data_len,unsigned char * output)1179 MBEDTLS_STATIC_TESTABLE int mbedtls_ssl_cf_hmac(
1180 mbedtls_md_context_t *ctx,
1181 const unsigned char *add_data, size_t add_data_len,
1182 const unsigned char *data, size_t data_len_secret,
1183 size_t min_data_len, size_t max_data_len,
1184 unsigned char *output )
1185 {
1186 /*
1187 * This function breaks the HMAC abstraction and uses the md_clone()
1188 * extension to the MD API in order to get constant-flow behaviour.
1189 *
1190 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
1191 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
1192 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
1193 *
1194 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
1195 * minlen, then cloning the context, and for each byte up to maxlen
1196 * finishing up the hash computation, keeping only the correct result.
1197 *
1198 * Then we only need to compute HASH(okey + inner_hash) and we're done.
1199 */
1200 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
1201 /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
1202 * all of which have the same block size except SHA-384. */
1203 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
1204 const unsigned char * const ikey = ctx->hmac_ctx;
1205 const unsigned char * const okey = ikey + block_size;
1206 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
1207
1208 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
1209 mbedtls_md_context_t aux;
1210 size_t offset;
1211 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1212
1213 mbedtls_md_init( &aux );
1214
1215 #define MD_CHK( func_call ) \
1216 do { \
1217 ret = (func_call); \
1218 if( ret != 0 ) \
1219 goto cleanup; \
1220 } while( 0 )
1221
1222 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
1223
1224 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
1225 * so we can start directly with the message */
1226 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
1227 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
1228
1229 /* For each possible length, compute the hash up to that point */
1230 for( offset = min_data_len; offset <= max_data_len; offset++ )
1231 {
1232 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
1233 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
1234 /* Keep only the correct inner_hash in the output buffer */
1235 mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size,
1236 offset, data_len_secret );
1237
1238 if( offset < max_data_len )
1239 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
1240 }
1241
1242 /* Now compute HASH(okey + inner_hash) */
1243 MD_CHK( mbedtls_md_starts( ctx ) );
1244 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
1245 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
1246 MD_CHK( mbedtls_md_finish( ctx, output ) );
1247
1248 /* Done, get ready for next time */
1249 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
1250
1251 #undef MD_CHK
1252
1253 cleanup:
1254 mbedtls_md_free( &aux );
1255 return( ret );
1256 }
1257
1258 /*
1259 * Constant-flow memcpy from variable position in buffer.
1260 * - functionally equivalent to memcpy(dst, src + offset_secret, len)
1261 * - but with execution flow independent from the value of offset_secret.
1262 */
mbedtls_ssl_cf_memcpy_offset(unsigned char * dst,const unsigned char * src_base,size_t offset_secret,size_t offset_min,size_t offset_max,size_t len)1263 MBEDTLS_STATIC_TESTABLE void mbedtls_ssl_cf_memcpy_offset(
1264 unsigned char *dst,
1265 const unsigned char *src_base,
1266 size_t offset_secret,
1267 size_t offset_min, size_t offset_max,
1268 size_t len )
1269 {
1270 size_t offset;
1271
1272 for( offset = offset_min; offset <= offset_max; offset++ )
1273 {
1274 mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len,
1275 offset, offset_secret );
1276 }
1277 }
1278 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
1279
mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const * ssl,mbedtls_ssl_transform * transform,mbedtls_record * rec)1280 int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl,
1281 mbedtls_ssl_transform *transform,
1282 mbedtls_record *rec )
1283 {
1284 size_t olen;
1285 mbedtls_cipher_mode_t mode;
1286 int ret, auth_done = 0;
1287 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1288 size_t padlen = 0, correct = 1;
1289 #endif
1290 unsigned char* data;
1291 unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_IN_LEN_MAX ];
1292 size_t add_data_len;
1293
1294 #if !defined(MBEDTLS_DEBUG_C)
1295 ssl = NULL; /* make sure we don't use it except for debug */
1296 ((void) ssl);
1297 #endif
1298
1299 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1300 if( rec == NULL ||
1301 rec->buf == NULL ||
1302 rec->buf_len < rec->data_offset ||
1303 rec->buf_len - rec->data_offset < rec->data_len )
1304 {
1305 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to decrypt_buf" ) );
1306 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1307 }
1308
1309 data = rec->buf + rec->data_offset;
1310 mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_dec );
1311
1312 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1313 /*
1314 * Match record's CID with incoming CID.
1315 */
1316 if( rec->cid_len != transform->in_cid_len ||
1317 memcmp( rec->cid, transform->in_cid, rec->cid_len ) != 0 )
1318 {
1319 return( MBEDTLS_ERR_SSL_UNEXPECTED_CID );
1320 }
1321 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1322
1323 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1324 if( mode == MBEDTLS_MODE_STREAM )
1325 {
1326 padlen = 0;
1327 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec,
1328 transform->iv_dec,
1329 transform->ivlen,
1330 data, rec->data_len,
1331 data, &olen ) ) != 0 )
1332 {
1333 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1334 return( ret );
1335 }
1336
1337 if( rec->data_len != olen )
1338 {
1339 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1340 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1341 }
1342 }
1343 else
1344 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1345 #if defined(MBEDTLS_GCM_C) || \
1346 defined(MBEDTLS_CCM_C) || \
1347 defined(MBEDTLS_CHACHAPOLY_C)
1348 if( mode == MBEDTLS_MODE_GCM ||
1349 mode == MBEDTLS_MODE_CCM ||
1350 mode == MBEDTLS_MODE_CHACHAPOLY )
1351 {
1352 unsigned char iv[12];
1353 unsigned char *dynamic_iv;
1354 size_t dynamic_iv_len;
1355
1356 /*
1357 * Extract dynamic part of nonce for AEAD decryption.
1358 *
1359 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
1360 * part of the IV is prepended to the ciphertext and
1361 * can be chosen freely - in particular, it need not
1362 * agree with the record sequence number.
1363 */
1364 dynamic_iv_len = sizeof( rec->ctr );
1365 if( ssl_transform_aead_dynamic_iv_is_explicit( transform ) == 1 )
1366 {
1367 if( rec->data_len < dynamic_iv_len )
1368 {
1369 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) ",
1370 rec->data_len,
1371 dynamic_iv_len ) );
1372 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1373 }
1374 dynamic_iv = data;
1375
1376 data += dynamic_iv_len;
1377 rec->data_offset += dynamic_iv_len;
1378 rec->data_len -= dynamic_iv_len;
1379 }
1380 else
1381 {
1382 dynamic_iv = rec->ctr;
1383 }
1384
1385 /* Check that there's space for the authentication tag. */
1386 if( rec->data_len < transform->taglen )
1387 {
1388 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < taglen (%d) ",
1389 rec->data_len,
1390 transform->taglen ) );
1391 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1392 }
1393 rec->data_len -= transform->taglen;
1394
1395 /*
1396 * Prepare nonce from dynamic and static parts.
1397 */
1398 ssl_build_record_nonce( iv, sizeof( iv ),
1399 transform->iv_dec,
1400 transform->fixed_ivlen,
1401 dynamic_iv,
1402 dynamic_iv_len );
1403
1404 /*
1405 * Build additional data for AEAD encryption.
1406 * This depends on the TLS version.
1407 */
1408 ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
1409 transform->minor_ver );
1410 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
1411 add_data, add_data_len );
1412
1413 /* Because of the check above, we know that there are
1414 * explicit_iv_len Bytes preceeding data, and taglen
1415 * bytes following data + data_len. This justifies
1416 * the debug message and the invocation of
1417 * mbedtls_cipher_auth_decrypt() below. */
1418
1419 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
1420 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", data + rec->data_len,
1421 transform->taglen );
1422
1423 /*
1424 * Decrypt and authenticate
1425 */
1426 if( ( ret = mbedtls_cipher_auth_decrypt_ext( &transform->cipher_ctx_dec,
1427 iv, transform->ivlen,
1428 add_data, add_data_len,
1429 data, rec->data_len + transform->taglen, /* src */
1430 data, rec->buf_len - (data - rec->buf), &olen, /* dst */
1431 transform->taglen ) ) != 0 )
1432 {
1433 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
1434
1435 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
1436 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1437
1438 return( ret );
1439 }
1440 auth_done++;
1441
1442 /* Double-check that AEAD decryption doesn't change content length. */
1443 if( olen != rec->data_len )
1444 {
1445 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1446 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1447 }
1448 }
1449 else
1450 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1451 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1452 if( mode == MBEDTLS_MODE_CBC )
1453 {
1454 size_t minlen = 0;
1455
1456 /*
1457 * Check immediate ciphertext sanity
1458 */
1459 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1460 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1461 {
1462 /* The ciphertext is prefixed with the CBC IV. */
1463 minlen += transform->ivlen;
1464 }
1465 #endif
1466
1467 /* Size considerations:
1468 *
1469 * - The CBC cipher text must not be empty and hence
1470 * at least of size transform->ivlen.
1471 *
1472 * Together with the potential IV-prefix, this explains
1473 * the first of the two checks below.
1474 *
1475 * - The record must contain a MAC, either in plain or
1476 * encrypted, depending on whether Encrypt-then-MAC
1477 * is used or not.
1478 * - If it is, the message contains the IV-prefix,
1479 * the CBC ciphertext, and the MAC.
1480 * - If it is not, the padded plaintext, and hence
1481 * the CBC ciphertext, has at least length maclen + 1
1482 * because there is at least the padding length byte.
1483 *
1484 * As the CBC ciphertext is not empty, both cases give the
1485 * lower bound minlen + maclen + 1 on the record size, which
1486 * we test for in the second check below.
1487 */
1488 if( rec->data_len < minlen + transform->ivlen ||
1489 rec->data_len < minlen + transform->maclen + 1 )
1490 {
1491 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
1492 "+ 1 ) ( + expl IV )", rec->data_len,
1493 transform->ivlen,
1494 transform->maclen ) );
1495 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1496 }
1497
1498 /*
1499 * Authenticate before decrypt if enabled
1500 */
1501 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1502 if( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1503 {
1504 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1505
1506 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1507
1508 /* Update data_len in tandem with add_data.
1509 *
1510 * The subtraction is safe because of the previous check
1511 * data_len >= minlen + maclen + 1.
1512 *
1513 * Afterwards, we know that data + data_len is followed by at
1514 * least maclen Bytes, which justifies the call to
1515 * mbedtls_ssl_safer_memcmp() below.
1516 *
1517 * Further, we still know that data_len > minlen */
1518 rec->data_len -= transform->maclen;
1519 ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
1520 transform->minor_ver );
1521
1522 /* Calculate expected MAC. */
1523 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data,
1524 add_data_len );
1525 mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data,
1526 add_data_len );
1527 mbedtls_md_hmac_update( &transform->md_ctx_dec,
1528 data, rec->data_len );
1529 mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect );
1530 mbedtls_md_hmac_reset( &transform->md_ctx_dec );
1531
1532 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", data + rec->data_len,
1533 transform->maclen );
1534 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
1535 transform->maclen );
1536
1537 /* Compare expected MAC with MAC at the end of the record. */
1538 if( mbedtls_ssl_safer_memcmp( data + rec->data_len, mac_expect,
1539 transform->maclen ) != 0 )
1540 {
1541 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1542 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1543 }
1544 auth_done++;
1545 }
1546 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1547
1548 /*
1549 * Check length sanity
1550 */
1551
1552 /* We know from above that data_len > minlen >= 0,
1553 * so the following check in particular implies that
1554 * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */
1555 if( rec->data_len % transform->ivlen != 0 )
1556 {
1557 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
1558 rec->data_len, transform->ivlen ) );
1559 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1560 }
1561
1562 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1563 /*
1564 * Initialize for prepended IV for block cipher in TLS v1.1 and up
1565 */
1566 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
1567 {
1568 /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */
1569 memcpy( transform->iv_dec, data, transform->ivlen );
1570
1571 data += transform->ivlen;
1572 rec->data_offset += transform->ivlen;
1573 rec->data_len -= transform->ivlen;
1574 }
1575 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1576
1577 /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */
1578
1579 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec,
1580 transform->iv_dec, transform->ivlen,
1581 data, rec->data_len, data, &olen ) ) != 0 )
1582 {
1583 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1584 return( ret );
1585 }
1586
1587 /* Double-check that length hasn't changed during decryption. */
1588 if( rec->data_len != olen )
1589 {
1590 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1591 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1592 }
1593
1594 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1595 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
1596 {
1597 /*
1598 * Save IV in SSL3 and TLS1, where CBC decryption of consecutive
1599 * records is equivalent to CBC decryption of the concatenation
1600 * of the records; in other words, IVs are maintained across
1601 * record decryptions.
1602 */
1603 memcpy( transform->iv_dec, transform->cipher_ctx_dec.iv,
1604 transform->ivlen );
1605 }
1606 #endif
1607
1608 /* Safe since data_len >= minlen + maclen + 1, so after having
1609 * subtracted at most minlen and maclen up to this point,
1610 * data_len > 0 (because of data_len % ivlen == 0, it's actually
1611 * >= ivlen ). */
1612 padlen = data[rec->data_len - 1];
1613
1614 if( auth_done == 1 )
1615 {
1616 const size_t mask = mbedtls_ssl_cf_mask_ge(
1617 rec->data_len,
1618 padlen + 1 );
1619 correct &= mask;
1620 padlen &= mask;
1621 }
1622 else
1623 {
1624 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1625 if( rec->data_len < transform->maclen + padlen + 1 )
1626 {
1627 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
1628 rec->data_len,
1629 transform->maclen,
1630 padlen + 1 ) );
1631 }
1632 #endif
1633
1634 const size_t mask = mbedtls_ssl_cf_mask_ge(
1635 rec->data_len,
1636 transform->maclen + padlen + 1 );
1637 correct &= mask;
1638 padlen &= mask;
1639 }
1640
1641 padlen++;
1642
1643 /* Regardless of the validity of the padding,
1644 * we have data_len >= padlen here. */
1645
1646 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1647 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1648 {
1649 /* This is the SSL 3.0 path, we don't have to worry about Lucky
1650 * 13, because there's a strictly worse padding attack built in
1651 * the protocol (known as part of POODLE), so we don't care if the
1652 * code is not constant-time, in particular branches are OK. */
1653 if( padlen > transform->ivlen )
1654 {
1655 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1656 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
1657 "should be no more than %d",
1658 padlen, transform->ivlen ) );
1659 #endif
1660 correct = 0;
1661 }
1662 }
1663 else
1664 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1665 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1666 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1667 if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1668 {
1669 /* The padding check involves a series of up to 256
1670 * consecutive memory reads at the end of the record
1671 * plaintext buffer. In order to hide the length and
1672 * validity of the padding, always perform exactly
1673 * `min(256,plaintext_len)` reads (but take into account
1674 * only the last `padlen` bytes for the padding check). */
1675 size_t pad_count = 0;
1676 volatile unsigned char* const check = data;
1677
1678 /* Index of first padding byte; it has been ensured above
1679 * that the subtraction is safe. */
1680 size_t const padding_idx = rec->data_len - padlen;
1681 size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256;
1682 size_t const start_idx = rec->data_len - num_checks;
1683 size_t idx;
1684
1685 for( idx = start_idx; idx < rec->data_len; idx++ )
1686 {
1687 /* pad_count += (idx >= padding_idx) &&
1688 * (check[idx] == padlen - 1);
1689 */
1690 const size_t mask = mbedtls_ssl_cf_mask_ge( idx, padding_idx );
1691 const size_t equal = mbedtls_ssl_cf_bool_eq( check[idx],
1692 padlen - 1 );
1693 pad_count += mask & equal;
1694 }
1695 correct &= mbedtls_ssl_cf_bool_eq( pad_count, padlen );
1696
1697 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1698 if( padlen > 0 && correct == 0 )
1699 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
1700 #endif
1701 padlen &= mbedtls_ssl_cf_mask_from_bit( correct );
1702 }
1703 else
1704 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1705 MBEDTLS_SSL_PROTO_TLS1_2 */
1706 {
1707 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1708 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1709 }
1710
1711 /* If the padding was found to be invalid, padlen == 0
1712 * and the subtraction is safe. If the padding was found valid,
1713 * padlen hasn't been changed and the previous assertion
1714 * data_len >= padlen still holds. */
1715 rec->data_len -= padlen;
1716 }
1717 else
1718 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
1719 {
1720 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1721 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1722 }
1723
1724 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1725 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
1726 data, rec->data_len );
1727 #endif
1728
1729 /*
1730 * Authenticate if not done yet.
1731 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1732 */
1733 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1734 if( auth_done == 0 )
1735 {
1736 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1737 unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD];
1738
1739 /* If the initial value of padlen was such that
1740 * data_len < maclen + padlen + 1, then padlen
1741 * got reset to 1, and the initial check
1742 * data_len >= minlen + maclen + 1
1743 * guarantees that at this point we still
1744 * have at least data_len >= maclen.
1745 *
1746 * If the initial value of padlen was such that
1747 * data_len >= maclen + padlen + 1, then we have
1748 * subtracted either padlen + 1 (if the padding was correct)
1749 * or 0 (if the padding was incorrect) since then,
1750 * hence data_len >= maclen in any case.
1751 */
1752 rec->data_len -= transform->maclen;
1753 ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
1754 transform->minor_ver );
1755
1756 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1757 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1758 {
1759 ssl_mac( &transform->md_ctx_dec,
1760 transform->mac_dec,
1761 data, rec->data_len,
1762 rec->ctr, rec->type,
1763 mac_expect );
1764 memcpy( mac_peer, data + rec->data_len, transform->maclen );
1765 }
1766 else
1767 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1768 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1769 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1770 if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
1771 {
1772 /*
1773 * The next two sizes are the minimum and maximum values of
1774 * data_len over all padlen values.
1775 *
1776 * They're independent of padlen, since we previously did
1777 * data_len -= padlen.
1778 *
1779 * Note that max_len + maclen is never more than the buffer
1780 * length, as we previously did in_msglen -= maclen too.
1781 */
1782 const size_t max_len = rec->data_len + padlen;
1783 const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
1784
1785 ret = mbedtls_ssl_cf_hmac( &transform->md_ctx_dec,
1786 add_data, add_data_len,
1787 data, rec->data_len, min_len, max_len,
1788 mac_expect );
1789 if( ret != 0 )
1790 {
1791 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret );
1792 return( ret );
1793 }
1794
1795 mbedtls_ssl_cf_memcpy_offset( mac_peer, data,
1796 rec->data_len,
1797 min_len, max_len,
1798 transform->maclen );
1799 }
1800 else
1801 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1802 MBEDTLS_SSL_PROTO_TLS1_2 */
1803 {
1804 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1805 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1806 }
1807
1808 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1809 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen );
1810 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, transform->maclen );
1811 #endif
1812
1813 if( mbedtls_ssl_safer_memcmp( mac_peer, mac_expect,
1814 transform->maclen ) != 0 )
1815 {
1816 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1817 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
1818 #endif
1819 correct = 0;
1820 }
1821 auth_done++;
1822 }
1823
1824 /*
1825 * Finally check the correct flag
1826 */
1827 if( correct == 0 )
1828 return( MBEDTLS_ERR_SSL_INVALID_MAC );
1829 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1830
1831 /* Make extra sure authentication was performed, exactly once */
1832 if( auth_done != 1 )
1833 {
1834 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1835 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1836 }
1837
1838 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
1839 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 )
1840 {
1841 /* Remove inner padding and infer true content type. */
1842 ret = ssl_parse_inner_plaintext( data, &rec->data_len,
1843 &rec->type );
1844
1845 if( ret != 0 )
1846 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
1847 }
1848 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
1849
1850 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1851 if( rec->cid_len != 0 )
1852 {
1853 ret = ssl_parse_inner_plaintext( data, &rec->data_len,
1854 &rec->type );
1855 if( ret != 0 )
1856 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
1857 }
1858 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1859
1860 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
1861
1862 return( 0 );
1863 }
1864
1865 #undef MAC_NONE
1866 #undef MAC_PLAINTEXT
1867 #undef MAC_CIPHERTEXT
1868
1869 #if defined(MBEDTLS_ZLIB_SUPPORT)
1870 /*
1871 * Compression/decompression functions
1872 */
ssl_compress_buf(mbedtls_ssl_context * ssl)1873 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
1874 {
1875 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1876 unsigned char *msg_post = ssl->out_msg;
1877 ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
1878 size_t len_pre = ssl->out_msglen;
1879 unsigned char *msg_pre = ssl->compress_buf;
1880 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1881 size_t out_buf_len = ssl->out_buf_len;
1882 #else
1883 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
1884 #endif
1885
1886 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
1887
1888 if( len_pre == 0 )
1889 return( 0 );
1890
1891 memcpy( msg_pre, ssl->out_msg, len_pre );
1892
1893 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
1894 ssl->out_msglen ) );
1895
1896 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
1897 ssl->out_msg, ssl->out_msglen );
1898
1899 ssl->transform_out->ctx_deflate.next_in = msg_pre;
1900 ssl->transform_out->ctx_deflate.avail_in = len_pre;
1901 ssl->transform_out->ctx_deflate.next_out = msg_post;
1902 ssl->transform_out->ctx_deflate.avail_out = out_buf_len - bytes_written;
1903
1904 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
1905 if( ret != Z_OK )
1906 {
1907 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
1908 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
1909 }
1910
1911 ssl->out_msglen = out_buf_len -
1912 ssl->transform_out->ctx_deflate.avail_out - bytes_written;
1913
1914 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
1915 ssl->out_msglen ) );
1916
1917 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
1918 ssl->out_msg, ssl->out_msglen );
1919
1920 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
1921
1922 return( 0 );
1923 }
1924
ssl_decompress_buf(mbedtls_ssl_context * ssl)1925 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
1926 {
1927 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1928 unsigned char *msg_post = ssl->in_msg;
1929 ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
1930 size_t len_pre = ssl->in_msglen;
1931 unsigned char *msg_pre = ssl->compress_buf;
1932 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1933 size_t in_buf_len = ssl->in_buf_len;
1934 #else
1935 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
1936 #endif
1937
1938 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
1939
1940 if( len_pre == 0 )
1941 return( 0 );
1942
1943 memcpy( msg_pre, ssl->in_msg, len_pre );
1944
1945 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
1946 ssl->in_msglen ) );
1947
1948 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
1949 ssl->in_msg, ssl->in_msglen );
1950
1951 ssl->transform_in->ctx_inflate.next_in = msg_pre;
1952 ssl->transform_in->ctx_inflate.avail_in = len_pre;
1953 ssl->transform_in->ctx_inflate.next_out = msg_post;
1954 ssl->transform_in->ctx_inflate.avail_out = in_buf_len - header_bytes;
1955
1956 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
1957 if( ret != Z_OK )
1958 {
1959 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
1960 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
1961 }
1962
1963 ssl->in_msglen = in_buf_len -
1964 ssl->transform_in->ctx_inflate.avail_out - header_bytes;
1965
1966 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
1967 ssl->in_msglen ) );
1968
1969 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
1970 ssl->in_msg, ssl->in_msglen );
1971
1972 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
1973
1974 return( 0 );
1975 }
1976 #endif /* MBEDTLS_ZLIB_SUPPORT */
1977
1978 /*
1979 * Fill the input message buffer by appending data to it.
1980 * The amount of data already fetched is in ssl->in_left.
1981 *
1982 * If we return 0, is it guaranteed that (at least) nb_want bytes are
1983 * available (from this read and/or a previous one). Otherwise, an error code
1984 * is returned (possibly EOF or WANT_READ).
1985 *
1986 * With stream transport (TLS) on success ssl->in_left == nb_want, but
1987 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
1988 * since we always read a whole datagram at once.
1989 *
1990 * For DTLS, it is up to the caller to set ssl->next_record_offset when
1991 * they're done reading a record.
1992 */
mbedtls_ssl_fetch_input(mbedtls_ssl_context * ssl,size_t nb_want)1993 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
1994 {
1995 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1996 size_t len;
1997 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1998 size_t in_buf_len = ssl->in_buf_len;
1999 #else
2000 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
2001 #endif
2002
2003 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2004
2005 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2006 {
2007 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2008 "or mbedtls_ssl_set_bio()" ) );
2009 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2010 }
2011
2012 if( nb_want > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2013 {
2014 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2015 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2016 }
2017
2018 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2019 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2020 {
2021 uint32_t timeout;
2022
2023 /*
2024 * The point is, we need to always read a full datagram at once, so we
2025 * sometimes read more then requested, and handle the additional data.
2026 * It could be the rest of the current record (while fetching the
2027 * header) and/or some other records in the same datagram.
2028 */
2029
2030 /*
2031 * Move to the next record in the already read datagram if applicable
2032 */
2033 if( ssl->next_record_offset != 0 )
2034 {
2035 if( ssl->in_left < ssl->next_record_offset )
2036 {
2037 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2038 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2039 }
2040
2041 ssl->in_left -= ssl->next_record_offset;
2042
2043 if( ssl->in_left != 0 )
2044 {
2045 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2046 ssl->next_record_offset ) );
2047 memmove( ssl->in_hdr,
2048 ssl->in_hdr + ssl->next_record_offset,
2049 ssl->in_left );
2050 }
2051
2052 ssl->next_record_offset = 0;
2053 }
2054
2055 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2056 ssl->in_left, nb_want ) );
2057
2058 /*
2059 * Done if we already have enough data.
2060 */
2061 if( nb_want <= ssl->in_left)
2062 {
2063 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2064 return( 0 );
2065 }
2066
2067 /*
2068 * A record can't be split across datagrams. If we need to read but
2069 * are not at the beginning of a new record, the caller did something
2070 * wrong.
2071 */
2072 if( ssl->in_left != 0 )
2073 {
2074 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2075 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2076 }
2077
2078 /*
2079 * Don't even try to read if time's out already.
2080 * This avoids by-passing the timer when repeatedly receiving messages
2081 * that will end up being dropped.
2082 */
2083 if( mbedtls_ssl_check_timer( ssl ) != 0 )
2084 {
2085 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
2086 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2087 }
2088 else
2089 {
2090 len = in_buf_len - ( ssl->in_hdr - ssl->in_buf );
2091
2092 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2093 timeout = ssl->handshake->retransmit_timeout;
2094 else
2095 timeout = ssl->conf->read_timeout;
2096
2097 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2098
2099 if( ssl->f_recv_timeout != NULL )
2100 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2101 timeout );
2102 else
2103 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2104
2105 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2106
2107 if( ret == 0 )
2108 return( MBEDTLS_ERR_SSL_CONN_EOF );
2109 }
2110
2111 if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
2112 {
2113 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2114 mbedtls_ssl_set_timer( ssl, 0 );
2115
2116 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2117 {
2118 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2119 {
2120 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2121 return( MBEDTLS_ERR_SSL_TIMEOUT );
2122 }
2123
2124 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2125 {
2126 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2127 return( ret );
2128 }
2129
2130 return( MBEDTLS_ERR_SSL_WANT_READ );
2131 }
2132 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2133 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2134 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
2135 {
2136 if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 )
2137 {
2138 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request",
2139 ret );
2140 return( ret );
2141 }
2142
2143 return( MBEDTLS_ERR_SSL_WANT_READ );
2144 }
2145 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2146 }
2147
2148 if( ret < 0 )
2149 return( ret );
2150
2151 ssl->in_left = ret;
2152 }
2153 else
2154 #endif
2155 {
2156 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2157 ssl->in_left, nb_want ) );
2158
2159 while( ssl->in_left < nb_want )
2160 {
2161 len = nb_want - ssl->in_left;
2162
2163 if( mbedtls_ssl_check_timer( ssl ) != 0 )
2164 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2165 else
2166 {
2167 if( ssl->f_recv_timeout != NULL )
2168 {
2169 ret = ssl->f_recv_timeout( ssl->p_bio,
2170 ssl->in_hdr + ssl->in_left, len,
2171 ssl->conf->read_timeout );
2172 }
2173 else
2174 {
2175 ret = ssl->f_recv( ssl->p_bio,
2176 ssl->in_hdr + ssl->in_left, len );
2177 }
2178 }
2179
2180 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2181 ssl->in_left, nb_want ) );
2182 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2183
2184 if( ret == 0 )
2185 return( MBEDTLS_ERR_SSL_CONN_EOF );
2186
2187 if( ret < 0 )
2188 return( ret );
2189
2190 if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
2191 {
2192 MBEDTLS_SSL_DEBUG_MSG( 1,
2193 ( "f_recv returned %d bytes but only %lu were requested",
2194 ret, (unsigned long)len ) );
2195 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2196 }
2197
2198 ssl->in_left += ret;
2199 }
2200 }
2201
2202 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2203
2204 return( 0 );
2205 }
2206
2207 /*
2208 * Flush any data not yet written
2209 */
mbedtls_ssl_flush_output(mbedtls_ssl_context * ssl)2210 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
2211 {
2212 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2213 unsigned char *buf;
2214
2215 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2216
2217 if( ssl->f_send == NULL )
2218 {
2219 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2220 "or mbedtls_ssl_set_bio()" ) );
2221 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2222 }
2223
2224 /* Avoid incrementing counter if data is flushed */
2225 if( ssl->out_left == 0 )
2226 {
2227 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2228 return( 0 );
2229 }
2230
2231 while( ssl->out_left > 0 )
2232 {
2233 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2234 mbedtls_ssl_out_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2235
2236 buf = ssl->out_hdr - ssl->out_left;
2237 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2238
2239 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2240
2241 if( ret <= 0 )
2242 return( ret );
2243
2244 if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
2245 {
2246 MBEDTLS_SSL_DEBUG_MSG( 1,
2247 ( "f_send returned %d bytes but only %lu bytes were sent",
2248 ret, (unsigned long)ssl->out_left ) );
2249 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2250 }
2251
2252 ssl->out_left -= ret;
2253 }
2254
2255 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2256 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2257 {
2258 ssl->out_hdr = ssl->out_buf;
2259 }
2260 else
2261 #endif
2262 {
2263 ssl->out_hdr = ssl->out_buf + 8;
2264 }
2265 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out );
2266
2267 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2268
2269 return( 0 );
2270 }
2271
2272 /*
2273 * Functions to handle the DTLS retransmission state machine
2274 */
2275 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2276 /*
2277 * Append current handshake message to current outgoing flight
2278 */
ssl_flight_append(mbedtls_ssl_context * ssl)2279 static int ssl_flight_append( mbedtls_ssl_context *ssl )
2280 {
2281 mbedtls_ssl_flight_item *msg;
2282 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
2283 MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
2284 ssl->out_msg, ssl->out_msglen );
2285
2286 /* Allocate space for current message */
2287 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2288 {
2289 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2290 sizeof( mbedtls_ssl_flight_item ) ) );
2291 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2292 }
2293
2294 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2295 {
2296 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2297 mbedtls_free( msg );
2298 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2299 }
2300
2301 /* Copy current handshake message with headers */
2302 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2303 msg->len = ssl->out_msglen;
2304 msg->type = ssl->out_msgtype;
2305 msg->next = NULL;
2306
2307 /* Append to the current flight */
2308 if( ssl->handshake->flight == NULL )
2309 ssl->handshake->flight = msg;
2310 else
2311 {
2312 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2313 while( cur->next != NULL )
2314 cur = cur->next;
2315 cur->next = msg;
2316 }
2317
2318 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
2319 return( 0 );
2320 }
2321
2322 /*
2323 * Free the current flight of handshake messages
2324 */
mbedtls_ssl_flight_free(mbedtls_ssl_flight_item * flight)2325 void mbedtls_ssl_flight_free( mbedtls_ssl_flight_item *flight )
2326 {
2327 mbedtls_ssl_flight_item *cur = flight;
2328 mbedtls_ssl_flight_item *next;
2329
2330 while( cur != NULL )
2331 {
2332 next = cur->next;
2333
2334 mbedtls_free( cur->p );
2335 mbedtls_free( cur );
2336
2337 cur = next;
2338 }
2339 }
2340
2341 /*
2342 * Swap transform_out and out_ctr with the alternative ones
2343 */
ssl_swap_epochs(mbedtls_ssl_context * ssl)2344 static int ssl_swap_epochs( mbedtls_ssl_context *ssl )
2345 {
2346 mbedtls_ssl_transform *tmp_transform;
2347 unsigned char tmp_out_ctr[8];
2348
2349 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2350 {
2351 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2352 return( 0 );
2353 }
2354
2355 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2356
2357 /* Swap transforms */
2358 tmp_transform = ssl->transform_out;
2359 ssl->transform_out = ssl->handshake->alt_transform_out;
2360 ssl->handshake->alt_transform_out = tmp_transform;
2361
2362 /* Swap epoch + sequence_number */
2363 memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 );
2364 memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 );
2365 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
2366
2367 /* Adjust to the newly activated transform */
2368 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out );
2369
2370 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2371 if( mbedtls_ssl_hw_record_activate != NULL )
2372 {
2373 int ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND );
2374 if( ret != 0 )
2375 {
2376 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
2377 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2378 }
2379 }
2380 #endif
2381
2382 return( 0 );
2383 }
2384
2385 /*
2386 * Retransmit the current flight of messages.
2387 */
mbedtls_ssl_resend(mbedtls_ssl_context * ssl)2388 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
2389 {
2390 int ret = 0;
2391
2392 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
2393
2394 ret = mbedtls_ssl_flight_transmit( ssl );
2395
2396 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
2397
2398 return( ret );
2399 }
2400
2401 /*
2402 * Transmit or retransmit the current flight of messages.
2403 *
2404 * Need to remember the current message in case flush_output returns
2405 * WANT_WRITE, causing us to exit this function and come back later.
2406 * This function must be called until state is no longer SENDING.
2407 */
mbedtls_ssl_flight_transmit(mbedtls_ssl_context * ssl)2408 int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
2409 {
2410 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2411 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
2412
2413 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
2414 {
2415 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
2416
2417 ssl->handshake->cur_msg = ssl->handshake->flight;
2418 ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
2419 ret = ssl_swap_epochs( ssl );
2420 if( ret != 0 )
2421 return( ret );
2422
2423 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2424 }
2425
2426 while( ssl->handshake->cur_msg != NULL )
2427 {
2428 size_t max_frag_len;
2429 const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
2430
2431 int const is_finished =
2432 ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2433 cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
2434
2435 uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
2436 SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
2437
2438 /* Swap epochs before sending Finished: we can't do it after
2439 * sending ChangeCipherSpec, in case write returns WANT_READ.
2440 * Must be done before copying, may change out_msg pointer */
2441 if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
2442 {
2443 MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
2444 ret = ssl_swap_epochs( ssl );
2445 if( ret != 0 )
2446 return( ret );
2447 }
2448
2449 ret = ssl_get_remaining_payload_in_datagram( ssl );
2450 if( ret < 0 )
2451 return( ret );
2452 max_frag_len = (size_t) ret;
2453
2454 /* CCS is copied as is, while HS messages may need fragmentation */
2455 if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
2456 {
2457 if( max_frag_len == 0 )
2458 {
2459 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2460 return( ret );
2461
2462 continue;
2463 }
2464
2465 memcpy( ssl->out_msg, cur->p, cur->len );
2466 ssl->out_msglen = cur->len;
2467 ssl->out_msgtype = cur->type;
2468
2469 /* Update position inside current message */
2470 ssl->handshake->cur_msg_p += cur->len;
2471 }
2472 else
2473 {
2474 const unsigned char * const p = ssl->handshake->cur_msg_p;
2475 const size_t hs_len = cur->len - 12;
2476 const size_t frag_off = p - ( cur->p + 12 );
2477 const size_t rem_len = hs_len - frag_off;
2478 size_t cur_hs_frag_len, max_hs_frag_len;
2479
2480 if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
2481 {
2482 if( is_finished )
2483 {
2484 ret = ssl_swap_epochs( ssl );
2485 if( ret != 0 )
2486 return( ret );
2487 }
2488
2489 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2490 return( ret );
2491
2492 continue;
2493 }
2494 max_hs_frag_len = max_frag_len - 12;
2495
2496 cur_hs_frag_len = rem_len > max_hs_frag_len ?
2497 max_hs_frag_len : rem_len;
2498
2499 if( frag_off == 0 && cur_hs_frag_len != hs_len )
2500 {
2501 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
2502 (unsigned) cur_hs_frag_len,
2503 (unsigned) max_hs_frag_len ) );
2504 }
2505
2506 /* Messages are stored with handshake headers as if not fragmented,
2507 * copy beginning of headers then fill fragmentation fields.
2508 * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
2509 memcpy( ssl->out_msg, cur->p, 6 );
2510
2511 ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
2512 ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff );
2513 ssl->out_msg[8] = ( ( frag_off ) & 0xff );
2514
2515 ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
2516 ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff );
2517 ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff );
2518
2519 MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
2520
2521 /* Copy the handshake message content and set records fields */
2522 memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
2523 ssl->out_msglen = cur_hs_frag_len + 12;
2524 ssl->out_msgtype = cur->type;
2525
2526 /* Update position inside current message */
2527 ssl->handshake->cur_msg_p += cur_hs_frag_len;
2528 }
2529
2530 /* If done with the current message move to the next one if any */
2531 if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
2532 {
2533 if( cur->next != NULL )
2534 {
2535 ssl->handshake->cur_msg = cur->next;
2536 ssl->handshake->cur_msg_p = cur->next->p + 12;
2537 }
2538 else
2539 {
2540 ssl->handshake->cur_msg = NULL;
2541 ssl->handshake->cur_msg_p = NULL;
2542 }
2543 }
2544
2545 /* Actually send the message out */
2546 if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
2547 {
2548 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
2549 return( ret );
2550 }
2551 }
2552
2553 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2554 return( ret );
2555
2556 /* Update state and set timer */
2557 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
2558 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2559 else
2560 {
2561 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2562 mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2563 }
2564
2565 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
2566
2567 return( 0 );
2568 }
2569
2570 /*
2571 * To be called when the last message of an incoming flight is received.
2572 */
mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context * ssl)2573 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
2574 {
2575 /* We won't need to resend that one any more */
2576 mbedtls_ssl_flight_free( ssl->handshake->flight );
2577 ssl->handshake->flight = NULL;
2578 ssl->handshake->cur_msg = NULL;
2579
2580 /* The next incoming flight will start with this msg_seq */
2581 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2582
2583 /* We don't want to remember CCS's across flight boundaries. */
2584 ssl->handshake->buffering.seen_ccs = 0;
2585
2586 /* Clear future message buffering structure. */
2587 mbedtls_ssl_buffering_free( ssl );
2588
2589 /* Cancel timer */
2590 mbedtls_ssl_set_timer( ssl, 0 );
2591
2592 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2593 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2594 {
2595 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2596 }
2597 else
2598 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2599 }
2600
2601 /*
2602 * To be called when the last message of an outgoing flight is send.
2603 */
mbedtls_ssl_send_flight_completed(mbedtls_ssl_context * ssl)2604 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
2605 {
2606 ssl_reset_retransmit_timeout( ssl );
2607 mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
2608
2609 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2610 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
2611 {
2612 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2613 }
2614 else
2615 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2616 }
2617 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2618
2619 /*
2620 * Handshake layer functions
2621 */
2622
2623 /*
2624 * Write (DTLS: or queue) current handshake (including CCS) message.
2625 *
2626 * - fill in handshake headers
2627 * - update handshake checksum
2628 * - DTLS: save message for resending
2629 * - then pass to the record layer
2630 *
2631 * DTLS: except for HelloRequest, messages are only queued, and will only be
2632 * actually sent when calling flight_transmit() or resend().
2633 *
2634 * Inputs:
2635 * - ssl->out_msglen: 4 + actual handshake message len
2636 * (4 is the size of handshake headers for TLS)
2637 * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
2638 * - ssl->out_msg + 4: the handshake message body
2639 *
2640 * Outputs, ie state before passing to flight_append() or write_record():
2641 * - ssl->out_msglen: the length of the record contents
2642 * (including handshake headers but excluding record headers)
2643 * - ssl->out_msg: the record contents (handshake headers + content)
2644 */
mbedtls_ssl_write_handshake_msg(mbedtls_ssl_context * ssl)2645 int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
2646 {
2647 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2648 const size_t hs_len = ssl->out_msglen - 4;
2649 const unsigned char hs_type = ssl->out_msg[0];
2650
2651 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
2652
2653 /*
2654 * Sanity checks
2655 */
2656 if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
2657 ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
2658 {
2659 /* In SSLv3, the client might send a NoCertificate alert. */
2660 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
2661 if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
2662 ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT &&
2663 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
2664 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
2665 {
2666 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2667 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2668 }
2669 }
2670
2671 /* Whenever we send anything different from a
2672 * HelloRequest we should be in a handshake - double check. */
2673 if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2674 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
2675 ssl->handshake == NULL )
2676 {
2677 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2678 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2679 }
2680
2681 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2682 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2683 ssl->handshake != NULL &&
2684 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
2685 {
2686 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2687 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2688 }
2689 #endif
2690
2691 /* Double-check that we did not exceed the bounds
2692 * of the outgoing record buffer.
2693 * This should never fail as the various message
2694 * writing functions must obey the bounds of the
2695 * outgoing record buffer, but better be safe.
2696 *
2697 * Note: We deliberately do not check for the MTU or MFL here.
2698 */
2699 if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
2700 {
2701 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
2702 "size %u, maximum %u",
2703 (unsigned) ssl->out_msglen,
2704 (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
2705 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2706 }
2707
2708 /*
2709 * Fill handshake headers
2710 */
2711 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
2712 {
2713 ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
2714 ssl->out_msg[2] = (unsigned char)( hs_len >> 8 );
2715 ssl->out_msg[3] = (unsigned char)( hs_len );
2716
2717 /*
2718 * DTLS has additional fields in the Handshake layer,
2719 * between the length field and the actual payload:
2720 * uint16 message_seq;
2721 * uint24 fragment_offset;
2722 * uint24 fragment_length;
2723 */
2724 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2725 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2726 {
2727 /* Make room for the additional DTLS fields */
2728 if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
2729 {
2730 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
2731 "size %u, maximum %u",
2732 (unsigned) ( hs_len ),
2733 (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
2734 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2735 }
2736
2737 memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
2738 ssl->out_msglen += 8;
2739
2740 /* Write message_seq and update it, except for HelloRequest */
2741 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2742 {
2743 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
2744 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
2745 ++( ssl->handshake->out_msg_seq );
2746 }
2747 else
2748 {
2749 ssl->out_msg[4] = 0;
2750 ssl->out_msg[5] = 0;
2751 }
2752
2753 /* Handshake hashes are computed without fragmentation,
2754 * so set frag_offset = 0 and frag_len = hs_len for now */
2755 memset( ssl->out_msg + 6, 0x00, 3 );
2756 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
2757 }
2758 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2759
2760 /* Update running hashes of handshake messages seen */
2761 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
2762 ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
2763 }
2764
2765 /* Either send now, or just save to be sent (and resent) later */
2766 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2767 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2768 ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2769 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
2770 {
2771 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
2772 {
2773 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
2774 return( ret );
2775 }
2776 }
2777 else
2778 #endif
2779 {
2780 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
2781 {
2782 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
2783 return( ret );
2784 }
2785 }
2786
2787 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
2788
2789 return( 0 );
2790 }
2791
2792 /*
2793 * Record layer functions
2794 */
2795
2796 /*
2797 * Write current record.
2798 *
2799 * Uses:
2800 * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
2801 * - ssl->out_msglen: length of the record content (excl headers)
2802 * - ssl->out_msg: record content
2803 */
mbedtls_ssl_write_record(mbedtls_ssl_context * ssl,uint8_t force_flush)2804 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
2805 {
2806 int ret, done = 0;
2807 size_t len = ssl->out_msglen;
2808 uint8_t flush = force_flush;
2809
2810 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
2811
2812 #if defined(MBEDTLS_ZLIB_SUPPORT)
2813 if( ssl->transform_out != NULL &&
2814 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
2815 {
2816 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
2817 {
2818 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
2819 return( ret );
2820 }
2821
2822 len = ssl->out_msglen;
2823 }
2824 #endif /*MBEDTLS_ZLIB_SUPPORT */
2825
2826 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2827 if( mbedtls_ssl_hw_record_write != NULL )
2828 {
2829 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
2830
2831 ret = mbedtls_ssl_hw_record_write( ssl );
2832 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
2833 {
2834 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
2835 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2836 }
2837
2838 if( ret == 0 )
2839 done = 1;
2840 }
2841 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2842 if( !done )
2843 {
2844 unsigned i;
2845 size_t protected_record_size;
2846 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2847 size_t out_buf_len = ssl->out_buf_len;
2848 #else
2849 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
2850 #endif
2851 /* Skip writing the record content type to after the encryption,
2852 * as it may change when using the CID extension. */
2853
2854 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2855 ssl->conf->transport, ssl->out_hdr + 1 );
2856
2857 memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
2858 ssl->out_len[0] = (unsigned char)( len >> 8 );
2859 ssl->out_len[1] = (unsigned char)( len );
2860
2861 if( ssl->transform_out != NULL )
2862 {
2863 mbedtls_record rec;
2864
2865 rec.buf = ssl->out_iv;
2866 rec.buf_len = out_buf_len - ( ssl->out_iv - ssl->out_buf );
2867 rec.data_len = ssl->out_msglen;
2868 rec.data_offset = ssl->out_msg - rec.buf;
2869
2870 memcpy( &rec.ctr[0], ssl->out_ctr, 8 );
2871 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2872 ssl->conf->transport, rec.ver );
2873 rec.type = ssl->out_msgtype;
2874
2875 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2876 /* The CID is set by mbedtls_ssl_encrypt_buf(). */
2877 rec.cid_len = 0;
2878 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2879
2880 if( ( ret = mbedtls_ssl_encrypt_buf( ssl, ssl->transform_out, &rec,
2881 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2882 {
2883 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
2884 return( ret );
2885 }
2886
2887 if( rec.data_offset != 0 )
2888 {
2889 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2890 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2891 }
2892
2893 /* Update the record content type and CID. */
2894 ssl->out_msgtype = rec.type;
2895 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID )
2896 memcpy( ssl->out_cid, rec.cid, rec.cid_len );
2897 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2898 ssl->out_msglen = len = rec.data_len;
2899 ssl->out_len[0] = (unsigned char)( rec.data_len >> 8 );
2900 ssl->out_len[1] = (unsigned char)( rec.data_len );
2901 }
2902
2903 protected_record_size = len + mbedtls_ssl_out_hdr_len( ssl );
2904
2905 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2906 /* In case of DTLS, double-check that we don't exceed
2907 * the remaining space in the datagram. */
2908 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2909 {
2910 ret = ssl_get_remaining_space_in_datagram( ssl );
2911 if( ret < 0 )
2912 return( ret );
2913
2914 if( protected_record_size > (size_t) ret )
2915 {
2916 /* Should never happen */
2917 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2918 }
2919 }
2920 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2921
2922 /* Now write the potentially updated record content type. */
2923 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
2924
2925 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
2926 "version = [%d:%d], msglen = %d",
2927 ssl->out_hdr[0], ssl->out_hdr[1],
2928 ssl->out_hdr[2], len ) );
2929
2930 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
2931 ssl->out_hdr, protected_record_size );
2932
2933 ssl->out_left += protected_record_size;
2934 ssl->out_hdr += protected_record_size;
2935 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out );
2936
2937 for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- )
2938 if( ++ssl->cur_out_ctr[i - 1] != 0 )
2939 break;
2940
2941 /* The loop goes to its end iff the counter is wrapping */
2942 if( i == mbedtls_ssl_ep_len( ssl ) )
2943 {
2944 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
2945 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
2946 }
2947 }
2948
2949 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2950 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2951 flush == SSL_DONT_FORCE_FLUSH )
2952 {
2953 size_t remaining;
2954 ret = ssl_get_remaining_payload_in_datagram( ssl );
2955 if( ret < 0 )
2956 {
2957 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
2958 ret );
2959 return( ret );
2960 }
2961
2962 remaining = (size_t) ret;
2963 if( remaining == 0 )
2964 {
2965 flush = SSL_FORCE_FLUSH;
2966 }
2967 else
2968 {
2969 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
2970 }
2971 }
2972 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2973
2974 if( ( flush == SSL_FORCE_FLUSH ) &&
2975 ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
2976 {
2977 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
2978 return( ret );
2979 }
2980
2981 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
2982
2983 return( 0 );
2984 }
2985
2986 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2987
ssl_hs_is_proper_fragment(mbedtls_ssl_context * ssl)2988 static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
2989 {
2990 if( ssl->in_msglen < ssl->in_hslen ||
2991 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
2992 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
2993 {
2994 return( 1 );
2995 }
2996 return( 0 );
2997 }
2998
ssl_get_hs_frag_len(mbedtls_ssl_context const * ssl)2999 static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
3000 {
3001 return( ( ssl->in_msg[9] << 16 ) |
3002 ( ssl->in_msg[10] << 8 ) |
3003 ssl->in_msg[11] );
3004 }
3005
ssl_get_hs_frag_off(mbedtls_ssl_context const * ssl)3006 static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
3007 {
3008 return( ( ssl->in_msg[6] << 16 ) |
3009 ( ssl->in_msg[7] << 8 ) |
3010 ssl->in_msg[8] );
3011 }
3012
ssl_check_hs_header(mbedtls_ssl_context const * ssl)3013 static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
3014 {
3015 uint32_t msg_len, frag_off, frag_len;
3016
3017 msg_len = ssl_get_hs_total_len( ssl );
3018 frag_off = ssl_get_hs_frag_off( ssl );
3019 frag_len = ssl_get_hs_frag_len( ssl );
3020
3021 if( frag_off > msg_len )
3022 return( -1 );
3023
3024 if( frag_len > msg_len - frag_off )
3025 return( -1 );
3026
3027 if( frag_len + 12 > ssl->in_msglen )
3028 return( -1 );
3029
3030 return( 0 );
3031 }
3032
3033 /*
3034 * Mark bits in bitmask (used for DTLS HS reassembly)
3035 */
ssl_bitmask_set(unsigned char * mask,size_t offset,size_t len)3036 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
3037 {
3038 unsigned int start_bits, end_bits;
3039
3040 start_bits = 8 - ( offset % 8 );
3041 if( start_bits != 8 )
3042 {
3043 size_t first_byte_idx = offset / 8;
3044
3045 /* Special case */
3046 if( len <= start_bits )
3047 {
3048 for( ; len != 0; len-- )
3049 mask[first_byte_idx] |= 1 << ( start_bits - len );
3050
3051 /* Avoid potential issues with offset or len becoming invalid */
3052 return;
3053 }
3054
3055 offset += start_bits; /* Now offset % 8 == 0 */
3056 len -= start_bits;
3057
3058 for( ; start_bits != 0; start_bits-- )
3059 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
3060 }
3061
3062 end_bits = len % 8;
3063 if( end_bits != 0 )
3064 {
3065 size_t last_byte_idx = ( offset + len ) / 8;
3066
3067 len -= end_bits; /* Now len % 8 == 0 */
3068
3069 for( ; end_bits != 0; end_bits-- )
3070 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
3071 }
3072
3073 memset( mask + offset / 8, 0xFF, len / 8 );
3074 }
3075
3076 /*
3077 * Check that bitmask is full
3078 */
ssl_bitmask_check(unsigned char * mask,size_t len)3079 static int ssl_bitmask_check( unsigned char *mask, size_t len )
3080 {
3081 size_t i;
3082
3083 for( i = 0; i < len / 8; i++ )
3084 if( mask[i] != 0xFF )
3085 return( -1 );
3086
3087 for( i = 0; i < len % 8; i++ )
3088 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
3089 return( -1 );
3090
3091 return( 0 );
3092 }
3093
3094 /* msg_len does not include the handshake header */
ssl_get_reassembly_buffer_size(size_t msg_len,unsigned add_bitmap)3095 static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
3096 unsigned add_bitmap )
3097 {
3098 size_t alloc_len;
3099
3100 alloc_len = 12; /* Handshake header */
3101 alloc_len += msg_len; /* Content buffer */
3102
3103 if( add_bitmap )
3104 alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */
3105
3106 return( alloc_len );
3107 }
3108
3109 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3110
ssl_get_hs_total_len(mbedtls_ssl_context const * ssl)3111 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
3112 {
3113 return( ( ssl->in_msg[1] << 16 ) |
3114 ( ssl->in_msg[2] << 8 ) |
3115 ssl->in_msg[3] );
3116 }
3117
mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context * ssl)3118 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
3119 {
3120 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
3121 {
3122 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
3123 ssl->in_msglen ) );
3124 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3125 }
3126
3127 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
3128
3129 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
3130 " %d, type = %d, hslen = %d",
3131 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
3132
3133 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3134 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3135 {
3136 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3137 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
3138
3139 if( ssl_check_hs_header( ssl ) != 0 )
3140 {
3141 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
3142 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3143 }
3144
3145 if( ssl->handshake != NULL &&
3146 ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
3147 recv_msg_seq != ssl->handshake->in_msg_seq ) ||
3148 ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3149 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
3150 {
3151 if( recv_msg_seq > ssl->handshake->in_msg_seq )
3152 {
3153 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
3154 recv_msg_seq,
3155 ssl->handshake->in_msg_seq ) );
3156 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
3157 }
3158
3159 /* Retransmit only on last message from previous flight, to avoid
3160 * too many retransmissions.
3161 * Besides, No sane server ever retransmits HelloVerifyRequest */
3162 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3163 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
3164 {
3165 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
3166 "message_seq = %d, start_of_flight = %d",
3167 recv_msg_seq,
3168 ssl->handshake->in_flight_start_seq ) );
3169
3170 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3171 {
3172 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
3173 return( ret );
3174 }
3175 }
3176 else
3177 {
3178 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
3179 "message_seq = %d, expected = %d",
3180 recv_msg_seq,
3181 ssl->handshake->in_msg_seq ) );
3182 }
3183
3184 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
3185 }
3186 /* Wait until message completion to increment in_msg_seq */
3187
3188 /* Message reassembly is handled alongside buffering of future
3189 * messages; the commonality is that both handshake fragments and
3190 * future messages cannot be forwarded immediately to the
3191 * handshake logic layer. */
3192 if( ssl_hs_is_proper_fragment( ssl ) == 1 )
3193 {
3194 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
3195 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
3196 }
3197 }
3198 else
3199 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3200 /* With TLS we don't handle fragmentation (for now) */
3201 if( ssl->in_msglen < ssl->in_hslen )
3202 {
3203 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
3204 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3205 }
3206
3207 return( 0 );
3208 }
3209
mbedtls_ssl_update_handshake_status(mbedtls_ssl_context * ssl)3210 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
3211 {
3212 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
3213
3214 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
3215 {
3216 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
3217 }
3218
3219 /* Handshake message is complete, increment counter */
3220 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3221 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3222 ssl->handshake != NULL )
3223 {
3224 unsigned offset;
3225 mbedtls_ssl_hs_buffer *hs_buf;
3226
3227 /* Increment handshake sequence number */
3228 hs->in_msg_seq++;
3229
3230 /*
3231 * Clear up handshake buffering and reassembly structure.
3232 */
3233
3234 /* Free first entry */
3235 ssl_buffering_free_slot( ssl, 0 );
3236
3237 /* Shift all other entries */
3238 for( offset = 0, hs_buf = &hs->buffering.hs[0];
3239 offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
3240 offset++, hs_buf++ )
3241 {
3242 *hs_buf = *(hs_buf + 1);
3243 }
3244
3245 /* Create a fresh last entry */
3246 memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
3247 }
3248 #endif
3249 }
3250
3251 /*
3252 * DTLS anti-replay: RFC 6347 4.1.2.6
3253 *
3254 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3255 * Bit n is set iff record number in_window_top - n has been seen.
3256 *
3257 * Usually, in_window_top is the last record number seen and the lsb of
3258 * in_window is set. The only exception is the initial state (record number 0
3259 * not seen yet).
3260 */
3261 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context * ssl)3262 void mbedtls_ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
3263 {
3264 ssl->in_window_top = 0;
3265 ssl->in_window = 0;
3266 }
3267
ssl_load_six_bytes(unsigned char * buf)3268 static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
3269 {
3270 return( ( (uint64_t) buf[0] << 40 ) |
3271 ( (uint64_t) buf[1] << 32 ) |
3272 ( (uint64_t) buf[2] << 24 ) |
3273 ( (uint64_t) buf[3] << 16 ) |
3274 ( (uint64_t) buf[4] << 8 ) |
3275 ( (uint64_t) buf[5] ) );
3276 }
3277
mbedtls_ssl_dtls_record_replay_check(mbedtls_ssl_context * ssl,uint8_t * record_in_ctr)3278 static int mbedtls_ssl_dtls_record_replay_check( mbedtls_ssl_context *ssl, uint8_t *record_in_ctr )
3279 {
3280 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3281 unsigned char *original_in_ctr;
3282
3283 // save original in_ctr
3284 original_in_ctr = ssl->in_ctr;
3285
3286 // use counter from record
3287 ssl->in_ctr = record_in_ctr;
3288
3289 ret = mbedtls_ssl_dtls_replay_check( (mbedtls_ssl_context const *) ssl );
3290
3291 // restore the counter
3292 ssl->in_ctr = original_in_ctr;
3293
3294 return ret;
3295 }
3296
3297 /*
3298 * Return 0 if sequence number is acceptable, -1 otherwise
3299 */
mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const * ssl)3300 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const *ssl )
3301 {
3302 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3303 uint64_t bit;
3304
3305 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3306 return( 0 );
3307
3308 if( rec_seqnum > ssl->in_window_top )
3309 return( 0 );
3310
3311 bit = ssl->in_window_top - rec_seqnum;
3312
3313 if( bit >= 64 )
3314 return( -1 );
3315
3316 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
3317 return( -1 );
3318
3319 return( 0 );
3320 }
3321
3322 /*
3323 * Update replay window on new validated record
3324 */
mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context * ssl)3325 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
3326 {
3327 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3328
3329 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3330 return;
3331
3332 if( rec_seqnum > ssl->in_window_top )
3333 {
3334 /* Update window_top and the contents of the window */
3335 uint64_t shift = rec_seqnum - ssl->in_window_top;
3336
3337 if( shift >= 64 )
3338 ssl->in_window = 1;
3339 else
3340 {
3341 ssl->in_window <<= shift;
3342 ssl->in_window |= 1;
3343 }
3344
3345 ssl->in_window_top = rec_seqnum;
3346 }
3347 else
3348 {
3349 /* Mark that number as seen in the current window */
3350 uint64_t bit = ssl->in_window_top - rec_seqnum;
3351
3352 if( bit < 64 ) /* Always true, but be extra sure */
3353 ssl->in_window |= (uint64_t) 1 << bit;
3354 }
3355 }
3356 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3357
3358 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3359 /*
3360 * Without any SSL context, check if a datagram looks like a ClientHello with
3361 * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
3362 * Both input and output include full DTLS headers.
3363 *
3364 * - if cookie is valid, return 0
3365 * - if ClientHello looks superficially valid but cookie is not,
3366 * fill obuf and set olen, then
3367 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3368 * - otherwise return a specific error code
3369 */
ssl_check_dtls_clihlo_cookie(mbedtls_ssl_cookie_write_t * f_cookie_write,mbedtls_ssl_cookie_check_t * f_cookie_check,void * p_cookie,const unsigned char * cli_id,size_t cli_id_len,const unsigned char * in,size_t in_len,unsigned char * obuf,size_t buf_len,size_t * olen)3370 static int ssl_check_dtls_clihlo_cookie(
3371 mbedtls_ssl_cookie_write_t *f_cookie_write,
3372 mbedtls_ssl_cookie_check_t *f_cookie_check,
3373 void *p_cookie,
3374 const unsigned char *cli_id, size_t cli_id_len,
3375 const unsigned char *in, size_t in_len,
3376 unsigned char *obuf, size_t buf_len, size_t *olen )
3377 {
3378 size_t sid_len, cookie_len;
3379 unsigned char *p;
3380
3381 /*
3382 * Structure of ClientHello with record and handshake headers,
3383 * and expected values. We don't need to check a lot, more checks will be
3384 * done when actually parsing the ClientHello - skipping those checks
3385 * avoids code duplication and does not make cookie forging any easier.
3386 *
3387 * 0-0 ContentType type; copied, must be handshake
3388 * 1-2 ProtocolVersion version; copied
3389 * 3-4 uint16 epoch; copied, must be 0
3390 * 5-10 uint48 sequence_number; copied
3391 * 11-12 uint16 length; (ignored)
3392 *
3393 * 13-13 HandshakeType msg_type; (ignored)
3394 * 14-16 uint24 length; (ignored)
3395 * 17-18 uint16 message_seq; copied
3396 * 19-21 uint24 fragment_offset; copied, must be 0
3397 * 22-24 uint24 fragment_length; (ignored)
3398 *
3399 * 25-26 ProtocolVersion client_version; (ignored)
3400 * 27-58 Random random; (ignored)
3401 * 59-xx SessionID session_id; 1 byte len + sid_len content
3402 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3403 * ...
3404 *
3405 * Minimum length is 61 bytes.
3406 */
3407 if( in_len < 61 ||
3408 in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
3409 in[3] != 0 || in[4] != 0 ||
3410 in[19] != 0 || in[20] != 0 || in[21] != 0 )
3411 {
3412 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3413 }
3414
3415 sid_len = in[59];
3416 if( sid_len > in_len - 61 )
3417 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3418
3419 cookie_len = in[60 + sid_len];
3420 if( cookie_len > in_len - 60 )
3421 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
3422
3423 if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
3424 cli_id, cli_id_len ) == 0 )
3425 {
3426 /* Valid cookie */
3427 return( 0 );
3428 }
3429
3430 /*
3431 * If we get here, we've got an invalid cookie, let's prepare HVR.
3432 *
3433 * 0-0 ContentType type; copied
3434 * 1-2 ProtocolVersion version; copied
3435 * 3-4 uint16 epoch; copied
3436 * 5-10 uint48 sequence_number; copied
3437 * 11-12 uint16 length; olen - 13
3438 *
3439 * 13-13 HandshakeType msg_type; hello_verify_request
3440 * 14-16 uint24 length; olen - 25
3441 * 17-18 uint16 message_seq; copied
3442 * 19-21 uint24 fragment_offset; copied
3443 * 22-24 uint24 fragment_length; olen - 25
3444 *
3445 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3446 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3447 *
3448 * Minimum length is 28.
3449 */
3450 if( buf_len < 28 )
3451 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3452
3453 /* Copy most fields and adapt others */
3454 memcpy( obuf, in, 25 );
3455 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3456 obuf[25] = 0xfe;
3457 obuf[26] = 0xff;
3458
3459 /* Generate and write actual cookie */
3460 p = obuf + 28;
3461 if( f_cookie_write( p_cookie,
3462 &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
3463 {
3464 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3465 }
3466
3467 *olen = p - obuf;
3468
3469 /* Go back and fill length fields */
3470 obuf[27] = (unsigned char)( *olen - 28 );
3471
3472 obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
3473 obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
3474 obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
3475
3476 obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
3477 obuf[12] = (unsigned char)( ( *olen - 13 ) );
3478
3479 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
3480 }
3481
3482 /*
3483 * Handle possible client reconnect with the same UDP quadruplet
3484 * (RFC 6347 Section 4.2.8).
3485 *
3486 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3487 * that looks like a ClientHello.
3488 *
3489 * - if the input looks like a ClientHello without cookies,
3490 * send back HelloVerifyRequest, then return 0
3491 * - if the input looks like a ClientHello with a valid cookie,
3492 * reset the session of the current context, and
3493 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3494 * - if anything goes wrong, return a specific error code
3495 *
3496 * This function is called (through ssl_check_client_reconnect()) when an
3497 * unexpected record is found in ssl_get_next_record(), which will discard the
3498 * record if we return 0, and bubble up the return value otherwise (this
3499 * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected
3500 * errors, and is the right thing to do in both cases).
3501 */
ssl_handle_possible_reconnect(mbedtls_ssl_context * ssl)3502 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
3503 {
3504 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3505 size_t len;
3506
3507 if( ssl->conf->f_cookie_write == NULL ||
3508 ssl->conf->f_cookie_check == NULL )
3509 {
3510 /* If we can't use cookies to verify reachability of the peer,
3511 * drop the record. */
3512 MBEDTLS_SSL_DEBUG_MSG( 1, ( "no cookie callbacks, "
3513 "can't check reconnect validity" ) );
3514 return( 0 );
3515 }
3516
3517 ret = ssl_check_dtls_clihlo_cookie(
3518 ssl->conf->f_cookie_write,
3519 ssl->conf->f_cookie_check,
3520 ssl->conf->p_cookie,
3521 ssl->cli_id, ssl->cli_id_len,
3522 ssl->in_buf, ssl->in_left,
3523 ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
3524
3525 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
3526
3527 if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
3528 {
3529 int send_ret;
3530 MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) );
3531 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
3532 ssl->out_buf, len );
3533 /* Don't check write errors as we can't do anything here.
3534 * If the error is permanent we'll catch it later,
3535 * if it's not, then hopefully it'll work next time. */
3536 send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len );
3537 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret );
3538 (void) send_ret;
3539
3540 return( 0 );
3541 }
3542
3543 if( ret == 0 )
3544 {
3545 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) );
3546 if( ( ret = mbedtls_ssl_session_reset_int( ssl, 1 ) ) != 0 )
3547 {
3548 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
3549 return( ret );
3550 }
3551
3552 return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
3553 }
3554
3555 return( ret );
3556 }
3557 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3558
ssl_check_record_type(uint8_t record_type)3559 static int ssl_check_record_type( uint8_t record_type )
3560 {
3561 if( record_type != MBEDTLS_SSL_MSG_HANDSHAKE &&
3562 record_type != MBEDTLS_SSL_MSG_ALERT &&
3563 record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3564 record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA )
3565 {
3566 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3567 }
3568
3569 return( 0 );
3570 }
3571
3572 /*
3573 * ContentType type;
3574 * ProtocolVersion version;
3575 * uint16 epoch; // DTLS only
3576 * uint48 sequence_number; // DTLS only
3577 * uint16 length;
3578 *
3579 * Return 0 if header looks sane (and, for DTLS, the record is expected)
3580 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
3581 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
3582 *
3583 * With DTLS, mbedtls_ssl_read_record() will:
3584 * 1. proceed with the record if this function returns 0
3585 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
3586 * 3. return CLIENT_RECONNECT if this function return that value
3587 * 4. drop the whole datagram if this function returns anything else.
3588 * Point 2 is needed when the peer is resending, and we have already received
3589 * the first record from a datagram but are still waiting for the others.
3590 */
ssl_parse_record_header(mbedtls_ssl_context const * ssl,unsigned char * buf,size_t len,mbedtls_record * rec)3591 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl,
3592 unsigned char *buf,
3593 size_t len,
3594 mbedtls_record *rec )
3595 {
3596 int major_ver, minor_ver;
3597
3598 size_t const rec_hdr_type_offset = 0;
3599 size_t const rec_hdr_type_len = 1;
3600
3601 size_t const rec_hdr_version_offset = rec_hdr_type_offset +
3602 rec_hdr_type_len;
3603 size_t const rec_hdr_version_len = 2;
3604
3605 size_t const rec_hdr_ctr_len = 8;
3606 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3607 uint32_t rec_epoch;
3608 size_t const rec_hdr_ctr_offset = rec_hdr_version_offset +
3609 rec_hdr_version_len;
3610
3611 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3612 size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset +
3613 rec_hdr_ctr_len;
3614 size_t rec_hdr_cid_len = 0;
3615 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3616 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3617
3618 size_t rec_hdr_len_offset; /* To be determined */
3619 size_t const rec_hdr_len_len = 2;
3620
3621 /*
3622 * Check minimum lengths for record header.
3623 */
3624
3625 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3626 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3627 {
3628 rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len;
3629 }
3630 else
3631 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3632 {
3633 rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len;
3634 }
3635
3636 if( len < rec_hdr_len_offset + rec_hdr_len_len )
3637 {
3638 MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header of length %u",
3639 (unsigned) len,
3640 (unsigned)( rec_hdr_len_len + rec_hdr_len_len ) ) );
3641 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3642 }
3643
3644 /*
3645 * Parse and validate record content type
3646 */
3647
3648 rec->type = buf[ rec_hdr_type_offset ];
3649
3650 /* Check record content type */
3651 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3652 rec->cid_len = 0;
3653
3654 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3655 ssl->conf->cid_len != 0 &&
3656 rec->type == MBEDTLS_SSL_MSG_CID )
3657 {
3658 /* Shift pointers to account for record header including CID
3659 * struct {
3660 * ContentType special_type = tls12_cid;
3661 * ProtocolVersion version;
3662 * uint16 epoch;
3663 * uint48 sequence_number;
3664 * opaque cid[cid_length]; // Additional field compared to
3665 * // default DTLS record format
3666 * uint16 length;
3667 * opaque enc_content[DTLSCiphertext.length];
3668 * } DTLSCiphertext;
3669 */
3670
3671 /* So far, we only support static CID lengths
3672 * fixed in the configuration. */
3673 rec_hdr_cid_len = ssl->conf->cid_len;
3674 rec_hdr_len_offset += rec_hdr_cid_len;
3675
3676 if( len < rec_hdr_len_offset + rec_hdr_len_len )
3677 {
3678 MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header including CID, length %u",
3679 (unsigned) len,
3680 (unsigned)( rec_hdr_len_offset + rec_hdr_len_len ) ) );
3681 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3682 }
3683
3684 /* configured CID len is guaranteed at most 255, see
3685 * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */
3686 rec->cid_len = (uint8_t) rec_hdr_cid_len;
3687 memcpy( rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len );
3688 }
3689 else
3690 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3691 {
3692 if( ssl_check_record_type( rec->type ) )
3693 {
3694 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type %u",
3695 (unsigned) rec->type ) );
3696 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3697 }
3698 }
3699
3700 /*
3701 * Parse and validate record version
3702 */
3703
3704 rec->ver[0] = buf[ rec_hdr_version_offset + 0 ];
3705 rec->ver[1] = buf[ rec_hdr_version_offset + 1 ];
3706 mbedtls_ssl_read_version( &major_ver, &minor_ver,
3707 ssl->conf->transport,
3708 &rec->ver[0] );
3709
3710 if( major_ver != ssl->major_ver )
3711 {
3712 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
3713 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3714 }
3715
3716 if( minor_ver > ssl->conf->max_minor_ver )
3717 {
3718 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
3719 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3720 }
3721
3722 /*
3723 * Parse/Copy record sequence number.
3724 */
3725
3726 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3727 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3728 {
3729 /* Copy explicit record sequence number from input buffer. */
3730 memcpy( &rec->ctr[0], buf + rec_hdr_ctr_offset,
3731 rec_hdr_ctr_len );
3732 }
3733 else
3734 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3735 {
3736 /* Copy implicit record sequence number from SSL context structure. */
3737 memcpy( &rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len );
3738 }
3739
3740 /*
3741 * Parse record length.
3742 */
3743
3744 rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len;
3745 rec->data_len = ( (size_t) buf[ rec_hdr_len_offset + 0 ] << 8 ) |
3746 ( (size_t) buf[ rec_hdr_len_offset + 1 ] << 0 );
3747 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", buf, rec->data_offset );
3748
3749 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
3750 "version = [%d:%d], msglen = %d",
3751 rec->type,
3752 major_ver, minor_ver, rec->data_len ) );
3753
3754 rec->buf = buf;
3755 rec->buf_len = rec->data_offset + rec->data_len;
3756
3757 if( rec->data_len == 0 )
3758 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3759
3760 /*
3761 * DTLS-related tests.
3762 * Check epoch before checking length constraint because
3763 * the latter varies with the epoch. E.g., if a ChangeCipherSpec
3764 * message gets duplicated before the corresponding Finished message,
3765 * the second ChangeCipherSpec should be discarded because it belongs
3766 * to an old epoch, but not because its length is shorter than
3767 * the minimum record length for packets using the new record transform.
3768 * Note that these two kinds of failures are handled differently,
3769 * as an unexpected record is silently skipped but an invalid
3770 * record leads to the entire datagram being dropped.
3771 */
3772 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3773 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3774 {
3775 rec_epoch = ( rec->ctr[0] << 8 ) | rec->ctr[1];
3776
3777 /* Check that the datagram is large enough to contain a record
3778 * of the advertised length. */
3779 if( len < rec->data_offset + rec->data_len )
3780 {
3781 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Datagram of length %u too small to contain record of advertised length %u.",
3782 (unsigned) len,
3783 (unsigned)( rec->data_offset + rec->data_len ) ) );
3784 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3785 }
3786
3787 /* Records from other, non-matching epochs are silently discarded.
3788 * (The case of same-port Client reconnects must be considered in
3789 * the caller). */
3790 if( rec_epoch != ssl->in_epoch )
3791 {
3792 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
3793 "expected %d, received %d",
3794 ssl->in_epoch, rec_epoch ) );
3795
3796 /* Records from the next epoch are considered for buffering
3797 * (concretely: early Finished messages). */
3798 if( rec_epoch == (unsigned) ssl->in_epoch + 1 )
3799 {
3800 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
3801 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
3802 }
3803
3804 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3805 }
3806 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3807 /* For records from the correct epoch, check whether their
3808 * sequence number has been seen before. */
3809 else if( mbedtls_ssl_dtls_record_replay_check( (mbedtls_ssl_context *) ssl,
3810 &rec->ctr[0] ) != 0 )
3811 {
3812 MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
3813 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3814 }
3815 #endif
3816 }
3817 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3818
3819 return( 0 );
3820 }
3821
3822
3823 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
ssl_check_client_reconnect(mbedtls_ssl_context * ssl)3824 static int ssl_check_client_reconnect( mbedtls_ssl_context *ssl )
3825 {
3826 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
3827
3828 /*
3829 * Check for an epoch 0 ClientHello. We can't use in_msg here to
3830 * access the first byte of record content (handshake type), as we
3831 * have an active transform (possibly iv_len != 0), so use the
3832 * fact that the record header len is 13 instead.
3833 */
3834 if( rec_epoch == 0 &&
3835 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3836 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3837 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3838 ssl->in_left > 13 &&
3839 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
3840 {
3841 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
3842 "from the same port" ) );
3843 return( ssl_handle_possible_reconnect( ssl ) );
3844 }
3845
3846 return( 0 );
3847 }
3848 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3849
3850 /*
3851 * If applicable, decrypt record content
3852 */
ssl_prepare_record_content(mbedtls_ssl_context * ssl,mbedtls_record * rec)3853 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl,
3854 mbedtls_record *rec )
3855 {
3856 int ret, done = 0;
3857
3858 MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
3859 rec->buf, rec->buf_len );
3860
3861 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3862 if( mbedtls_ssl_hw_record_read != NULL )
3863 {
3864 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
3865
3866 ret = mbedtls_ssl_hw_record_read( ssl );
3867 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
3868 {
3869 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
3870 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3871 }
3872
3873 if( ret == 0 )
3874 done = 1;
3875 }
3876 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3877 if( !done && ssl->transform_in != NULL )
3878 {
3879 unsigned char const old_msg_type = rec->type;
3880
3881 if( ( ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in,
3882 rec ) ) != 0 )
3883 {
3884 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
3885
3886 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3887 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID &&
3888 ssl->conf->ignore_unexpected_cid
3889 == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE )
3890 {
3891 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ignoring unexpected CID" ) );
3892 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
3893 }
3894 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3895
3896 return( ret );
3897 }
3898
3899 if( old_msg_type != rec->type )
3900 {
3901 MBEDTLS_SSL_DEBUG_MSG( 4, ( "record type after decrypt (before %d): %d",
3902 old_msg_type, rec->type ) );
3903 }
3904
3905 MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
3906 rec->buf + rec->data_offset, rec->data_len );
3907
3908 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3909 /* We have already checked the record content type
3910 * in ssl_parse_record_header(), failing or silently
3911 * dropping the record in the case of an unknown type.
3912 *
3913 * Since with the use of CIDs, the record content type
3914 * might change during decryption, re-check the record
3915 * content type, but treat a failure as fatal this time. */
3916 if( ssl_check_record_type( rec->type ) )
3917 {
3918 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
3919 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3920 }
3921 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3922
3923 if( rec->data_len == 0 )
3924 {
3925 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3926 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
3927 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA )
3928 {
3929 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
3930 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
3931 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3932 }
3933 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3934
3935 ssl->nb_zero++;
3936
3937 /*
3938 * Three or more empty messages may be a DoS attack
3939 * (excessive CPU consumption).
3940 */
3941 if( ssl->nb_zero > 3 )
3942 {
3943 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
3944 "messages, possible DoS attack" ) );
3945 /* Treat the records as if they were not properly authenticated,
3946 * thereby failing the connection if we see more than allowed
3947 * by the configured bad MAC threshold. */
3948 return( MBEDTLS_ERR_SSL_INVALID_MAC );
3949 }
3950 }
3951 else
3952 ssl->nb_zero = 0;
3953
3954 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3955 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3956 {
3957 ; /* in_ctr read from peer, not maintained internally */
3958 }
3959 else
3960 #endif
3961 {
3962 unsigned i;
3963 for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- )
3964 if( ++ssl->in_ctr[i - 1] != 0 )
3965 break;
3966
3967 /* The loop goes to its end iff the counter is wrapping */
3968 if( i == mbedtls_ssl_ep_len( ssl ) )
3969 {
3970 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
3971 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
3972 }
3973 }
3974
3975 }
3976
3977 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3978 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3979 {
3980 mbedtls_ssl_dtls_replay_update( ssl );
3981 }
3982 #endif
3983
3984 /* Check actual (decrypted) record content length against
3985 * configured maximum. */
3986 if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
3987 {
3988 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3989 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3990 }
3991
3992 return( 0 );
3993 }
3994
3995 /*
3996 * Read a record.
3997 *
3998 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
3999 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
4000 *
4001 */
4002
4003 /* Helper functions for mbedtls_ssl_read_record(). */
4004 static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
4005 static int ssl_get_next_record( mbedtls_ssl_context *ssl );
4006 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
4007
mbedtls_ssl_read_record(mbedtls_ssl_context * ssl,unsigned update_hs_digest)4008 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
4009 unsigned update_hs_digest )
4010 {
4011 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4012
4013 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
4014
4015 if( ssl->keep_current_message == 0 )
4016 {
4017 do {
4018
4019 ret = ssl_consume_current_message( ssl );
4020 if( ret != 0 )
4021 return( ret );
4022
4023 if( ssl_record_is_in_progress( ssl ) == 0 )
4024 {
4025 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4026 int have_buffered = 0;
4027
4028 /* We only check for buffered messages if the
4029 * current datagram is fully consumed. */
4030 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4031 ssl_next_record_is_in_datagram( ssl ) == 0 )
4032 {
4033 if( ssl_load_buffered_message( ssl ) == 0 )
4034 have_buffered = 1;
4035 }
4036
4037 if( have_buffered == 0 )
4038 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4039 {
4040 ret = ssl_get_next_record( ssl );
4041 if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
4042 continue;
4043
4044 if( ret != 0 )
4045 {
4046 MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
4047 return( ret );
4048 }
4049 }
4050 }
4051
4052 ret = mbedtls_ssl_handle_message_type( ssl );
4053
4054 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4055 if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
4056 {
4057 /* Buffer future message */
4058 ret = ssl_buffer_message( ssl );
4059 if( ret != 0 )
4060 return( ret );
4061
4062 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4063 }
4064 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4065
4066 } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ||
4067 MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
4068
4069 if( 0 != ret )
4070 {
4071 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
4072 return( ret );
4073 }
4074
4075 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4076 update_hs_digest == 1 )
4077 {
4078 mbedtls_ssl_update_handshake_status( ssl );
4079 }
4080 }
4081 else
4082 {
4083 MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
4084 ssl->keep_current_message = 0;
4085 }
4086
4087 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
4088
4089 return( 0 );
4090 }
4091
4092 #if defined(MBEDTLS_SSL_PROTO_DTLS)
ssl_next_record_is_in_datagram(mbedtls_ssl_context * ssl)4093 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
4094 {
4095 if( ssl->in_left > ssl->next_record_offset )
4096 return( 1 );
4097
4098 return( 0 );
4099 }
4100
ssl_load_buffered_message(mbedtls_ssl_context * ssl)4101 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
4102 {
4103 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4104 mbedtls_ssl_hs_buffer * hs_buf;
4105 int ret = 0;
4106
4107 if( hs == NULL )
4108 return( -1 );
4109
4110 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
4111
4112 if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
4113 ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
4114 {
4115 /* Check if we have seen a ChangeCipherSpec before.
4116 * If yes, synthesize a CCS record. */
4117 if( !hs->buffering.seen_ccs )
4118 {
4119 MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
4120 ret = -1;
4121 goto exit;
4122 }
4123
4124 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
4125 ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4126 ssl->in_msglen = 1;
4127 ssl->in_msg[0] = 1;
4128
4129 /* As long as they are equal, the exact value doesn't matter. */
4130 ssl->in_left = 0;
4131 ssl->next_record_offset = 0;
4132
4133 hs->buffering.seen_ccs = 0;
4134 goto exit;
4135 }
4136
4137 #if defined(MBEDTLS_DEBUG_C)
4138 /* Debug only */
4139 {
4140 unsigned offset;
4141 for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
4142 {
4143 hs_buf = &hs->buffering.hs[offset];
4144 if( hs_buf->is_valid == 1 )
4145 {
4146 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
4147 hs->in_msg_seq + offset,
4148 hs_buf->is_complete ? "fully" : "partially" ) );
4149 }
4150 }
4151 }
4152 #endif /* MBEDTLS_DEBUG_C */
4153
4154 /* Check if we have buffered and/or fully reassembled the
4155 * next handshake message. */
4156 hs_buf = &hs->buffering.hs[0];
4157 if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
4158 {
4159 /* Synthesize a record containing the buffered HS message. */
4160 size_t msg_len = ( hs_buf->data[1] << 16 ) |
4161 ( hs_buf->data[2] << 8 ) |
4162 hs_buf->data[3];
4163
4164 /* Double-check that we haven't accidentally buffered
4165 * a message that doesn't fit into the input buffer. */
4166 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
4167 {
4168 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4169 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4170 }
4171
4172 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
4173 MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
4174 hs_buf->data, msg_len + 12 );
4175
4176 ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4177 ssl->in_hslen = msg_len + 12;
4178 ssl->in_msglen = msg_len + 12;
4179 memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
4180
4181 ret = 0;
4182 goto exit;
4183 }
4184 else
4185 {
4186 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
4187 hs->in_msg_seq ) );
4188 }
4189
4190 ret = -1;
4191
4192 exit:
4193
4194 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
4195 return( ret );
4196 }
4197
ssl_buffer_make_space(mbedtls_ssl_context * ssl,size_t desired)4198 static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
4199 size_t desired )
4200 {
4201 int offset;
4202 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4203 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
4204 (unsigned) desired ) );
4205
4206 /* Get rid of future records epoch first, if such exist. */
4207 ssl_free_buffered_record( ssl );
4208
4209 /* Check if we have enough space available now. */
4210 if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4211 hs->buffering.total_bytes_buffered ) )
4212 {
4213 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
4214 return( 0 );
4215 }
4216
4217 /* We don't have enough space to buffer the next expected handshake
4218 * message. Remove buffers used for future messages to gain space,
4219 * starting with the most distant one. */
4220 for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
4221 offset >= 0; offset-- )
4222 {
4223 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
4224 offset ) );
4225
4226 ssl_buffering_free_slot( ssl, (uint8_t) offset );
4227
4228 /* Check if we have enough space available now. */
4229 if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4230 hs->buffering.total_bytes_buffered ) )
4231 {
4232 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
4233 return( 0 );
4234 }
4235 }
4236
4237 return( -1 );
4238 }
4239
ssl_buffer_message(mbedtls_ssl_context * ssl)4240 static int ssl_buffer_message( mbedtls_ssl_context *ssl )
4241 {
4242 int ret = 0;
4243 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4244
4245 if( hs == NULL )
4246 return( 0 );
4247
4248 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
4249
4250 switch( ssl->in_msgtype )
4251 {
4252 case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
4253 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
4254
4255 hs->buffering.seen_ccs = 1;
4256 break;
4257
4258 case MBEDTLS_SSL_MSG_HANDSHAKE:
4259 {
4260 unsigned recv_msg_seq_offset;
4261 unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
4262 mbedtls_ssl_hs_buffer *hs_buf;
4263 size_t msg_len = ssl->in_hslen - 12;
4264
4265 /* We should never receive an old handshake
4266 * message - double-check nonetheless. */
4267 if( recv_msg_seq < ssl->handshake->in_msg_seq )
4268 {
4269 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4270 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4271 }
4272
4273 recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
4274 if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
4275 {
4276 /* Silently ignore -- message too far in the future */
4277 MBEDTLS_SSL_DEBUG_MSG( 2,
4278 ( "Ignore future HS message with sequence number %u, "
4279 "buffering window %u - %u",
4280 recv_msg_seq, ssl->handshake->in_msg_seq,
4281 ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
4282
4283 goto exit;
4284 }
4285
4286 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
4287 recv_msg_seq, recv_msg_seq_offset ) );
4288
4289 hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
4290
4291 /* Check if the buffering for this seq nr has already commenced. */
4292 if( !hs_buf->is_valid )
4293 {
4294 size_t reassembly_buf_sz;
4295
4296 hs_buf->is_fragmented =
4297 ( ssl_hs_is_proper_fragment( ssl ) == 1 );
4298
4299 /* We copy the message back into the input buffer
4300 * after reassembly, so check that it's not too large.
4301 * This is an implementation-specific limitation
4302 * and not one from the standard, hence it is not
4303 * checked in ssl_check_hs_header(). */
4304 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
4305 {
4306 /* Ignore message */
4307 goto exit;
4308 }
4309
4310 /* Check if we have enough space to buffer the message. */
4311 if( hs->buffering.total_bytes_buffered >
4312 MBEDTLS_SSL_DTLS_MAX_BUFFERING )
4313 {
4314 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4315 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4316 }
4317
4318 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
4319 hs_buf->is_fragmented );
4320
4321 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4322 hs->buffering.total_bytes_buffered ) )
4323 {
4324 if( recv_msg_seq_offset > 0 )
4325 {
4326 /* If we can't buffer a future message because
4327 * of space limitations -- ignore. */
4328 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
4329 (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4330 (unsigned) hs->buffering.total_bytes_buffered ) );
4331 goto exit;
4332 }
4333 else
4334 {
4335 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- attempt to make space by freeing buffered future messages\n",
4336 (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4337 (unsigned) hs->buffering.total_bytes_buffered ) );
4338 }
4339
4340 if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
4341 {
4342 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %u (%u with bitmap) would exceed the compile-time limit %u (already %u bytes buffered) -- fail\n",
4343 (unsigned) msg_len,
4344 (unsigned) reassembly_buf_sz,
4345 MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4346 (unsigned) hs->buffering.total_bytes_buffered ) );
4347 ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
4348 goto exit;
4349 }
4350 }
4351
4352 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
4353 msg_len ) );
4354
4355 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
4356 if( hs_buf->data == NULL )
4357 {
4358 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
4359 goto exit;
4360 }
4361 hs_buf->data_len = reassembly_buf_sz;
4362
4363 /* Prepare final header: copy msg_type, length and message_seq,
4364 * then add standardised fragment_offset and fragment_length */
4365 memcpy( hs_buf->data, ssl->in_msg, 6 );
4366 memset( hs_buf->data + 6, 0, 3 );
4367 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
4368
4369 hs_buf->is_valid = 1;
4370
4371 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
4372 }
4373 else
4374 {
4375 /* Make sure msg_type and length are consistent */
4376 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
4377 {
4378 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
4379 /* Ignore */
4380 goto exit;
4381 }
4382 }
4383
4384 if( !hs_buf->is_complete )
4385 {
4386 size_t frag_len, frag_off;
4387 unsigned char * const msg = hs_buf->data + 12;
4388
4389 /*
4390 * Check and copy current fragment
4391 */
4392
4393 /* Validation of header fields already done in
4394 * mbedtls_ssl_prepare_handshake_record(). */
4395 frag_off = ssl_get_hs_frag_off( ssl );
4396 frag_len = ssl_get_hs_frag_len( ssl );
4397
4398 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
4399 frag_off, frag_len ) );
4400 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
4401
4402 if( hs_buf->is_fragmented )
4403 {
4404 unsigned char * const bitmask = msg + msg_len;
4405 ssl_bitmask_set( bitmask, frag_off, frag_len );
4406 hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
4407 msg_len ) == 0 );
4408 }
4409 else
4410 {
4411 hs_buf->is_complete = 1;
4412 }
4413
4414 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
4415 hs_buf->is_complete ? "" : "not yet " ) );
4416 }
4417
4418 break;
4419 }
4420
4421 default:
4422 /* We don't buffer other types of messages. */
4423 break;
4424 }
4425
4426 exit:
4427
4428 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
4429 return( ret );
4430 }
4431 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4432
ssl_consume_current_message(mbedtls_ssl_context * ssl)4433 static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
4434 {
4435 /*
4436 * Consume last content-layer message and potentially
4437 * update in_msglen which keeps track of the contents'
4438 * consumption state.
4439 *
4440 * (1) Handshake messages:
4441 * Remove last handshake message, move content
4442 * and adapt in_msglen.
4443 *
4444 * (2) Alert messages:
4445 * Consume whole record content, in_msglen = 0.
4446 *
4447 * (3) Change cipher spec:
4448 * Consume whole record content, in_msglen = 0.
4449 *
4450 * (4) Application data:
4451 * Don't do anything - the record layer provides
4452 * the application data as a stream transport
4453 * and consumes through mbedtls_ssl_read only.
4454 *
4455 */
4456
4457 /* Case (1): Handshake messages */
4458 if( ssl->in_hslen != 0 )
4459 {
4460 /* Hard assertion to be sure that no application data
4461 * is in flight, as corrupting ssl->in_msglen during
4462 * ssl->in_offt != NULL is fatal. */
4463 if( ssl->in_offt != NULL )
4464 {
4465 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4466 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4467 }
4468
4469 /*
4470 * Get next Handshake message in the current record
4471 */
4472
4473 /* Notes:
4474 * (1) in_hslen is not necessarily the size of the
4475 * current handshake content: If DTLS handshake
4476 * fragmentation is used, that's the fragment
4477 * size instead. Using the total handshake message
4478 * size here is faulty and should be changed at
4479 * some point.
4480 * (2) While it doesn't seem to cause problems, one
4481 * has to be very careful not to assume that in_hslen
4482 * is always <= in_msglen in a sensible communication.
4483 * Again, it's wrong for DTLS handshake fragmentation.
4484 * The following check is therefore mandatory, and
4485 * should not be treated as a silently corrected assertion.
4486 * Additionally, ssl->in_hslen might be arbitrarily out of
4487 * bounds after handling a DTLS message with an unexpected
4488 * sequence number, see mbedtls_ssl_prepare_handshake_record.
4489 */
4490 if( ssl->in_hslen < ssl->in_msglen )
4491 {
4492 ssl->in_msglen -= ssl->in_hslen;
4493 memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
4494 ssl->in_msglen );
4495
4496 MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
4497 ssl->in_msg, ssl->in_msglen );
4498 }
4499 else
4500 {
4501 ssl->in_msglen = 0;
4502 }
4503
4504 ssl->in_hslen = 0;
4505 }
4506 /* Case (4): Application data */
4507 else if( ssl->in_offt != NULL )
4508 {
4509 return( 0 );
4510 }
4511 /* Everything else (CCS & Alerts) */
4512 else
4513 {
4514 ssl->in_msglen = 0;
4515 }
4516
4517 return( 0 );
4518 }
4519
ssl_record_is_in_progress(mbedtls_ssl_context * ssl)4520 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
4521 {
4522 if( ssl->in_msglen > 0 )
4523 return( 1 );
4524
4525 return( 0 );
4526 }
4527
4528 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4529
ssl_free_buffered_record(mbedtls_ssl_context * ssl)4530 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
4531 {
4532 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4533 if( hs == NULL )
4534 return;
4535
4536 if( hs->buffering.future_record.data != NULL )
4537 {
4538 hs->buffering.total_bytes_buffered -=
4539 hs->buffering.future_record.len;
4540
4541 mbedtls_free( hs->buffering.future_record.data );
4542 hs->buffering.future_record.data = NULL;
4543 }
4544 }
4545
ssl_load_buffered_record(mbedtls_ssl_context * ssl)4546 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
4547 {
4548 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4549 unsigned char * rec;
4550 size_t rec_len;
4551 unsigned rec_epoch;
4552 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4553 size_t in_buf_len = ssl->in_buf_len;
4554 #else
4555 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
4556 #endif
4557 if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4558 return( 0 );
4559
4560 if( hs == NULL )
4561 return( 0 );
4562
4563 rec = hs->buffering.future_record.data;
4564 rec_len = hs->buffering.future_record.len;
4565 rec_epoch = hs->buffering.future_record.epoch;
4566
4567 if( rec == NULL )
4568 return( 0 );
4569
4570 /* Only consider loading future records if the
4571 * input buffer is empty. */
4572 if( ssl_next_record_is_in_datagram( ssl ) == 1 )
4573 return( 0 );
4574
4575 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
4576
4577 if( rec_epoch != ssl->in_epoch )
4578 {
4579 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
4580 goto exit;
4581 }
4582
4583 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
4584
4585 /* Double-check that the record is not too large */
4586 if( rec_len > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) )
4587 {
4588 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4589 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4590 }
4591
4592 memcpy( ssl->in_hdr, rec, rec_len );
4593 ssl->in_left = rec_len;
4594 ssl->next_record_offset = 0;
4595
4596 ssl_free_buffered_record( ssl );
4597
4598 exit:
4599 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
4600 return( 0 );
4601 }
4602
ssl_buffer_future_record(mbedtls_ssl_context * ssl,mbedtls_record const * rec)4603 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl,
4604 mbedtls_record const *rec )
4605 {
4606 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4607
4608 /* Don't buffer future records outside handshakes. */
4609 if( hs == NULL )
4610 return( 0 );
4611
4612 /* Only buffer handshake records (we are only interested
4613 * in Finished messages). */
4614 if( rec->type != MBEDTLS_SSL_MSG_HANDSHAKE )
4615 return( 0 );
4616
4617 /* Don't buffer more than one future epoch record. */
4618 if( hs->buffering.future_record.data != NULL )
4619 return( 0 );
4620
4621 /* Don't buffer record if there's not enough buffering space remaining. */
4622 if( rec->buf_len > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4623 hs->buffering.total_bytes_buffered ) )
4624 {
4625 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
4626 (unsigned) rec->buf_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4627 (unsigned) hs->buffering.total_bytes_buffered ) );
4628 return( 0 );
4629 }
4630
4631 /* Buffer record */
4632 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
4633 ssl->in_epoch + 1 ) );
4634 MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", rec->buf, rec->buf_len );
4635
4636 /* ssl_parse_record_header() only considers records
4637 * of the next epoch as candidates for buffering. */
4638 hs->buffering.future_record.epoch = ssl->in_epoch + 1;
4639 hs->buffering.future_record.len = rec->buf_len;
4640
4641 hs->buffering.future_record.data =
4642 mbedtls_calloc( 1, hs->buffering.future_record.len );
4643 if( hs->buffering.future_record.data == NULL )
4644 {
4645 /* If we run out of RAM trying to buffer a
4646 * record from the next epoch, just ignore. */
4647 return( 0 );
4648 }
4649
4650 memcpy( hs->buffering.future_record.data, rec->buf, rec->buf_len );
4651
4652 hs->buffering.total_bytes_buffered += rec->buf_len;
4653 return( 0 );
4654 }
4655
4656 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4657
ssl_get_next_record(mbedtls_ssl_context * ssl)4658 static int ssl_get_next_record( mbedtls_ssl_context *ssl )
4659 {
4660 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4661 mbedtls_record rec;
4662
4663 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4664 /* We might have buffered a future record; if so,
4665 * and if the epoch matches now, load it.
4666 * On success, this call will set ssl->in_left to
4667 * the length of the buffered record, so that
4668 * the calls to ssl_fetch_input() below will
4669 * essentially be no-ops. */
4670 ret = ssl_load_buffered_record( ssl );
4671 if( ret != 0 )
4672 return( ret );
4673 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4674
4675 /* Ensure that we have enough space available for the default form
4676 * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS,
4677 * with no space for CIDs counted in). */
4678 ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) );
4679 if( ret != 0 )
4680 {
4681 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
4682 return( ret );
4683 }
4684
4685 ret = ssl_parse_record_header( ssl, ssl->in_hdr, ssl->in_left, &rec );
4686 if( ret != 0 )
4687 {
4688 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4689 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4690 {
4691 if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
4692 {
4693 ret = ssl_buffer_future_record( ssl, &rec );
4694 if( ret != 0 )
4695 return( ret );
4696
4697 /* Fall through to handling of unexpected records */
4698 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
4699 }
4700
4701 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
4702 {
4703 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
4704 /* Reset in pointers to default state for TLS/DTLS records,
4705 * assuming no CID and no offset between record content and
4706 * record plaintext. */
4707 mbedtls_ssl_update_in_pointers( ssl );
4708
4709 /* Setup internal message pointers from record structure. */
4710 ssl->in_msgtype = rec.type;
4711 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4712 ssl->in_len = ssl->in_cid + rec.cid_len;
4713 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4714 ssl->in_iv = ssl->in_msg = ssl->in_len + 2;
4715 ssl->in_msglen = rec.data_len;
4716
4717 ret = ssl_check_client_reconnect( ssl );
4718 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_client_reconnect", ret );
4719 if( ret != 0 )
4720 return( ret );
4721 #endif
4722
4723 /* Skip unexpected record (but not whole datagram) */
4724 ssl->next_record_offset = rec.buf_len;
4725
4726 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
4727 "(header)" ) );
4728 }
4729 else
4730 {
4731 /* Skip invalid record and the rest of the datagram */
4732 ssl->next_record_offset = 0;
4733 ssl->in_left = 0;
4734
4735 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
4736 "(header)" ) );
4737 }
4738
4739 /* Get next record */
4740 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
4741 }
4742 else
4743 #endif
4744 {
4745 return( ret );
4746 }
4747 }
4748
4749 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4750 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4751 {
4752 /* Remember offset of next record within datagram. */
4753 ssl->next_record_offset = rec.buf_len;
4754 if( ssl->next_record_offset < ssl->in_left )
4755 {
4756 MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
4757 }
4758 }
4759 else
4760 #endif
4761 {
4762 /*
4763 * Fetch record contents from underlying transport.
4764 */
4765 ret = mbedtls_ssl_fetch_input( ssl, rec.buf_len );
4766 if( ret != 0 )
4767 {
4768 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
4769 return( ret );
4770 }
4771
4772 ssl->in_left = 0;
4773 }
4774
4775 /*
4776 * Decrypt record contents.
4777 */
4778
4779 if( ( ret = ssl_prepare_record_content( ssl, &rec ) ) != 0 )
4780 {
4781 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4782 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4783 {
4784 /* Silently discard invalid records */
4785 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4786 {
4787 /* Except when waiting for Finished as a bad mac here
4788 * probably means something went wrong in the handshake
4789 * (eg wrong psk used, mitm downgrade attempt, etc.) */
4790 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
4791 ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
4792 {
4793 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4794 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4795 {
4796 mbedtls_ssl_send_alert_message( ssl,
4797 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4798 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
4799 }
4800 #endif
4801 return( ret );
4802 }
4803
4804 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
4805 if( ssl->conf->badmac_limit != 0 &&
4806 ++ssl->badmac_seen >= ssl->conf->badmac_limit )
4807 {
4808 MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
4809 return( MBEDTLS_ERR_SSL_INVALID_MAC );
4810 }
4811 #endif
4812
4813 /* As above, invalid records cause
4814 * dismissal of the whole datagram. */
4815
4816 ssl->next_record_offset = 0;
4817 ssl->in_left = 0;
4818
4819 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
4820 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
4821 }
4822
4823 return( ret );
4824 }
4825 else
4826 #endif
4827 {
4828 /* Error out (and send alert) on invalid records */
4829 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4830 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4831 {
4832 mbedtls_ssl_send_alert_message( ssl,
4833 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4834 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
4835 }
4836 #endif
4837 return( ret );
4838 }
4839 }
4840
4841
4842 /* Reset in pointers to default state for TLS/DTLS records,
4843 * assuming no CID and no offset between record content and
4844 * record plaintext. */
4845 mbedtls_ssl_update_in_pointers( ssl );
4846 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4847 ssl->in_len = ssl->in_cid + rec.cid_len;
4848 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4849 ssl->in_iv = ssl->in_len + 2;
4850
4851 /* The record content type may change during decryption,
4852 * so re-read it. */
4853 ssl->in_msgtype = rec.type;
4854 /* Also update the input buffer, because unfortunately
4855 * the server-side ssl_parse_client_hello() reparses the
4856 * record header when receiving a ClientHello initiating
4857 * a renegotiation. */
4858 ssl->in_hdr[0] = rec.type;
4859 ssl->in_msg = rec.buf + rec.data_offset;
4860 ssl->in_msglen = rec.data_len;
4861 ssl->in_len[0] = (unsigned char)( rec.data_len >> 8 );
4862 ssl->in_len[1] = (unsigned char)( rec.data_len );
4863
4864 #if defined(MBEDTLS_ZLIB_SUPPORT)
4865 if( ssl->transform_in != NULL &&
4866 ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
4867 {
4868 if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
4869 {
4870 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
4871 return( ret );
4872 }
4873
4874 /* Check actual (decompress) record content length against
4875 * configured maximum. */
4876 if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
4877 {
4878 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4879 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
4880 }
4881 }
4882 #endif /* MBEDTLS_ZLIB_SUPPORT */
4883
4884 return( 0 );
4885 }
4886
mbedtls_ssl_handle_message_type(mbedtls_ssl_context * ssl)4887 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
4888 {
4889 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4890
4891 /*
4892 * Handle particular types of records
4893 */
4894 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
4895 {
4896 if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
4897 {
4898 return( ret );
4899 }
4900 }
4901
4902 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
4903 {
4904 if( ssl->in_msglen != 1 )
4905 {
4906 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
4907 ssl->in_msglen ) );
4908 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
4909 }
4910
4911 if( ssl->in_msg[0] != 1 )
4912 {
4913 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
4914 ssl->in_msg[0] ) );
4915 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
4916 }
4917
4918 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4919 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4920 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
4921 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
4922 {
4923 if( ssl->handshake == NULL )
4924 {
4925 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
4926 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
4927 }
4928
4929 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
4930 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
4931 }
4932 #endif
4933 }
4934
4935 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
4936 {
4937 if( ssl->in_msglen != 2 )
4938 {
4939 /* Note: Standard allows for more than one 2 byte alert
4940 to be packed in a single message, but Mbed TLS doesn't
4941 currently support this. */
4942 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
4943 ssl->in_msglen ) );
4944 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
4945 }
4946
4947 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
4948 ssl->in_msg[0], ssl->in_msg[1] ) );
4949
4950 /*
4951 * Ignore non-fatal alerts, except close_notify and no_renegotiation
4952 */
4953 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
4954 {
4955 MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
4956 ssl->in_msg[1] ) );
4957 return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
4958 }
4959
4960 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4961 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
4962 {
4963 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
4964 return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
4965 }
4966
4967 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
4968 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4969 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
4970 {
4971 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
4972 /* Will be handled when trying to parse ServerHello */
4973 return( 0 );
4974 }
4975 #endif
4976
4977 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
4978 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
4979 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4980 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4981 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4982 {
4983 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4984 /* Will be handled in mbedtls_ssl_parse_certificate() */
4985 return( 0 );
4986 }
4987 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
4988
4989 /* Silently ignore: fetch new message */
4990 return MBEDTLS_ERR_SSL_NON_FATAL;
4991 }
4992
4993 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4994 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4995 {
4996 /* Drop unexpected ApplicationData records,
4997 * except at the beginning of renegotiations */
4998 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
4999 ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
5000 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5001 && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
5002 ssl->state == MBEDTLS_SSL_SERVER_HELLO )
5003 #endif
5004 )
5005 {
5006 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
5007 return( MBEDTLS_ERR_SSL_NON_FATAL );
5008 }
5009
5010 if( ssl->handshake != NULL &&
5011 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
5012 {
5013 mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl );
5014 }
5015 }
5016 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5017
5018 return( 0 );
5019 }
5020
mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context * ssl)5021 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
5022 {
5023 return( mbedtls_ssl_send_alert_message( ssl,
5024 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5025 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) );
5026 }
5027
mbedtls_ssl_send_alert_message(mbedtls_ssl_context * ssl,unsigned char level,unsigned char message)5028 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
5029 unsigned char level,
5030 unsigned char message )
5031 {
5032 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5033
5034 if( ssl == NULL || ssl->conf == NULL )
5035 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5036
5037 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
5038 MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
5039
5040 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
5041 ssl->out_msglen = 2;
5042 ssl->out_msg[0] = level;
5043 ssl->out_msg[1] = message;
5044
5045 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
5046 {
5047 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5048 return( ret );
5049 }
5050 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
5051
5052 return( 0 );
5053 }
5054
mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context * ssl)5055 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
5056 {
5057 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5058
5059 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
5060
5061 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
5062 ssl->out_msglen = 1;
5063 ssl->out_msg[0] = 1;
5064
5065 ssl->state++;
5066
5067 if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
5068 {
5069 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
5070 return( ret );
5071 }
5072
5073 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
5074
5075 return( 0 );
5076 }
5077
mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context * ssl)5078 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
5079 {
5080 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5081
5082 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
5083
5084 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
5085 {
5086 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5087 return( ret );
5088 }
5089
5090 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
5091 {
5092 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
5093 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5094 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
5095 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5096 }
5097
5098 /* CCS records are only accepted if they have length 1 and content '1',
5099 * so we don't need to check this here. */
5100
5101 /*
5102 * Switch to our negotiated transform and session parameters for inbound
5103 * data.
5104 */
5105 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
5106 ssl->transform_in = ssl->transform_negotiate;
5107 ssl->session_in = ssl->session_negotiate;
5108
5109 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5110 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5111 {
5112 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5113 mbedtls_ssl_dtls_replay_reset( ssl );
5114 #endif
5115
5116 /* Increment epoch */
5117 if( ++ssl->in_epoch == 0 )
5118 {
5119 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
5120 /* This is highly unlikely to happen for legitimate reasons, so
5121 treat it as an attack and don't send an alert. */
5122 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
5123 }
5124 }
5125 else
5126 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5127 memset( ssl->in_ctr, 0, 8 );
5128
5129 mbedtls_ssl_update_in_pointers( ssl );
5130
5131 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5132 if( mbedtls_ssl_hw_record_activate != NULL )
5133 {
5134 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
5135 {
5136 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
5137 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5138 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
5139 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5140 }
5141 }
5142 #endif
5143
5144 ssl->state++;
5145
5146 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
5147
5148 return( 0 );
5149 }
5150
5151 /* Once ssl->out_hdr as the address of the beginning of the
5152 * next outgoing record is set, deduce the other pointers.
5153 *
5154 * Note: For TLS, we save the implicit record sequence number
5155 * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
5156 * and the caller has to make sure there's space for this.
5157 */
5158
ssl_transform_get_explicit_iv_len(mbedtls_ssl_transform const * transform)5159 static size_t ssl_transform_get_explicit_iv_len(
5160 mbedtls_ssl_transform const *transform )
5161 {
5162 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
5163 return( 0 );
5164
5165 return( transform->ivlen - transform->fixed_ivlen );
5166 }
5167
mbedtls_ssl_update_out_pointers(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform)5168 void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl,
5169 mbedtls_ssl_transform *transform )
5170 {
5171 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5172 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5173 {
5174 ssl->out_ctr = ssl->out_hdr + 3;
5175 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5176 ssl->out_cid = ssl->out_ctr + 8;
5177 ssl->out_len = ssl->out_cid;
5178 if( transform != NULL )
5179 ssl->out_len += transform->out_cid_len;
5180 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5181 ssl->out_len = ssl->out_ctr + 8;
5182 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5183 ssl->out_iv = ssl->out_len + 2;
5184 }
5185 else
5186 #endif
5187 {
5188 ssl->out_ctr = ssl->out_hdr - 8;
5189 ssl->out_len = ssl->out_hdr + 3;
5190 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5191 ssl->out_cid = ssl->out_len;
5192 #endif
5193 ssl->out_iv = ssl->out_hdr + 5;
5194 }
5195
5196 ssl->out_msg = ssl->out_iv;
5197 /* Adjust out_msg to make space for explicit IV, if used. */
5198 if( transform != NULL )
5199 ssl->out_msg += ssl_transform_get_explicit_iv_len( transform );
5200 }
5201
5202 /* Once ssl->in_hdr as the address of the beginning of the
5203 * next incoming record is set, deduce the other pointers.
5204 *
5205 * Note: For TLS, we save the implicit record sequence number
5206 * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
5207 * and the caller has to make sure there's space for this.
5208 */
5209
mbedtls_ssl_update_in_pointers(mbedtls_ssl_context * ssl)5210 void mbedtls_ssl_update_in_pointers( mbedtls_ssl_context *ssl )
5211 {
5212 /* This function sets the pointers to match the case
5213 * of unprotected TLS/DTLS records, with both ssl->in_iv
5214 * and ssl->in_msg pointing to the beginning of the record
5215 * content.
5216 *
5217 * When decrypting a protected record, ssl->in_msg
5218 * will be shifted to point to the beginning of the
5219 * record plaintext.
5220 */
5221
5222 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5223 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5224 {
5225 /* This sets the header pointers to match records
5226 * without CID. When we receive a record containing
5227 * a CID, the fields are shifted accordingly in
5228 * ssl_parse_record_header(). */
5229 ssl->in_ctr = ssl->in_hdr + 3;
5230 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5231 ssl->in_cid = ssl->in_ctr + 8;
5232 ssl->in_len = ssl->in_cid; /* Default: no CID */
5233 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5234 ssl->in_len = ssl->in_ctr + 8;
5235 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5236 ssl->in_iv = ssl->in_len + 2;
5237 }
5238 else
5239 #endif
5240 {
5241 ssl->in_ctr = ssl->in_hdr - 8;
5242 ssl->in_len = ssl->in_hdr + 3;
5243 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5244 ssl->in_cid = ssl->in_len;
5245 #endif
5246 ssl->in_iv = ssl->in_hdr + 5;
5247 }
5248
5249 /* This will be adjusted at record decryption time. */
5250 ssl->in_msg = ssl->in_iv;
5251 }
5252
5253 /*
5254 * Setup an SSL context
5255 */
5256
mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context * ssl)5257 void mbedtls_ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
5258 {
5259 /* Set the incoming and outgoing record pointers. */
5260 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5261 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5262 {
5263 ssl->out_hdr = ssl->out_buf;
5264 ssl->in_hdr = ssl->in_buf;
5265 }
5266 else
5267 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5268 {
5269 ssl->out_hdr = ssl->out_buf + 8;
5270 ssl->in_hdr = ssl->in_buf + 8;
5271 }
5272
5273 /* Derive other internal pointers. */
5274 mbedtls_ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
5275 mbedtls_ssl_update_in_pointers ( ssl );
5276 }
5277
5278 /*
5279 * SSL get accessors
5280 */
mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context * ssl)5281 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
5282 {
5283 return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
5284 }
5285
mbedtls_ssl_check_pending(const mbedtls_ssl_context * ssl)5286 int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
5287 {
5288 /*
5289 * Case A: We're currently holding back
5290 * a message for further processing.
5291 */
5292
5293 if( ssl->keep_current_message == 1 )
5294 {
5295 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
5296 return( 1 );
5297 }
5298
5299 /*
5300 * Case B: Further records are pending in the current datagram.
5301 */
5302
5303 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5304 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5305 ssl->in_left > ssl->next_record_offset )
5306 {
5307 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
5308 return( 1 );
5309 }
5310 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5311
5312 /*
5313 * Case C: A handshake message is being processed.
5314 */
5315
5316 if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
5317 {
5318 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
5319 return( 1 );
5320 }
5321
5322 /*
5323 * Case D: An application data message is being processed
5324 */
5325 if( ssl->in_offt != NULL )
5326 {
5327 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
5328 return( 1 );
5329 }
5330
5331 /*
5332 * In all other cases, the rest of the message can be dropped.
5333 * As in ssl_get_next_record, this needs to be adapted if
5334 * we implement support for multiple alerts in single records.
5335 */
5336
5337 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
5338 return( 0 );
5339 }
5340
5341
mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context * ssl)5342 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
5343 {
5344 size_t transform_expansion = 0;
5345 const mbedtls_ssl_transform *transform = ssl->transform_out;
5346 unsigned block_size;
5347
5348 size_t out_hdr_len = mbedtls_ssl_out_hdr_len( ssl );
5349
5350 if( transform == NULL )
5351 return( (int) out_hdr_len );
5352
5353 #if defined(MBEDTLS_ZLIB_SUPPORT)
5354 if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
5355 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5356 #endif
5357
5358 switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
5359 {
5360 case MBEDTLS_MODE_GCM:
5361 case MBEDTLS_MODE_CCM:
5362 case MBEDTLS_MODE_CHACHAPOLY:
5363 case MBEDTLS_MODE_STREAM:
5364 transform_expansion = transform->minlen;
5365 break;
5366
5367 case MBEDTLS_MODE_CBC:
5368
5369 block_size = mbedtls_cipher_get_block_size(
5370 &transform->cipher_ctx_enc );
5371
5372 /* Expansion due to the addition of the MAC. */
5373 transform_expansion += transform->maclen;
5374
5375 /* Expansion due to the addition of CBC padding;
5376 * Theoretically up to 256 bytes, but we never use
5377 * more than the block size of the underlying cipher. */
5378 transform_expansion += block_size;
5379
5380 /* For TLS 1.1 or higher, an explicit IV is added
5381 * after the record header. */
5382 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
5383 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
5384 transform_expansion += block_size;
5385 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
5386
5387 break;
5388
5389 default:
5390 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
5391 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5392 }
5393
5394 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5395 if( transform->out_cid_len != 0 )
5396 transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION;
5397 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5398
5399 return( (int)( out_hdr_len + transform_expansion ) );
5400 }
5401
5402 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5403 /*
5404 * Check record counters and renegotiate if they're above the limit.
5405 */
ssl_check_ctr_renegotiate(mbedtls_ssl_context * ssl)5406 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
5407 {
5408 size_t ep_len = mbedtls_ssl_ep_len( ssl );
5409 int in_ctr_cmp;
5410 int out_ctr_cmp;
5411
5412 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
5413 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
5414 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
5415 {
5416 return( 0 );
5417 }
5418
5419 in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
5420 ssl->conf->renego_period + ep_len, 8 - ep_len );
5421 out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
5422 ssl->conf->renego_period + ep_len, 8 - ep_len );
5423
5424 if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
5425 {
5426 return( 0 );
5427 }
5428
5429 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
5430 return( mbedtls_ssl_renegotiate( ssl ) );
5431 }
5432 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5433
5434 /*
5435 * Receive application data decrypted from the SSL layer
5436 */
mbedtls_ssl_read(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)5437 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
5438 {
5439 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5440 size_t n;
5441
5442 if( ssl == NULL || ssl->conf == NULL )
5443 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5444
5445 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
5446
5447 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5448 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5449 {
5450 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
5451 return( ret );
5452
5453 if( ssl->handshake != NULL &&
5454 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
5455 {
5456 if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
5457 return( ret );
5458 }
5459 }
5460 #endif
5461
5462 /*
5463 * Check if renegotiation is necessary and/or handshake is
5464 * in process. If yes, perform/continue, and fall through
5465 * if an unexpected packet is received while the client
5466 * is waiting for the ServerHello.
5467 *
5468 * (There is no equivalent to the last condition on
5469 * the server-side as it is not treated as within
5470 * a handshake while waiting for the ClientHello
5471 * after a renegotiation request.)
5472 */
5473
5474 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5475 ret = ssl_check_ctr_renegotiate( ssl );
5476 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5477 ret != 0 )
5478 {
5479 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
5480 return( ret );
5481 }
5482 #endif
5483
5484 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
5485 {
5486 ret = mbedtls_ssl_handshake( ssl );
5487 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5488 ret != 0 )
5489 {
5490 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
5491 return( ret );
5492 }
5493 }
5494
5495 /* Loop as long as no application data record is available */
5496 while( ssl->in_offt == NULL )
5497 {
5498 /* Start timer if not already running */
5499 if( ssl->f_get_timer != NULL &&
5500 ssl->f_get_timer( ssl->p_timer ) == -1 )
5501 {
5502 mbedtls_ssl_set_timer( ssl, ssl->conf->read_timeout );
5503 }
5504
5505 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
5506 {
5507 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
5508 return( 0 );
5509
5510 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5511 return( ret );
5512 }
5513
5514 if( ssl->in_msglen == 0 &&
5515 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
5516 {
5517 /*
5518 * OpenSSL sends empty messages to randomize the IV
5519 */
5520 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
5521 {
5522 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
5523 return( 0 );
5524
5525 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5526 return( ret );
5527 }
5528 }
5529
5530 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
5531 {
5532 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
5533
5534 /*
5535 * - For client-side, expect SERVER_HELLO_REQUEST.
5536 * - For server-side, expect CLIENT_HELLO.
5537 * - Fail (TLS) or silently drop record (DTLS) in other cases.
5538 */
5539
5540 #if defined(MBEDTLS_SSL_CLI_C)
5541 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5542 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
5543 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
5544 {
5545 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
5546
5547 /* With DTLS, drop the packet (probably from last handshake) */
5548 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5549 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5550 {
5551 continue;
5552 }
5553 #endif
5554 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5555 }
5556 #endif /* MBEDTLS_SSL_CLI_C */
5557
5558 #if defined(MBEDTLS_SSL_SRV_C)
5559 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
5560 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
5561 {
5562 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
5563
5564 /* With DTLS, drop the packet (probably from last handshake) */
5565 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5566 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5567 {
5568 continue;
5569 }
5570 #endif
5571 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5572 }
5573 #endif /* MBEDTLS_SSL_SRV_C */
5574
5575 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5576 /* Determine whether renegotiation attempt should be accepted */
5577 if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
5578 ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
5579 ssl->conf->allow_legacy_renegotiation ==
5580 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
5581 {
5582 /*
5583 * Accept renegotiation request
5584 */
5585
5586 /* DTLS clients need to know renego is server-initiated */
5587 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5588 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5589 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5590 {
5591 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
5592 }
5593 #endif
5594 ret = mbedtls_ssl_start_renegotiation( ssl );
5595 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5596 ret != 0 )
5597 {
5598 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation",
5599 ret );
5600 return( ret );
5601 }
5602 }
5603 else
5604 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5605 {
5606 /*
5607 * Refuse renegotiation
5608 */
5609
5610 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
5611
5612 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5613 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
5614 {
5615 /* SSLv3 does not have a "no_renegotiation" warning, so
5616 we send a fatal alert and abort the connection. */
5617 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5618 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
5619 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5620 }
5621 else
5622 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
5623 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
5624 defined(MBEDTLS_SSL_PROTO_TLS1_2)
5625 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
5626 {
5627 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
5628 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
5629 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
5630 {
5631 return( ret );
5632 }
5633 }
5634 else
5635 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
5636 MBEDTLS_SSL_PROTO_TLS1_2 */
5637 {
5638 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
5639 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5640 }
5641 }
5642
5643 /* At this point, we don't know whether the renegotiation has been
5644 * completed or not. The cases to consider are the following:
5645 * 1) The renegotiation is complete. In this case, no new record
5646 * has been read yet.
5647 * 2) The renegotiation is incomplete because the client received
5648 * an application data record while awaiting the ServerHello.
5649 * 3) The renegotiation is incomplete because the client received
5650 * a non-handshake, non-application data message while awaiting
5651 * the ServerHello.
5652 * In each of these case, looping will be the proper action:
5653 * - For 1), the next iteration will read a new record and check
5654 * if it's application data.
5655 * - For 2), the loop condition isn't satisfied as application data
5656 * is present, hence continue is the same as break
5657 * - For 3), the loop condition is satisfied and read_record
5658 * will re-deliver the message that was held back by the client
5659 * when expecting the ServerHello.
5660 */
5661 continue;
5662 }
5663 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5664 else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
5665 {
5666 if( ssl->conf->renego_max_records >= 0 )
5667 {
5668 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
5669 {
5670 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
5671 "but not honored by client" ) );
5672 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5673 }
5674 }
5675 }
5676 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5677
5678 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
5679 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
5680 {
5681 MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
5682 return( MBEDTLS_ERR_SSL_WANT_READ );
5683 }
5684
5685 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
5686 {
5687 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
5688 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5689 }
5690
5691 ssl->in_offt = ssl->in_msg;
5692
5693 /* We're going to return something now, cancel timer,
5694 * except if handshake (renegotiation) is in progress */
5695 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
5696 mbedtls_ssl_set_timer( ssl, 0 );
5697
5698 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5699 /* If we requested renego but received AppData, resend HelloRequest.
5700 * Do it now, after setting in_offt, to avoid taking this branch
5701 * again if ssl_write_hello_request() returns WANT_WRITE */
5702 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
5703 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
5704 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
5705 {
5706 if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 )
5707 {
5708 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request",
5709 ret );
5710 return( ret );
5711 }
5712 }
5713 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
5714 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5715 }
5716
5717 n = ( len < ssl->in_msglen )
5718 ? len : ssl->in_msglen;
5719
5720 memcpy( buf, ssl->in_offt, n );
5721 ssl->in_msglen -= n;
5722
5723 /* Zeroising the plaintext buffer to erase unused application data
5724 from the memory. */
5725 mbedtls_platform_zeroize( ssl->in_offt, n );
5726
5727 if( ssl->in_msglen == 0 )
5728 {
5729 /* all bytes consumed */
5730 ssl->in_offt = NULL;
5731 ssl->keep_current_message = 0;
5732 }
5733 else
5734 {
5735 /* more data available */
5736 ssl->in_offt += n;
5737 }
5738
5739 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
5740
5741 return( (int) n );
5742 }
5743
5744 /*
5745 * Send application data to be encrypted by the SSL layer, taking care of max
5746 * fragment length and buffer size.
5747 *
5748 * According to RFC 5246 Section 6.2.1:
5749 *
5750 * Zero-length fragments of Application data MAY be sent as they are
5751 * potentially useful as a traffic analysis countermeasure.
5752 *
5753 * Therefore, it is possible that the input message length is 0 and the
5754 * corresponding return code is 0 on success.
5755 */
ssl_write_real(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)5756 static int ssl_write_real( mbedtls_ssl_context *ssl,
5757 const unsigned char *buf, size_t len )
5758 {
5759 int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
5760 const size_t max_len = (size_t) ret;
5761
5762 if( ret < 0 )
5763 {
5764 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
5765 return( ret );
5766 }
5767
5768 if( len > max_len )
5769 {
5770 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5771 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5772 {
5773 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
5774 "maximum fragment length: %d > %d",
5775 len, max_len ) );
5776 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5777 }
5778 else
5779 #endif
5780 len = max_len;
5781 }
5782
5783 if( ssl->out_left != 0 )
5784 {
5785 /*
5786 * The user has previously tried to send the data and
5787 * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
5788 * written. In this case, we expect the high-level write function
5789 * (e.g. mbedtls_ssl_write()) to be called with the same parameters
5790 */
5791 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
5792 {
5793 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
5794 return( ret );
5795 }
5796 }
5797 else
5798 {
5799 /*
5800 * The user is trying to send a message the first time, so we need to
5801 * copy the data into the internal buffers and setup the data structure
5802 * to keep track of partial writes
5803 */
5804 ssl->out_msglen = len;
5805 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
5806 memcpy( ssl->out_msg, buf, len );
5807
5808 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
5809 {
5810 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5811 return( ret );
5812 }
5813 }
5814
5815 return( (int) len );
5816 }
5817
5818 /*
5819 * Write application data, doing 1/n-1 splitting if necessary.
5820 *
5821 * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
5822 * then the caller will call us again with the same arguments, so
5823 * remember whether we already did the split or not.
5824 */
5825 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
ssl_write_split(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)5826 static int ssl_write_split( mbedtls_ssl_context *ssl,
5827 const unsigned char *buf, size_t len )
5828 {
5829 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5830
5831 if( ssl->conf->cbc_record_splitting ==
5832 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
5833 len <= 1 ||
5834 ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
5835 mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
5836 != MBEDTLS_MODE_CBC )
5837 {
5838 return( ssl_write_real( ssl, buf, len ) );
5839 }
5840
5841 if( ssl->split_done == 0 )
5842 {
5843 if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
5844 return( ret );
5845 ssl->split_done = 1;
5846 }
5847
5848 if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
5849 return( ret );
5850 ssl->split_done = 0;
5851
5852 return( ret + 1 );
5853 }
5854 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
5855
5856 /*
5857 * Write application data (public-facing wrapper)
5858 */
mbedtls_ssl_write(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)5859 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
5860 {
5861 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5862
5863 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
5864
5865 if( ssl == NULL || ssl->conf == NULL )
5866 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5867
5868 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5869 if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
5870 {
5871 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
5872 return( ret );
5873 }
5874 #endif
5875
5876 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
5877 {
5878 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
5879 {
5880 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
5881 return( ret );
5882 }
5883 }
5884
5885 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
5886 ret = ssl_write_split( ssl, buf, len );
5887 #else
5888 ret = ssl_write_real( ssl, buf, len );
5889 #endif
5890
5891 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
5892
5893 return( ret );
5894 }
5895
5896 /*
5897 * Notify the peer that the connection is being closed
5898 */
mbedtls_ssl_close_notify(mbedtls_ssl_context * ssl)5899 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
5900 {
5901 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5902
5903 if( ssl == NULL || ssl->conf == NULL )
5904 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5905
5906 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
5907
5908 if( ssl->out_left != 0 )
5909 return( mbedtls_ssl_flush_output( ssl ) );
5910
5911 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
5912 {
5913 if( ( ret = mbedtls_ssl_send_alert_message( ssl,
5914 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
5915 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
5916 {
5917 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
5918 return( ret );
5919 }
5920 }
5921
5922 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
5923
5924 return( 0 );
5925 }
5926
mbedtls_ssl_transform_free(mbedtls_ssl_transform * transform)5927 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
5928 {
5929 if( transform == NULL )
5930 return;
5931
5932 #if defined(MBEDTLS_ZLIB_SUPPORT)
5933 deflateEnd( &transform->ctx_deflate );
5934 inflateEnd( &transform->ctx_inflate );
5935 #endif
5936
5937 mbedtls_cipher_free( &transform->cipher_ctx_enc );
5938 mbedtls_cipher_free( &transform->cipher_ctx_dec );
5939
5940 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
5941 mbedtls_md_free( &transform->md_ctx_enc );
5942 mbedtls_md_free( &transform->md_ctx_dec );
5943 #endif
5944
5945 mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
5946 }
5947
5948 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5949
mbedtls_ssl_buffering_free(mbedtls_ssl_context * ssl)5950 void mbedtls_ssl_buffering_free( mbedtls_ssl_context *ssl )
5951 {
5952 unsigned offset;
5953 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
5954
5955 if( hs == NULL )
5956 return;
5957
5958 ssl_free_buffered_record( ssl );
5959
5960 for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
5961 ssl_buffering_free_slot( ssl, offset );
5962 }
5963
ssl_buffering_free_slot(mbedtls_ssl_context * ssl,uint8_t slot)5964 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
5965 uint8_t slot )
5966 {
5967 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
5968 mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
5969
5970 if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
5971 return;
5972
5973 if( hs_buf->is_valid == 1 )
5974 {
5975 hs->buffering.total_bytes_buffered -= hs_buf->data_len;
5976 mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len );
5977 mbedtls_free( hs_buf->data );
5978 memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
5979 }
5980 }
5981
5982 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5983
5984 /*
5985 * Convert version numbers to/from wire format
5986 * and, for DTLS, to/from TLS equivalent.
5987 *
5988 * For TLS this is the identity.
5989 * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
5990 * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1)
5991 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
5992 */
mbedtls_ssl_write_version(int major,int minor,int transport,unsigned char ver[2])5993 void mbedtls_ssl_write_version( int major, int minor, int transport,
5994 unsigned char ver[2] )
5995 {
5996 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5997 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5998 {
5999 if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
6000 --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
6001
6002 ver[0] = (unsigned char)( 255 - ( major - 2 ) );
6003 ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
6004 }
6005 else
6006 #else
6007 ((void) transport);
6008 #endif
6009 {
6010 ver[0] = (unsigned char) major;
6011 ver[1] = (unsigned char) minor;
6012 }
6013 }
6014
mbedtls_ssl_read_version(int * major,int * minor,int transport,const unsigned char ver[2])6015 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
6016 const unsigned char ver[2] )
6017 {
6018 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6019 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6020 {
6021 *major = 255 - ver[0] + 2;
6022 *minor = 255 - ver[1] + 1;
6023
6024 if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
6025 ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
6026 }
6027 else
6028 #else
6029 ((void) transport);
6030 #endif
6031 {
6032 *major = ver[0];
6033 *minor = ver[1];
6034 }
6035 }
6036
6037 #endif /* MBEDTLS_SSL_TLS_C */
6038