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