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