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