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