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