1 /**
2  * \file ssl_misc.h
3  *
4  * \brief Internal functions shared by the SSL modules
5  */
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9  */
10 #ifndef MBEDTLS_SSL_MISC_H
11 #define MBEDTLS_SSL_MISC_H
12 
13 #include "mbedtls/build_info.h"
14 
15 #include "mbedtls/error.h"
16 
17 #include "mbedtls/ssl.h"
18 #include "mbedtls/cipher.h"
19 
20 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
21 #include "psa/crypto.h"
22 #include "psa_util_internal.h"
23 #endif
24 
25 #if defined(MBEDTLS_MD_CAN_MD5)
26 #include "mbedtls/md5.h"
27 #endif
28 
29 #if defined(MBEDTLS_MD_CAN_SHA1)
30 #include "mbedtls/sha1.h"
31 #endif
32 
33 #if defined(MBEDTLS_MD_CAN_SHA256)
34 #include "mbedtls/sha256.h"
35 #endif
36 
37 #if defined(MBEDTLS_MD_CAN_SHA512)
38 #include "mbedtls/sha512.h"
39 #endif
40 
41 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
42     !defined(MBEDTLS_USE_PSA_CRYPTO)
43 #include "mbedtls/ecjpake.h"
44 #endif
45 
46 #include "mbedtls/pk.h"
47 #include "ssl_ciphersuites_internal.h"
48 #include "x509_internal.h"
49 #include "pk_internal.h"
50 #include "common.h"
51 
52 /* Shorthand for restartable ECC */
53 #if defined(MBEDTLS_ECP_RESTARTABLE) && \
54     defined(MBEDTLS_SSL_CLI_C) && \
55     defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
56     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
57 #define MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED
58 #endif
59 
60 #define MBEDTLS_SSL_INITIAL_HANDSHAKE           0
61 #define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS   1   /* In progress */
62 #define MBEDTLS_SSL_RENEGOTIATION_DONE          2   /* Done or aborted */
63 #define MBEDTLS_SSL_RENEGOTIATION_PENDING       3   /* Requested (server only) */
64 
65 /* Faked handshake message identity for HelloRetryRequest. */
66 #define MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST (-MBEDTLS_SSL_HS_SERVER_HELLO)
67 
68 /*
69  * Internal identity of handshake extensions
70  */
71 #define MBEDTLS_SSL_EXT_ID_UNRECOGNIZED                0
72 #define MBEDTLS_SSL_EXT_ID_SERVERNAME                  1
73 #define MBEDTLS_SSL_EXT_ID_SERVERNAME_HOSTNAME         1
74 #define MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH         2
75 #define MBEDTLS_SSL_EXT_ID_STATUS_REQUEST              3
76 #define MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS            4
77 #define MBEDTLS_SSL_EXT_ID_SUPPORTED_ELLIPTIC_CURVES   4
78 #define MBEDTLS_SSL_EXT_ID_SIG_ALG                     5
79 #define MBEDTLS_SSL_EXT_ID_USE_SRTP                    6
80 #define MBEDTLS_SSL_EXT_ID_HEARTBEAT                   7
81 #define MBEDTLS_SSL_EXT_ID_ALPN                        8
82 #define MBEDTLS_SSL_EXT_ID_SCT                         9
83 #define MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE              10
84 #define MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE             11
85 #define MBEDTLS_SSL_EXT_ID_PADDING                    12
86 #define MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY             13
87 #define MBEDTLS_SSL_EXT_ID_EARLY_DATA                 14
88 #define MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS         15
89 #define MBEDTLS_SSL_EXT_ID_COOKIE                     16
90 #define MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES     17
91 #define MBEDTLS_SSL_EXT_ID_CERT_AUTH                  18
92 #define MBEDTLS_SSL_EXT_ID_OID_FILTERS                19
93 #define MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH        20
94 #define MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT               21
95 #define MBEDTLS_SSL_EXT_ID_KEY_SHARE                  22
96 #define MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC             23
97 #define MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS    24
98 #define MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC           25
99 #define MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET     26
100 #define MBEDTLS_SSL_EXT_ID_SESSION_TICKET             27
101 #define MBEDTLS_SSL_EXT_ID_RECORD_SIZE_LIMIT          28
102 
103 /* Utility for translating IANA extension type. */
104 uint32_t mbedtls_ssl_get_extension_id(unsigned int extension_type);
105 uint32_t mbedtls_ssl_get_extension_mask(unsigned int extension_type);
106 /* Macros used to define mask constants */
107 #define MBEDTLS_SSL_EXT_MASK(id)       (1ULL << (MBEDTLS_SSL_EXT_ID_##id))
108 /* Reset value of extension mask */
109 #define MBEDTLS_SSL_EXT_MASK_NONE                                              0
110 
111 /* In messages containing extension requests, we should ignore unrecognized
112  * extensions. In messages containing extension responses, unrecognized
113  * extensions should result in handshake abortion. Messages containing
114  * extension requests include ClientHello, CertificateRequest and
115  * NewSessionTicket. Messages containing extension responses include
116  * ServerHello, HelloRetryRequest, EncryptedExtensions and Certificate.
117  *
118  * RFC 8446 section 4.1.3
119  *
120  * The ServerHello MUST only include extensions which are required to establish
121  * the cryptographic context and negotiate the protocol version.
122  *
123  * RFC 8446 section 4.2
124  *
125  * If an implementation receives an extension which it recognizes and which is
126  * not specified for the message in which it appears, it MUST abort the handshake
127  * with an "illegal_parameter" alert.
128  */
129 
130 /* Extensions that are not recognized by TLS 1.3 */
131 #define MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED                               \
132     (MBEDTLS_SSL_EXT_MASK(SUPPORTED_POINT_FORMATS)                | \
133      MBEDTLS_SSL_EXT_MASK(ENCRYPT_THEN_MAC)                       | \
134      MBEDTLS_SSL_EXT_MASK(EXTENDED_MASTER_SECRET)                 | \
135      MBEDTLS_SSL_EXT_MASK(SESSION_TICKET)                         | \
136      MBEDTLS_SSL_EXT_MASK(TRUNCATED_HMAC)                         | \
137      MBEDTLS_SSL_EXT_MASK(UNRECOGNIZED))
138 
139 /* RFC 8446 section 4.2. Allowed extensions for ClientHello */
140 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH                                  \
141     (MBEDTLS_SSL_EXT_MASK(SERVERNAME)                             | \
142      MBEDTLS_SSL_EXT_MASK(MAX_FRAGMENT_LENGTH)                    | \
143      MBEDTLS_SSL_EXT_MASK(STATUS_REQUEST)                         | \
144      MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS)                       | \
145      MBEDTLS_SSL_EXT_MASK(SIG_ALG)                                | \
146      MBEDTLS_SSL_EXT_MASK(USE_SRTP)                               | \
147      MBEDTLS_SSL_EXT_MASK(HEARTBEAT)                              | \
148      MBEDTLS_SSL_EXT_MASK(ALPN)                                   | \
149      MBEDTLS_SSL_EXT_MASK(SCT)                                    | \
150      MBEDTLS_SSL_EXT_MASK(CLI_CERT_TYPE)                          | \
151      MBEDTLS_SSL_EXT_MASK(SERV_CERT_TYPE)                         | \
152      MBEDTLS_SSL_EXT_MASK(PADDING)                                | \
153      MBEDTLS_SSL_EXT_MASK(KEY_SHARE)                              | \
154      MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)                         | \
155      MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES)                 | \
156      MBEDTLS_SSL_EXT_MASK(EARLY_DATA)                             | \
157      MBEDTLS_SSL_EXT_MASK(COOKIE)                                 | \
158      MBEDTLS_SSL_EXT_MASK(SUPPORTED_VERSIONS)                     | \
159      MBEDTLS_SSL_EXT_MASK(CERT_AUTH)                              | \
160      MBEDTLS_SSL_EXT_MASK(POST_HANDSHAKE_AUTH)                    | \
161      MBEDTLS_SSL_EXT_MASK(SIG_ALG_CERT)                           | \
162      MBEDTLS_SSL_EXT_MASK(RECORD_SIZE_LIMIT)                      | \
163      MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED)
164 
165 /* RFC 8446 section 4.2. Allowed extensions for EncryptedExtensions */
166 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_EE                                  \
167     (MBEDTLS_SSL_EXT_MASK(SERVERNAME)                             | \
168      MBEDTLS_SSL_EXT_MASK(MAX_FRAGMENT_LENGTH)                    | \
169      MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS)                       | \
170      MBEDTLS_SSL_EXT_MASK(USE_SRTP)                               | \
171      MBEDTLS_SSL_EXT_MASK(HEARTBEAT)                              | \
172      MBEDTLS_SSL_EXT_MASK(ALPN)                                   | \
173      MBEDTLS_SSL_EXT_MASK(CLI_CERT_TYPE)                          | \
174      MBEDTLS_SSL_EXT_MASK(SERV_CERT_TYPE)                         | \
175      MBEDTLS_SSL_EXT_MASK(EARLY_DATA)                             | \
176      MBEDTLS_SSL_EXT_MASK(RECORD_SIZE_LIMIT))
177 
178 /* RFC 8446 section 4.2. Allowed extensions for CertificateRequest */
179 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CR                                  \
180     (MBEDTLS_SSL_EXT_MASK(STATUS_REQUEST)                         | \
181      MBEDTLS_SSL_EXT_MASK(SIG_ALG)                                | \
182      MBEDTLS_SSL_EXT_MASK(SCT)                                    | \
183      MBEDTLS_SSL_EXT_MASK(CERT_AUTH)                              | \
184      MBEDTLS_SSL_EXT_MASK(OID_FILTERS)                            | \
185      MBEDTLS_SSL_EXT_MASK(SIG_ALG_CERT)                           | \
186      MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED)
187 
188 /* RFC 8446 section 4.2. Allowed extensions for Certificate */
189 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CT                                  \
190     (MBEDTLS_SSL_EXT_MASK(STATUS_REQUEST)                         | \
191      MBEDTLS_SSL_EXT_MASK(SCT))
192 
193 /* RFC 8446 section 4.2. Allowed extensions for ServerHello */
194 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_SH                                  \
195     (MBEDTLS_SSL_EXT_MASK(KEY_SHARE)                              | \
196      MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)                         | \
197      MBEDTLS_SSL_EXT_MASK(SUPPORTED_VERSIONS))
198 
199 /* RFC 8446 section 4.2. Allowed extensions for HelloRetryRequest */
200 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_HRR                                 \
201     (MBEDTLS_SSL_EXT_MASK(KEY_SHARE)                              | \
202      MBEDTLS_SSL_EXT_MASK(COOKIE)                                 | \
203      MBEDTLS_SSL_EXT_MASK(SUPPORTED_VERSIONS))
204 
205 /* RFC 8446 section 4.2. Allowed extensions for NewSessionTicket */
206 #define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_NST                                 \
207     (MBEDTLS_SSL_EXT_MASK(EARLY_DATA)                             | \
208      MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED)
209 
210 /*
211  * Helper macros for function call with return check.
212  */
213 /*
214  * Exit when return non-zero value
215  */
216 #define MBEDTLS_SSL_PROC_CHK(f)                               \
217     do {                                                        \
218         ret = (f);                                            \
219         if (ret != 0)                                          \
220         {                                                       \
221             goto cleanup;                                       \
222         }                                                       \
223     } while (0)
224 /*
225  * Exit when return negative value
226  */
227 #define MBEDTLS_SSL_PROC_CHK_NEG(f)                           \
228     do {                                                        \
229         ret = (f);                                            \
230         if (ret < 0)                                           \
231         {                                                       \
232             goto cleanup;                                       \
233         }                                                       \
234     } while (0)
235 
236 /*
237  * DTLS retransmission states, see RFC 6347 4.2.4
238  *
239  * The SENDING state is merged in PREPARING for initial sends,
240  * but is distinct for resends.
241  *
242  * Note: initial state is wrong for server, but is not used anyway.
243  */
244 #define MBEDTLS_SSL_RETRANS_PREPARING       0
245 #define MBEDTLS_SSL_RETRANS_SENDING         1
246 #define MBEDTLS_SSL_RETRANS_WAITING         2
247 #define MBEDTLS_SSL_RETRANS_FINISHED        3
248 
249 /*
250  * Allow extra bytes for record, authentication and encryption overhead:
251  * counter (8) + header (5) + IV(16) + MAC (16-48) + padding (0-256).
252  */
253 
254 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
255 
256 /* This macro determines whether CBC is supported. */
257 #if defined(MBEDTLS_SSL_HAVE_CBC)      &&                                  \
258     (defined(MBEDTLS_SSL_HAVE_AES)     ||                                  \
259     defined(MBEDTLS_SSL_HAVE_CAMELLIA) ||                                  \
260     defined(MBEDTLS_SSL_HAVE_ARIA))
261 #define MBEDTLS_SSL_SOME_SUITES_USE_CBC
262 #endif
263 
264 /* This macro determines whether a ciphersuite using a
265  * stream cipher can be used. */
266 #if defined(MBEDTLS_CIPHER_NULL_CIPHER)
267 #define MBEDTLS_SSL_SOME_SUITES_USE_STREAM
268 #endif
269 
270 /* This macro determines whether the CBC construct used in TLS 1.2 is supported. */
271 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
272     defined(MBEDTLS_SSL_PROTO_TLS1_2)
273 #define MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC
274 #endif
275 
276 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM) || \
277     defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
278 #define MBEDTLS_SSL_SOME_SUITES_USE_MAC
279 #endif
280 
281 /* This macro determines whether a ciphersuite uses Encrypt-then-MAC with CBC */
282 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
283     defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
284 #define MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM
285 #endif
286 
287 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
288 
289 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
290 /* Ciphersuites using HMAC */
291 #if defined(MBEDTLS_MD_CAN_SHA384)
292 #define MBEDTLS_SSL_MAC_ADD                 48  /* SHA-384 used for HMAC */
293 #elif defined(MBEDTLS_MD_CAN_SHA256)
294 #define MBEDTLS_SSL_MAC_ADD                 32  /* SHA-256 used for HMAC */
295 #else
296 #define MBEDTLS_SSL_MAC_ADD                 20  /* SHA-1   used for HMAC */
297 #endif
298 #else /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
299 /* AEAD ciphersuites: GCM and CCM use a 128 bits tag */
300 #define MBEDTLS_SSL_MAC_ADD                 16
301 #endif
302 
303 #if defined(MBEDTLS_SSL_HAVE_CBC)
304 #define MBEDTLS_SSL_PADDING_ADD            256
305 #else
306 #define MBEDTLS_SSL_PADDING_ADD              0
307 #endif
308 
309 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
310 #define MBEDTLS_SSL_MAX_CID_EXPANSION      MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY
311 #else
312 #define MBEDTLS_SSL_MAX_CID_EXPANSION        0
313 #endif
314 
315 #define MBEDTLS_SSL_PAYLOAD_OVERHEAD (MBEDTLS_MAX_IV_LENGTH +          \
316                                       MBEDTLS_SSL_MAC_ADD +            \
317                                       MBEDTLS_SSL_PADDING_ADD +        \
318                                       MBEDTLS_SSL_MAX_CID_EXPANSION    \
319                                       )
320 
321 #define MBEDTLS_SSL_IN_PAYLOAD_LEN (MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
322                                     (MBEDTLS_SSL_IN_CONTENT_LEN))
323 
324 #define MBEDTLS_SSL_OUT_PAYLOAD_LEN (MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
325                                      (MBEDTLS_SSL_OUT_CONTENT_LEN))
326 
327 /* The maximum number of buffered handshake messages. */
328 #define MBEDTLS_SSL_MAX_BUFFERED_HS 4
329 
330 /* Maximum length we can advertise as our max content length for
331    RFC 6066 max_fragment_length extension negotiation purposes
332    (the lesser of both sizes, if they are unequal.)
333  */
334 #define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN (                            \
335         (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN)   \
336         ? (MBEDTLS_SSL_OUT_CONTENT_LEN)                            \
337         : (MBEDTLS_SSL_IN_CONTENT_LEN)                             \
338         )
339 
340 /* Maximum size in bytes of list in signature algorithms ext., RFC 5246/8446 */
341 #define MBEDTLS_SSL_MAX_SIG_ALG_LIST_LEN       65534
342 
343 /* Minimum size in bytes of list in signature algorithms ext., RFC 5246/8446 */
344 #define MBEDTLS_SSL_MIN_SIG_ALG_LIST_LEN       2
345 
346 /* Maximum size in bytes of list in supported elliptic curve ext., RFC 4492 */
347 #define MBEDTLS_SSL_MAX_CURVE_LIST_LEN         65535
348 
349 #define MBEDTLS_RECEIVED_SIG_ALGS_SIZE         20
350 
351 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
352 
353 #define MBEDTLS_TLS_SIG_NONE MBEDTLS_TLS1_3_SIG_NONE
354 
355 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
356 #define MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(sig, hash) ((hash << 8) | sig)
357 #define MBEDTLS_SSL_TLS12_SIG_ALG_FROM_SIG_AND_HASH_ALG(alg) (alg & 0xFF)
358 #define MBEDTLS_SSL_TLS12_HASH_ALG_FROM_SIG_AND_HASH_ALG(alg) (alg >> 8)
359 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
360 
361 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
362 
363 /*
364  * Check that we obey the standard's message size bounds
365  */
366 
367 #if MBEDTLS_SSL_IN_CONTENT_LEN > 16384
368 #error "Bad configuration - incoming record content too large."
369 #endif
370 
371 #if MBEDTLS_SSL_OUT_CONTENT_LEN > 16384
372 #error "Bad configuration - outgoing record content too large."
373 #endif
374 
375 #if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_IN_CONTENT_LEN + 2048
376 #error "Bad configuration - incoming protected record payload too large."
377 #endif
378 
379 #if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN + 2048
380 #error "Bad configuration - outgoing protected record payload too large."
381 #endif
382 
383 /* Calculate buffer sizes */
384 
385 /* Note: Even though the TLS record header is only 5 bytes
386    long, we're internally using 8 bytes to store the
387    implicit sequence number. */
388 #define MBEDTLS_SSL_HEADER_LEN 13
389 
390 #if !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
391 #define MBEDTLS_SSL_IN_BUFFER_LEN  \
392     ((MBEDTLS_SSL_HEADER_LEN) + (MBEDTLS_SSL_IN_PAYLOAD_LEN))
393 #else
394 #define MBEDTLS_SSL_IN_BUFFER_LEN  \
395     ((MBEDTLS_SSL_HEADER_LEN) + (MBEDTLS_SSL_IN_PAYLOAD_LEN) \
396      + (MBEDTLS_SSL_CID_IN_LEN_MAX))
397 #endif
398 
399 #if !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
400 #define MBEDTLS_SSL_OUT_BUFFER_LEN  \
401     ((MBEDTLS_SSL_HEADER_LEN) + (MBEDTLS_SSL_OUT_PAYLOAD_LEN))
402 #else
403 #define MBEDTLS_SSL_OUT_BUFFER_LEN                               \
404     ((MBEDTLS_SSL_HEADER_LEN) + (MBEDTLS_SSL_OUT_PAYLOAD_LEN)    \
405      + (MBEDTLS_SSL_CID_OUT_LEN_MAX))
406 #endif
407 
408 #define MBEDTLS_CLIENT_HELLO_RANDOM_LEN 32
409 #define MBEDTLS_SERVER_HELLO_RANDOM_LEN 32
410 
411 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
412 /**
413  * \brief          Return the maximum fragment length (payload, in bytes) for
414  *                 the output buffer. For the client, this is the configured
415  *                 value. For the server, it is the minimum of two - the
416  *                 configured value and the negotiated one.
417  *
418  * \sa             mbedtls_ssl_conf_max_frag_len()
419  * \sa             mbedtls_ssl_get_max_out_record_payload()
420  *
421  * \param ssl      SSL context
422  *
423  * \return         Current maximum fragment length for the output buffer.
424  */
425 size_t mbedtls_ssl_get_output_max_frag_len(const mbedtls_ssl_context *ssl);
426 
427 /**
428  * \brief          Return the maximum fragment length (payload, in bytes) for
429  *                 the input buffer. This is the negotiated maximum fragment
430  *                 length, or, if there is none, MBEDTLS_SSL_IN_CONTENT_LEN.
431  *                 If it is not defined either, the value is 2^14. This function
432  *                 works as its predecessor, \c mbedtls_ssl_get_max_frag_len().
433  *
434  * \sa             mbedtls_ssl_conf_max_frag_len()
435  * \sa             mbedtls_ssl_get_max_in_record_payload()
436  *
437  * \param ssl      SSL context
438  *
439  * \return         Current maximum fragment length for the output buffer.
440  */
441 size_t mbedtls_ssl_get_input_max_frag_len(const mbedtls_ssl_context *ssl);
442 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
443 
444 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
445 /**
446  * \brief    Get the size limit in bytes for the protected outgoing records
447  *           as defined in RFC 8449
448  *
449  * \param ssl      SSL context
450  *
451  * \return         The size limit in bytes for the protected outgoing
452  *                 records as defined in RFC 8449.
453  */
454 size_t mbedtls_ssl_get_output_record_size_limit(const mbedtls_ssl_context *ssl);
455 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
456 
457 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
mbedtls_ssl_get_output_buflen(const mbedtls_ssl_context * ctx)458 static inline size_t mbedtls_ssl_get_output_buflen(const mbedtls_ssl_context *ctx)
459 {
460 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
461     return mbedtls_ssl_get_output_max_frag_len(ctx)
462            + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD
463            + MBEDTLS_SSL_CID_OUT_LEN_MAX;
464 #else
465     return mbedtls_ssl_get_output_max_frag_len(ctx)
466            + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD;
467 #endif
468 }
469 
mbedtls_ssl_get_input_buflen(const mbedtls_ssl_context * ctx)470 static inline size_t mbedtls_ssl_get_input_buflen(const mbedtls_ssl_context *ctx)
471 {
472 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
473     return mbedtls_ssl_get_input_max_frag_len(ctx)
474            + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD
475            + MBEDTLS_SSL_CID_IN_LEN_MAX;
476 #else
477     return mbedtls_ssl_get_input_max_frag_len(ctx)
478            + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD;
479 #endif
480 }
481 #endif
482 
483 /*
484  * TLS extension flags (for extensions with outgoing ServerHello content
485  * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
486  * of state of the renegotiation flag, so no indicator is required)
487  */
488 #define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0)
489 #define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK                 (1 << 1)
490 
491 /**
492  * \brief        This function checks if the remaining size in a buffer is
493  *               greater or equal than a needed space.
494  *
495  * \param cur    Pointer to the current position in the buffer.
496  * \param end    Pointer to one past the end of the buffer.
497  * \param need   Needed space in bytes.
498  *
499  * \return       Zero if the needed space is available in the buffer, non-zero
500  *               otherwise.
501  */
502 #if !defined(MBEDTLS_TEST_HOOKS)
mbedtls_ssl_chk_buf_ptr(const uint8_t * cur,const uint8_t * end,size_t need)503 static inline int mbedtls_ssl_chk_buf_ptr(const uint8_t *cur,
504                                           const uint8_t *end, size_t need)
505 {
506     return (cur > end) || (need > (size_t) (end - cur));
507 }
508 #else
509 typedef struct {
510     const uint8_t *cur;
511     const uint8_t *end;
512     size_t need;
513 } mbedtls_ssl_chk_buf_ptr_args;
514 
515 void mbedtls_ssl_set_chk_buf_ptr_fail_args(
516     const uint8_t *cur, const uint8_t *end, size_t need);
517 void mbedtls_ssl_reset_chk_buf_ptr_fail_args(void);
518 
519 MBEDTLS_CHECK_RETURN_CRITICAL
520 int mbedtls_ssl_cmp_chk_buf_ptr_fail_args(mbedtls_ssl_chk_buf_ptr_args *args);
521 
mbedtls_ssl_chk_buf_ptr(const uint8_t * cur,const uint8_t * end,size_t need)522 static inline int mbedtls_ssl_chk_buf_ptr(const uint8_t *cur,
523                                           const uint8_t *end, size_t need)
524 {
525     if ((cur > end) || (need > (size_t) (end - cur))) {
526         mbedtls_ssl_set_chk_buf_ptr_fail_args(cur, end, need);
527         return 1;
528     }
529     return 0;
530 }
531 #endif /* MBEDTLS_TEST_HOOKS */
532 
533 /**
534  * \brief        This macro checks if the remaining size in a buffer is
535  *               greater or equal than a needed space. If it is not the case,
536  *               it returns an SSL_BUFFER_TOO_SMALL error.
537  *
538  * \param cur    Pointer to the current position in the buffer.
539  * \param end    Pointer to one past the end of the buffer.
540  * \param need   Needed space in bytes.
541  *
542  */
543 #define MBEDTLS_SSL_CHK_BUF_PTR(cur, end, need)                        \
544     do {                                                                 \
545         if (mbedtls_ssl_chk_buf_ptr((cur), (end), (need)) != 0) \
546         {                                                                \
547             return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;                  \
548         }                                                                \
549     } while (0)
550 
551 /**
552  * \brief        This macro checks if the remaining length in an input buffer is
553  *               greater or equal than a needed length. If it is not the case, it
554  *               returns #MBEDTLS_ERR_SSL_DECODE_ERROR error and pends a
555  *               #MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR alert message.
556  *
557  *               This is a function-like macro. It is guaranteed to evaluate each
558  *               argument exactly once.
559  *
560  * \param cur    Pointer to the current position in the buffer.
561  * \param end    Pointer to one past the end of the buffer.
562  * \param need   Needed length in bytes.
563  *
564  */
565 #define MBEDTLS_SSL_CHK_BUF_READ_PTR(cur, end, need)                          \
566     do {                                                                        \
567         if (mbedtls_ssl_chk_buf_ptr((cur), (end), (need)) != 0)        \
568         {                                                                       \
569             MBEDTLS_SSL_DEBUG_MSG(1,                                           \
570                                   ("missing input data in %s", __func__));  \
571             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,   \
572                                          MBEDTLS_ERR_SSL_DECODE_ERROR);       \
573             return MBEDTLS_ERR_SSL_DECODE_ERROR;                             \
574         }                                                                       \
575     } while (0)
576 
577 #ifdef __cplusplus
578 extern "C" {
579 #endif
580 
581 typedef int  mbedtls_ssl_tls_prf_cb(const unsigned char *secret, size_t slen,
582                                     const char *label,
583                                     const unsigned char *random, size_t rlen,
584                                     unsigned char *dstbuf, size_t dlen);
585 
586 /* cipher.h exports the maximum IV, key and block length from
587  * all ciphers enabled in the config, regardless of whether those
588  * ciphers are actually usable in SSL/TLS. Notably, XTS is enabled
589  * in the default configuration and uses 64 Byte keys, but it is
590  * not used for record protection in SSL/TLS.
591  *
592  * In order to prevent unnecessary inflation of key structures,
593  * we introduce SSL-specific variants of the max-{key,block,IV}
594  * macros here which are meant to only take those ciphers into
595  * account which can be negotiated in SSL/TLS.
596  *
597  * Since the current definitions of MBEDTLS_MAX_{KEY|BLOCK|IV}_LENGTH
598  * in cipher.h are rough overapproximations of the real maxima, here
599  * we content ourselves with replicating those overapproximations
600  * for the maximum block and IV length, and excluding XTS from the
601  * computation of the maximum key length. */
602 #define MBEDTLS_SSL_MAX_BLOCK_LENGTH 16
603 #define MBEDTLS_SSL_MAX_IV_LENGTH    16
604 #define MBEDTLS_SSL_MAX_KEY_LENGTH   32
605 
606 /**
607  * \brief   The data structure holding the cryptographic material (key and IV)
608  *          used for record protection in TLS 1.3.
609  */
610 struct mbedtls_ssl_key_set {
611     /*! The key for client->server records. */
612     unsigned char client_write_key[MBEDTLS_SSL_MAX_KEY_LENGTH];
613     /*! The key for server->client records. */
614     unsigned char server_write_key[MBEDTLS_SSL_MAX_KEY_LENGTH];
615     /*! The IV  for client->server records. */
616     unsigned char client_write_iv[MBEDTLS_SSL_MAX_IV_LENGTH];
617     /*! The IV  for server->client records. */
618     unsigned char server_write_iv[MBEDTLS_SSL_MAX_IV_LENGTH];
619 
620     size_t key_len; /*!< The length of client_write_key and
621                      *   server_write_key, in Bytes. */
622     size_t iv_len;  /*!< The length of client_write_iv and
623                      *   server_write_iv, in Bytes. */
624 };
625 typedef struct mbedtls_ssl_key_set mbedtls_ssl_key_set;
626 
627 typedef struct {
628     unsigned char binder_key[MBEDTLS_TLS1_3_MD_MAX_SIZE];
629     unsigned char client_early_traffic_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
630     unsigned char early_exporter_master_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
631 } mbedtls_ssl_tls13_early_secrets;
632 
633 typedef struct {
634     unsigned char client_handshake_traffic_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
635     unsigned char server_handshake_traffic_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
636 } mbedtls_ssl_tls13_handshake_secrets;
637 
638 /*
639  * This structure contains the parameters only needed during handshake.
640  */
641 struct mbedtls_ssl_handshake_params {
642     /* Frequently-used boolean or byte fields (placed early to take
643      * advantage of smaller code size for indirect access on Arm Thumb) */
644     uint8_t resume;                     /*!<  session resume indicator*/
645     uint8_t cli_exts;                   /*!< client extension presence*/
646 
647 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
648     uint8_t sni_authmode;               /*!< authmode from SNI callback     */
649 #endif
650 
651 #if defined(MBEDTLS_SSL_SRV_C)
652     /* Flag indicating if a CertificateRequest message has been sent
653      * to the client or not. */
654     uint8_t certificate_request_sent;
655 #if defined(MBEDTLS_SSL_EARLY_DATA)
656     /* Flag indicating if the server has accepted early data or not. */
657     uint8_t early_data_accepted;
658 #endif
659 #endif /* MBEDTLS_SSL_SRV_C */
660 
661 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
662     uint8_t new_session_ticket;         /*!< use NewSessionTicket?    */
663 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
664 
665 #if defined(MBEDTLS_SSL_CLI_C)
666     /** Minimum TLS version to be negotiated.
667      *
668      * It is set up in the ClientHello writing preparation stage and used
669      * throughout the ClientHello writing. Not relevant anymore as soon as
670      * the protocol version has been negotiated thus as soon as the
671      * ServerHello is received.
672      * For a fresh handshake not linked to any previous handshake, it is
673      * equal to the configured minimum minor version to be negotiated. When
674      * renegotiating or resuming a session, it is equal to the previously
675      * negotiated minor version.
676      *
677      * There is no maximum TLS version field in this handshake context.
678      * From the start of the handshake, we need to define a current protocol
679      * version for the record layer which we define as the maximum TLS
680      * version to be negotiated. The `tls_version` field of the SSL context is
681      * used to store this maximum value until it contains the actual
682      * negotiated value.
683      */
684     mbedtls_ssl_protocol_version min_tls_version;
685 #endif
686 
687 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
688     uint8_t extended_ms;                /*!< use Extended Master Secret? */
689 #endif
690 
691 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
692     uint8_t async_in_progress; /*!< an asynchronous operation is in progress */
693 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
694 
695 #if defined(MBEDTLS_SSL_PROTO_DTLS)
696     unsigned char retransmit_state;     /*!<  Retransmission state           */
697 #endif
698 
699 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
700     unsigned char group_list_heap_allocated;
701     unsigned char sig_algs_heap_allocated;
702 #endif
703 
704 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
705     uint8_t ecrs_enabled;               /*!< Handshake supports EC restart? */
706     enum { /* this complements ssl->state with info on intra-state operations */
707         ssl_ecrs_none = 0,              /*!< nothing going on (yet)         */
708         ssl_ecrs_crt_verify,            /*!< Certificate: crt_verify()      */
709         ssl_ecrs_ske_start_processing,  /*!< ServerKeyExchange: pk_verify() */
710         ssl_ecrs_cke_ecdh_calc_secret,  /*!< ClientKeyExchange: ECDH step 2 */
711         ssl_ecrs_crt_vrfy_sign,         /*!< CertificateVerify: pk_sign()   */
712     } ecrs_state;                       /*!< current (or last) operation    */
713     mbedtls_x509_crt *ecrs_peer_cert;   /*!< The peer's CRT chain.          */
714     size_t ecrs_n;                      /*!< place for saving a length      */
715 #endif
716 
717     mbedtls_ssl_ciphersuite_t const *ciphersuite_info;
718 
719     MBEDTLS_CHECK_RETURN_CRITICAL
720     int (*update_checksum)(mbedtls_ssl_context *, const unsigned char *, size_t);
721     MBEDTLS_CHECK_RETURN_CRITICAL
722     int (*calc_verify)(const mbedtls_ssl_context *, unsigned char *, size_t *);
723     MBEDTLS_CHECK_RETURN_CRITICAL
724     int (*calc_finished)(mbedtls_ssl_context *, unsigned char *, int);
725     mbedtls_ssl_tls_prf_cb *tls_prf;
726 
727     /*
728      * Handshake specific crypto variables
729      */
730 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
731     uint8_t key_exchange_mode; /*!< Selected key exchange mode */
732 
733     /**
734      * Flag indicating if, in the course of the current handshake, an
735      * HelloRetryRequest message has been sent by the server or received by
736      * the client (<> 0) or not (0).
737      */
738     uint8_t hello_retry_request_flag;
739 
740 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
741     /**
742      * Flag indicating if, in the course of the current handshake, a dummy
743      * change_cipher_spec (CCS) record has already been sent. Used to send only
744      * one CCS per handshake while not complicating the handshake state
745      * transitions for that purpose.
746      */
747     uint8_t ccs_sent;
748 #endif
749 
750 #if defined(MBEDTLS_SSL_SRV_C)
751 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
752     uint8_t tls13_kex_modes; /*!< Key exchange modes supported by the client */
753 #endif
754     /** selected_group of key_share extension in HelloRetryRequest message. */
755     uint16_t hrr_selected_group;
756 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
757     uint16_t new_session_tickets_count;         /*!< number of session tickets */
758 #endif
759 #endif /* MBEDTLS_SSL_SRV_C */
760 
761 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
762 
763 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
764     uint16_t received_sig_algs[MBEDTLS_RECEIVED_SIG_ALGS_SIZE];
765 #endif
766 
767 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
768     const uint16_t *group_list;
769     const uint16_t *sig_algs;
770 #endif
771 
772 #if defined(MBEDTLS_DHM_C)
773     mbedtls_dhm_context dhm_ctx;                /*!<  DHM key exchange        */
774 #endif
775 
776 #if !defined(MBEDTLS_USE_PSA_CRYPTO) && \
777     defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED)
778     mbedtls_ecdh_context ecdh_ctx;              /*!<  ECDH key exchange       */
779 #endif /* !MBEDTLS_USE_PSA_CRYPTO &&
780           MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED */
781 
782 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_XXDH_PSA_ANY_ENABLED)
783     psa_key_type_t xxdh_psa_type;
784     size_t xxdh_psa_bits;
785     mbedtls_svc_key_id_t xxdh_psa_privkey;
786     uint8_t xxdh_psa_privkey_is_external;
787     unsigned char xxdh_psa_peerkey[PSA_EXPORT_PUBLIC_KEY_MAX_SIZE];
788     size_t xxdh_psa_peerkey_len;
789 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_XXDH_PSA_ANY_ENABLED */
790 
791 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
792 #if defined(MBEDTLS_USE_PSA_CRYPTO)
793     psa_pake_operation_t psa_pake_ctx;        /*!< EC J-PAKE key exchange */
794     mbedtls_svc_key_id_t psa_pake_password;
795     uint8_t psa_pake_ctx_is_ok;
796 #else
797     mbedtls_ecjpake_context ecjpake_ctx;        /*!< EC J-PAKE key exchange */
798 #endif /* MBEDTLS_USE_PSA_CRYPTO */
799 #if defined(MBEDTLS_SSL_CLI_C)
800     unsigned char *ecjpake_cache;               /*!< Cache for ClientHello ext */
801     size_t ecjpake_cache_len;                   /*!< Length of cached data */
802 #endif
803 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
804 
805 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_ANY_ENABLED) || \
806     defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ANY_ALLOWED_ENABLED) || \
807     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
808     uint16_t *curves_tls_id;      /*!<  List of TLS IDs of supported elliptic curves */
809 #endif
810 
811 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
812 #if defined(MBEDTLS_USE_PSA_CRYPTO)
813     mbedtls_svc_key_id_t psk_opaque;            /*!< Opaque PSK from the callback   */
814     uint8_t psk_opaque_is_internal;
815 #else
816     unsigned char *psk;                 /*!<  PSK from the callback         */
817     size_t psk_len;                     /*!<  Length of PSK from callback   */
818 #endif /* MBEDTLS_USE_PSA_CRYPTO */
819     uint16_t    selected_identity;
820 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
821 
822 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
823     mbedtls_x509_crt_restart_ctx ecrs_ctx;  /*!< restart context            */
824 #endif
825 
826 #if defined(MBEDTLS_X509_CRT_PARSE_C)
827     mbedtls_ssl_key_cert *key_cert;     /*!< chosen key/cert pair (server)  */
828 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
829     mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI         */
830     mbedtls_x509_crt *sni_ca_chain;     /*!< trusted CAs from SNI callback  */
831     mbedtls_x509_crl *sni_ca_crl;       /*!< trusted CAs CRLs from SNI      */
832 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
833 #endif /* MBEDTLS_X509_CRT_PARSE_C */
834 
835 #if defined(MBEDTLS_X509_CRT_PARSE_C) &&        \
836     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
837     mbedtls_pk_context peer_pubkey;     /*!< The public key from the peer.  */
838 #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
839 
840     struct {
841         size_t total_bytes_buffered; /*!< Cumulative size of heap allocated
842                                       *   buffers used for message buffering. */
843 
844         uint8_t seen_ccs;               /*!< Indicates if a CCS message has
845                                          *   been seen in the current flight. */
846 
847         struct mbedtls_ssl_hs_buffer {
848             unsigned is_valid      : 1;
849             unsigned is_fragmented : 1;
850             unsigned is_complete   : 1;
851             unsigned char *data;
852             size_t data_len;
853         } hs[MBEDTLS_SSL_MAX_BUFFERED_HS];
854 
855         struct {
856             unsigned char *data;
857             size_t len;
858             unsigned epoch;
859         } future_record;
860 
861     } buffering;
862 
863 #if defined(MBEDTLS_SSL_CLI_C) && \
864     (defined(MBEDTLS_SSL_PROTO_DTLS) || \
865     defined(MBEDTLS_SSL_PROTO_TLS1_3))
866     unsigned char *cookie;              /*!< HelloVerifyRequest cookie for DTLS
867                                          *   HelloRetryRequest cookie for TLS 1.3 */
868 #if !defined(MBEDTLS_SSL_PROTO_TLS1_3)
869     /* RFC 6347 page 15
870        ...
871        opaque cookie<0..2^8-1>;
872        ...
873      */
874     uint8_t cookie_len;
875 #else
876     /* RFC 8446 page 39
877        ...
878        opaque cookie<0..2^16-1>;
879        ...
880        If TLS1_3 is enabled, the max length is 2^16 - 1
881      */
882     uint16_t cookie_len;                /*!< DTLS: HelloVerifyRequest cookie length
883                                          *   TLS1_3: HelloRetryRequest cookie length */
884 #endif
885 #endif /* MBEDTLS_SSL_CLI_C &&
886           ( MBEDTLS_SSL_PROTO_DTLS ||
887             MBEDTLS_SSL_PROTO_TLS1_3 ) */
888 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_PROTO_DTLS)
889     unsigned char cookie_verify_result; /*!< Srv: flag for sending a cookie */
890 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_DTLS */
891 
892 #if defined(MBEDTLS_SSL_PROTO_DTLS)
893     unsigned int out_msg_seq;           /*!<  Outgoing handshake sequence number */
894     unsigned int in_msg_seq;            /*!<  Incoming handshake sequence number */
895 
896     uint32_t retransmit_timeout;        /*!<  Current value of timeout       */
897     mbedtls_ssl_flight_item *flight;    /*!<  Current outgoing flight        */
898     mbedtls_ssl_flight_item *cur_msg;   /*!<  Current message in flight      */
899     unsigned char *cur_msg_p;           /*!<  Position in current message    */
900     unsigned int in_flight_start_seq;   /*!<  Minimum message sequence in the
901                                               flight being received          */
902     mbedtls_ssl_transform *alt_transform_out;   /*!<  Alternative transform for
903                                                    resending messages             */
904     unsigned char alt_out_ctr[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN]; /*!<  Alternative record epoch/counter
905                                                                       for resending messages         */
906 
907 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
908     /* The state of CID configuration in this handshake. */
909 
910     uint8_t cid_in_use; /*!< This indicates whether the use of the CID extension
911                          *   has been negotiated. Possible values are
912                          *   #MBEDTLS_SSL_CID_ENABLED and
913                          *   #MBEDTLS_SSL_CID_DISABLED. */
914     unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];   /*! The peer's CID */
915     uint8_t peer_cid_len;                                  /*!< The length of
916                                                             *   \c peer_cid.  */
917 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
918 
919     uint16_t mtu;                       /*!<  Handshake mtu, used to fragment outgoing messages */
920 #endif /* MBEDTLS_SSL_PROTO_DTLS */
921 
922     /*
923      * Checksum contexts
924      */
925 #if defined(MBEDTLS_MD_CAN_SHA256)
926 #if defined(MBEDTLS_USE_PSA_CRYPTO)
927     psa_hash_operation_t fin_sha256_psa;
928 #else
929     mbedtls_md_context_t fin_sha256;
930 #endif
931 #endif
932 #if defined(MBEDTLS_MD_CAN_SHA384)
933 #if defined(MBEDTLS_USE_PSA_CRYPTO)
934     psa_hash_operation_t fin_sha384_psa;
935 #else
936     mbedtls_md_context_t fin_sha384;
937 #endif
938 #endif
939 
940 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
941     uint16_t offered_group_id; /* The NamedGroup value for the group
942                                 * that is being used for ephemeral
943                                 * key exchange.
944                                 *
945                                 * On the client: Defaults to the first
946                                 * entry in the client's group list,
947                                 * but can be overwritten by the HRR. */
948 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
949 
950 #if defined(MBEDTLS_SSL_CLI_C)
951     uint8_t client_auth;       /*!< used to check if CertificateRequest has been
952                                     received from server side. If CertificateRequest
953                                     has been received, Certificate and CertificateVerify
954                                     should be sent to server */
955 #endif /* MBEDTLS_SSL_CLI_C */
956     /*
957      * State-local variables used during the processing
958      * of a specific handshake state.
959      */
960     union {
961         /* Outgoing Finished message */
962         struct {
963             uint8_t preparation_done;
964 
965             /* Buffer holding digest of the handshake up to
966              * but excluding the outgoing finished message. */
967             unsigned char digest[MBEDTLS_TLS1_3_MD_MAX_SIZE];
968             size_t digest_len;
969         } finished_out;
970 
971         /* Incoming Finished message */
972         struct {
973             uint8_t preparation_done;
974 
975             /* Buffer holding digest of the handshake up to but
976              * excluding the peer's incoming finished message. */
977             unsigned char digest[MBEDTLS_TLS1_3_MD_MAX_SIZE];
978             size_t digest_len;
979         } finished_in;
980 
981     } state_local;
982 
983     /* End of state-local variables. */
984 
985     unsigned char randbytes[MBEDTLS_CLIENT_HELLO_RANDOM_LEN +
986                             MBEDTLS_SERVER_HELLO_RANDOM_LEN];
987     /*!<  random bytes            */
988 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
989     unsigned char premaster[MBEDTLS_PREMASTER_SIZE];
990     /*!<  premaster secret        */
991     size_t pmslen;                      /*!<  premaster length        */
992 #endif
993 
994 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
995     uint32_t sent_extensions;       /*!< extensions sent by endpoint */
996     uint32_t received_extensions;   /*!< extensions received by endpoint */
997 
998 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
999     unsigned char certificate_request_context_len;
1000     unsigned char *certificate_request_context;
1001 #endif
1002 
1003     /** TLS 1.3 transform for encrypted handshake messages. */
1004     mbedtls_ssl_transform *transform_handshake;
1005     union {
1006         unsigned char early[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1007         unsigned char handshake[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1008         unsigned char app[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1009     } tls13_master_secrets;
1010 
1011     mbedtls_ssl_tls13_handshake_secrets tls13_hs_secrets;
1012 #if defined(MBEDTLS_SSL_EARLY_DATA)
1013     /** TLS 1.3 transform for early data and handshake messages. */
1014     mbedtls_ssl_transform *transform_earlydata;
1015 #endif
1016 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1017 
1018 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1019     /** Asynchronous operation context. This field is meant for use by the
1020      * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start,
1021      * mbedtls_ssl_config::f_async_decrypt_start,
1022      * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel).
1023      * The library does not use it internally. */
1024     void *user_async_ctx;
1025 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
1026 
1027 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1028     const unsigned char *sni_name;      /*!< raw SNI                        */
1029     size_t sni_name_len;                /*!< raw SNI len                    */
1030 #if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
1031     const mbedtls_x509_crt *dn_hints;   /*!< acceptable client cert issuers */
1032 #endif
1033 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1034 };
1035 
1036 typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer;
1037 
1038 /*
1039  * Representation of decryption/encryption transformations on records
1040  *
1041  * There are the following general types of record transformations:
1042  * - Stream transformations (TLS versions == 1.2 only)
1043  *   Transformation adding a MAC and applying a stream-cipher
1044  *   to the authenticated message.
1045  * - CBC block cipher transformations ([D]TLS versions == 1.2 only)
1046  *   For TLS 1.2, no IV is generated at key extraction time, but every
1047  *   encrypted record is explicitly prefixed by the IV with which it was
1048  *   encrypted.
1049  * - AEAD transformations ([D]TLS versions == 1.2 only)
1050  *   These come in two fundamentally different versions, the first one
1051  *   used in TLS 1.2, excluding ChaChaPoly ciphersuites, and the second
1052  *   one used for ChaChaPoly ciphersuites in TLS 1.2 as well as for TLS 1.3.
1053  *   In the first transformation, the IV to be used for a record is obtained
1054  *   as the concatenation of an explicit, static 4-byte IV and the 8-byte
1055  *   record sequence number, and explicitly prepending this sequence number
1056  *   to the encrypted record. In contrast, in the second transformation
1057  *   the IV is obtained by XOR'ing a static IV obtained at key extraction
1058  *   time with the 8-byte record sequence number, without prepending the
1059  *   latter to the encrypted record.
1060  *
1061  * Additionally, DTLS 1.2 + CID as well as TLS 1.3 use an inner plaintext
1062  * which allows to add flexible length padding and to hide a record's true
1063  * content type.
1064  *
1065  * In addition to type and version, the following parameters are relevant:
1066  * - The symmetric cipher algorithm to be used.
1067  * - The (static) encryption/decryption keys for the cipher.
1068  * - For stream/CBC, the type of message digest to be used.
1069  * - For stream/CBC, (static) encryption/decryption keys for the digest.
1070  * - For AEAD transformations, the size (potentially 0) of an explicit,
1071  *   random initialization vector placed in encrypted records.
1072  * - For some transformations (currently AEAD) an implicit IV. It is static
1073  *   and (if present) is combined with the explicit IV in a transformation-
1074  *   -dependent way (e.g. appending in TLS 1.2 and XOR'ing in TLS 1.3).
1075  * - For stream/CBC, a flag determining the order of encryption and MAC.
1076  * - The details of the transformation depend on the SSL/TLS version.
1077  * - The length of the authentication tag.
1078  *
1079  * The struct below refines this abstract view as follows:
1080  * - The cipher underlying the transformation is managed in
1081  *   cipher contexts cipher_ctx_{enc/dec}, which must have the
1082  *   same cipher type. The mode of these cipher contexts determines
1083  *   the type of the transformation in the sense above: e.g., if
1084  *   the type is MBEDTLS_CIPHER_AES_256_CBC resp. MBEDTLS_CIPHER_AES_192_GCM
1085  *   then the transformation has type CBC resp. AEAD.
1086  * - The cipher keys are never stored explicitly but
1087  *   are maintained within cipher_ctx_{enc/dec}.
1088  * - For stream/CBC transformations, the message digest contexts
1089  *   used for the MAC's are stored in md_ctx_{enc/dec}. These contexts
1090  *   are unused for AEAD transformations.
1091  * - For stream/CBC transformations, the MAC keys are not stored explicitly
1092  *   but maintained within md_ctx_{enc/dec}.
1093  * - The mac_enc and mac_dec fields are unused for EAD transformations.
1094  * - For transformations using an implicit IV maintained within
1095  *   the transformation context, its contents are stored within
1096  *   iv_{enc/dec}.
1097  * - The value of ivlen indicates the length of the IV.
1098  *   This is redundant in case of stream/CBC transformations
1099  *   which always use 0 resp. the cipher's block length as the
1100  *   IV length, but is needed for AEAD ciphers and may be
1101  *   different from the underlying cipher's block length
1102  *   in this case.
1103  * - The field fixed_ivlen is nonzero for AEAD transformations only
1104  *   and indicates the length of the static part of the IV which is
1105  *   constant throughout the communication, and which is stored in
1106  *   the first fixed_ivlen bytes of the iv_{enc/dec} arrays.
1107  * - tls_version denotes the 2-byte TLS version
1108  * - For stream/CBC transformations, maclen denotes the length of the
1109  *   authentication tag, while taglen is unused and 0.
1110  * - For AEAD transformations, taglen denotes the length of the
1111  *   authentication tag, while maclen is unused and 0.
1112  * - For CBC transformations, encrypt_then_mac determines the
1113  *   order of encryption and authentication. This field is unused
1114  *   in other transformations.
1115  *
1116  */
1117 struct mbedtls_ssl_transform {
1118     /*
1119      * Session specific crypto layer
1120      */
1121     size_t minlen;                      /*!<  min. ciphertext length  */
1122     size_t ivlen;                       /*!<  IV length               */
1123     size_t fixed_ivlen;                 /*!<  Fixed part of IV (AEAD) */
1124     size_t maclen;                      /*!<  MAC(CBC) len            */
1125     size_t taglen;                      /*!<  TAG(AEAD) len           */
1126 
1127     unsigned char iv_enc[16];           /*!<  IV (encryption)         */
1128     unsigned char iv_dec[16];           /*!<  IV (decryption)         */
1129 
1130 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1131 
1132 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1133     mbedtls_svc_key_id_t psa_mac_enc;           /*!<  MAC (encryption)        */
1134     mbedtls_svc_key_id_t psa_mac_dec;           /*!<  MAC (decryption)        */
1135     psa_algorithm_t psa_mac_alg;                /*!<  psa MAC algorithm       */
1136 #else
1137     mbedtls_md_context_t md_ctx_enc;            /*!<  MAC (encryption)        */
1138     mbedtls_md_context_t md_ctx_dec;            /*!<  MAC (decryption)        */
1139 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1140 
1141 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1142     int encrypt_then_mac;       /*!< flag for EtM activation                */
1143 #endif
1144 
1145 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
1146 
1147     mbedtls_ssl_protocol_version tls_version;
1148 
1149 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1150     mbedtls_svc_key_id_t psa_key_enc;           /*!<  psa encryption key      */
1151     mbedtls_svc_key_id_t psa_key_dec;           /*!<  psa decryption key      */
1152     psa_algorithm_t psa_alg;                    /*!<  psa algorithm           */
1153 #else
1154     mbedtls_cipher_context_t cipher_ctx_enc;    /*!<  encryption context      */
1155     mbedtls_cipher_context_t cipher_ctx_dec;    /*!<  decryption context      */
1156 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1157 
1158 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1159     uint8_t in_cid_len;
1160     uint8_t out_cid_len;
1161     unsigned char in_cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
1162     unsigned char out_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
1163 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1164 
1165 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
1166     /* We need the Hello random bytes in order to re-derive keys from the
1167      * Master Secret and other session info,
1168      * see ssl_tls12_populate_transform() */
1169     unsigned char randbytes[MBEDTLS_SERVER_HELLO_RANDOM_LEN +
1170                             MBEDTLS_CLIENT_HELLO_RANDOM_LEN];
1171     /*!< ServerHello.random+ClientHello.random */
1172 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
1173 };
1174 
1175 /*
1176  * Return 1 if the transform uses an AEAD cipher, 0 otherwise.
1177  * Equivalently, return 0 if a separate MAC is used, 1 otherwise.
1178  */
mbedtls_ssl_transform_uses_aead(const mbedtls_ssl_transform * transform)1179 static inline int mbedtls_ssl_transform_uses_aead(
1180     const mbedtls_ssl_transform *transform)
1181 {
1182 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1183     return transform->maclen == 0 && transform->taglen != 0;
1184 #else
1185     (void) transform;
1186     return 1;
1187 #endif
1188 }
1189 
1190 /*
1191  * Internal representation of record frames
1192  *
1193  * Instances come in two flavors:
1194  * (1) Encrypted
1195  *     These always have data_offset = 0
1196  * (2) Unencrypted
1197  *     These have data_offset set to the amount of
1198  *     pre-expansion during record protection. Concretely,
1199  *     this is the length of the fixed part of the explicit IV
1200  *     used for encryption, or 0 if no explicit IV is used
1201  *     (e.g. for stream ciphers).
1202  *
1203  * The reason for the data_offset in the unencrypted case
1204  * is to allow for in-place conversion of an unencrypted to
1205  * an encrypted record. If the offset wasn't included, the
1206  * encrypted content would need to be shifted afterwards to
1207  * make space for the fixed IV.
1208  *
1209  */
1210 #if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX
1211 #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_OUT_LEN_MAX
1212 #else
1213 #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_IN_LEN_MAX
1214 #endif
1215 
1216 typedef struct {
1217     uint8_t ctr[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN];  /* In TLS:  The implicit record sequence number.
1218                                                     * In DTLS: The 2-byte epoch followed by
1219                                                     *          the 6-byte sequence number.
1220                                                     * This is stored as a raw big endian byte array
1221                                                     * as opposed to a uint64_t because we rarely
1222                                                     * need to perform arithmetic on this, but do
1223                                                     * need it as a Byte array for the purpose of
1224                                                     * MAC computations.                             */
1225     uint8_t type;           /* The record content type.                      */
1226     uint8_t ver[2];         /* SSL/TLS version as present on the wire.
1227                              * Convert to internal presentation of versions
1228                              * using mbedtls_ssl_read_version() and
1229                              * mbedtls_ssl_write_version().
1230                              * Keep wire-format for MAC computations.        */
1231 
1232     unsigned char *buf;     /* Memory buffer enclosing the record content    */
1233     size_t buf_len;         /* Buffer length                                 */
1234     size_t data_offset;     /* Offset of record content                      */
1235     size_t data_len;        /* Length of record content                      */
1236 
1237 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1238     uint8_t cid_len;        /* Length of the CID (0 if not present)          */
1239     unsigned char cid[MBEDTLS_SSL_CID_LEN_MAX];   /* The CID                 */
1240 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1241 } mbedtls_record;
1242 
1243 #if defined(MBEDTLS_X509_CRT_PARSE_C)
1244 /*
1245  * List of certificate + private key pairs
1246  */
1247 struct mbedtls_ssl_key_cert {
1248     mbedtls_x509_crt *cert;                 /*!< cert                       */
1249     mbedtls_pk_context *key;                /*!< private key                */
1250     mbedtls_ssl_key_cert *next;             /*!< next key/cert pair         */
1251 };
1252 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1253 
1254 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1255 /*
1256  * List of handshake messages kept around for resending
1257  */
1258 struct mbedtls_ssl_flight_item {
1259     unsigned char *p;       /*!< message, including handshake headers   */
1260     size_t len;             /*!< length of p                            */
1261     unsigned char type;     /*!< type of the message: handshake or CCS  */
1262     mbedtls_ssl_flight_item *next;  /*!< next handshake message(s)              */
1263 };
1264 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1265 
1266 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1267 /**
1268  * \brief Given an SSL context and its associated configuration, write the TLS
1269  *        1.2 specific extensions of the ClientHello message.
1270  *
1271  * \param[in]   ssl     SSL context
1272  * \param[in]   buf     Base address of the buffer where to write the extensions
1273  * \param[in]   end     End address of the buffer where to write the extensions
1274  * \param       uses_ec Whether one proposed ciphersuite uses an elliptic curve
1275  *                      (<> 0) or not ( 0 ).
1276  * \param[out]  out_len Length of the data written into the buffer \p buf
1277  */
1278 MBEDTLS_CHECK_RETURN_CRITICAL
1279 int mbedtls_ssl_tls12_write_client_hello_exts(mbedtls_ssl_context *ssl,
1280                                               unsigned char *buf,
1281                                               const unsigned char *end,
1282                                               int uses_ec,
1283                                               size_t *out_len);
1284 #endif
1285 
1286 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1287     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1288 
1289 /**
1290  * \brief Find the preferred hash for a given signature algorithm.
1291  *
1292  * \param[in]   ssl     SSL context
1293  * \param[in]   sig_alg A signature algorithm identifier as defined in the
1294  *                      TLS 1.2 SignatureAlgorithm enumeration.
1295  *
1296  * \return  The preferred hash algorithm for \p sig_alg. It is a hash algorithm
1297  *          identifier as defined in the TLS 1.2 HashAlgorithm enumeration.
1298  */
1299 unsigned int mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
1300     mbedtls_ssl_context *ssl,
1301     unsigned int sig_alg);
1302 
1303 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1304           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1305 
1306 /**
1307  * \brief           Free referenced items in an SSL transform context and clear
1308  *                  memory
1309  *
1310  * \param transform SSL transform context
1311  */
1312 void mbedtls_ssl_transform_free(mbedtls_ssl_transform *transform);
1313 
1314 /**
1315  * \brief           Free referenced items in an SSL handshake context and clear
1316  *                  memory
1317  *
1318  * \param ssl       SSL context
1319  */
1320 void mbedtls_ssl_handshake_free(mbedtls_ssl_context *ssl);
1321 
1322 /* set inbound transform of ssl context */
1323 void mbedtls_ssl_set_inbound_transform(mbedtls_ssl_context *ssl,
1324                                        mbedtls_ssl_transform *transform);
1325 
1326 /* set outbound transform of ssl context */
1327 void mbedtls_ssl_set_outbound_transform(mbedtls_ssl_context *ssl,
1328                                         mbedtls_ssl_transform *transform);
1329 
1330 MBEDTLS_CHECK_RETURN_CRITICAL
1331 int mbedtls_ssl_handshake_client_step(mbedtls_ssl_context *ssl);
1332 MBEDTLS_CHECK_RETURN_CRITICAL
1333 int mbedtls_ssl_handshake_server_step(mbedtls_ssl_context *ssl);
1334 void mbedtls_ssl_handshake_wrapup(mbedtls_ssl_context *ssl);
mbedtls_ssl_handshake_set_state(mbedtls_ssl_context * ssl,mbedtls_ssl_states state)1335 static inline void mbedtls_ssl_handshake_set_state(mbedtls_ssl_context *ssl,
1336                                                    mbedtls_ssl_states state)
1337 {
1338     ssl->state = (int) state;
1339 }
1340 
1341 MBEDTLS_CHECK_RETURN_CRITICAL
1342 int mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context *ssl);
1343 
1344 MBEDTLS_CHECK_RETURN_CRITICAL
1345 int mbedtls_ssl_reset_checksum(mbedtls_ssl_context *ssl);
1346 
1347 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1348 MBEDTLS_CHECK_RETURN_CRITICAL
1349 int mbedtls_ssl_derive_keys(mbedtls_ssl_context *ssl);
1350 #endif /* MBEDTLS_SSL_PROTO_TLS1_2  */
1351 
1352 MBEDTLS_CHECK_RETURN_CRITICAL
1353 int mbedtls_ssl_handle_message_type(mbedtls_ssl_context *ssl);
1354 MBEDTLS_CHECK_RETURN_CRITICAL
1355 int mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context *ssl);
1356 MBEDTLS_CHECK_RETURN_CRITICAL
1357 int mbedtls_ssl_update_handshake_status(mbedtls_ssl_context *ssl);
1358 
1359 /**
1360  * \brief       Update record layer
1361  *
1362  *              This function roughly separates the implementation
1363  *              of the logic of (D)TLS from the implementation
1364  *              of the secure transport.
1365  *
1366  * \param  ssl              The SSL context to use.
1367  * \param  update_hs_digest This indicates if the handshake digest
1368  *                          should be automatically updated in case
1369  *                          a handshake message is found.
1370  *
1371  * \return      0 or non-zero error code.
1372  *
1373  * \note        A clarification on what is called 'record layer' here
1374  *              is in order, as many sensible definitions are possible:
1375  *
1376  *              The record layer takes as input an untrusted underlying
1377  *              transport (stream or datagram) and transforms it into
1378  *              a serially multiplexed, secure transport, which
1379  *              conceptually provides the following:
1380  *
1381  *              (1) Three datagram based, content-agnostic transports
1382  *                  for handshake, alert and CCS messages.
1383  *              (2) One stream- or datagram-based transport
1384  *                  for application data.
1385  *              (3) Functionality for changing the underlying transform
1386  *                  securing the contents.
1387  *
1388  *              The interface to this functionality is given as follows:
1389  *
1390  *              a Updating
1391  *                [Currently implemented by mbedtls_ssl_read_record]
1392  *
1393  *                Check if and on which of the four 'ports' data is pending:
1394  *                Nothing, a controlling datagram of type (1), or application
1395  *                data (2). In any case data is present, internal buffers
1396  *                provide access to the data for the user to process it.
1397  *                Consumption of type (1) datagrams is done automatically
1398  *                on the next update, invalidating that the internal buffers
1399  *                for previous datagrams, while consumption of application
1400  *                data (2) is user-controlled.
1401  *
1402  *              b Reading of application data
1403  *                [Currently manual adaption of ssl->in_offt pointer]
1404  *
1405  *                As mentioned in the last paragraph, consumption of data
1406  *                is different from the automatic consumption of control
1407  *                datagrams (1) because application data is treated as a stream.
1408  *
1409  *              c Tracking availability of application data
1410  *                [Currently manually through decreasing ssl->in_msglen]
1411  *
1412  *                For efficiency and to retain datagram semantics for
1413  *                application data in case of DTLS, the record layer
1414  *                provides functionality for checking how much application
1415  *                data is still available in the internal buffer.
1416  *
1417  *              d Changing the transformation securing the communication.
1418  *
1419  *              Given an opaque implementation of the record layer in the
1420  *              above sense, it should be possible to implement the logic
1421  *              of (D)TLS on top of it without the need to know anything
1422  *              about the record layer's internals. This is done e.g.
1423  *              in all the handshake handling functions, and in the
1424  *              application data reading function mbedtls_ssl_read.
1425  *
1426  * \note        The above tries to give a conceptual picture of the
1427  *              record layer, but the current implementation deviates
1428  *              from it in some places. For example, our implementation of
1429  *              the update functionality through mbedtls_ssl_read_record
1430  *              discards datagrams depending on the current state, which
1431  *              wouldn't fall under the record layer's responsibility
1432  *              following the above definition.
1433  *
1434  */
1435 MBEDTLS_CHECK_RETURN_CRITICAL
1436 int mbedtls_ssl_read_record(mbedtls_ssl_context *ssl,
1437                             unsigned update_hs_digest);
1438 MBEDTLS_CHECK_RETURN_CRITICAL
1439 int mbedtls_ssl_fetch_input(mbedtls_ssl_context *ssl, size_t nb_want);
1440 
1441 /*
1442  * Write handshake message header
1443  */
1444 MBEDTLS_CHECK_RETURN_CRITICAL
1445 int mbedtls_ssl_start_handshake_msg(mbedtls_ssl_context *ssl, unsigned char hs_type,
1446                                     unsigned char **buf, size_t *buf_len);
1447 
1448 MBEDTLS_CHECK_RETURN_CRITICAL
1449 int mbedtls_ssl_write_handshake_msg_ext(mbedtls_ssl_context *ssl,
1450                                         int update_checksum,
1451                                         int force_flush);
mbedtls_ssl_write_handshake_msg(mbedtls_ssl_context * ssl)1452 static inline int mbedtls_ssl_write_handshake_msg(mbedtls_ssl_context *ssl)
1453 {
1454     return mbedtls_ssl_write_handshake_msg_ext(ssl, 1 /* update checksum */, 1 /* force flush */);
1455 }
1456 
1457 /*
1458  * Write handshake message tail
1459  */
1460 MBEDTLS_CHECK_RETURN_CRITICAL
1461 int mbedtls_ssl_finish_handshake_msg(mbedtls_ssl_context *ssl,
1462                                      size_t buf_len, size_t msg_len);
1463 
1464 MBEDTLS_CHECK_RETURN_CRITICAL
1465 int mbedtls_ssl_write_record(mbedtls_ssl_context *ssl, int force_flush);
1466 MBEDTLS_CHECK_RETURN_CRITICAL
1467 int mbedtls_ssl_flush_output(mbedtls_ssl_context *ssl);
1468 
1469 MBEDTLS_CHECK_RETURN_CRITICAL
1470 int mbedtls_ssl_parse_certificate(mbedtls_ssl_context *ssl);
1471 MBEDTLS_CHECK_RETURN_CRITICAL
1472 int mbedtls_ssl_write_certificate(mbedtls_ssl_context *ssl);
1473 
1474 MBEDTLS_CHECK_RETURN_CRITICAL
1475 int mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context *ssl);
1476 MBEDTLS_CHECK_RETURN_CRITICAL
1477 int mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context *ssl);
1478 
1479 MBEDTLS_CHECK_RETURN_CRITICAL
1480 int mbedtls_ssl_parse_finished(mbedtls_ssl_context *ssl);
1481 MBEDTLS_CHECK_RETURN_CRITICAL
1482 int mbedtls_ssl_write_finished(mbedtls_ssl_context *ssl);
1483 
1484 void mbedtls_ssl_optimize_checksum(mbedtls_ssl_context *ssl,
1485                                    const mbedtls_ssl_ciphersuite_t *ciphersuite_info);
1486 
1487 /*
1488  * Update checksum of handshake messages.
1489  */
1490 MBEDTLS_CHECK_RETURN_CRITICAL
1491 int mbedtls_ssl_add_hs_msg_to_checksum(mbedtls_ssl_context *ssl,
1492                                        unsigned hs_type,
1493                                        unsigned char const *msg,
1494                                        size_t msg_len);
1495 
1496 MBEDTLS_CHECK_RETURN_CRITICAL
1497 int mbedtls_ssl_add_hs_hdr_to_checksum(mbedtls_ssl_context *ssl,
1498                                        unsigned hs_type,
1499                                        size_t total_hs_len);
1500 
1501 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1502 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
1503 MBEDTLS_CHECK_RETURN_CRITICAL
1504 int mbedtls_ssl_psk_derive_premaster(mbedtls_ssl_context *ssl,
1505                                      mbedtls_key_exchange_type_t key_ex);
1506 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
1507 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
1508 
1509 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1510 #if defined(MBEDTLS_SSL_CLI_C)
1511 MBEDTLS_CHECK_RETURN_CRITICAL
1512 int mbedtls_ssl_conf_has_static_psk(mbedtls_ssl_config const *conf);
1513 #endif
1514 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1515 /**
1516  * Get the first defined opaque PSK by order of precedence:
1517  * 1. handshake PSK set by \c mbedtls_ssl_set_hs_psk_opaque() in the PSK
1518  *    callback
1519  * 2. static PSK configured by \c mbedtls_ssl_conf_psk_opaque()
1520  * Return an opaque PSK
1521  */
mbedtls_ssl_get_opaque_psk(const mbedtls_ssl_context * ssl)1522 static inline mbedtls_svc_key_id_t mbedtls_ssl_get_opaque_psk(
1523     const mbedtls_ssl_context *ssl)
1524 {
1525     if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
1526         return ssl->handshake->psk_opaque;
1527     }
1528 
1529     if (!mbedtls_svc_key_id_is_null(ssl->conf->psk_opaque)) {
1530         return ssl->conf->psk_opaque;
1531     }
1532 
1533     return MBEDTLS_SVC_KEY_ID_INIT;
1534 }
1535 #else
1536 /**
1537  * Get the first defined PSK by order of precedence:
1538  * 1. handshake PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback
1539  * 2. static PSK configured by \c mbedtls_ssl_conf_psk()
1540  * Return a code and update the pair (PSK, PSK length) passed to this function
1541  */
mbedtls_ssl_get_psk(const mbedtls_ssl_context * ssl,const unsigned char ** psk,size_t * psk_len)1542 static inline int mbedtls_ssl_get_psk(const mbedtls_ssl_context *ssl,
1543                                       const unsigned char **psk, size_t *psk_len)
1544 {
1545     if (ssl->handshake->psk != NULL && ssl->handshake->psk_len > 0) {
1546         *psk = ssl->handshake->psk;
1547         *psk_len = ssl->handshake->psk_len;
1548     } else if (ssl->conf->psk != NULL && ssl->conf->psk_len > 0) {
1549         *psk = ssl->conf->psk;
1550         *psk_len = ssl->conf->psk_len;
1551     } else {
1552         *psk = NULL;
1553         *psk_len = 0;
1554         return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
1555     }
1556 
1557     return 0;
1558 }
1559 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1560 
1561 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1562 
1563 #if defined(MBEDTLS_PK_C)
1564 unsigned char mbedtls_ssl_sig_from_pk(mbedtls_pk_context *pk);
1565 unsigned char mbedtls_ssl_sig_from_pk_alg(mbedtls_pk_type_t type);
1566 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig(unsigned char sig);
1567 #endif
1568 
1569 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash(unsigned char hash);
1570 unsigned char mbedtls_ssl_hash_from_md_alg(int md);
1571 
1572 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1573 MBEDTLS_CHECK_RETURN_CRITICAL
1574 int mbedtls_ssl_set_calc_verify_md(mbedtls_ssl_context *ssl, int md);
1575 #endif
1576 
1577 MBEDTLS_CHECK_RETURN_CRITICAL
1578 int mbedtls_ssl_check_curve_tls_id(const mbedtls_ssl_context *ssl, uint16_t tls_id);
1579 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1580 MBEDTLS_CHECK_RETURN_CRITICAL
1581 int mbedtls_ssl_check_curve(const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id);
1582 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
1583 
1584 /**
1585  * \brief Return PSA EC info for the specified TLS ID.
1586  *
1587  * \param tls_id    The TLS ID to look for
1588  * \param type      If the TLD ID is supported, then proper \c psa_key_type_t
1589  *                  value is returned here. Can be NULL.
1590  * \param bits      If the TLD ID is supported, then proper bit size is returned
1591  *                  here. Can be NULL.
1592  * \return          PSA_SUCCESS if the TLS ID is supported,
1593  *                  PSA_ERROR_NOT_SUPPORTED otherwise
1594  *
1595  * \note            If either \c family or \c bits parameters are NULL, then
1596  *                  the corresponding value is not returned.
1597  *                  The function can be called with both parameters as NULL
1598  *                  simply to check if a specific TLS ID is supported.
1599  */
1600 int mbedtls_ssl_get_psa_curve_info_from_tls_id(uint16_t tls_id,
1601                                                psa_key_type_t *type,
1602                                                size_t *bits);
1603 
1604 /**
1605  * \brief Return \c mbedtls_ecp_group_id for the specified TLS ID.
1606  *
1607  * \param tls_id    The TLS ID to look for
1608  * \return          Proper \c mbedtls_ecp_group_id if the TLS ID is supported,
1609  *                  or MBEDTLS_ECP_DP_NONE otherwise
1610  */
1611 mbedtls_ecp_group_id mbedtls_ssl_get_ecp_group_id_from_tls_id(uint16_t tls_id);
1612 
1613 /**
1614  * \brief Return TLS ID for the specified \c mbedtls_ecp_group_id.
1615  *
1616  * \param grp_id    The \c mbedtls_ecp_group_id ID to look for
1617  * \return          Proper TLS ID if the \c mbedtls_ecp_group_id is supported,
1618  *                  or 0 otherwise
1619  */
1620 uint16_t mbedtls_ssl_get_tls_id_from_ecp_group_id(mbedtls_ecp_group_id grp_id);
1621 
1622 #if defined(MBEDTLS_DEBUG_C)
1623 /**
1624  * \brief Return EC's name for the specified TLS ID.
1625  *
1626  * \param tls_id    The TLS ID to look for
1627  * \return          A pointer to a const string with the proper name. If TLS
1628  *                  ID is not supported, a NULL pointer is returned instead.
1629  */
1630 const char *mbedtls_ssl_get_curve_name_from_tls_id(uint16_t tls_id);
1631 #endif
1632 
1633 #if defined(MBEDTLS_SSL_DTLS_SRTP)
mbedtls_ssl_check_srtp_profile_value(const uint16_t srtp_profile_value)1634 static inline mbedtls_ssl_srtp_profile mbedtls_ssl_check_srtp_profile_value
1635     (const uint16_t srtp_profile_value)
1636 {
1637     switch (srtp_profile_value) {
1638         case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80:
1639         case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32:
1640         case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80:
1641         case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32:
1642             return srtp_profile_value;
1643         default: break;
1644     }
1645     return MBEDTLS_TLS_SRTP_UNSET;
1646 }
1647 #endif
1648 
1649 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_own_key(mbedtls_ssl_context * ssl)1650 static inline mbedtls_pk_context *mbedtls_ssl_own_key(mbedtls_ssl_context *ssl)
1651 {
1652     mbedtls_ssl_key_cert *key_cert;
1653 
1654     if (ssl->handshake != NULL && ssl->handshake->key_cert != NULL) {
1655         key_cert = ssl->handshake->key_cert;
1656     } else {
1657         key_cert = ssl->conf->key_cert;
1658     }
1659 
1660     return key_cert == NULL ? NULL : key_cert->key;
1661 }
1662 
mbedtls_ssl_own_cert(mbedtls_ssl_context * ssl)1663 static inline mbedtls_x509_crt *mbedtls_ssl_own_cert(mbedtls_ssl_context *ssl)
1664 {
1665     mbedtls_ssl_key_cert *key_cert;
1666 
1667     if (ssl->handshake != NULL && ssl->handshake->key_cert != NULL) {
1668         key_cert = ssl->handshake->key_cert;
1669     } else {
1670         key_cert = ssl->conf->key_cert;
1671     }
1672 
1673     return key_cert == NULL ? NULL : key_cert->cert;
1674 }
1675 
1676 /*
1677  * Check usage of a certificate wrt extensions:
1678  * keyUsage, extendedKeyUsage (later), and nSCertType (later).
1679  *
1680  * Warning: cert_endpoint is the endpoint of the cert (ie, of our peer when we
1681  * check a cert we received from them)!
1682  *
1683  * Return 0 if everything is OK, -1 if not.
1684  */
1685 MBEDTLS_CHECK_RETURN_CRITICAL
1686 int mbedtls_ssl_check_cert_usage(const mbedtls_x509_crt *cert,
1687                                  const mbedtls_ssl_ciphersuite_t *ciphersuite,
1688                                  int cert_endpoint,
1689                                  uint32_t *flags);
1690 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1691 
1692 void mbedtls_ssl_write_version(unsigned char version[2], int transport,
1693                                mbedtls_ssl_protocol_version tls_version);
1694 uint16_t mbedtls_ssl_read_version(const unsigned char version[2],
1695                                   int transport);
1696 
mbedtls_ssl_in_hdr_len(const mbedtls_ssl_context * ssl)1697 static inline size_t mbedtls_ssl_in_hdr_len(const mbedtls_ssl_context *ssl)
1698 {
1699 #if !defined(MBEDTLS_SSL_PROTO_DTLS)
1700     ((void) ssl);
1701 #endif
1702 
1703 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1704     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1705         return 13;
1706     } else
1707 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1708     {
1709         return 5;
1710     }
1711 }
1712 
mbedtls_ssl_out_hdr_len(const mbedtls_ssl_context * ssl)1713 static inline size_t mbedtls_ssl_out_hdr_len(const mbedtls_ssl_context *ssl)
1714 {
1715     return (size_t) (ssl->out_iv - ssl->out_hdr);
1716 }
1717 
mbedtls_ssl_hs_hdr_len(const mbedtls_ssl_context * ssl)1718 static inline size_t mbedtls_ssl_hs_hdr_len(const mbedtls_ssl_context *ssl)
1719 {
1720 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1721     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1722         return 12;
1723     }
1724 #else
1725     ((void) ssl);
1726 #endif
1727     return 4;
1728 }
1729 
1730 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1731 void mbedtls_ssl_send_flight_completed(mbedtls_ssl_context *ssl);
1732 void mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context *ssl);
1733 MBEDTLS_CHECK_RETURN_CRITICAL
1734 int mbedtls_ssl_resend(mbedtls_ssl_context *ssl);
1735 MBEDTLS_CHECK_RETURN_CRITICAL
1736 int mbedtls_ssl_flight_transmit(mbedtls_ssl_context *ssl);
1737 #endif
1738 
1739 /* Visible for testing purposes only */
1740 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1741 MBEDTLS_CHECK_RETURN_CRITICAL
1742 int mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const *ssl);
1743 void mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context *ssl);
1744 #endif
1745 
1746 MBEDTLS_CHECK_RETURN_CRITICAL
1747 int mbedtls_ssl_session_copy(mbedtls_ssl_session *dst,
1748                              const mbedtls_ssl_session *src);
1749 
1750 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1751 /* The hash buffer must have at least MBEDTLS_MD_MAX_SIZE bytes of length. */
1752 MBEDTLS_CHECK_RETURN_CRITICAL
1753 int mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context *ssl,
1754                                            unsigned char *hash, size_t *hashlen,
1755                                            unsigned char *data, size_t data_len,
1756                                            mbedtls_md_type_t md_alg);
1757 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1758 
1759 #ifdef __cplusplus
1760 }
1761 #endif
1762 
1763 void mbedtls_ssl_transform_init(mbedtls_ssl_transform *transform);
1764 MBEDTLS_CHECK_RETURN_CRITICAL
1765 int mbedtls_ssl_encrypt_buf(mbedtls_ssl_context *ssl,
1766                             mbedtls_ssl_transform *transform,
1767                             mbedtls_record *rec,
1768                             int (*f_rng)(void *, unsigned char *, size_t),
1769                             void *p_rng);
1770 MBEDTLS_CHECK_RETURN_CRITICAL
1771 int mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const *ssl,
1772                             mbedtls_ssl_transform *transform,
1773                             mbedtls_record *rec);
1774 
1775 /* Length of the "epoch" field in the record header */
mbedtls_ssl_ep_len(const mbedtls_ssl_context * ssl)1776 static inline size_t mbedtls_ssl_ep_len(const mbedtls_ssl_context *ssl)
1777 {
1778 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1779     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1780         return 2;
1781     }
1782 #else
1783     ((void) ssl);
1784 #endif
1785     return 0;
1786 }
1787 
1788 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1789 MBEDTLS_CHECK_RETURN_CRITICAL
1790 int mbedtls_ssl_resend_hello_request(mbedtls_ssl_context *ssl);
1791 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1792 
1793 void mbedtls_ssl_set_timer(mbedtls_ssl_context *ssl, uint32_t millisecs);
1794 MBEDTLS_CHECK_RETURN_CRITICAL
1795 int mbedtls_ssl_check_timer(mbedtls_ssl_context *ssl);
1796 
1797 void mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context *ssl);
1798 void mbedtls_ssl_update_out_pointers(mbedtls_ssl_context *ssl,
1799                                      mbedtls_ssl_transform *transform);
1800 void mbedtls_ssl_update_in_pointers(mbedtls_ssl_context *ssl);
1801 
1802 MBEDTLS_CHECK_RETURN_CRITICAL
1803 int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial);
1804 void mbedtls_ssl_session_reset_msg_layer(mbedtls_ssl_context *ssl,
1805                                          int partial);
1806 
1807 /*
1808  * Send pending alert
1809  */
1810 MBEDTLS_CHECK_RETURN_CRITICAL
1811 int mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context *ssl);
1812 
1813 /*
1814  * Set pending fatal alert flag.
1815  */
1816 void mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context *ssl,
1817                                   unsigned char alert_type,
1818                                   int alert_reason);
1819 
1820 /* Alias of mbedtls_ssl_pend_fatal_alert */
1821 #define MBEDTLS_SSL_PEND_FATAL_ALERT(type, user_return_value)         \
1822     mbedtls_ssl_pend_fatal_alert(ssl, type, user_return_value)
1823 
1824 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1825 void mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context *ssl);
1826 #endif
1827 
1828 void mbedtls_ssl_handshake_wrapup_free_hs_transform(mbedtls_ssl_context *ssl);
1829 
1830 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1831 MBEDTLS_CHECK_RETURN_CRITICAL
1832 int mbedtls_ssl_start_renegotiation(mbedtls_ssl_context *ssl);
1833 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1834 
1835 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1836 size_t mbedtls_ssl_get_current_mtu(const mbedtls_ssl_context *ssl);
1837 void mbedtls_ssl_buffering_free(mbedtls_ssl_context *ssl);
1838 void mbedtls_ssl_flight_free(mbedtls_ssl_flight_item *flight);
1839 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1840 
1841 /**
1842  * ssl utils functions for checking configuration.
1843  */
1844 
1845 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_ssl_conf_is_tls13_only(const mbedtls_ssl_config * conf)1846 static inline int mbedtls_ssl_conf_is_tls13_only(const mbedtls_ssl_config *conf)
1847 {
1848     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_3 &&
1849            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_3;
1850 }
1851 
1852 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1853 
1854 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_ssl_conf_is_tls12_only(const mbedtls_ssl_config * conf)1855 static inline int mbedtls_ssl_conf_is_tls12_only(const mbedtls_ssl_config *conf)
1856 {
1857     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_2 &&
1858            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_2;
1859 }
1860 
1861 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1862 
mbedtls_ssl_conf_is_tls13_enabled(const mbedtls_ssl_config * conf)1863 static inline int mbedtls_ssl_conf_is_tls13_enabled(const mbedtls_ssl_config *conf)
1864 {
1865 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1866     return conf->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_3 &&
1867            conf->max_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3;
1868 #else
1869     ((void) conf);
1870     return 0;
1871 #endif
1872 }
1873 
mbedtls_ssl_conf_is_tls12_enabled(const mbedtls_ssl_config * conf)1874 static inline int mbedtls_ssl_conf_is_tls12_enabled(const mbedtls_ssl_config *conf)
1875 {
1876 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1877     return conf->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_2 &&
1878            conf->max_tls_version >= MBEDTLS_SSL_VERSION_TLS1_2;
1879 #else
1880     ((void) conf);
1881     return 0;
1882 #endif
1883 }
1884 
1885 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_ssl_conf_is_hybrid_tls12_tls13(const mbedtls_ssl_config * conf)1886 static inline int mbedtls_ssl_conf_is_hybrid_tls12_tls13(const mbedtls_ssl_config *conf)
1887 {
1888     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_2 &&
1889            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_3;
1890 }
1891 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_SSL_PROTO_TLS1_3 */
1892 
1893 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1894 extern const uint8_t mbedtls_ssl_tls13_hello_retry_request_magic[
1895     MBEDTLS_SERVER_HELLO_RANDOM_LEN];
1896 MBEDTLS_CHECK_RETURN_CRITICAL
1897 int mbedtls_ssl_tls13_process_finished_message(mbedtls_ssl_context *ssl);
1898 MBEDTLS_CHECK_RETURN_CRITICAL
1899 int mbedtls_ssl_tls13_write_finished_message(mbedtls_ssl_context *ssl);
1900 void mbedtls_ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl);
1901 
1902 /**
1903  * \brief Given an SSL context and its associated configuration, write the TLS
1904  *        1.3 specific extensions of the ClientHello message.
1905  *
1906  * \param[in]   ssl     SSL context
1907  * \param[in]   buf     Base address of the buffer where to write the extensions
1908  * \param[in]   end     End address of the buffer where to write the extensions
1909  * \param[out]  out_len Length of the data written into the buffer \p buf
1910  */
1911 MBEDTLS_CHECK_RETURN_CRITICAL
1912 int mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context *ssl,
1913                                               unsigned char *buf,
1914                                               unsigned char *end,
1915                                               size_t *out_len);
1916 
1917 /**
1918  * \brief           TLS 1.3 client side state machine entry
1919  *
1920  * \param ssl       SSL context
1921  */
1922 MBEDTLS_CHECK_RETURN_CRITICAL
1923 int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl);
1924 
1925 /**
1926  * \brief           TLS 1.3 server side state machine entry
1927  *
1928  * \param ssl       SSL context
1929  */
1930 MBEDTLS_CHECK_RETURN_CRITICAL
1931 int mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context *ssl);
1932 
1933 
1934 /*
1935  * Helper functions around key exchange modes.
1936  */
mbedtls_ssl_conf_tls13_is_kex_mode_enabled(mbedtls_ssl_context * ssl,int kex_mode_mask)1937 static inline int mbedtls_ssl_conf_tls13_is_kex_mode_enabled(mbedtls_ssl_context *ssl,
1938                                                              int kex_mode_mask)
1939 {
1940     return (ssl->conf->tls13_kex_modes & kex_mode_mask) != 0;
1941 }
1942 
mbedtls_ssl_conf_tls13_is_psk_enabled(mbedtls_ssl_context * ssl)1943 static inline int mbedtls_ssl_conf_tls13_is_psk_enabled(mbedtls_ssl_context *ssl)
1944 {
1945     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
1946                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK);
1947 }
1948 
mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(mbedtls_ssl_context * ssl)1949 static inline int mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(mbedtls_ssl_context *ssl)
1950 {
1951     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
1952                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL);
1953 }
1954 
mbedtls_ssl_conf_tls13_is_ephemeral_enabled(mbedtls_ssl_context * ssl)1955 static inline int mbedtls_ssl_conf_tls13_is_ephemeral_enabled(mbedtls_ssl_context *ssl)
1956 {
1957     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
1958                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL);
1959 }
1960 
mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(mbedtls_ssl_context * ssl)1961 static inline int mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(mbedtls_ssl_context *ssl)
1962 {
1963     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
1964                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
1965 }
1966 
mbedtls_ssl_conf_tls13_is_some_psk_enabled(mbedtls_ssl_context * ssl)1967 static inline int mbedtls_ssl_conf_tls13_is_some_psk_enabled(mbedtls_ssl_context *ssl)
1968 {
1969     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
1970                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
1971 }
1972 
1973 #if defined(MBEDTLS_SSL_SRV_C) && \
1974     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1975 /**
1976  * Given a list of key exchange modes, check if at least one of them is
1977  * supported by peer.
1978  *
1979  * \param[in] ssl  SSL context
1980  * \param kex_modes_mask  Mask of the key exchange modes to check
1981  *
1982  * \return Non-zero if at least one of the key exchange modes is supported by
1983  *         the peer, otherwise \c 0.
1984  */
mbedtls_ssl_tls13_is_kex_mode_supported(mbedtls_ssl_context * ssl,int kex_modes_mask)1985 static inline int mbedtls_ssl_tls13_is_kex_mode_supported(mbedtls_ssl_context *ssl,
1986                                                           int kex_modes_mask)
1987 {
1988     return (ssl->handshake->tls13_kex_modes & kex_modes_mask) != 0;
1989 }
1990 
mbedtls_ssl_tls13_is_psk_supported(mbedtls_ssl_context * ssl)1991 static inline int mbedtls_ssl_tls13_is_psk_supported(mbedtls_ssl_context *ssl)
1992 {
1993     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
1994                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK);
1995 }
1996 
mbedtls_ssl_tls13_is_psk_ephemeral_supported(mbedtls_ssl_context * ssl)1997 static inline int mbedtls_ssl_tls13_is_psk_ephemeral_supported(
1998     mbedtls_ssl_context *ssl)
1999 {
2000     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2001                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL);
2002 }
2003 
mbedtls_ssl_tls13_is_ephemeral_supported(mbedtls_ssl_context * ssl)2004 static inline int mbedtls_ssl_tls13_is_ephemeral_supported(mbedtls_ssl_context *ssl)
2005 {
2006     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2007                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL);
2008 }
2009 
mbedtls_ssl_tls13_is_some_ephemeral_supported(mbedtls_ssl_context * ssl)2010 static inline int mbedtls_ssl_tls13_is_some_ephemeral_supported(mbedtls_ssl_context *ssl)
2011 {
2012     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2013                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
2014 }
2015 
mbedtls_ssl_tls13_is_some_psk_supported(mbedtls_ssl_context * ssl)2016 static inline int mbedtls_ssl_tls13_is_some_psk_supported(mbedtls_ssl_context *ssl)
2017 {
2018     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2019                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
2020 }
2021 #endif /* MBEDTLS_SSL_SRV_C &&
2022           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
2023 
2024 /*
2025  * Helper functions for extensions checking.
2026  */
2027 
2028 MBEDTLS_CHECK_RETURN_CRITICAL
2029 int mbedtls_ssl_tls13_check_received_extension(
2030     mbedtls_ssl_context *ssl,
2031     int hs_msg_type,
2032     unsigned int received_extension_type,
2033     uint32_t hs_msg_allowed_extensions_mask);
2034 
mbedtls_ssl_tls13_set_hs_sent_ext_mask(mbedtls_ssl_context * ssl,unsigned int extension_type)2035 static inline void mbedtls_ssl_tls13_set_hs_sent_ext_mask(
2036     mbedtls_ssl_context *ssl, unsigned int extension_type)
2037 {
2038     ssl->handshake->sent_extensions |=
2039         mbedtls_ssl_get_extension_mask(extension_type);
2040 }
2041 
2042 /*
2043  * Helper functions to check the selected key exchange mode.
2044  */
mbedtls_ssl_tls13_key_exchange_mode_check(mbedtls_ssl_context * ssl,int kex_mask)2045 static inline int mbedtls_ssl_tls13_key_exchange_mode_check(
2046     mbedtls_ssl_context *ssl, int kex_mask)
2047 {
2048     return (ssl->handshake->key_exchange_mode & kex_mask) != 0;
2049 }
2050 
mbedtls_ssl_tls13_key_exchange_mode_with_psk(mbedtls_ssl_context * ssl)2051 static inline int mbedtls_ssl_tls13_key_exchange_mode_with_psk(
2052     mbedtls_ssl_context *ssl)
2053 {
2054     return mbedtls_ssl_tls13_key_exchange_mode_check(ssl,
2055                                                      MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
2056 }
2057 
mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(mbedtls_ssl_context * ssl)2058 static inline int mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(
2059     mbedtls_ssl_context *ssl)
2060 {
2061     return mbedtls_ssl_tls13_key_exchange_mode_check(ssl,
2062                                                      MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
2063 }
2064 
2065 /*
2066  * Fetch TLS 1.3 handshake message header
2067  */
2068 MBEDTLS_CHECK_RETURN_CRITICAL
2069 int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
2070                                           unsigned hs_type,
2071                                           unsigned char **buf,
2072                                           size_t *buf_len);
2073 
2074 /**
2075  * \brief Detect if a list of extensions contains a supported_versions
2076  *        extension or not.
2077  *
2078  * \param[in] ssl  SSL context
2079  * \param[in] buf  Address of the first byte of the extensions vector.
2080  * \param[in] end  End of the buffer containing the list of extensions.
2081  * \param[out] supported_versions_data  If the extension is present, address of
2082  *                                      its first byte of data, NULL otherwise.
2083  * \param[out] supported_versions_data_end  If the extension is present, address
2084  *                                          of the first byte immediately
2085  *                                          following the extension data, NULL
2086  *                                          otherwise.
2087  * \return 0  if the list of extensions does not contain a supported_versions
2088  *            extension.
2089  * \return 1  if the list of extensions contains a supported_versions
2090  *            extension.
2091  * \return    A negative value if an error occurred while parsing the
2092  *            extensions.
2093  */
2094 MBEDTLS_CHECK_RETURN_CRITICAL
2095 int mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
2096     mbedtls_ssl_context *ssl,
2097     const unsigned char *buf, const unsigned char *end,
2098     const unsigned char **supported_versions_data,
2099     const unsigned char **supported_versions_data_end);
2100 
2101 /*
2102  * Handler of TLS 1.3 server certificate message
2103  */
2104 MBEDTLS_CHECK_RETURN_CRITICAL
2105 int mbedtls_ssl_tls13_process_certificate(mbedtls_ssl_context *ssl);
2106 
2107 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2108 /*
2109  * Handler of TLS 1.3 write Certificate message
2110  */
2111 MBEDTLS_CHECK_RETURN_CRITICAL
2112 int mbedtls_ssl_tls13_write_certificate(mbedtls_ssl_context *ssl);
2113 
2114 /*
2115  * Handler of TLS 1.3 write Certificate Verify message
2116  */
2117 MBEDTLS_CHECK_RETURN_CRITICAL
2118 int mbedtls_ssl_tls13_write_certificate_verify(mbedtls_ssl_context *ssl);
2119 
2120 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2121 
2122 /*
2123  * Generic handler of Certificate Verify
2124  */
2125 MBEDTLS_CHECK_RETURN_CRITICAL
2126 int mbedtls_ssl_tls13_process_certificate_verify(mbedtls_ssl_context *ssl);
2127 
2128 /*
2129  * Write of dummy-CCS's for middlebox compatibility
2130  */
2131 MBEDTLS_CHECK_RETURN_CRITICAL
2132 int mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context *ssl);
2133 
2134 MBEDTLS_CHECK_RETURN_CRITICAL
2135 int mbedtls_ssl_reset_transcript_for_hrr(mbedtls_ssl_context *ssl);
2136 
2137 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
2138 MBEDTLS_CHECK_RETURN_CRITICAL
2139 int mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
2140     mbedtls_ssl_context *ssl,
2141     uint16_t named_group,
2142     unsigned char *buf,
2143     unsigned char *end,
2144     size_t *out_len);
2145 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
2146 
2147 #if defined(MBEDTLS_SSL_EARLY_DATA)
2148 int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
2149                                            int in_new_session_ticket,
2150                                            unsigned char *buf,
2151                                            const unsigned char *end,
2152                                            size_t *out_len);
2153 
2154 int mbedtls_ssl_tls13_check_early_data_len(mbedtls_ssl_context *ssl,
2155                                            size_t early_data_len);
2156 
2157 typedef enum {
2158 /*
2159  * The client has not sent the first ClientHello yet, the negotiation of early
2160  * data has not started yet.
2161  */
2162     MBEDTLS_SSL_EARLY_DATA_STATE_IDLE,
2163 
2164 /*
2165  * In its ClientHello, the client has not included an early data indication
2166  * extension.
2167  */
2168     MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT,
2169 
2170 /*
2171  * The client has sent an early data indication extension in its first
2172  * ClientHello, it has not received the response (ServerHello or
2173  * HelloRetryRequest) from the server yet. The transform to protect early data
2174  * is not set either as for middlebox compatibility a dummy CCS may have to be
2175  * sent in clear. Early data cannot be sent to the server yet.
2176  */
2177     MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT,
2178 
2179 /*
2180  * The client has sent an early data indication extension in its first
2181  * ClientHello, it has not received the response (ServerHello or
2182  * HelloRetryRequest) from the server yet. The transform to protect early data
2183  * has been set and early data can be written now.
2184  */
2185     MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE,
2186 
2187 /*
2188  * The client has indicated the use of early data and the server has accepted
2189  * it.
2190  */
2191     MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED,
2192 
2193 /*
2194  * The client has indicated the use of early data but the server has rejected
2195  * it.
2196  */
2197     MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED,
2198 
2199 /*
2200  * The client has sent an early data indication extension in its first
2201  * ClientHello, the server has accepted them and the client has received the
2202  * server Finished message. It cannot send early data to the server anymore.
2203  */
2204     MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED,
2205 
2206 } mbedtls_ssl_early_data_state;
2207 #endif /* MBEDTLS_SSL_EARLY_DATA */
2208 
2209 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2210 
2211 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2212 /*
2213  * Write Signature Algorithm extension
2214  */
2215 MBEDTLS_CHECK_RETURN_CRITICAL
2216 int mbedtls_ssl_write_sig_alg_ext(mbedtls_ssl_context *ssl, unsigned char *buf,
2217                                   const unsigned char *end, size_t *out_len);
2218 /*
2219  * Parse TLS Signature Algorithm extension
2220  */
2221 MBEDTLS_CHECK_RETURN_CRITICAL
2222 int mbedtls_ssl_parse_sig_alg_ext(mbedtls_ssl_context *ssl,
2223                                   const unsigned char *buf,
2224                                   const unsigned char *end);
2225 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2226 
2227 /* Get handshake transcript */
2228 MBEDTLS_CHECK_RETURN_CRITICAL
2229 int mbedtls_ssl_get_handshake_transcript(mbedtls_ssl_context *ssl,
2230                                          const mbedtls_md_type_t md,
2231                                          unsigned char *dst,
2232                                          size_t dst_len,
2233                                          size_t *olen);
2234 
2235 /*
2236  * Return supported groups.
2237  *
2238  * In future, invocations can be changed to ssl->conf->group_list
2239  * when mbedtls_ssl_conf_curves() is deleted.
2240  *
2241  * ssl->handshake->group_list is either a translation of curve_list to IANA TLS group
2242  * identifiers when mbedtls_ssl_conf_curves() has been used, or a pointer to
2243  * ssl->conf->group_list when mbedtls_ssl_conf_groups() has been more recently invoked.
2244  *
2245  */
mbedtls_ssl_get_groups(const mbedtls_ssl_context * ssl)2246 static inline const void *mbedtls_ssl_get_groups(const mbedtls_ssl_context *ssl)
2247 {
2248     #if defined(MBEDTLS_DEPRECATED_REMOVED) || !defined(MBEDTLS_ECP_C)
2249     return ssl->conf->group_list;
2250     #else
2251     if ((ssl->handshake != NULL) && (ssl->handshake->group_list != NULL)) {
2252         return ssl->handshake->group_list;
2253     } else {
2254         return ssl->conf->group_list;
2255     }
2256     #endif
2257 }
2258 
2259 /*
2260  * Helper functions for NamedGroup.
2261  */
mbedtls_ssl_tls12_named_group_is_ecdhe(uint16_t named_group)2262 static inline int mbedtls_ssl_tls12_named_group_is_ecdhe(uint16_t named_group)
2263 {
2264     /*
2265      * RFC 8422 section 5.1.1
2266      */
2267     return named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X25519    ||
2268            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP256R1   ||
2269            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP384R1   ||
2270            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP512R1   ||
2271            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X448      ||
2272            /* Below deprecated curves should be removed with notice to users */
2273            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP192K1 ||
2274            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1 ||
2275            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP224K1 ||
2276            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1 ||
2277            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256K1 ||
2278            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 ||
2279            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 ||
2280            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1;
2281 }
2282 
mbedtls_ssl_tls13_named_group_is_ecdhe(uint16_t named_group)2283 static inline int mbedtls_ssl_tls13_named_group_is_ecdhe(uint16_t named_group)
2284 {
2285     return named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X25519    ||
2286            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 ||
2287            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 ||
2288            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1 ||
2289            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X448;
2290 }
2291 
mbedtls_ssl_tls13_named_group_is_ffdh(uint16_t named_group)2292 static inline int mbedtls_ssl_tls13_named_group_is_ffdh(uint16_t named_group)
2293 {
2294     return named_group >= MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048 &&
2295            named_group <= MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192;
2296 }
2297 
mbedtls_ssl_named_group_is_offered(const mbedtls_ssl_context * ssl,uint16_t named_group)2298 static inline int mbedtls_ssl_named_group_is_offered(
2299     const mbedtls_ssl_context *ssl, uint16_t named_group)
2300 {
2301     const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
2302 
2303     if (group_list == NULL) {
2304         return 0;
2305     }
2306 
2307     for (; *group_list != 0; group_list++) {
2308         if (*group_list == named_group) {
2309             return 1;
2310         }
2311     }
2312 
2313     return 0;
2314 }
2315 
mbedtls_ssl_named_group_is_supported(uint16_t named_group)2316 static inline int mbedtls_ssl_named_group_is_supported(uint16_t named_group)
2317 {
2318 #if defined(PSA_WANT_ALG_ECDH)
2319     if (mbedtls_ssl_tls13_named_group_is_ecdhe(named_group)) {
2320         if (mbedtls_ssl_get_ecp_group_id_from_tls_id(named_group) !=
2321             MBEDTLS_ECP_DP_NONE) {
2322             return 1;
2323         }
2324     }
2325 #endif
2326 #if defined(PSA_WANT_ALG_FFDH)
2327     if (mbedtls_ssl_tls13_named_group_is_ffdh(named_group)) {
2328         return 1;
2329     }
2330 #endif
2331 #if !defined(PSA_WANT_ALG_ECDH) && !defined(PSA_WANT_ALG_FFDH)
2332     (void) named_group;
2333 #endif
2334     return 0;
2335 }
2336 
2337 /*
2338  * Return supported signature algorithms.
2339  *
2340  * In future, invocations can be changed to ssl->conf->sig_algs when
2341  * mbedtls_ssl_conf_sig_hashes() is deleted.
2342  *
2343  * ssl->handshake->sig_algs is either a translation of sig_hashes to IANA TLS
2344  * signature algorithm identifiers when mbedtls_ssl_conf_sig_hashes() has been
2345  * used, or a pointer to ssl->conf->sig_algs when mbedtls_ssl_conf_sig_algs() has
2346  * been more recently invoked.
2347  *
2348  */
mbedtls_ssl_get_sig_algs(const mbedtls_ssl_context * ssl)2349 static inline const void *mbedtls_ssl_get_sig_algs(
2350     const mbedtls_ssl_context *ssl)
2351 {
2352 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2353 
2354 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2355     if (ssl->handshake != NULL &&
2356         ssl->handshake->sig_algs_heap_allocated == 1 &&
2357         ssl->handshake->sig_algs != NULL) {
2358         return ssl->handshake->sig_algs;
2359     }
2360 #endif
2361     return ssl->conf->sig_algs;
2362 
2363 #else /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2364 
2365     ((void) ssl);
2366     return NULL;
2367 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2368 }
2369 
2370 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
mbedtls_ssl_sig_alg_is_received(const mbedtls_ssl_context * ssl,uint16_t own_sig_alg)2371 static inline int mbedtls_ssl_sig_alg_is_received(const mbedtls_ssl_context *ssl,
2372                                                   uint16_t own_sig_alg)
2373 {
2374     const uint16_t *sig_alg = ssl->handshake->received_sig_algs;
2375     if (sig_alg == NULL) {
2376         return 0;
2377     }
2378 
2379     for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2380         if (*sig_alg == own_sig_alg) {
2381             return 1;
2382         }
2383     }
2384     return 0;
2385 }
2386 
mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(const uint16_t sig_alg)2387 static inline int mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(
2388     const uint16_t sig_alg)
2389 {
2390     switch (sig_alg) {
2391 #if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
2392 #if defined(PSA_WANT_ALG_SHA_256) && defined(PSA_WANT_ECC_SECP_R1_256)
2393         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256:
2394             break;
2395 #endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_ECP_DP_SECP256R1_ENABLED */
2396 #if defined(PSA_WANT_ALG_SHA_384) && defined(PSA_WANT_ECC_SECP_R1_384)
2397         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384:
2398             break;
2399 #endif /* PSA_WANT_ALG_SHA_384 && MBEDTLS_ECP_DP_SECP384R1_ENABLED */
2400 #if defined(PSA_WANT_ALG_SHA_512) && defined(PSA_WANT_ECC_SECP_R1_521)
2401         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512:
2402             break;
2403 #endif /* PSA_WANT_ALG_SHA_512 && MBEDTLS_ECP_DP_SECP521R1_ENABLED */
2404 #endif /* MBEDTLS_PK_CAN_ECDSA_SOME */
2405 
2406 #if defined(MBEDTLS_PKCS1_V21)
2407 #if defined(PSA_WANT_ALG_SHA_256)
2408         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
2409             break;
2410 #endif /* PSA_WANT_ALG_SHA_256  */
2411 #if defined(PSA_WANT_ALG_SHA_384)
2412         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
2413             break;
2414 #endif /* PSA_WANT_ALG_SHA_384 */
2415 #if defined(PSA_WANT_ALG_SHA_512)
2416         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
2417             break;
2418 #endif /* PSA_WANT_ALG_SHA_512 */
2419 #endif /* MBEDTLS_PKCS1_V21 */
2420         default:
2421             return 0;
2422     }
2423     return 1;
2424 
2425 }
2426 
mbedtls_ssl_tls13_sig_alg_is_supported(const uint16_t sig_alg)2427 static inline int mbedtls_ssl_tls13_sig_alg_is_supported(
2428     const uint16_t sig_alg)
2429 {
2430     switch (sig_alg) {
2431 #if defined(MBEDTLS_PKCS1_V15)
2432 #if defined(MBEDTLS_MD_CAN_SHA256)
2433         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256:
2434             break;
2435 #endif /* MBEDTLS_MD_CAN_SHA256 */
2436 #if defined(MBEDTLS_MD_CAN_SHA384)
2437         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384:
2438             break;
2439 #endif /* MBEDTLS_MD_CAN_SHA384 */
2440 #if defined(MBEDTLS_MD_CAN_SHA512)
2441         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512:
2442             break;
2443 #endif /* MBEDTLS_MD_CAN_SHA512 */
2444 #endif /* MBEDTLS_PKCS1_V15 */
2445         default:
2446             return mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(
2447                 sig_alg);
2448     }
2449     return 1;
2450 }
2451 
2452 MBEDTLS_CHECK_RETURN_CRITICAL
2453 int mbedtls_ssl_tls13_check_sig_alg_cert_key_match(uint16_t sig_alg,
2454                                                    mbedtls_pk_context *key);
2455 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2456 
2457 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
mbedtls_ssl_sig_alg_is_offered(const mbedtls_ssl_context * ssl,uint16_t proposed_sig_alg)2458 static inline int mbedtls_ssl_sig_alg_is_offered(const mbedtls_ssl_context *ssl,
2459                                                  uint16_t proposed_sig_alg)
2460 {
2461     const uint16_t *sig_alg = mbedtls_ssl_get_sig_algs(ssl);
2462     if (sig_alg == NULL) {
2463         return 0;
2464     }
2465 
2466     for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2467         if (*sig_alg == proposed_sig_alg) {
2468             return 1;
2469         }
2470     }
2471     return 0;
2472 }
2473 
mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(uint16_t sig_alg,mbedtls_pk_type_t * pk_type,mbedtls_md_type_t * md_alg)2474 static inline int mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
2475     uint16_t sig_alg, mbedtls_pk_type_t *pk_type, mbedtls_md_type_t *md_alg)
2476 {
2477     *pk_type = mbedtls_ssl_pk_alg_from_sig(sig_alg & 0xff);
2478     *md_alg = mbedtls_ssl_md_alg_from_hash((sig_alg >> 8) & 0xff);
2479 
2480     if (*pk_type != MBEDTLS_PK_NONE && *md_alg != MBEDTLS_MD_NONE) {
2481         return 0;
2482     }
2483 
2484     switch (sig_alg) {
2485 #if defined(MBEDTLS_PKCS1_V21)
2486 #if defined(MBEDTLS_MD_CAN_SHA256)
2487         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
2488             *md_alg = MBEDTLS_MD_SHA256;
2489             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2490             break;
2491 #endif /* MBEDTLS_MD_CAN_SHA256  */
2492 #if defined(MBEDTLS_MD_CAN_SHA384)
2493         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
2494             *md_alg = MBEDTLS_MD_SHA384;
2495             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2496             break;
2497 #endif /* MBEDTLS_MD_CAN_SHA384 */
2498 #if defined(MBEDTLS_MD_CAN_SHA512)
2499         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
2500             *md_alg = MBEDTLS_MD_SHA512;
2501             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2502             break;
2503 #endif /* MBEDTLS_MD_CAN_SHA512 */
2504 #endif /* MBEDTLS_PKCS1_V21 */
2505         default:
2506             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2507     }
2508     return 0;
2509 }
2510 
2511 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_ssl_tls12_sig_alg_is_supported(const uint16_t sig_alg)2512 static inline int mbedtls_ssl_tls12_sig_alg_is_supported(
2513     const uint16_t sig_alg)
2514 {
2515     /* High byte is hash */
2516     unsigned char hash = MBEDTLS_BYTE_1(sig_alg);
2517     unsigned char sig = MBEDTLS_BYTE_0(sig_alg);
2518 
2519     switch (hash) {
2520 #if defined(MBEDTLS_MD_CAN_MD5)
2521         case MBEDTLS_SSL_HASH_MD5:
2522             break;
2523 #endif
2524 
2525 #if defined(MBEDTLS_MD_CAN_SHA1)
2526         case MBEDTLS_SSL_HASH_SHA1:
2527             break;
2528 #endif
2529 
2530 #if defined(MBEDTLS_MD_CAN_SHA224)
2531         case MBEDTLS_SSL_HASH_SHA224:
2532             break;
2533 #endif
2534 
2535 #if defined(MBEDTLS_MD_CAN_SHA256)
2536         case MBEDTLS_SSL_HASH_SHA256:
2537             break;
2538 #endif
2539 
2540 #if defined(MBEDTLS_MD_CAN_SHA384)
2541         case MBEDTLS_SSL_HASH_SHA384:
2542             break;
2543 #endif
2544 
2545 #if defined(MBEDTLS_MD_CAN_SHA512)
2546         case MBEDTLS_SSL_HASH_SHA512:
2547             break;
2548 #endif
2549 
2550         default:
2551             return 0;
2552     }
2553 
2554     switch (sig) {
2555 #if defined(MBEDTLS_RSA_C)
2556         case MBEDTLS_SSL_SIG_RSA:
2557             break;
2558 #endif
2559 
2560 #if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
2561         case MBEDTLS_SSL_SIG_ECDSA:
2562             break;
2563 #endif
2564 
2565         default:
2566             return 0;
2567     }
2568 
2569     return 1;
2570 }
2571 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2572 
mbedtls_ssl_sig_alg_is_supported(const mbedtls_ssl_context * ssl,const uint16_t sig_alg)2573 static inline int mbedtls_ssl_sig_alg_is_supported(
2574     const mbedtls_ssl_context *ssl,
2575     const uint16_t sig_alg)
2576 {
2577 
2578 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2579     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2580         return mbedtls_ssl_tls12_sig_alg_is_supported(sig_alg);
2581     }
2582 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2583 
2584 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2585     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2586         return mbedtls_ssl_tls13_sig_alg_is_supported(sig_alg);
2587     }
2588 #endif
2589     ((void) ssl);
2590     ((void) sig_alg);
2591     return 0;
2592 }
2593 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2594 
2595 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
2596 /* Corresponding PSA algorithm for MBEDTLS_CIPHER_NULL.
2597  * Same value is used for PSA_ALG_CATEGORY_CIPHER, hence it is
2598  * guaranteed to not be a valid PSA algorithm identifier.
2599  */
2600 #define MBEDTLS_SSL_NULL_CIPHER 0x04000000
2601 
2602 /**
2603  * \brief       Translate mbedtls cipher type/taglen pair to psa:
2604  *              algorithm, key type and key size.
2605  *
2606  * \param  mbedtls_cipher_type [in] given mbedtls cipher type
2607  * \param  taglen              [in] given tag length
2608  *                                  0 - default tag length
2609  * \param  alg                 [out] corresponding PSA alg
2610  *                                   There is no corresponding PSA
2611  *                                   alg for MBEDTLS_CIPHER_NULL, so
2612  *                                   in this case MBEDTLS_SSL_NULL_CIPHER
2613  *                                   is returned via this parameter
2614  * \param  key_type            [out] corresponding PSA key type
2615  * \param  key_size            [out] corresponding PSA key size
2616  *
2617  * \return                     PSA_SUCCESS on success or PSA_ERROR_NOT_SUPPORTED if
2618  *                             conversion is not supported.
2619  */
2620 psa_status_t mbedtls_ssl_cipher_to_psa(mbedtls_cipher_type_t mbedtls_cipher_type,
2621                                        size_t taglen,
2622                                        psa_algorithm_t *alg,
2623                                        psa_key_type_t *key_type,
2624                                        size_t *key_size);
2625 
2626 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2627 /**
2628  * \brief       Convert given PSA status to mbedtls error code.
2629  *
2630  * \param  status      [in] given PSA status
2631  *
2632  * \return             corresponding mbedtls error code
2633  */
psa_ssl_status_to_mbedtls(psa_status_t status)2634 static inline MBEDTLS_DEPRECATED int psa_ssl_status_to_mbedtls(psa_status_t status)
2635 {
2636     switch (status) {
2637         case PSA_SUCCESS:
2638             return 0;
2639         case PSA_ERROR_INSUFFICIENT_MEMORY:
2640             return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2641         case PSA_ERROR_NOT_SUPPORTED:
2642             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2643         case PSA_ERROR_INVALID_SIGNATURE:
2644             return MBEDTLS_ERR_SSL_INVALID_MAC;
2645         case PSA_ERROR_INVALID_ARGUMENT:
2646             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2647         case PSA_ERROR_BAD_STATE:
2648             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2649         case PSA_ERROR_BUFFER_TOO_SMALL:
2650             return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
2651         default:
2652             return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
2653     }
2654 }
2655 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
2656 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
2657 
2658 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
2659     defined(MBEDTLS_USE_PSA_CRYPTO)
2660 
2661 typedef enum {
2662     MBEDTLS_ECJPAKE_ROUND_ONE,
2663     MBEDTLS_ECJPAKE_ROUND_TWO
2664 } mbedtls_ecjpake_rounds_t;
2665 
2666 /**
2667  * \brief       Parse the provided input buffer for getting the first round
2668  *              of key exchange. This code is common between server and client
2669  *
2670  * \param  pake_ctx [in] the PAKE's operation/context structure
2671  * \param  buf      [in] input buffer to parse
2672  * \param  len      [in] length of the input buffer
2673  * \param  round    [in] either MBEDTLS_ECJPAKE_ROUND_ONE or
2674  *                       MBEDTLS_ECJPAKE_ROUND_TWO
2675  *
2676  * \return               0 on success or a negative error code in case of failure
2677  */
2678 int mbedtls_psa_ecjpake_read_round(
2679     psa_pake_operation_t *pake_ctx,
2680     const unsigned char *buf,
2681     size_t len, mbedtls_ecjpake_rounds_t round);
2682 
2683 /**
2684  * \brief       Write the first round of key exchange into the provided output
2685  *              buffer. This code is common between server and client
2686  *
2687  * \param  pake_ctx [in] the PAKE's operation/context structure
2688  * \param  buf      [out] the output buffer in which data will be written to
2689  * \param  len      [in] length of the output buffer
2690  * \param  olen     [out] the length of the data really written on the buffer
2691  * \param  round    [in] either MBEDTLS_ECJPAKE_ROUND_ONE or
2692  *                       MBEDTLS_ECJPAKE_ROUND_TWO
2693  *
2694  * \return               0 on success or a negative error code in case of failure
2695  */
2696 int mbedtls_psa_ecjpake_write_round(
2697     psa_pake_operation_t *pake_ctx,
2698     unsigned char *buf,
2699     size_t len, size_t *olen,
2700     mbedtls_ecjpake_rounds_t round);
2701 
2702 #endif //MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED && MBEDTLS_USE_PSA_CRYPTO
2703 
2704 /**
2705  * \brief       TLS record protection modes
2706  */
2707 typedef enum {
2708     MBEDTLS_SSL_MODE_STREAM = 0,
2709     MBEDTLS_SSL_MODE_CBC,
2710     MBEDTLS_SSL_MODE_CBC_ETM,
2711     MBEDTLS_SSL_MODE_AEAD
2712 } mbedtls_ssl_mode_t;
2713 
2714 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_transform(
2715     const mbedtls_ssl_transform *transform);
2716 
2717 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2718 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
2719     int encrypt_then_mac,
2720     const mbedtls_ssl_ciphersuite_t *suite);
2721 #else
2722 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
2723     const mbedtls_ssl_ciphersuite_t *suite);
2724 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
2725 
2726 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
2727 
2728 MBEDTLS_CHECK_RETURN_CRITICAL
2729 int mbedtls_ssl_tls13_read_public_xxdhe_share(mbedtls_ssl_context *ssl,
2730                                               const unsigned char *buf,
2731                                               size_t buf_len);
2732 
2733 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
2734 
mbedtls_ssl_tls13_cipher_suite_is_offered(mbedtls_ssl_context * ssl,int cipher_suite)2735 static inline int mbedtls_ssl_tls13_cipher_suite_is_offered(
2736     mbedtls_ssl_context *ssl, int cipher_suite)
2737 {
2738     const int *ciphersuite_list = ssl->conf->ciphersuite_list;
2739 
2740     /* Check whether we have offered this ciphersuite */
2741     for (size_t i = 0; ciphersuite_list[i] != 0; i++) {
2742         if (ciphersuite_list[i] == cipher_suite) {
2743             return 1;
2744         }
2745     }
2746     return 0;
2747 }
2748 
2749 /**
2750  * \brief Validate cipher suite against config in SSL context.
2751  *
2752  * \param ssl              SSL context
2753  * \param suite_info       Cipher suite to validate
2754  * \param min_tls_version  Minimal TLS version to accept a cipher suite
2755  * \param max_tls_version  Maximal TLS version to accept a cipher suite
2756  *
2757  * \return 0 if valid, negative value otherwise.
2758  */
2759 MBEDTLS_CHECK_RETURN_CRITICAL
2760 int mbedtls_ssl_validate_ciphersuite(
2761     const mbedtls_ssl_context *ssl,
2762     const mbedtls_ssl_ciphersuite_t *suite_info,
2763     mbedtls_ssl_protocol_version min_tls_version,
2764     mbedtls_ssl_protocol_version max_tls_version);
2765 
2766 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2767 MBEDTLS_CHECK_RETURN_CRITICAL
2768 int mbedtls_ssl_parse_server_name_ext(mbedtls_ssl_context *ssl,
2769                                       const unsigned char *buf,
2770                                       const unsigned char *end);
2771 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
2772 
2773 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2774 #define MBEDTLS_SSL_RECORD_SIZE_LIMIT_EXTENSION_DATA_LENGTH (2)
2775 #define MBEDTLS_SSL_RECORD_SIZE_LIMIT_MIN (64)      /* As defined in RFC 8449 */
2776 
2777 MBEDTLS_CHECK_RETURN_CRITICAL
2778 int mbedtls_ssl_tls13_parse_record_size_limit_ext(mbedtls_ssl_context *ssl,
2779                                                   const unsigned char *buf,
2780                                                   const unsigned char *end);
2781 
2782 MBEDTLS_CHECK_RETURN_CRITICAL
2783 int mbedtls_ssl_tls13_write_record_size_limit_ext(mbedtls_ssl_context *ssl,
2784                                                   unsigned char *buf,
2785                                                   const unsigned char *end,
2786                                                   size_t *out_len);
2787 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
2788 
2789 #if defined(MBEDTLS_SSL_ALPN)
2790 MBEDTLS_CHECK_RETURN_CRITICAL
2791 int mbedtls_ssl_parse_alpn_ext(mbedtls_ssl_context *ssl,
2792                                const unsigned char *buf,
2793                                const unsigned char *end);
2794 
2795 
2796 MBEDTLS_CHECK_RETURN_CRITICAL
2797 int mbedtls_ssl_write_alpn_ext(mbedtls_ssl_context *ssl,
2798                                unsigned char *buf,
2799                                unsigned char *end,
2800                                size_t *out_len);
2801 #endif /* MBEDTLS_SSL_ALPN */
2802 
2803 #if defined(MBEDTLS_TEST_HOOKS)
2804 int mbedtls_ssl_check_dtls_clihlo_cookie(
2805     mbedtls_ssl_context *ssl,
2806     const unsigned char *cli_id, size_t cli_id_len,
2807     const unsigned char *in, size_t in_len,
2808     unsigned char *obuf, size_t buf_len, size_t *olen);
2809 #endif
2810 
2811 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
2812 /**
2813  * \brief Given an SSL context and its associated configuration, write the TLS
2814  *        1.3 specific Pre-Shared key extension.
2815  *
2816  * \param[in]   ssl     SSL context
2817  * \param[in]   buf     Base address of the buffer where to write the extension
2818  * \param[in]   end     End address of the buffer where to write the extension
2819  * \param[out]  out_len Length in bytes of the Pre-Shared key extension: data
2820  *                      written into the buffer \p buf by this function plus
2821  *                      the length of the binders to be written.
2822  * \param[out]  binders_len Length of the binders to be written at the end of
2823  *                          the extension.
2824  */
2825 MBEDTLS_CHECK_RETURN_CRITICAL
2826 int mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext(
2827     mbedtls_ssl_context *ssl,
2828     unsigned char *buf, unsigned char *end,
2829     size_t *out_len, size_t *binders_len);
2830 
2831 /**
2832  * \brief Given an SSL context and its associated configuration, write the TLS
2833  *        1.3 specific Pre-Shared key extension binders at the end of the
2834  *        ClientHello.
2835  *
2836  * \param[in]   ssl     SSL context
2837  * \param[in]   buf     Base address of the buffer where to write the binders
2838  * \param[in]   end     End address of the buffer where to write the binders
2839  */
2840 MBEDTLS_CHECK_RETURN_CRITICAL
2841 int mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(
2842     mbedtls_ssl_context *ssl,
2843     unsigned char *buf, unsigned char *end);
2844 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
2845 
2846 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
2847     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
2848     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \
2849     defined(MBEDTLS_SSL_CLI_C)
2850 MBEDTLS_CHECK_RETURN_CRITICAL
2851 int mbedtls_ssl_session_set_hostname(mbedtls_ssl_session *session,
2852                                      const char *hostname);
2853 #endif
2854 
2855 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA) && \
2856     defined(MBEDTLS_SSL_ALPN)
2857 MBEDTLS_CHECK_RETURN_CRITICAL
2858 int mbedtls_ssl_session_set_ticket_alpn(mbedtls_ssl_session *session,
2859                                         const char *alpn);
2860 #endif
2861 
2862 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
2863 
2864 #define MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME (604800)
2865 
mbedtls_ssl_tls13_session_get_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2866 static inline unsigned int mbedtls_ssl_tls13_session_get_ticket_flags(
2867     mbedtls_ssl_session *session, unsigned int flags)
2868 {
2869     return session->ticket_flags &
2870            (flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2871 }
2872 
2873 /**
2874  * Check if at least one of the given flags is set in
2875  * the session ticket. See the definition of
2876  * `MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK` to get all
2877  * permitted flags.
2878  */
mbedtls_ssl_tls13_session_ticket_has_flags(mbedtls_ssl_session * session,unsigned int flags)2879 static inline int mbedtls_ssl_tls13_session_ticket_has_flags(
2880     mbedtls_ssl_session *session, unsigned int flags)
2881 {
2882     return mbedtls_ssl_tls13_session_get_ticket_flags(session, flags) != 0;
2883 }
2884 
mbedtls_ssl_tls13_session_ticket_allow_psk(mbedtls_ssl_session * session)2885 static inline int mbedtls_ssl_tls13_session_ticket_allow_psk(
2886     mbedtls_ssl_session *session)
2887 {
2888     return mbedtls_ssl_tls13_session_ticket_has_flags(
2889         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_RESUMPTION);
2890 }
2891 
mbedtls_ssl_tls13_session_ticket_allow_psk_ephemeral(mbedtls_ssl_session * session)2892 static inline int mbedtls_ssl_tls13_session_ticket_allow_psk_ephemeral(
2893     mbedtls_ssl_session *session)
2894 {
2895     return mbedtls_ssl_tls13_session_ticket_has_flags(
2896         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_EPHEMERAL_RESUMPTION);
2897 }
2898 
mbedtls_ssl_tls13_session_ticket_allow_early_data(mbedtls_ssl_session * session)2899 static inline unsigned int mbedtls_ssl_tls13_session_ticket_allow_early_data(
2900     mbedtls_ssl_session *session)
2901 {
2902     return mbedtls_ssl_tls13_session_ticket_has_flags(
2903         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
2904 }
2905 
mbedtls_ssl_tls13_session_set_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2906 static inline void mbedtls_ssl_tls13_session_set_ticket_flags(
2907     mbedtls_ssl_session *session, unsigned int flags)
2908 {
2909     session->ticket_flags |= (flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2910 }
2911 
mbedtls_ssl_tls13_session_clear_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2912 static inline void mbedtls_ssl_tls13_session_clear_ticket_flags(
2913     mbedtls_ssl_session *session, unsigned int flags)
2914 {
2915     session->ticket_flags &= ~(flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2916 }
2917 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_SESSION_TICKETS */
2918 
2919 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
2920 int mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context *ssl);
2921 #endif
2922 
2923 #if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
2924 
2925 /** Compute the HMAC of variable-length data with constant flow.
2926  *
2927  * This function computes the HMAC of the concatenation of \p add_data and \p
2928  * data, and does with a code flow and memory access pattern that does not
2929  * depend on \p data_len_secret, but only on \p min_data_len and \p
2930  * max_data_len. In particular, this function always reads exactly \p
2931  * max_data_len bytes from \p data.
2932  *
2933  * \param ctx               The HMAC context. It must have keys configured
2934  *                          with mbedtls_md_hmac_starts() and use one of the
2935  *                          following hashes: SHA-384, SHA-256, SHA-1 or MD-5.
2936  *                          It is reset using mbedtls_md_hmac_reset() after
2937  *                          the computation is complete to prepare for the
2938  *                          next computation.
2939  * \param add_data          The first part of the message whose HMAC is being
2940  *                          calculated. This must point to a readable buffer
2941  *                          of \p add_data_len bytes.
2942  * \param add_data_len      The length of \p add_data in bytes.
2943  * \param data              The buffer containing the second part of the
2944  *                          message. This must point to a readable buffer
2945  *                          of \p max_data_len bytes.
2946  * \param data_len_secret   The length of the data to process in \p data.
2947  *                          This must be no less than \p min_data_len and no
2948  *                          greater than \p max_data_len.
2949  * \param min_data_len      The minimal length of the second part of the
2950  *                          message, read from \p data.
2951  * \param max_data_len      The maximal length of the second part of the
2952  *                          message, read from \p data.
2953  * \param output            The HMAC will be written here. This must point to
2954  *                          a writable buffer of sufficient size to hold the
2955  *                          HMAC value.
2956  *
2957  * \retval 0 on success.
2958  * \retval #MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED
2959  *         The hardware accelerator failed.
2960  */
2961 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2962 int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
2963                     psa_algorithm_t mac_alg,
2964                     const unsigned char *add_data,
2965                     size_t add_data_len,
2966                     const unsigned char *data,
2967                     size_t data_len_secret,
2968                     size_t min_data_len,
2969                     size_t max_data_len,
2970                     unsigned char *output);
2971 #else
2972 int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
2973                     const unsigned char *add_data,
2974                     size_t add_data_len,
2975                     const unsigned char *data,
2976                     size_t data_len_secret,
2977                     size_t min_data_len,
2978                     size_t max_data_len,
2979                     unsigned char *output);
2980 #endif /* defined(MBEDTLS_USE_PSA_CRYPTO) */
2981 #endif /* MBEDTLS_TEST_HOOKS && defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC) */
2982 
2983 #endif /* ssl_misc.h */
2984