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