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) || defined(MBEDTLS_SSL_SRV_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  * Verify a certificate.
1678  *
1679  * [in/out] ssl: misc. things read
1680  *               ssl->session_negotiate->verify_result updated
1681  * [in] authmode: one of MBEDTLS_SSL_VERIFY_{NONE,OPTIONAL,REQUIRED}
1682  * [in] chain: the certificate chain to verify (ie the peer's chain)
1683  * [in] ciphersuite_info: For TLS 1.2, this session's ciphersuite;
1684  *                        for TLS 1.3, may be left NULL.
1685  * [in] rs_ctx: restart context if restartable ECC is in use;
1686  *              leave NULL for no restartable behaviour.
1687  *
1688  * Return:
1689  * - 0 if the handshake should continue. Depending on the
1690  *   authmode it means:
1691  *   - REQUIRED: the certificate was found to be valid, trusted & acceptable.
1692  *     ssl->session_negotiate->verify_result is 0.
1693  *   - OPTIONAL: the certificate may or may not be acceptable, but
1694  *     ssl->session_negotiate->verify_result was updated with the result.
1695  *   - NONE: the certificate wasn't even checked.
1696  * - MBEDTLS_ERR_X509_CERT_VERIFY_FAILED or MBEDTLS_ERR_SSL_BAD_CERTIFICATE if
1697  *   the certificate was found to be invalid/untrusted/unacceptable and the
1698  *   handshake should be aborted (can only happen with REQUIRED).
1699  * - another error code if another error happened (out-of-memory, etc.)
1700  */
1701 MBEDTLS_CHECK_RETURN_CRITICAL
1702 int mbedtls_ssl_verify_certificate(mbedtls_ssl_context *ssl,
1703                                    int authmode,
1704                                    mbedtls_x509_crt *chain,
1705                                    const mbedtls_ssl_ciphersuite_t *ciphersuite_info,
1706                                    void *rs_ctx);
1707 
1708 /*
1709  * Check usage of a certificate wrt usage extensions:
1710  * keyUsage and extendedKeyUsage.
1711  * (Note: nSCertType is deprecated and not standard, we don't check it.)
1712  *
1713  * Note: if tls_version is 1.3, ciphersuite is ignored and can be NULL.
1714  *
1715  * Note: recv_endpoint is the receiver's endpoint.
1716  *
1717  * Return 0 if everything is OK, -1 if not.
1718  */
1719 MBEDTLS_CHECK_RETURN_CRITICAL
1720 int mbedtls_ssl_check_cert_usage(const mbedtls_x509_crt *cert,
1721                                  const mbedtls_ssl_ciphersuite_t *ciphersuite,
1722                                  int recv_endpoint,
1723                                  mbedtls_ssl_protocol_version tls_version,
1724                                  uint32_t *flags);
1725 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1726 
1727 void mbedtls_ssl_write_version(unsigned char version[2], int transport,
1728                                mbedtls_ssl_protocol_version tls_version);
1729 uint16_t mbedtls_ssl_read_version(const unsigned char version[2],
1730                                   int transport);
1731 
mbedtls_ssl_in_hdr_len(const mbedtls_ssl_context * ssl)1732 static inline size_t mbedtls_ssl_in_hdr_len(const mbedtls_ssl_context *ssl)
1733 {
1734 #if !defined(MBEDTLS_SSL_PROTO_DTLS)
1735     ((void) ssl);
1736 #endif
1737 
1738 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1739     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1740         return 13;
1741     } else
1742 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1743     {
1744         return 5;
1745     }
1746 }
1747 
mbedtls_ssl_out_hdr_len(const mbedtls_ssl_context * ssl)1748 static inline size_t mbedtls_ssl_out_hdr_len(const mbedtls_ssl_context *ssl)
1749 {
1750     return (size_t) (ssl->out_iv - ssl->out_hdr);
1751 }
1752 
mbedtls_ssl_hs_hdr_len(const mbedtls_ssl_context * ssl)1753 static inline size_t mbedtls_ssl_hs_hdr_len(const mbedtls_ssl_context *ssl)
1754 {
1755 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1756     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1757         return 12;
1758     }
1759 #else
1760     ((void) ssl);
1761 #endif
1762     return 4;
1763 }
1764 
1765 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1766 void mbedtls_ssl_send_flight_completed(mbedtls_ssl_context *ssl);
1767 void mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context *ssl);
1768 MBEDTLS_CHECK_RETURN_CRITICAL
1769 int mbedtls_ssl_resend(mbedtls_ssl_context *ssl);
1770 MBEDTLS_CHECK_RETURN_CRITICAL
1771 int mbedtls_ssl_flight_transmit(mbedtls_ssl_context *ssl);
1772 #endif
1773 
1774 /* Visible for testing purposes only */
1775 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1776 MBEDTLS_CHECK_RETURN_CRITICAL
1777 int mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const *ssl);
1778 void mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context *ssl);
1779 #endif
1780 
1781 MBEDTLS_CHECK_RETURN_CRITICAL
1782 int mbedtls_ssl_session_copy(mbedtls_ssl_session *dst,
1783                              const mbedtls_ssl_session *src);
1784 
1785 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1786 /* The hash buffer must have at least MBEDTLS_MD_MAX_SIZE bytes of length. */
1787 MBEDTLS_CHECK_RETURN_CRITICAL
1788 int mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context *ssl,
1789                                            unsigned char *hash, size_t *hashlen,
1790                                            unsigned char *data, size_t data_len,
1791                                            mbedtls_md_type_t md_alg);
1792 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1793 
1794 #ifdef __cplusplus
1795 }
1796 #endif
1797 
1798 void mbedtls_ssl_transform_init(mbedtls_ssl_transform *transform);
1799 MBEDTLS_CHECK_RETURN_CRITICAL
1800 int mbedtls_ssl_encrypt_buf(mbedtls_ssl_context *ssl,
1801                             mbedtls_ssl_transform *transform,
1802                             mbedtls_record *rec,
1803                             int (*f_rng)(void *, unsigned char *, size_t),
1804                             void *p_rng);
1805 MBEDTLS_CHECK_RETURN_CRITICAL
1806 int mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const *ssl,
1807                             mbedtls_ssl_transform *transform,
1808                             mbedtls_record *rec);
1809 
1810 /* Length of the "epoch" field in the record header */
mbedtls_ssl_ep_len(const mbedtls_ssl_context * ssl)1811 static inline size_t mbedtls_ssl_ep_len(const mbedtls_ssl_context *ssl)
1812 {
1813 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1814     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1815         return 2;
1816     }
1817 #else
1818     ((void) ssl);
1819 #endif
1820     return 0;
1821 }
1822 
1823 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1824 MBEDTLS_CHECK_RETURN_CRITICAL
1825 int mbedtls_ssl_resend_hello_request(mbedtls_ssl_context *ssl);
1826 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1827 
1828 void mbedtls_ssl_set_timer(mbedtls_ssl_context *ssl, uint32_t millisecs);
1829 MBEDTLS_CHECK_RETURN_CRITICAL
1830 int mbedtls_ssl_check_timer(mbedtls_ssl_context *ssl);
1831 
1832 void mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context *ssl);
1833 void mbedtls_ssl_update_out_pointers(mbedtls_ssl_context *ssl,
1834                                      mbedtls_ssl_transform *transform);
1835 void mbedtls_ssl_update_in_pointers(mbedtls_ssl_context *ssl);
1836 
1837 MBEDTLS_CHECK_RETURN_CRITICAL
1838 int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial);
1839 void mbedtls_ssl_session_reset_msg_layer(mbedtls_ssl_context *ssl,
1840                                          int partial);
1841 
1842 /*
1843  * Send pending alert
1844  */
1845 MBEDTLS_CHECK_RETURN_CRITICAL
1846 int mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context *ssl);
1847 
1848 /*
1849  * Set pending fatal alert flag.
1850  */
1851 void mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context *ssl,
1852                                   unsigned char alert_type,
1853                                   int alert_reason);
1854 
1855 /* Alias of mbedtls_ssl_pend_fatal_alert */
1856 #define MBEDTLS_SSL_PEND_FATAL_ALERT(type, user_return_value)         \
1857     mbedtls_ssl_pend_fatal_alert(ssl, type, user_return_value)
1858 
1859 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1860 void mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context *ssl);
1861 #endif
1862 
1863 void mbedtls_ssl_handshake_wrapup_free_hs_transform(mbedtls_ssl_context *ssl);
1864 
1865 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1866 MBEDTLS_CHECK_RETURN_CRITICAL
1867 int mbedtls_ssl_start_renegotiation(mbedtls_ssl_context *ssl);
1868 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1869 
1870 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1871 size_t mbedtls_ssl_get_current_mtu(const mbedtls_ssl_context *ssl);
1872 void mbedtls_ssl_buffering_free(mbedtls_ssl_context *ssl);
1873 void mbedtls_ssl_flight_free(mbedtls_ssl_flight_item *flight);
1874 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1875 
1876 /**
1877  * ssl utils functions for checking configuration.
1878  */
1879 
1880 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_ssl_conf_is_tls13_only(const mbedtls_ssl_config * conf)1881 static inline int mbedtls_ssl_conf_is_tls13_only(const mbedtls_ssl_config *conf)
1882 {
1883     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_3 &&
1884            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_3;
1885 }
1886 
1887 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1888 
1889 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_ssl_conf_is_tls12_only(const mbedtls_ssl_config * conf)1890 static inline int mbedtls_ssl_conf_is_tls12_only(const mbedtls_ssl_config *conf)
1891 {
1892     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_2 &&
1893            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_2;
1894 }
1895 
1896 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1897 
mbedtls_ssl_conf_is_tls13_enabled(const mbedtls_ssl_config * conf)1898 static inline int mbedtls_ssl_conf_is_tls13_enabled(const mbedtls_ssl_config *conf)
1899 {
1900 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1901     return conf->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_3 &&
1902            conf->max_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3;
1903 #else
1904     ((void) conf);
1905     return 0;
1906 #endif
1907 }
1908 
mbedtls_ssl_conf_is_tls12_enabled(const mbedtls_ssl_config * conf)1909 static inline int mbedtls_ssl_conf_is_tls12_enabled(const mbedtls_ssl_config *conf)
1910 {
1911 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1912     return conf->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_2 &&
1913            conf->max_tls_version >= MBEDTLS_SSL_VERSION_TLS1_2;
1914 #else
1915     ((void) conf);
1916     return 0;
1917 #endif
1918 }
1919 
1920 #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)1921 static inline int mbedtls_ssl_conf_is_hybrid_tls12_tls13(const mbedtls_ssl_config *conf)
1922 {
1923     return conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_2 &&
1924            conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_3;
1925 }
1926 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_SSL_PROTO_TLS1_3 */
1927 
1928 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1929 
1930 /** \brief Initialize the PSA crypto subsystem if necessary.
1931  *
1932  * Call this function before doing any cryptography in a TLS 1.3 handshake.
1933  *
1934  * This is necessary in Mbed TLS 3.x for backward compatibility.
1935  * Up to Mbed TLS 3.5, in the default configuration, you could perform
1936  * a TLS connection with default parameters without having called
1937  * psa_crypto_init(), since the TLS layer only supported TLS 1.2 and
1938  * did not use PSA crypto. (TLS 1.2 only uses PSA crypto if
1939  * MBEDTLS_USE_PSA_CRYPTO is enabled, which is not the case in the default
1940  * configuration.) Starting with Mbed TLS 3.6.0, TLS 1.3 is enabled
1941  * by default, and the TLS 1.3 layer uses PSA crypto. This means that
1942  * applications that are not otherwise using PSA crypto and that worked
1943  * with Mbed TLS 3.5 started failing in TLS 3.6.0 if they connected to
1944  * a peer that supports TLS 1.3. See
1945  * https://github.com/Mbed-TLS/mbedtls/issues/9072
1946  */
1947 int mbedtls_ssl_tls13_crypto_init(mbedtls_ssl_context *ssl);
1948 
1949 extern const uint8_t mbedtls_ssl_tls13_hello_retry_request_magic[
1950     MBEDTLS_SERVER_HELLO_RANDOM_LEN];
1951 MBEDTLS_CHECK_RETURN_CRITICAL
1952 int mbedtls_ssl_tls13_process_finished_message(mbedtls_ssl_context *ssl);
1953 MBEDTLS_CHECK_RETURN_CRITICAL
1954 int mbedtls_ssl_tls13_write_finished_message(mbedtls_ssl_context *ssl);
1955 void mbedtls_ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl);
1956 
1957 /**
1958  * \brief Given an SSL context and its associated configuration, write the TLS
1959  *        1.3 specific extensions of the ClientHello message.
1960  *
1961  * \param[in]   ssl     SSL context
1962  * \param[in]   buf     Base address of the buffer where to write the extensions
1963  * \param[in]   end     End address of the buffer where to write the extensions
1964  * \param[out]  out_len Length of the data written into the buffer \p buf
1965  */
1966 MBEDTLS_CHECK_RETURN_CRITICAL
1967 int mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context *ssl,
1968                                               unsigned char *buf,
1969                                               unsigned char *end,
1970                                               size_t *out_len);
1971 
1972 /**
1973  * \brief           TLS 1.3 client side state machine entry
1974  *
1975  * \param ssl       SSL context
1976  */
1977 MBEDTLS_CHECK_RETURN_CRITICAL
1978 int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl);
1979 
1980 /**
1981  * \brief           TLS 1.3 server side state machine entry
1982  *
1983  * \param ssl       SSL context
1984  */
1985 MBEDTLS_CHECK_RETURN_CRITICAL
1986 int mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context *ssl);
1987 
1988 
1989 /*
1990  * Helper functions around key exchange modes.
1991  */
mbedtls_ssl_conf_tls13_is_kex_mode_enabled(mbedtls_ssl_context * ssl,int kex_mode_mask)1992 static inline int mbedtls_ssl_conf_tls13_is_kex_mode_enabled(mbedtls_ssl_context *ssl,
1993                                                              int kex_mode_mask)
1994 {
1995     return (ssl->conf->tls13_kex_modes & kex_mode_mask) != 0;
1996 }
1997 
mbedtls_ssl_conf_tls13_is_psk_enabled(mbedtls_ssl_context * ssl)1998 static inline int mbedtls_ssl_conf_tls13_is_psk_enabled(mbedtls_ssl_context *ssl)
1999 {
2000     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
2001                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK);
2002 }
2003 
mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(mbedtls_ssl_context * ssl)2004 static inline int mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(mbedtls_ssl_context *ssl)
2005 {
2006     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
2007                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL);
2008 }
2009 
mbedtls_ssl_conf_tls13_is_ephemeral_enabled(mbedtls_ssl_context * ssl)2010 static inline int mbedtls_ssl_conf_tls13_is_ephemeral_enabled(mbedtls_ssl_context *ssl)
2011 {
2012     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
2013                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL);
2014 }
2015 
mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(mbedtls_ssl_context * ssl)2016 static inline int mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(mbedtls_ssl_context *ssl)
2017 {
2018     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
2019                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
2020 }
2021 
mbedtls_ssl_conf_tls13_is_some_psk_enabled(mbedtls_ssl_context * ssl)2022 static inline int mbedtls_ssl_conf_tls13_is_some_psk_enabled(mbedtls_ssl_context *ssl)
2023 {
2024     return mbedtls_ssl_conf_tls13_is_kex_mode_enabled(ssl,
2025                                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
2026 }
2027 
2028 #if defined(MBEDTLS_SSL_SRV_C) && \
2029     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
2030 /**
2031  * Given a list of key exchange modes, check if at least one of them is
2032  * supported by peer.
2033  *
2034  * \param[in] ssl  SSL context
2035  * \param kex_modes_mask  Mask of the key exchange modes to check
2036  *
2037  * \return Non-zero if at least one of the key exchange modes is supported by
2038  *         the peer, otherwise \c 0.
2039  */
mbedtls_ssl_tls13_is_kex_mode_supported(mbedtls_ssl_context * ssl,int kex_modes_mask)2040 static inline int mbedtls_ssl_tls13_is_kex_mode_supported(mbedtls_ssl_context *ssl,
2041                                                           int kex_modes_mask)
2042 {
2043     return (ssl->handshake->tls13_kex_modes & kex_modes_mask) != 0;
2044 }
2045 
mbedtls_ssl_tls13_is_psk_supported(mbedtls_ssl_context * ssl)2046 static inline int mbedtls_ssl_tls13_is_psk_supported(mbedtls_ssl_context *ssl)
2047 {
2048     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2049                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK);
2050 }
2051 
mbedtls_ssl_tls13_is_psk_ephemeral_supported(mbedtls_ssl_context * ssl)2052 static inline int mbedtls_ssl_tls13_is_psk_ephemeral_supported(
2053     mbedtls_ssl_context *ssl)
2054 {
2055     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2056                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL);
2057 }
2058 
mbedtls_ssl_tls13_is_ephemeral_supported(mbedtls_ssl_context * ssl)2059 static inline int mbedtls_ssl_tls13_is_ephemeral_supported(mbedtls_ssl_context *ssl)
2060 {
2061     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2062                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL);
2063 }
2064 
mbedtls_ssl_tls13_is_some_ephemeral_supported(mbedtls_ssl_context * ssl)2065 static inline int mbedtls_ssl_tls13_is_some_ephemeral_supported(mbedtls_ssl_context *ssl)
2066 {
2067     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2068                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
2069 }
2070 
mbedtls_ssl_tls13_is_some_psk_supported(mbedtls_ssl_context * ssl)2071 static inline int mbedtls_ssl_tls13_is_some_psk_supported(mbedtls_ssl_context *ssl)
2072 {
2073     return mbedtls_ssl_tls13_is_kex_mode_supported(ssl,
2074                                                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
2075 }
2076 #endif /* MBEDTLS_SSL_SRV_C &&
2077           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
2078 
2079 /*
2080  * Helper functions for extensions checking.
2081  */
2082 
2083 MBEDTLS_CHECK_RETURN_CRITICAL
2084 int mbedtls_ssl_tls13_check_received_extension(
2085     mbedtls_ssl_context *ssl,
2086     int hs_msg_type,
2087     unsigned int received_extension_type,
2088     uint32_t hs_msg_allowed_extensions_mask);
2089 
mbedtls_ssl_tls13_set_hs_sent_ext_mask(mbedtls_ssl_context * ssl,unsigned int extension_type)2090 static inline void mbedtls_ssl_tls13_set_hs_sent_ext_mask(
2091     mbedtls_ssl_context *ssl, unsigned int extension_type)
2092 {
2093     ssl->handshake->sent_extensions |=
2094         mbedtls_ssl_get_extension_mask(extension_type);
2095 }
2096 
2097 /*
2098  * Helper functions to check the selected key exchange mode.
2099  */
mbedtls_ssl_tls13_key_exchange_mode_check(mbedtls_ssl_context * ssl,int kex_mask)2100 static inline int mbedtls_ssl_tls13_key_exchange_mode_check(
2101     mbedtls_ssl_context *ssl, int kex_mask)
2102 {
2103     return (ssl->handshake->key_exchange_mode & kex_mask) != 0;
2104 }
2105 
mbedtls_ssl_tls13_key_exchange_mode_with_psk(mbedtls_ssl_context * ssl)2106 static inline int mbedtls_ssl_tls13_key_exchange_mode_with_psk(
2107     mbedtls_ssl_context *ssl)
2108 {
2109     return mbedtls_ssl_tls13_key_exchange_mode_check(ssl,
2110                                                      MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL);
2111 }
2112 
mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(mbedtls_ssl_context * ssl)2113 static inline int mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(
2114     mbedtls_ssl_context *ssl)
2115 {
2116     return mbedtls_ssl_tls13_key_exchange_mode_check(ssl,
2117                                                      MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL);
2118 }
2119 
2120 /*
2121  * Fetch TLS 1.3 handshake message header
2122  */
2123 MBEDTLS_CHECK_RETURN_CRITICAL
2124 int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
2125                                           unsigned hs_type,
2126                                           unsigned char **buf,
2127                                           size_t *buf_len);
2128 
2129 /**
2130  * \brief Detect if a list of extensions contains a supported_versions
2131  *        extension or not.
2132  *
2133  * \param[in] ssl  SSL context
2134  * \param[in] buf  Address of the first byte of the extensions vector.
2135  * \param[in] end  End of the buffer containing the list of extensions.
2136  * \param[out] supported_versions_data  If the extension is present, address of
2137  *                                      its first byte of data, NULL otherwise.
2138  * \param[out] supported_versions_data_end  If the extension is present, address
2139  *                                          of the first byte immediately
2140  *                                          following the extension data, NULL
2141  *                                          otherwise.
2142  * \return 0  if the list of extensions does not contain a supported_versions
2143  *            extension.
2144  * \return 1  if the list of extensions contains a supported_versions
2145  *            extension.
2146  * \return    A negative value if an error occurred while parsing the
2147  *            extensions.
2148  */
2149 MBEDTLS_CHECK_RETURN_CRITICAL
2150 int mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
2151     mbedtls_ssl_context *ssl,
2152     const unsigned char *buf, const unsigned char *end,
2153     const unsigned char **supported_versions_data,
2154     const unsigned char **supported_versions_data_end);
2155 
2156 /*
2157  * Handler of TLS 1.3 server certificate message
2158  */
2159 MBEDTLS_CHECK_RETURN_CRITICAL
2160 int mbedtls_ssl_tls13_process_certificate(mbedtls_ssl_context *ssl);
2161 
2162 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2163 /*
2164  * Handler of TLS 1.3 write Certificate message
2165  */
2166 MBEDTLS_CHECK_RETURN_CRITICAL
2167 int mbedtls_ssl_tls13_write_certificate(mbedtls_ssl_context *ssl);
2168 
2169 /*
2170  * Handler of TLS 1.3 write Certificate Verify message
2171  */
2172 MBEDTLS_CHECK_RETURN_CRITICAL
2173 int mbedtls_ssl_tls13_write_certificate_verify(mbedtls_ssl_context *ssl);
2174 
2175 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2176 
2177 /*
2178  * Generic handler of Certificate Verify
2179  */
2180 MBEDTLS_CHECK_RETURN_CRITICAL
2181 int mbedtls_ssl_tls13_process_certificate_verify(mbedtls_ssl_context *ssl);
2182 
2183 /*
2184  * Write of dummy-CCS's for middlebox compatibility
2185  */
2186 MBEDTLS_CHECK_RETURN_CRITICAL
2187 int mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context *ssl);
2188 
2189 MBEDTLS_CHECK_RETURN_CRITICAL
2190 int mbedtls_ssl_reset_transcript_for_hrr(mbedtls_ssl_context *ssl);
2191 
2192 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
2193 MBEDTLS_CHECK_RETURN_CRITICAL
2194 int mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
2195     mbedtls_ssl_context *ssl,
2196     uint16_t named_group,
2197     unsigned char *buf,
2198     unsigned char *end,
2199     size_t *out_len);
2200 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
2201 
2202 #if defined(MBEDTLS_SSL_EARLY_DATA)
2203 int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
2204                                            int in_new_session_ticket,
2205                                            unsigned char *buf,
2206                                            const unsigned char *end,
2207                                            size_t *out_len);
2208 
2209 int mbedtls_ssl_tls13_check_early_data_len(mbedtls_ssl_context *ssl,
2210                                            size_t early_data_len);
2211 
2212 typedef enum {
2213 /*
2214  * The client has not sent the first ClientHello yet, the negotiation of early
2215  * data has not started yet.
2216  */
2217     MBEDTLS_SSL_EARLY_DATA_STATE_IDLE,
2218 
2219 /*
2220  * In its ClientHello, the client has not included an early data indication
2221  * extension.
2222  */
2223     MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT,
2224 
2225 /*
2226  * The client has sent an early data indication extension in its first
2227  * ClientHello, it has not received the response (ServerHello or
2228  * HelloRetryRequest) from the server yet. The transform to protect early data
2229  * is not set either as for middlebox compatibility a dummy CCS may have to be
2230  * sent in clear. Early data cannot be sent to the server yet.
2231  */
2232     MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT,
2233 
2234 /*
2235  * The client has sent an early data indication extension in its first
2236  * ClientHello, it has not received the response (ServerHello or
2237  * HelloRetryRequest) from the server yet. The transform to protect early data
2238  * has been set and early data can be written now.
2239  */
2240     MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE,
2241 
2242 /*
2243  * The client has indicated the use of early data and the server has accepted
2244  * it.
2245  */
2246     MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED,
2247 
2248 /*
2249  * The client has indicated the use of early data but the server has rejected
2250  * it.
2251  */
2252     MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED,
2253 
2254 /*
2255  * The client has sent an early data indication extension in its first
2256  * ClientHello, the server has accepted them and the client has received the
2257  * server Finished message. It cannot send early data to the server anymore.
2258  */
2259     MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED,
2260 
2261 } mbedtls_ssl_early_data_state;
2262 #endif /* MBEDTLS_SSL_EARLY_DATA */
2263 
2264 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2265 
2266 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2267 /*
2268  * Write Signature Algorithm extension
2269  */
2270 MBEDTLS_CHECK_RETURN_CRITICAL
2271 int mbedtls_ssl_write_sig_alg_ext(mbedtls_ssl_context *ssl, unsigned char *buf,
2272                                   const unsigned char *end, size_t *out_len);
2273 /*
2274  * Parse TLS Signature Algorithm extension
2275  */
2276 MBEDTLS_CHECK_RETURN_CRITICAL
2277 int mbedtls_ssl_parse_sig_alg_ext(mbedtls_ssl_context *ssl,
2278                                   const unsigned char *buf,
2279                                   const unsigned char *end);
2280 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2281 
2282 /* Get handshake transcript */
2283 MBEDTLS_CHECK_RETURN_CRITICAL
2284 int mbedtls_ssl_get_handshake_transcript(mbedtls_ssl_context *ssl,
2285                                          const mbedtls_md_type_t md,
2286                                          unsigned char *dst,
2287                                          size_t dst_len,
2288                                          size_t *olen);
2289 
2290 /*
2291  * Return supported groups.
2292  *
2293  * In future, invocations can be changed to ssl->conf->group_list
2294  * when mbedtls_ssl_conf_curves() is deleted.
2295  *
2296  * ssl->handshake->group_list is either a translation of curve_list to IANA TLS group
2297  * identifiers when mbedtls_ssl_conf_curves() has been used, or a pointer to
2298  * ssl->conf->group_list when mbedtls_ssl_conf_groups() has been more recently invoked.
2299  *
2300  */
mbedtls_ssl_get_groups(const mbedtls_ssl_context * ssl)2301 static inline const void *mbedtls_ssl_get_groups(const mbedtls_ssl_context *ssl)
2302 {
2303     #if defined(MBEDTLS_DEPRECATED_REMOVED) || !defined(MBEDTLS_ECP_C)
2304     return ssl->conf->group_list;
2305     #else
2306     if ((ssl->handshake != NULL) && (ssl->handshake->group_list != NULL)) {
2307         return ssl->handshake->group_list;
2308     } else {
2309         return ssl->conf->group_list;
2310     }
2311     #endif
2312 }
2313 
2314 /*
2315  * Helper functions for NamedGroup.
2316  */
mbedtls_ssl_tls12_named_group_is_ecdhe(uint16_t named_group)2317 static inline int mbedtls_ssl_tls12_named_group_is_ecdhe(uint16_t named_group)
2318 {
2319     /*
2320      * RFC 8422 section 5.1.1
2321      */
2322     return named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X25519    ||
2323            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP256R1   ||
2324            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP384R1   ||
2325            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_BP512R1   ||
2326            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X448      ||
2327            /* Below deprecated curves should be removed with notice to users */
2328            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP192K1 ||
2329            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1 ||
2330            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP224K1 ||
2331            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1 ||
2332            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256K1 ||
2333            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 ||
2334            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 ||
2335            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1;
2336 }
2337 
mbedtls_ssl_tls13_named_group_is_ecdhe(uint16_t named_group)2338 static inline int mbedtls_ssl_tls13_named_group_is_ecdhe(uint16_t named_group)
2339 {
2340     return named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X25519    ||
2341            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 ||
2342            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 ||
2343            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1 ||
2344            named_group == MBEDTLS_SSL_IANA_TLS_GROUP_X448;
2345 }
2346 
mbedtls_ssl_tls13_named_group_is_ffdh(uint16_t named_group)2347 static inline int mbedtls_ssl_tls13_named_group_is_ffdh(uint16_t named_group)
2348 {
2349     return named_group >= MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048 &&
2350            named_group <= MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192;
2351 }
2352 
mbedtls_ssl_named_group_is_offered(const mbedtls_ssl_context * ssl,uint16_t named_group)2353 static inline int mbedtls_ssl_named_group_is_offered(
2354     const mbedtls_ssl_context *ssl, uint16_t named_group)
2355 {
2356     const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
2357 
2358     if (group_list == NULL) {
2359         return 0;
2360     }
2361 
2362     for (; *group_list != 0; group_list++) {
2363         if (*group_list == named_group) {
2364             return 1;
2365         }
2366     }
2367 
2368     return 0;
2369 }
2370 
mbedtls_ssl_named_group_is_supported(uint16_t named_group)2371 static inline int mbedtls_ssl_named_group_is_supported(uint16_t named_group)
2372 {
2373 #if defined(PSA_WANT_ALG_ECDH)
2374     if (mbedtls_ssl_tls13_named_group_is_ecdhe(named_group)) {
2375         if (mbedtls_ssl_get_ecp_group_id_from_tls_id(named_group) !=
2376             MBEDTLS_ECP_DP_NONE) {
2377             return 1;
2378         }
2379     }
2380 #endif
2381 #if defined(PSA_WANT_ALG_FFDH)
2382     if (mbedtls_ssl_tls13_named_group_is_ffdh(named_group)) {
2383         return 1;
2384     }
2385 #endif
2386 #if !defined(PSA_WANT_ALG_ECDH) && !defined(PSA_WANT_ALG_FFDH)
2387     (void) named_group;
2388 #endif
2389     return 0;
2390 }
2391 
2392 /*
2393  * Return supported signature algorithms.
2394  *
2395  * In future, invocations can be changed to ssl->conf->sig_algs when
2396  * mbedtls_ssl_conf_sig_hashes() is deleted.
2397  *
2398  * ssl->handshake->sig_algs is either a translation of sig_hashes to IANA TLS
2399  * signature algorithm identifiers when mbedtls_ssl_conf_sig_hashes() has been
2400  * used, or a pointer to ssl->conf->sig_algs when mbedtls_ssl_conf_sig_algs() has
2401  * been more recently invoked.
2402  *
2403  */
mbedtls_ssl_get_sig_algs(const mbedtls_ssl_context * ssl)2404 static inline const void *mbedtls_ssl_get_sig_algs(
2405     const mbedtls_ssl_context *ssl)
2406 {
2407 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2408 
2409 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2410     if (ssl->handshake != NULL &&
2411         ssl->handshake->sig_algs_heap_allocated == 1 &&
2412         ssl->handshake->sig_algs != NULL) {
2413         return ssl->handshake->sig_algs;
2414     }
2415 #endif
2416     return ssl->conf->sig_algs;
2417 
2418 #else /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2419 
2420     ((void) ssl);
2421     return NULL;
2422 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2423 }
2424 
2425 #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)2426 static inline int mbedtls_ssl_sig_alg_is_received(const mbedtls_ssl_context *ssl,
2427                                                   uint16_t own_sig_alg)
2428 {
2429     const uint16_t *sig_alg = ssl->handshake->received_sig_algs;
2430     if (sig_alg == NULL) {
2431         return 0;
2432     }
2433 
2434     for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2435         if (*sig_alg == own_sig_alg) {
2436             return 1;
2437         }
2438     }
2439     return 0;
2440 }
2441 
mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(const uint16_t sig_alg)2442 static inline int mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(
2443     const uint16_t sig_alg)
2444 {
2445     switch (sig_alg) {
2446 #if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
2447 #if defined(PSA_WANT_ALG_SHA_256) && defined(PSA_WANT_ECC_SECP_R1_256)
2448         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256:
2449             break;
2450 #endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_ECP_DP_SECP256R1_ENABLED */
2451 #if defined(PSA_WANT_ALG_SHA_384) && defined(PSA_WANT_ECC_SECP_R1_384)
2452         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384:
2453             break;
2454 #endif /* PSA_WANT_ALG_SHA_384 && MBEDTLS_ECP_DP_SECP384R1_ENABLED */
2455 #if defined(PSA_WANT_ALG_SHA_512) && defined(PSA_WANT_ECC_SECP_R1_521)
2456         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512:
2457             break;
2458 #endif /* PSA_WANT_ALG_SHA_512 && MBEDTLS_ECP_DP_SECP521R1_ENABLED */
2459 #endif /* MBEDTLS_PK_CAN_ECDSA_SOME */
2460 
2461 #if defined(MBEDTLS_PKCS1_V21)
2462 #if defined(PSA_WANT_ALG_SHA_256)
2463         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
2464             break;
2465 #endif /* PSA_WANT_ALG_SHA_256  */
2466 #if defined(PSA_WANT_ALG_SHA_384)
2467         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
2468             break;
2469 #endif /* PSA_WANT_ALG_SHA_384 */
2470 #if defined(PSA_WANT_ALG_SHA_512)
2471         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
2472             break;
2473 #endif /* PSA_WANT_ALG_SHA_512 */
2474 #endif /* MBEDTLS_PKCS1_V21 */
2475         default:
2476             return 0;
2477     }
2478     return 1;
2479 
2480 }
2481 
mbedtls_ssl_tls13_sig_alg_is_supported(const uint16_t sig_alg)2482 static inline int mbedtls_ssl_tls13_sig_alg_is_supported(
2483     const uint16_t sig_alg)
2484 {
2485     switch (sig_alg) {
2486 #if defined(MBEDTLS_PKCS1_V15)
2487 #if defined(MBEDTLS_MD_CAN_SHA256)
2488         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256:
2489             break;
2490 #endif /* MBEDTLS_MD_CAN_SHA256 */
2491 #if defined(MBEDTLS_MD_CAN_SHA384)
2492         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384:
2493             break;
2494 #endif /* MBEDTLS_MD_CAN_SHA384 */
2495 #if defined(MBEDTLS_MD_CAN_SHA512)
2496         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512:
2497             break;
2498 #endif /* MBEDTLS_MD_CAN_SHA512 */
2499 #endif /* MBEDTLS_PKCS1_V15 */
2500         default:
2501             return mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(
2502                 sig_alg);
2503     }
2504     return 1;
2505 }
2506 
2507 MBEDTLS_CHECK_RETURN_CRITICAL
2508 int mbedtls_ssl_tls13_check_sig_alg_cert_key_match(uint16_t sig_alg,
2509                                                    mbedtls_pk_context *key);
2510 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2511 
2512 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
mbedtls_ssl_sig_alg_is_offered(const mbedtls_ssl_context * ssl,uint16_t proposed_sig_alg)2513 static inline int mbedtls_ssl_sig_alg_is_offered(const mbedtls_ssl_context *ssl,
2514                                                  uint16_t proposed_sig_alg)
2515 {
2516     const uint16_t *sig_alg = mbedtls_ssl_get_sig_algs(ssl);
2517     if (sig_alg == NULL) {
2518         return 0;
2519     }
2520 
2521     for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2522         if (*sig_alg == proposed_sig_alg) {
2523             return 1;
2524         }
2525     }
2526     return 0;
2527 }
2528 
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)2529 static inline int mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
2530     uint16_t sig_alg, mbedtls_pk_type_t *pk_type, mbedtls_md_type_t *md_alg)
2531 {
2532     *pk_type = mbedtls_ssl_pk_alg_from_sig(sig_alg & 0xff);
2533     *md_alg = mbedtls_ssl_md_alg_from_hash((sig_alg >> 8) & 0xff);
2534 
2535     if (*pk_type != MBEDTLS_PK_NONE && *md_alg != MBEDTLS_MD_NONE) {
2536         return 0;
2537     }
2538 
2539     switch (sig_alg) {
2540 #if defined(MBEDTLS_PKCS1_V21)
2541 #if defined(MBEDTLS_MD_CAN_SHA256)
2542         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
2543             *md_alg = MBEDTLS_MD_SHA256;
2544             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2545             break;
2546 #endif /* MBEDTLS_MD_CAN_SHA256  */
2547 #if defined(MBEDTLS_MD_CAN_SHA384)
2548         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
2549             *md_alg = MBEDTLS_MD_SHA384;
2550             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2551             break;
2552 #endif /* MBEDTLS_MD_CAN_SHA384 */
2553 #if defined(MBEDTLS_MD_CAN_SHA512)
2554         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
2555             *md_alg = MBEDTLS_MD_SHA512;
2556             *pk_type = MBEDTLS_PK_RSASSA_PSS;
2557             break;
2558 #endif /* MBEDTLS_MD_CAN_SHA512 */
2559 #endif /* MBEDTLS_PKCS1_V21 */
2560         default:
2561             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2562     }
2563     return 0;
2564 }
2565 
2566 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_ssl_tls12_sig_alg_is_supported(const uint16_t sig_alg)2567 static inline int mbedtls_ssl_tls12_sig_alg_is_supported(
2568     const uint16_t sig_alg)
2569 {
2570     /* High byte is hash */
2571     unsigned char hash = MBEDTLS_BYTE_1(sig_alg);
2572     unsigned char sig = MBEDTLS_BYTE_0(sig_alg);
2573 
2574     switch (hash) {
2575 #if defined(MBEDTLS_MD_CAN_MD5)
2576         case MBEDTLS_SSL_HASH_MD5:
2577             break;
2578 #endif
2579 
2580 #if defined(MBEDTLS_MD_CAN_SHA1)
2581         case MBEDTLS_SSL_HASH_SHA1:
2582             break;
2583 #endif
2584 
2585 #if defined(MBEDTLS_MD_CAN_SHA224)
2586         case MBEDTLS_SSL_HASH_SHA224:
2587             break;
2588 #endif
2589 
2590 #if defined(MBEDTLS_MD_CAN_SHA256)
2591         case MBEDTLS_SSL_HASH_SHA256:
2592             break;
2593 #endif
2594 
2595 #if defined(MBEDTLS_MD_CAN_SHA384)
2596         case MBEDTLS_SSL_HASH_SHA384:
2597             break;
2598 #endif
2599 
2600 #if defined(MBEDTLS_MD_CAN_SHA512)
2601         case MBEDTLS_SSL_HASH_SHA512:
2602             break;
2603 #endif
2604 
2605         default:
2606             return 0;
2607     }
2608 
2609     switch (sig) {
2610 #if defined(MBEDTLS_RSA_C)
2611         case MBEDTLS_SSL_SIG_RSA:
2612             break;
2613 #endif
2614 
2615 #if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
2616         case MBEDTLS_SSL_SIG_ECDSA:
2617             break;
2618 #endif
2619 
2620         default:
2621             return 0;
2622     }
2623 
2624     return 1;
2625 }
2626 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2627 
mbedtls_ssl_sig_alg_is_supported(const mbedtls_ssl_context * ssl,const uint16_t sig_alg)2628 static inline int mbedtls_ssl_sig_alg_is_supported(
2629     const mbedtls_ssl_context *ssl,
2630     const uint16_t sig_alg)
2631 {
2632 
2633 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2634     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2635         return mbedtls_ssl_tls12_sig_alg_is_supported(sig_alg);
2636     }
2637 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2638 
2639 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2640     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2641         return mbedtls_ssl_tls13_sig_alg_is_supported(sig_alg);
2642     }
2643 #endif
2644     ((void) ssl);
2645     ((void) sig_alg);
2646     return 0;
2647 }
2648 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2649 
2650 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
2651 /* Corresponding PSA algorithm for MBEDTLS_CIPHER_NULL.
2652  * Same value is used for PSA_ALG_CATEGORY_CIPHER, hence it is
2653  * guaranteed to not be a valid PSA algorithm identifier.
2654  */
2655 #define MBEDTLS_SSL_NULL_CIPHER 0x04000000
2656 
2657 /**
2658  * \brief       Translate mbedtls cipher type/taglen pair to psa:
2659  *              algorithm, key type and key size.
2660  *
2661  * \param  mbedtls_cipher_type [in] given mbedtls cipher type
2662  * \param  taglen              [in] given tag length
2663  *                                  0 - default tag length
2664  * \param  alg                 [out] corresponding PSA alg
2665  *                                   There is no corresponding PSA
2666  *                                   alg for MBEDTLS_CIPHER_NULL, so
2667  *                                   in this case MBEDTLS_SSL_NULL_CIPHER
2668  *                                   is returned via this parameter
2669  * \param  key_type            [out] corresponding PSA key type
2670  * \param  key_size            [out] corresponding PSA key size
2671  *
2672  * \return                     PSA_SUCCESS on success or PSA_ERROR_NOT_SUPPORTED if
2673  *                             conversion is not supported.
2674  */
2675 psa_status_t mbedtls_ssl_cipher_to_psa(mbedtls_cipher_type_t mbedtls_cipher_type,
2676                                        size_t taglen,
2677                                        psa_algorithm_t *alg,
2678                                        psa_key_type_t *key_type,
2679                                        size_t *key_size);
2680 
2681 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2682 /**
2683  * \brief       Convert given PSA status to mbedtls error code.
2684  *
2685  * \param  status      [in] given PSA status
2686  *
2687  * \return             corresponding mbedtls error code
2688  */
psa_ssl_status_to_mbedtls(psa_status_t status)2689 static inline MBEDTLS_DEPRECATED int psa_ssl_status_to_mbedtls(psa_status_t status)
2690 {
2691     switch (status) {
2692         case PSA_SUCCESS:
2693             return 0;
2694         case PSA_ERROR_INSUFFICIENT_MEMORY:
2695             return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2696         case PSA_ERROR_NOT_SUPPORTED:
2697             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2698         case PSA_ERROR_INVALID_SIGNATURE:
2699             return MBEDTLS_ERR_SSL_INVALID_MAC;
2700         case PSA_ERROR_INVALID_ARGUMENT:
2701             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2702         case PSA_ERROR_BAD_STATE:
2703             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2704         case PSA_ERROR_BUFFER_TOO_SMALL:
2705             return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
2706         default:
2707             return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
2708     }
2709 }
2710 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
2711 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
2712 
2713 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
2714     defined(MBEDTLS_USE_PSA_CRYPTO)
2715 
2716 typedef enum {
2717     MBEDTLS_ECJPAKE_ROUND_ONE,
2718     MBEDTLS_ECJPAKE_ROUND_TWO
2719 } mbedtls_ecjpake_rounds_t;
2720 
2721 /**
2722  * \brief       Parse the provided input buffer for getting the first round
2723  *              of key exchange. This code is common between server and client
2724  *
2725  * \param  pake_ctx [in] the PAKE's operation/context structure
2726  * \param  buf      [in] input buffer to parse
2727  * \param  len      [in] length of the input buffer
2728  * \param  round    [in] either MBEDTLS_ECJPAKE_ROUND_ONE or
2729  *                       MBEDTLS_ECJPAKE_ROUND_TWO
2730  *
2731  * \return               0 on success or a negative error code in case of failure
2732  */
2733 int mbedtls_psa_ecjpake_read_round(
2734     psa_pake_operation_t *pake_ctx,
2735     const unsigned char *buf,
2736     size_t len, mbedtls_ecjpake_rounds_t round);
2737 
2738 /**
2739  * \brief       Write the first round of key exchange into the provided output
2740  *              buffer. This code is common between server and client
2741  *
2742  * \param  pake_ctx [in] the PAKE's operation/context structure
2743  * \param  buf      [out] the output buffer in which data will be written to
2744  * \param  len      [in] length of the output buffer
2745  * \param  olen     [out] the length of the data really written on the buffer
2746  * \param  round    [in] either MBEDTLS_ECJPAKE_ROUND_ONE or
2747  *                       MBEDTLS_ECJPAKE_ROUND_TWO
2748  *
2749  * \return               0 on success or a negative error code in case of failure
2750  */
2751 int mbedtls_psa_ecjpake_write_round(
2752     psa_pake_operation_t *pake_ctx,
2753     unsigned char *buf,
2754     size_t len, size_t *olen,
2755     mbedtls_ecjpake_rounds_t round);
2756 
2757 #endif //MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED && MBEDTLS_USE_PSA_CRYPTO
2758 
2759 /**
2760  * \brief       TLS record protection modes
2761  */
2762 typedef enum {
2763     MBEDTLS_SSL_MODE_STREAM = 0,
2764     MBEDTLS_SSL_MODE_CBC,
2765     MBEDTLS_SSL_MODE_CBC_ETM,
2766     MBEDTLS_SSL_MODE_AEAD
2767 } mbedtls_ssl_mode_t;
2768 
2769 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_transform(
2770     const mbedtls_ssl_transform *transform);
2771 
2772 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2773 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
2774     int encrypt_then_mac,
2775     const mbedtls_ssl_ciphersuite_t *suite);
2776 #else
2777 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
2778     const mbedtls_ssl_ciphersuite_t *suite);
2779 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
2780 
2781 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
2782 
2783 MBEDTLS_CHECK_RETURN_CRITICAL
2784 int mbedtls_ssl_tls13_read_public_xxdhe_share(mbedtls_ssl_context *ssl,
2785                                               const unsigned char *buf,
2786                                               size_t buf_len);
2787 
2788 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
2789 
mbedtls_ssl_tls13_cipher_suite_is_offered(mbedtls_ssl_context * ssl,int cipher_suite)2790 static inline int mbedtls_ssl_tls13_cipher_suite_is_offered(
2791     mbedtls_ssl_context *ssl, int cipher_suite)
2792 {
2793     const int *ciphersuite_list = ssl->conf->ciphersuite_list;
2794 
2795     /* Check whether we have offered this ciphersuite */
2796     for (size_t i = 0; ciphersuite_list[i] != 0; i++) {
2797         if (ciphersuite_list[i] == cipher_suite) {
2798             return 1;
2799         }
2800     }
2801     return 0;
2802 }
2803 
2804 /**
2805  * \brief Validate cipher suite against config in SSL context.
2806  *
2807  * \param ssl              SSL context
2808  * \param suite_info       Cipher suite to validate
2809  * \param min_tls_version  Minimal TLS version to accept a cipher suite
2810  * \param max_tls_version  Maximal TLS version to accept a cipher suite
2811  *
2812  * \return 0 if valid, negative value otherwise.
2813  */
2814 MBEDTLS_CHECK_RETURN_CRITICAL
2815 int mbedtls_ssl_validate_ciphersuite(
2816     const mbedtls_ssl_context *ssl,
2817     const mbedtls_ssl_ciphersuite_t *suite_info,
2818     mbedtls_ssl_protocol_version min_tls_version,
2819     mbedtls_ssl_protocol_version max_tls_version);
2820 
2821 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2822 MBEDTLS_CHECK_RETURN_CRITICAL
2823 int mbedtls_ssl_parse_server_name_ext(mbedtls_ssl_context *ssl,
2824                                       const unsigned char *buf,
2825                                       const unsigned char *end);
2826 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
2827 
2828 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2829 #define MBEDTLS_SSL_RECORD_SIZE_LIMIT_EXTENSION_DATA_LENGTH (2)
2830 #define MBEDTLS_SSL_RECORD_SIZE_LIMIT_MIN (64)      /* As defined in RFC 8449 */
2831 
2832 MBEDTLS_CHECK_RETURN_CRITICAL
2833 int mbedtls_ssl_tls13_parse_record_size_limit_ext(mbedtls_ssl_context *ssl,
2834                                                   const unsigned char *buf,
2835                                                   const unsigned char *end);
2836 
2837 MBEDTLS_CHECK_RETURN_CRITICAL
2838 int mbedtls_ssl_tls13_write_record_size_limit_ext(mbedtls_ssl_context *ssl,
2839                                                   unsigned char *buf,
2840                                                   const unsigned char *end,
2841                                                   size_t *out_len);
2842 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
2843 
2844 #if defined(MBEDTLS_SSL_ALPN)
2845 MBEDTLS_CHECK_RETURN_CRITICAL
2846 int mbedtls_ssl_parse_alpn_ext(mbedtls_ssl_context *ssl,
2847                                const unsigned char *buf,
2848                                const unsigned char *end);
2849 
2850 
2851 MBEDTLS_CHECK_RETURN_CRITICAL
2852 int mbedtls_ssl_write_alpn_ext(mbedtls_ssl_context *ssl,
2853                                unsigned char *buf,
2854                                unsigned char *end,
2855                                size_t *out_len);
2856 #endif /* MBEDTLS_SSL_ALPN */
2857 
2858 #if defined(MBEDTLS_TEST_HOOKS)
2859 int mbedtls_ssl_check_dtls_clihlo_cookie(
2860     mbedtls_ssl_context *ssl,
2861     const unsigned char *cli_id, size_t cli_id_len,
2862     const unsigned char *in, size_t in_len,
2863     unsigned char *obuf, size_t buf_len, size_t *olen);
2864 #endif
2865 
2866 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
2867 /**
2868  * \brief Given an SSL context and its associated configuration, write the TLS
2869  *        1.3 specific Pre-Shared key extension.
2870  *
2871  * \param[in]   ssl     SSL context
2872  * \param[in]   buf     Base address of the buffer where to write the extension
2873  * \param[in]   end     End address of the buffer where to write the extension
2874  * \param[out]  out_len Length in bytes of the Pre-Shared key extension: data
2875  *                      written into the buffer \p buf by this function plus
2876  *                      the length of the binders to be written.
2877  * \param[out]  binders_len Length of the binders to be written at the end of
2878  *                          the extension.
2879  */
2880 MBEDTLS_CHECK_RETURN_CRITICAL
2881 int mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext(
2882     mbedtls_ssl_context *ssl,
2883     unsigned char *buf, unsigned char *end,
2884     size_t *out_len, size_t *binders_len);
2885 
2886 /**
2887  * \brief Given an SSL context and its associated configuration, write the TLS
2888  *        1.3 specific Pre-Shared key extension binders at the end of the
2889  *        ClientHello.
2890  *
2891  * \param[in]   ssl     SSL context
2892  * \param[in]   buf     Base address of the buffer where to write the binders
2893  * \param[in]   end     End address of the buffer where to write the binders
2894  */
2895 MBEDTLS_CHECK_RETURN_CRITICAL
2896 int mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(
2897     mbedtls_ssl_context *ssl,
2898     unsigned char *buf, unsigned char *end);
2899 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
2900 
2901 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
2902     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
2903     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \
2904     defined(MBEDTLS_SSL_CLI_C)
2905 MBEDTLS_CHECK_RETURN_CRITICAL
2906 int mbedtls_ssl_session_set_hostname(mbedtls_ssl_session *session,
2907                                      const char *hostname);
2908 #endif
2909 
2910 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA) && \
2911     defined(MBEDTLS_SSL_ALPN)
2912 MBEDTLS_CHECK_RETURN_CRITICAL
2913 int mbedtls_ssl_session_set_ticket_alpn(mbedtls_ssl_session *session,
2914                                         const char *alpn);
2915 #endif
2916 
2917 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
2918 
2919 #define MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME (604800)
2920 
mbedtls_ssl_tls13_session_get_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2921 static inline unsigned int mbedtls_ssl_tls13_session_get_ticket_flags(
2922     mbedtls_ssl_session *session, unsigned int flags)
2923 {
2924     return session->ticket_flags &
2925            (flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2926 }
2927 
2928 /**
2929  * Check if at least one of the given flags is set in
2930  * the session ticket. See the definition of
2931  * `MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK` to get all
2932  * permitted flags.
2933  */
mbedtls_ssl_tls13_session_ticket_has_flags(mbedtls_ssl_session * session,unsigned int flags)2934 static inline int mbedtls_ssl_tls13_session_ticket_has_flags(
2935     mbedtls_ssl_session *session, unsigned int flags)
2936 {
2937     return mbedtls_ssl_tls13_session_get_ticket_flags(session, flags) != 0;
2938 }
2939 
mbedtls_ssl_tls13_session_ticket_allow_psk(mbedtls_ssl_session * session)2940 static inline int mbedtls_ssl_tls13_session_ticket_allow_psk(
2941     mbedtls_ssl_session *session)
2942 {
2943     return mbedtls_ssl_tls13_session_ticket_has_flags(
2944         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_RESUMPTION);
2945 }
2946 
mbedtls_ssl_tls13_session_ticket_allow_psk_ephemeral(mbedtls_ssl_session * session)2947 static inline int mbedtls_ssl_tls13_session_ticket_allow_psk_ephemeral(
2948     mbedtls_ssl_session *session)
2949 {
2950     return mbedtls_ssl_tls13_session_ticket_has_flags(
2951         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_EPHEMERAL_RESUMPTION);
2952 }
2953 
mbedtls_ssl_tls13_session_ticket_allow_early_data(mbedtls_ssl_session * session)2954 static inline unsigned int mbedtls_ssl_tls13_session_ticket_allow_early_data(
2955     mbedtls_ssl_session *session)
2956 {
2957     return mbedtls_ssl_tls13_session_ticket_has_flags(
2958         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
2959 }
2960 
mbedtls_ssl_tls13_session_set_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2961 static inline void mbedtls_ssl_tls13_session_set_ticket_flags(
2962     mbedtls_ssl_session *session, unsigned int flags)
2963 {
2964     session->ticket_flags |= (flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2965 }
2966 
mbedtls_ssl_tls13_session_clear_ticket_flags(mbedtls_ssl_session * session,unsigned int flags)2967 static inline void mbedtls_ssl_tls13_session_clear_ticket_flags(
2968     mbedtls_ssl_session *session, unsigned int flags)
2969 {
2970     session->ticket_flags &= ~(flags & MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2971 }
2972 
2973 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_SESSION_TICKETS */
2974 
2975 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2976 #define MBEDTLS_SSL_SESSION_TICKETS_TLS1_2_BIT 0
2977 #define MBEDTLS_SSL_SESSION_TICKETS_TLS1_3_BIT 1
2978 
2979 #define MBEDTLS_SSL_SESSION_TICKETS_TLS1_2_MASK \
2980     (1 << MBEDTLS_SSL_SESSION_TICKETS_TLS1_2_BIT)
2981 #define MBEDTLS_SSL_SESSION_TICKETS_TLS1_3_MASK \
2982     (1 << MBEDTLS_SSL_SESSION_TICKETS_TLS1_3_BIT)
2983 
mbedtls_ssl_conf_get_session_tickets(const mbedtls_ssl_config * conf)2984 static inline int mbedtls_ssl_conf_get_session_tickets(
2985     const mbedtls_ssl_config *conf)
2986 {
2987     return conf->session_tickets & MBEDTLS_SSL_SESSION_TICKETS_TLS1_2_MASK ?
2988            MBEDTLS_SSL_SESSION_TICKETS_ENABLED :
2989            MBEDTLS_SSL_SESSION_TICKETS_DISABLED;
2990 }
2991 
2992 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_ssl_conf_is_signal_new_session_tickets_enabled(const mbedtls_ssl_config * conf)2993 static inline int mbedtls_ssl_conf_is_signal_new_session_tickets_enabled(
2994     const mbedtls_ssl_config *conf)
2995 {
2996     return conf->session_tickets & MBEDTLS_SSL_SESSION_TICKETS_TLS1_3_MASK ?
2997            MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED :
2998            MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_DISABLED;
2999 }
3000 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3001 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
3002 
3003 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
3004 int mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context *ssl);
3005 #endif
3006 
3007 #if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
3008 
3009 /** Compute the HMAC of variable-length data with constant flow.
3010  *
3011  * This function computes the HMAC of the concatenation of \p add_data and \p
3012  * data, and does with a code flow and memory access pattern that does not
3013  * depend on \p data_len_secret, but only on \p min_data_len and \p
3014  * max_data_len. In particular, this function always reads exactly \p
3015  * max_data_len bytes from \p data.
3016  *
3017  * \param ctx               The HMAC context. It must have keys configured
3018  *                          with mbedtls_md_hmac_starts() and use one of the
3019  *                          following hashes: SHA-384, SHA-256, SHA-1 or MD-5.
3020  *                          It is reset using mbedtls_md_hmac_reset() after
3021  *                          the computation is complete to prepare for the
3022  *                          next computation.
3023  * \param add_data          The first part of the message whose HMAC is being
3024  *                          calculated. This must point to a readable buffer
3025  *                          of \p add_data_len bytes.
3026  * \param add_data_len      The length of \p add_data in bytes.
3027  * \param data              The buffer containing the second part of the
3028  *                          message. This must point to a readable buffer
3029  *                          of \p max_data_len bytes.
3030  * \param data_len_secret   The length of the data to process in \p data.
3031  *                          This must be no less than \p min_data_len and no
3032  *                          greater than \p max_data_len.
3033  * \param min_data_len      The minimal length of the second part of the
3034  *                          message, read from \p data.
3035  * \param max_data_len      The maximal length of the second part of the
3036  *                          message, read from \p data.
3037  * \param output            The HMAC will be written here. This must point to
3038  *                          a writable buffer of sufficient size to hold the
3039  *                          HMAC value.
3040  *
3041  * \retval 0 on success.
3042  * \retval #MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED
3043  *         The hardware accelerator failed.
3044  */
3045 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3046 int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
3047                     psa_algorithm_t mac_alg,
3048                     const unsigned char *add_data,
3049                     size_t add_data_len,
3050                     const unsigned char *data,
3051                     size_t data_len_secret,
3052                     size_t min_data_len,
3053                     size_t max_data_len,
3054                     unsigned char *output);
3055 #else
3056 int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
3057                     const unsigned char *add_data,
3058                     size_t add_data_len,
3059                     const unsigned char *data,
3060                     size_t data_len_secret,
3061                     size_t min_data_len,
3062                     size_t max_data_len,
3063                     unsigned char *output);
3064 #endif /* defined(MBEDTLS_USE_PSA_CRYPTO) */
3065 #endif /* MBEDTLS_TEST_HOOKS && defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC) */
3066 
3067 #endif /* ssl_misc.h */
3068