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