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