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