1 /*
2  *  TLS 1.3 functionality shared between client and server
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #include "common.h"
9 
10 #if defined(MBEDTLS_SSL_TLS_C) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
11 
12 #include <string.h>
13 
14 #include "mbedtls/error.h"
15 #include "mbedtls/debug.h"
16 #include "mbedtls/oid.h"
17 #include "mbedtls/platform.h"
18 #include "mbedtls/constant_time.h"
19 #include "psa/crypto.h"
20 #include "md_psa.h"
21 
22 #include "ssl_misc.h"
23 #include "ssl_tls13_invasive.h"
24 #include "ssl_tls13_keys.h"
25 #include "ssl_debug_helpers.h"
26 
27 #include "psa/crypto.h"
28 #include "psa_util_internal.h"
29 
30 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
31 /* Define a local translating function to save code size by not using too many
32  * arguments in each translating place. */
local_err_translation(psa_status_t status)33 static int local_err_translation(psa_status_t status)
34 {
35     return psa_status_to_mbedtls(status, psa_to_ssl_errors,
36                                  ARRAY_LENGTH(psa_to_ssl_errors),
37                                  psa_generic_status_to_mbedtls);
38 }
39 #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
40 #endif
41 
42 const uint8_t mbedtls_ssl_tls13_hello_retry_request_magic[
43     MBEDTLS_SERVER_HELLO_RANDOM_LEN] =
44 { 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
45   0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
46   0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
47   0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C };
48 
mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context * ssl,unsigned hs_type,unsigned char ** buf,size_t * buf_len)49 int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
50                                           unsigned hs_type,
51                                           unsigned char **buf,
52                                           size_t *buf_len)
53 {
54     int ret;
55 
56     if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
57         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
58         goto cleanup;
59     }
60 
61     if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
62         ssl->in_msg[0]  != hs_type) {
63         MBEDTLS_SSL_DEBUG_MSG(1, ("Receive unexpected handshake message."));
64         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
65                                      MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
66         ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
67         goto cleanup;
68     }
69 
70     /*
71      * Jump handshake header (4 bytes, see Section 4 of RFC 8446).
72      *    ...
73      *    HandshakeType msg_type;
74      *    uint24 length;
75      *    ...
76      */
77     *buf = ssl->in_msg   + 4;
78     *buf_len = ssl->in_hslen - 4;
79 
80 cleanup:
81 
82     return ret;
83 }
84 
mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end,const unsigned char ** supported_versions_data,const unsigned char ** supported_versions_data_end)85 int mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
86     mbedtls_ssl_context *ssl,
87     const unsigned char *buf, const unsigned char *end,
88     const unsigned char **supported_versions_data,
89     const unsigned char **supported_versions_data_end)
90 {
91     const unsigned char *p = buf;
92     size_t extensions_len;
93     const unsigned char *extensions_end;
94 
95     *supported_versions_data = NULL;
96     *supported_versions_data_end = NULL;
97 
98     /* Case of no extension */
99     if (p == end) {
100         return 0;
101     }
102 
103     /* ...
104      * Extension extensions<x..2^16-1>;
105      * ...
106      * struct {
107      *      ExtensionType extension_type; (2 bytes)
108      *      opaque extension_data<0..2^16-1>;
109      * } Extension;
110      */
111     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
112     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
113     p += 2;
114 
115     /* Check extensions do not go beyond the buffer of data. */
116     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
117     extensions_end = p + extensions_len;
118 
119     while (p < extensions_end) {
120         unsigned int extension_type;
121         size_t extension_data_len;
122 
123         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
124         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
125         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
126         p += 4;
127         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
128 
129         if (extension_type == MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS) {
130             *supported_versions_data = p;
131             *supported_versions_data_end = p + extension_data_len;
132             return 1;
133         }
134         p += extension_data_len;
135     }
136 
137     return 0;
138 }
139 
140 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
141 /*
142  * STATE HANDLING: Read CertificateVerify
143  */
144 /* Macro to express the maximum length of the verify structure.
145  *
146  * The structure is computed per TLS 1.3 specification as:
147  *   - 64 bytes of octet 32,
148  *   - 33 bytes for the context string
149  *        (which is either "TLS 1.3, client CertificateVerify"
150  *         or "TLS 1.3, server CertificateVerify"),
151  *   - 1 byte for the octet 0x0, which serves as a separator,
152  *   - 32 or 48 bytes for the Transcript-Hash(Handshake Context, Certificate)
153  *     (depending on the size of the transcript_hash)
154  *
155  * This results in a total size of
156  * - 130 bytes for a SHA256-based transcript hash, or
157  *   (64 + 33 + 1 + 32 bytes)
158  * - 146 bytes for a SHA384-based transcript hash.
159  *   (64 + 33 + 1 + 48 bytes)
160  *
161  */
162 #define SSL_VERIFY_STRUCT_MAX_SIZE  (64 +                          \
163                                      33 +                          \
164                                      1 +                          \
165                                      MBEDTLS_TLS1_3_MD_MAX_SIZE    \
166                                      )
167 
168 /*
169  * The ssl_tls13_create_verify_structure() creates the verify structure.
170  * As input, it requires the transcript hash.
171  *
172  * The caller has to ensure that the buffer has size at least
173  * SSL_VERIFY_STRUCT_MAX_SIZE bytes.
174  */
ssl_tls13_create_verify_structure(const unsigned char * transcript_hash,size_t transcript_hash_len,unsigned char * verify_buffer,size_t * verify_buffer_len,int from)175 static void ssl_tls13_create_verify_structure(const unsigned char *transcript_hash,
176                                               size_t transcript_hash_len,
177                                               unsigned char *verify_buffer,
178                                               size_t *verify_buffer_len,
179                                               int from)
180 {
181     size_t idx;
182 
183     /* RFC 8446, Section 4.4.3:
184      *
185      * The digital signature [in the CertificateVerify message] is then
186      * computed over the concatenation of:
187      * -  A string that consists of octet 32 (0x20) repeated 64 times
188      * -  The context string
189      * -  A single 0 byte which serves as the separator
190      * -  The content to be signed
191      */
192     memset(verify_buffer, 0x20, 64);
193     idx = 64;
194 
195     if (from == MBEDTLS_SSL_IS_CLIENT) {
196         memcpy(verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(client_cv));
197         idx += MBEDTLS_SSL_TLS1_3_LBL_LEN(client_cv);
198     } else { /* from == MBEDTLS_SSL_IS_SERVER */
199         memcpy(verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(server_cv));
200         idx += MBEDTLS_SSL_TLS1_3_LBL_LEN(server_cv);
201     }
202 
203     verify_buffer[idx++] = 0x0;
204 
205     memcpy(verify_buffer + idx, transcript_hash, transcript_hash_len);
206     idx += transcript_hash_len;
207 
208     *verify_buffer_len = idx;
209 }
210 
211 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_certificate_verify(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end,const unsigned char * verify_buffer,size_t verify_buffer_len)212 static int ssl_tls13_parse_certificate_verify(mbedtls_ssl_context *ssl,
213                                               const unsigned char *buf,
214                                               const unsigned char *end,
215                                               const unsigned char *verify_buffer,
216                                               size_t verify_buffer_len)
217 {
218     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
219     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
220     const unsigned char *p = buf;
221     uint16_t algorithm;
222     size_t signature_len;
223     mbedtls_pk_type_t sig_alg;
224     mbedtls_md_type_t md_alg;
225     psa_algorithm_t hash_alg = PSA_ALG_NONE;
226     unsigned char verify_hash[PSA_HASH_MAX_SIZE];
227     size_t verify_hash_len;
228 
229     void const *options = NULL;
230 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
231     mbedtls_pk_rsassa_pss_options rsassa_pss_options;
232 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
233 
234     /*
235      * struct {
236      *     SignatureScheme algorithm;
237      *     opaque signature<0..2^16-1>;
238      * } CertificateVerify;
239      */
240     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
241     algorithm = MBEDTLS_GET_UINT16_BE(p, 0);
242     p += 2;
243 
244     /* RFC 8446 section 4.4.3
245      *
246      * If the CertificateVerify message is sent by a server, the signature
247      * algorithm MUST be one offered in the client's "signature_algorithms"
248      * extension unless no valid certificate chain can be produced without
249      * unsupported algorithms
250      *
251      * RFC 8446 section 4.4.2.2
252      *
253      * If the client cannot construct an acceptable chain using the provided
254      * certificates and decides to abort the handshake, then it MUST abort the
255      * handshake with an appropriate certificate-related alert
256      * (by default, "unsupported_certificate").
257      *
258      * Check if algorithm is an offered signature algorithm.
259      */
260     if (!mbedtls_ssl_sig_alg_is_offered(ssl, algorithm)) {
261         /* algorithm not in offered signature algorithms list */
262         MBEDTLS_SSL_DEBUG_MSG(1, ("Received signature algorithm(%04x) is not "
263                                   "offered.",
264                                   (unsigned int) algorithm));
265         goto error;
266     }
267 
268     if (mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
269             algorithm, &sig_alg, &md_alg) != 0) {
270         goto error;
271     }
272 
273     hash_alg = mbedtls_md_psa_alg_from_type(md_alg);
274     if (hash_alg == 0) {
275         goto error;
276     }
277 
278     MBEDTLS_SSL_DEBUG_MSG(3, ("Certificate Verify: Signature algorithm ( %04x )",
279                               (unsigned int) algorithm));
280 
281     /*
282      * Check the certificate's key type matches the signature alg
283      */
284     if (!mbedtls_pk_can_do(&ssl->session_negotiate->peer_cert->pk, sig_alg)) {
285         MBEDTLS_SSL_DEBUG_MSG(1, ("signature algorithm doesn't match cert key"));
286         goto error;
287     }
288 
289     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
290     signature_len = MBEDTLS_GET_UINT16_BE(p, 0);
291     p += 2;
292     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, signature_len);
293 
294     status = psa_hash_compute(hash_alg,
295                               verify_buffer,
296                               verify_buffer_len,
297                               verify_hash,
298                               sizeof(verify_hash),
299                               &verify_hash_len);
300     if (status != PSA_SUCCESS) {
301         MBEDTLS_SSL_DEBUG_RET(1, "hash computation PSA error", status);
302         goto error;
303     }
304 
305     MBEDTLS_SSL_DEBUG_BUF(3, "verify hash", verify_hash, verify_hash_len);
306 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
307     if (sig_alg == MBEDTLS_PK_RSASSA_PSS) {
308         rsassa_pss_options.mgf1_hash_id = md_alg;
309 
310         rsassa_pss_options.expected_salt_len = PSA_HASH_LENGTH(hash_alg);
311         options = (const void *) &rsassa_pss_options;
312     }
313 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
314 
315     if ((ret = mbedtls_pk_verify_ext(sig_alg, options,
316                                      &ssl->session_negotiate->peer_cert->pk,
317                                      md_alg, verify_hash, verify_hash_len,
318                                      p, signature_len)) == 0) {
319         return 0;
320     }
321     MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify_ext", ret);
322 
323 error:
324     /* RFC 8446 section 4.4.3
325      *
326      * If the verification fails, the receiver MUST terminate the handshake
327      * with a "decrypt_error" alert.
328      */
329     MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
330                                  MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
331     return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
332 
333 }
334 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
335 
mbedtls_ssl_tls13_process_certificate_verify(mbedtls_ssl_context * ssl)336 int mbedtls_ssl_tls13_process_certificate_verify(mbedtls_ssl_context *ssl)
337 {
338 
339 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
340     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
341     unsigned char verify_buffer[SSL_VERIFY_STRUCT_MAX_SIZE];
342     size_t verify_buffer_len;
343     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
344     size_t transcript_len;
345     unsigned char *buf;
346     size_t buf_len;
347 
348     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
349 
350     MBEDTLS_SSL_PROC_CHK(
351         mbedtls_ssl_tls13_fetch_handshake_msg(
352             ssl, MBEDTLS_SSL_HS_CERTIFICATE_VERIFY, &buf, &buf_len));
353 
354     /* Need to calculate the hash of the transcript first
355      * before reading the message since otherwise it gets
356      * included in the transcript
357      */
358     ret = mbedtls_ssl_get_handshake_transcript(
359         ssl,
360         ssl->handshake->ciphersuite_info->mac,
361         transcript, sizeof(transcript),
362         &transcript_len);
363     if (ret != 0) {
364         MBEDTLS_SSL_PEND_FATAL_ALERT(
365             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
366             MBEDTLS_ERR_SSL_INTERNAL_ERROR);
367         return ret;
368     }
369 
370     MBEDTLS_SSL_DEBUG_BUF(3, "handshake hash", transcript, transcript_len);
371 
372     /* Create verify structure */
373     ssl_tls13_create_verify_structure(transcript,
374                                       transcript_len,
375                                       verify_buffer,
376                                       &verify_buffer_len,
377                                       (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) ?
378                                       MBEDTLS_SSL_IS_SERVER :
379                                       MBEDTLS_SSL_IS_CLIENT);
380 
381     /* Process the message contents */
382     MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_certificate_verify(
383                              ssl, buf, buf + buf_len,
384                              verify_buffer, verify_buffer_len));
385 
386     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
387                              ssl, MBEDTLS_SSL_HS_CERTIFICATE_VERIFY,
388                              buf, buf_len));
389 
390 cleanup:
391 
392     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate verify"));
393     MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_process_certificate_verify", ret);
394     return ret;
395 #else
396     ((void) ssl);
397     MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
398     return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
399 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
400 }
401 
402 /*
403  *
404  * STATE HANDLING: Incoming Certificate.
405  *
406  */
407 
408 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
409 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
410 /*
411  * Structure of Certificate message:
412  *
413  * enum {
414  *     X509(0),
415  *     RawPublicKey(2),
416  *     (255)
417  * } CertificateType;
418  *
419  * struct {
420  *     select (certificate_type) {
421  *         case RawPublicKey:
422  *           * From RFC 7250 ASN.1_subjectPublicKeyInfo *
423  *           opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
424  *         case X509:
425  *           opaque cert_data<1..2^24-1>;
426  *     };
427  *     Extension extensions<0..2^16-1>;
428  * } CertificateEntry;
429  *
430  * struct {
431  *     opaque certificate_request_context<0..2^8-1>;
432  *     CertificateEntry certificate_list<0..2^24-1>;
433  * } Certificate;
434  *
435  */
436 
437 /* Parse certificate chain send by the server. */
438 MBEDTLS_CHECK_RETURN_CRITICAL
439 MBEDTLS_STATIC_TESTABLE
mbedtls_ssl_tls13_parse_certificate(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)440 int mbedtls_ssl_tls13_parse_certificate(mbedtls_ssl_context *ssl,
441                                         const unsigned char *buf,
442                                         const unsigned char *end)
443 {
444     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
445     size_t certificate_request_context_len = 0;
446     size_t certificate_list_len = 0;
447     const unsigned char *p = buf;
448     const unsigned char *certificate_list_end;
449     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
450 
451     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 4);
452     certificate_request_context_len = p[0];
453     certificate_list_len = MBEDTLS_GET_UINT24_BE(p, 1);
454     p += 4;
455 
456     /* In theory, the certificate list can be up to 2^24 Bytes, but we don't
457      * support anything beyond 2^16 = 64K.
458      */
459     if ((certificate_request_context_len != 0) ||
460         (certificate_list_len >= 0x10000)) {
461         MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
462         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
463                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
464         return MBEDTLS_ERR_SSL_DECODE_ERROR;
465     }
466 
467     /* In case we tried to reuse a session but it failed */
468     if (ssl->session_negotiate->peer_cert != NULL) {
469         mbedtls_x509_crt_free(ssl->session_negotiate->peer_cert);
470         mbedtls_free(ssl->session_negotiate->peer_cert);
471     }
472 
473     if (certificate_list_len == 0) {
474         ssl->session_negotiate->peer_cert = NULL;
475         ret = 0;
476         goto exit;
477     }
478 
479     if ((ssl->session_negotiate->peer_cert =
480              mbedtls_calloc(1, sizeof(mbedtls_x509_crt))) == NULL) {
481         MBEDTLS_SSL_DEBUG_MSG(1, ("alloc( %" MBEDTLS_PRINTF_SIZET " bytes ) failed",
482                                   sizeof(mbedtls_x509_crt)));
483         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
484                                      MBEDTLS_ERR_SSL_ALLOC_FAILED);
485         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
486     }
487 
488     mbedtls_x509_crt_init(ssl->session_negotiate->peer_cert);
489 
490     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, certificate_list_len);
491     certificate_list_end = p + certificate_list_len;
492     while (p < certificate_list_end) {
493         size_t cert_data_len, extensions_len;
494         const unsigned char *extensions_end;
495 
496         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, certificate_list_end, 3);
497         cert_data_len = MBEDTLS_GET_UINT24_BE(p, 0);
498         p += 3;
499 
500         /* In theory, the CRT can be up to 2^24 Bytes, but we don't support
501          * anything beyond 2^16 = 64K. Otherwise as in the TLS 1.2 code,
502          * check that we have a minimum of 128 bytes of data, this is not
503          * clear why we need that though.
504          */
505         if ((cert_data_len < 128) || (cert_data_len >= 0x10000)) {
506             MBEDTLS_SSL_DEBUG_MSG(1, ("bad Certificate message"));
507             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
508                                          MBEDTLS_ERR_SSL_DECODE_ERROR);
509             return MBEDTLS_ERR_SSL_DECODE_ERROR;
510         }
511 
512         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, certificate_list_end, cert_data_len);
513         ret = mbedtls_x509_crt_parse_der(ssl->session_negotiate->peer_cert,
514                                          p, cert_data_len);
515 
516         switch (ret) {
517             case 0: /*ok*/
518                 break;
519             case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
520                 /* Ignore certificate with an unknown algorithm: maybe a
521                    prior certificate was already trusted. */
522                 break;
523 
524             case MBEDTLS_ERR_X509_ALLOC_FAILED:
525                 MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
526                                              MBEDTLS_ERR_X509_ALLOC_FAILED);
527                 MBEDTLS_SSL_DEBUG_RET(1, " mbedtls_x509_crt_parse_der", ret);
528                 return ret;
529 
530             case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
531                 MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT,
532                                              MBEDTLS_ERR_X509_UNKNOWN_VERSION);
533                 MBEDTLS_SSL_DEBUG_RET(1, " mbedtls_x509_crt_parse_der", ret);
534                 return ret;
535 
536             default:
537                 MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_BAD_CERT,
538                                              ret);
539                 MBEDTLS_SSL_DEBUG_RET(1, " mbedtls_x509_crt_parse_der", ret);
540                 return ret;
541         }
542 
543         p += cert_data_len;
544 
545         /* Certificate extensions length */
546         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, certificate_list_end, 2);
547         extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
548         p += 2;
549         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, certificate_list_end, extensions_len);
550 
551         extensions_end = p + extensions_len;
552         handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
553 
554         while (p < extensions_end) {
555             unsigned int extension_type;
556             size_t extension_data_len;
557 
558             /*
559              * struct {
560              *     ExtensionType extension_type; (2 bytes)
561              *     opaque extension_data<0..2^16-1>;
562              * } Extension;
563              */
564             MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
565             extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
566             extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
567             p += 4;
568 
569             MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
570 
571             ret = mbedtls_ssl_tls13_check_received_extension(
572                 ssl, MBEDTLS_SSL_HS_CERTIFICATE, extension_type,
573                 MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CT);
574             if (ret != 0) {
575                 return ret;
576             }
577 
578             switch (extension_type) {
579                 default:
580                     MBEDTLS_SSL_PRINT_EXT(
581                         3, MBEDTLS_SSL_HS_CERTIFICATE,
582                         extension_type, "( ignored )");
583                     break;
584             }
585 
586             p += extension_data_len;
587         }
588 
589         MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_CERTIFICATE,
590                                handshake->received_extensions);
591     }
592 
593 exit:
594     /* Check that all the message is consumed. */
595     if (p != end) {
596         MBEDTLS_SSL_DEBUG_MSG(1, ("bad Certificate message"));
597         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
598                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
599         return MBEDTLS_ERR_SSL_DECODE_ERROR;
600     }
601 
602     MBEDTLS_SSL_DEBUG_CRT(3, "peer certificate",
603                           ssl->session_negotiate->peer_cert);
604 
605     return ret;
606 }
607 #else
608 MBEDTLS_CHECK_RETURN_CRITICAL
609 MBEDTLS_STATIC_TESTABLE
mbedtls_ssl_tls13_parse_certificate(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)610 int mbedtls_ssl_tls13_parse_certificate(mbedtls_ssl_context *ssl,
611                                         const unsigned char *buf,
612                                         const unsigned char *end)
613 {
614     ((void) ssl);
615     ((void) buf);
616     ((void) end);
617     return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
618 }
619 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
620 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
621 
622 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
623 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
624 /* Validate certificate chain sent by the server. */
625 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_validate_certificate(mbedtls_ssl_context * ssl)626 static int ssl_tls13_validate_certificate(mbedtls_ssl_context *ssl)
627 {
628     int ret = 0;
629     int authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
630     mbedtls_x509_crt *ca_chain;
631     mbedtls_x509_crl *ca_crl;
632     const char *ext_oid;
633     size_t ext_len;
634     uint32_t verify_result = 0;
635 
636     /* If SNI was used, overwrite authentication mode
637      * from the configuration. */
638 #if defined(MBEDTLS_SSL_SRV_C)
639     if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
640 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
641         if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
642             authmode = ssl->handshake->sni_authmode;
643         } else
644 #endif
645         authmode = ssl->conf->authmode;
646     }
647 #endif
648 
649     /*
650      * If the peer hasn't sent a certificate ( i.e. it sent
651      * an empty certificate chain ), this is reflected in the peer CRT
652      * structure being unset.
653      * Check for that and handle it depending on the
654      * authentication mode.
655      */
656     if (ssl->session_negotiate->peer_cert == NULL) {
657         MBEDTLS_SSL_DEBUG_MSG(1, ("peer has no certificate"));
658 
659 #if defined(MBEDTLS_SSL_SRV_C)
660         if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
661             /* The client was asked for a certificate but didn't send
662              * one. The client should know what's going on, so we
663              * don't send an alert.
664              */
665             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
666             if (authmode == MBEDTLS_SSL_VERIFY_OPTIONAL) {
667                 return 0;
668             } else {
669                 MBEDTLS_SSL_PEND_FATAL_ALERT(
670                     MBEDTLS_SSL_ALERT_MSG_NO_CERT,
671                     MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE);
672                 return MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
673             }
674         }
675 #endif /* MBEDTLS_SSL_SRV_C */
676 
677 #if defined(MBEDTLS_SSL_CLI_C)
678         if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
679             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_NO_CERT,
680                                          MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE);
681             return MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE;
682         }
683 #endif /* MBEDTLS_SSL_CLI_C */
684     }
685 
686 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
687     if (ssl->handshake->sni_ca_chain != NULL) {
688         ca_chain = ssl->handshake->sni_ca_chain;
689         ca_crl = ssl->handshake->sni_ca_crl;
690     } else
691 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
692     {
693         ca_chain = ssl->conf->ca_chain;
694         ca_crl = ssl->conf->ca_crl;
695     }
696 
697     /*
698      * Main check: verify certificate
699      */
700     ret = mbedtls_x509_crt_verify_with_profile(
701         ssl->session_negotiate->peer_cert,
702         ca_chain, ca_crl,
703         ssl->conf->cert_profile,
704         ssl->hostname,
705         &verify_result,
706         ssl->conf->f_vrfy, ssl->conf->p_vrfy);
707 
708     if (ret != 0) {
709         MBEDTLS_SSL_DEBUG_RET(1, "x509_verify_cert", ret);
710     }
711 
712     /*
713      * Secondary checks: always done, but change 'ret' only if it was 0
714      */
715     if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
716         ext_oid = MBEDTLS_OID_SERVER_AUTH;
717         ext_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH);
718     } else {
719         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
720         ext_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_CLIENT_AUTH);
721     }
722 
723     if ((mbedtls_x509_crt_check_key_usage(
724              ssl->session_negotiate->peer_cert,
725              MBEDTLS_X509_KU_DIGITAL_SIGNATURE) != 0) ||
726         (mbedtls_x509_crt_check_extended_key_usage(
727              ssl->session_negotiate->peer_cert,
728              ext_oid, ext_len) != 0)) {
729         MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate (usage extensions)"));
730         if (ret == 0) {
731             ret = MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
732         }
733     }
734 
735     /* mbedtls_x509_crt_verify_with_profile is supposed to report a
736      * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
737      * with details encoded in the verification flags. All other kinds
738      * of error codes, including those from the user provided f_vrfy
739      * functions, are treated as fatal and lead to a failure of
740      * mbedtls_ssl_tls13_parse_certificate even if verification was optional.
741      */
742     if (authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
743         (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
744          ret == MBEDTLS_ERR_SSL_BAD_CERTIFICATE)) {
745         ret = 0;
746     }
747 
748     if (ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED) {
749         MBEDTLS_SSL_DEBUG_MSG(1, ("got no CA chain"));
750         ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
751     }
752 
753     if (ret != 0) {
754         /* The certificate may have been rejected for several reasons.
755            Pick one and send the corresponding alert. Which alert to send
756            may be a subject of debate in some cases. */
757         if (verify_result & MBEDTLS_X509_BADCERT_OTHER) {
758             MBEDTLS_SSL_PEND_FATAL_ALERT(
759                 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED, ret);
760         } else if (verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
761             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_BAD_CERT, ret);
762         } else if (verify_result & (MBEDTLS_X509_BADCERT_KEY_USAGE |
763                                     MBEDTLS_X509_BADCERT_EXT_KEY_USAGE |
764                                     MBEDTLS_X509_BADCERT_NS_CERT_TYPE |
765                                     MBEDTLS_X509_BADCERT_BAD_PK |
766                                     MBEDTLS_X509_BADCERT_BAD_KEY)) {
767             MBEDTLS_SSL_PEND_FATAL_ALERT(
768                 MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT, ret);
769         } else if (verify_result & MBEDTLS_X509_BADCERT_EXPIRED) {
770             MBEDTLS_SSL_PEND_FATAL_ALERT(
771                 MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED, ret);
772         } else if (verify_result & MBEDTLS_X509_BADCERT_REVOKED) {
773             MBEDTLS_SSL_PEND_FATAL_ALERT(
774                 MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED, ret);
775         } else if (verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
776             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA, ret);
777         } else {
778             MBEDTLS_SSL_PEND_FATAL_ALERT(
779                 MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN, ret);
780         }
781     }
782 
783 #if defined(MBEDTLS_DEBUG_C)
784     if (verify_result != 0) {
785         MBEDTLS_SSL_DEBUG_MSG(3, ("! Certificate verification flags %08x",
786                                   (unsigned int) verify_result));
787     } else {
788         MBEDTLS_SSL_DEBUG_MSG(3, ("Certificate verification flags clear"));
789     }
790 #endif /* MBEDTLS_DEBUG_C */
791 
792     ssl->session_negotiate->verify_result = verify_result;
793     return ret;
794 }
795 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
796 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_validate_certificate(mbedtls_ssl_context * ssl)797 static int ssl_tls13_validate_certificate(mbedtls_ssl_context *ssl)
798 {
799     ((void) ssl);
800     return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
801 }
802 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
803 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
804 
mbedtls_ssl_tls13_process_certificate(mbedtls_ssl_context * ssl)805 int mbedtls_ssl_tls13_process_certificate(mbedtls_ssl_context *ssl)
806 {
807     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
808     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate"));
809 
810 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
811     unsigned char *buf;
812     size_t buf_len;
813 
814     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
815                              ssl, MBEDTLS_SSL_HS_CERTIFICATE,
816                              &buf, &buf_len));
817 
818     /* Parse the certificate chain sent by the peer. */
819     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_parse_certificate(ssl, buf,
820                                                              buf + buf_len));
821     /* Validate the certificate chain and set the verification results. */
822     MBEDTLS_SSL_PROC_CHK(ssl_tls13_validate_certificate(ssl));
823 
824     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
825                              ssl, MBEDTLS_SSL_HS_CERTIFICATE, buf, buf_len));
826 
827 cleanup:
828 #else /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
829     (void) ssl;
830 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
831 
832     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate"));
833     return ret;
834 }
835 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
836 /*
837  *  enum {
838  *        X509(0),
839  *        RawPublicKey(2),
840  *        (255)
841  *    } CertificateType;
842  *
843  *    struct {
844  *        select (certificate_type) {
845  *            case RawPublicKey:
846  *              // From RFC 7250 ASN.1_subjectPublicKeyInfo
847  *              opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
848  *
849  *            case X509:
850  *              opaque cert_data<1..2^24-1>;
851  *        };
852  *        Extension extensions<0..2^16-1>;
853  *    } CertificateEntry;
854  *
855  *    struct {
856  *        opaque certificate_request_context<0..2^8-1>;
857  *        CertificateEntry certificate_list<0..2^24-1>;
858  *    } Certificate;
859  */
860 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_certificate_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)861 static int ssl_tls13_write_certificate_body(mbedtls_ssl_context *ssl,
862                                             unsigned char *buf,
863                                             unsigned char *end,
864                                             size_t *out_len)
865 {
866     const mbedtls_x509_crt *crt = mbedtls_ssl_own_cert(ssl);
867     unsigned char *p = buf;
868     unsigned char *certificate_request_context =
869         ssl->handshake->certificate_request_context;
870     unsigned char certificate_request_context_len =
871         ssl->handshake->certificate_request_context_len;
872     unsigned char *p_certificate_list_len;
873 
874 
875     /* ...
876      * opaque certificate_request_context<0..2^8-1>;
877      * ...
878      */
879     MBEDTLS_SSL_CHK_BUF_PTR(p, end, certificate_request_context_len + 1);
880     *p++ = certificate_request_context_len;
881     if (certificate_request_context_len > 0) {
882         memcpy(p, certificate_request_context, certificate_request_context_len);
883         p += certificate_request_context_len;
884     }
885 
886     /* ...
887      * CertificateEntry certificate_list<0..2^24-1>;
888      * ...
889      */
890     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 3);
891     p_certificate_list_len = p;
892     p += 3;
893 
894     MBEDTLS_SSL_DEBUG_CRT(3, "own certificate", crt);
895 
896     while (crt != NULL) {
897         size_t cert_data_len = crt->raw.len;
898 
899         MBEDTLS_SSL_CHK_BUF_PTR(p, end, cert_data_len + 3 + 2);
900         MBEDTLS_PUT_UINT24_BE(cert_data_len, p, 0);
901         p += 3;
902 
903         memcpy(p, crt->raw.p, cert_data_len);
904         p += cert_data_len;
905         crt = crt->next;
906 
907         /* Currently, we don't have any certificate extensions defined.
908          * Hence, we are sending an empty extension with length zero.
909          */
910         MBEDTLS_PUT_UINT16_BE(0, p, 0);
911         p += 2;
912     }
913 
914     MBEDTLS_PUT_UINT24_BE(p - p_certificate_list_len - 3,
915                           p_certificate_list_len, 0);
916 
917     *out_len = p - buf;
918 
919     MBEDTLS_SSL_PRINT_EXTS(
920         3, MBEDTLS_SSL_HS_CERTIFICATE, ssl->handshake->sent_extensions);
921 
922     return 0;
923 }
924 
mbedtls_ssl_tls13_write_certificate(mbedtls_ssl_context * ssl)925 int mbedtls_ssl_tls13_write_certificate(mbedtls_ssl_context *ssl)
926 {
927     int ret;
928     unsigned char *buf;
929     size_t buf_len, msg_len;
930 
931     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate"));
932 
933     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
934                              ssl, MBEDTLS_SSL_HS_CERTIFICATE, &buf, &buf_len));
935 
936     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_certificate_body(ssl,
937                                                           buf,
938                                                           buf + buf_len,
939                                                           &msg_len));
940 
941     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
942                              ssl, MBEDTLS_SSL_HS_CERTIFICATE, buf, msg_len));
943 
944     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
945                              ssl, buf_len, msg_len));
946 cleanup:
947 
948     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate"));
949     return ret;
950 }
951 
952 /*
953  * STATE HANDLING: Output Certificate Verify
954  */
mbedtls_ssl_tls13_check_sig_alg_cert_key_match(uint16_t sig_alg,mbedtls_pk_context * key)955 int mbedtls_ssl_tls13_check_sig_alg_cert_key_match(uint16_t sig_alg,
956                                                    mbedtls_pk_context *key)
957 {
958     mbedtls_pk_type_t pk_type = mbedtls_ssl_sig_from_pk(key);
959     size_t key_size = mbedtls_pk_get_bitlen(key);
960 
961     switch (pk_type) {
962         case MBEDTLS_SSL_SIG_ECDSA:
963             switch (key_size) {
964                 case 256:
965                     return
966                         sig_alg == MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256;
967 
968                 case 384:
969                     return
970                         sig_alg == MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384;
971 
972                 case 521:
973                     return
974                         sig_alg == MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512;
975                 default:
976                     break;
977             }
978             break;
979 
980         case MBEDTLS_SSL_SIG_RSA:
981             switch (sig_alg) {
982                 case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256: /* Intentional fallthrough */
983                 case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384: /* Intentional fallthrough */
984                 case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
985                     return 1;
986 
987                 default:
988                     break;
989             }
990             break;
991 
992         default:
993             break;
994     }
995 
996     return 0;
997 }
998 
999 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_certificate_verify_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)1000 static int ssl_tls13_write_certificate_verify_body(mbedtls_ssl_context *ssl,
1001                                                    unsigned char *buf,
1002                                                    unsigned char *end,
1003                                                    size_t *out_len)
1004 {
1005     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1006     unsigned char *p = buf;
1007     mbedtls_pk_context *own_key;
1008 
1009     unsigned char handshake_hash[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1010     size_t handshake_hash_len;
1011     unsigned char verify_buffer[SSL_VERIFY_STRUCT_MAX_SIZE];
1012     size_t verify_buffer_len;
1013 
1014     uint16_t *sig_alg = ssl->handshake->received_sig_algs;
1015     size_t signature_len = 0;
1016 
1017     *out_len = 0;
1018 
1019     own_key = mbedtls_ssl_own_key(ssl);
1020     if (own_key == NULL) {
1021         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1022         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1023     }
1024 
1025     ret = mbedtls_ssl_get_handshake_transcript(
1026         ssl, ssl->handshake->ciphersuite_info->mac,
1027         handshake_hash, sizeof(handshake_hash), &handshake_hash_len);
1028     if (ret != 0) {
1029         return ret;
1030     }
1031 
1032     MBEDTLS_SSL_DEBUG_BUF(3, "handshake hash",
1033                           handshake_hash,
1034                           handshake_hash_len);
1035 
1036     ssl_tls13_create_verify_structure(handshake_hash, handshake_hash_len,
1037                                       verify_buffer, &verify_buffer_len,
1038                                       ssl->conf->endpoint);
1039 
1040     /*
1041      *  struct {
1042      *    SignatureScheme algorithm;
1043      *    opaque signature<0..2^16-1>;
1044      *  } CertificateVerify;
1045      */
1046     /* Check there is space for the algorithm identifier (2 bytes) and the
1047      * signature length (2 bytes).
1048      */
1049     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
1050 
1051     for (; *sig_alg != MBEDTLS_TLS1_3_SIG_NONE; sig_alg++) {
1052         psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1053         mbedtls_pk_type_t pk_type = MBEDTLS_PK_NONE;
1054         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
1055         psa_algorithm_t psa_algorithm = PSA_ALG_NONE;
1056         unsigned char verify_hash[PSA_HASH_MAX_SIZE];
1057         size_t verify_hash_len;
1058 
1059         if (!mbedtls_ssl_sig_alg_is_offered(ssl, *sig_alg)) {
1060             continue;
1061         }
1062 
1063         if (!mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(*sig_alg)) {
1064             continue;
1065         }
1066 
1067         if (!mbedtls_ssl_tls13_check_sig_alg_cert_key_match(*sig_alg, own_key)) {
1068             continue;
1069         }
1070 
1071         if (mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
1072                 *sig_alg, &pk_type, &md_alg) != 0) {
1073             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1074         }
1075 
1076         /* Hash verify buffer with indicated hash function */
1077         psa_algorithm = mbedtls_md_psa_alg_from_type(md_alg);
1078         status = psa_hash_compute(psa_algorithm,
1079                                   verify_buffer,
1080                                   verify_buffer_len,
1081                                   verify_hash, sizeof(verify_hash),
1082                                   &verify_hash_len);
1083         if (status != PSA_SUCCESS) {
1084             return PSA_TO_MBEDTLS_ERR(status);
1085         }
1086 
1087         MBEDTLS_SSL_DEBUG_BUF(3, "verify hash", verify_hash, verify_hash_len);
1088 
1089         if ((ret = mbedtls_pk_sign_ext(pk_type, own_key,
1090                                        md_alg, verify_hash, verify_hash_len,
1091                                        p + 4, (size_t) (end - (p + 4)), &signature_len,
1092                                        ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
1093             MBEDTLS_SSL_DEBUG_MSG(2, ("CertificateVerify signature failed with %s",
1094                                       mbedtls_ssl_sig_alg_to_str(*sig_alg)));
1095             MBEDTLS_SSL_DEBUG_RET(2, "mbedtls_pk_sign_ext", ret);
1096 
1097             /* The signature failed. This is possible if the private key
1098              * was not suitable for the signature operation as purposely we
1099              * did not check its suitability completely. Let's try with
1100              * another signature algorithm.
1101              */
1102             continue;
1103         }
1104 
1105         MBEDTLS_SSL_DEBUG_MSG(2, ("CertificateVerify signature with %s",
1106                                   mbedtls_ssl_sig_alg_to_str(*sig_alg)));
1107 
1108         break;
1109     }
1110 
1111     if (*sig_alg == MBEDTLS_TLS1_3_SIG_NONE) {
1112         MBEDTLS_SSL_DEBUG_MSG(1, ("no suitable signature algorithm"));
1113         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
1114                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
1115         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1116     }
1117 
1118     MBEDTLS_PUT_UINT16_BE(*sig_alg, p, 0);
1119     MBEDTLS_PUT_UINT16_BE(signature_len, p, 2);
1120 
1121     *out_len = 4 + signature_len;
1122 
1123     return 0;
1124 }
1125 
mbedtls_ssl_tls13_write_certificate_verify(mbedtls_ssl_context * ssl)1126 int mbedtls_ssl_tls13_write_certificate_verify(mbedtls_ssl_context *ssl)
1127 {
1128     int ret = 0;
1129     unsigned char *buf;
1130     size_t buf_len, msg_len;
1131 
1132     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate verify"));
1133 
1134     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
1135                              ssl, MBEDTLS_SSL_HS_CERTIFICATE_VERIFY,
1136                              &buf, &buf_len));
1137 
1138     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_certificate_verify_body(
1139                              ssl, buf, buf + buf_len, &msg_len));
1140 
1141     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
1142                              ssl, MBEDTLS_SSL_HS_CERTIFICATE_VERIFY,
1143                              buf, msg_len));
1144 
1145     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
1146                              ssl, buf_len, msg_len));
1147 
1148 cleanup:
1149 
1150     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate verify"));
1151     return ret;
1152 }
1153 
1154 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1155 
1156 /*
1157  *
1158  * STATE HANDLING: Incoming Finished message.
1159  */
1160 /*
1161  * Implementation
1162  */
1163 
1164 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_preprocess_finished_message(mbedtls_ssl_context * ssl)1165 static int ssl_tls13_preprocess_finished_message(mbedtls_ssl_context *ssl)
1166 {
1167     int ret;
1168 
1169     ret = mbedtls_ssl_tls13_calculate_verify_data(
1170         ssl,
1171         ssl->handshake->state_local.finished_in.digest,
1172         sizeof(ssl->handshake->state_local.finished_in.digest),
1173         &ssl->handshake->state_local.finished_in.digest_len,
1174         ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ?
1175         MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT);
1176     if (ret != 0) {
1177         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_calculate_verify_data", ret);
1178         return ret;
1179     }
1180 
1181     return 0;
1182 }
1183 
1184 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_finished_message(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1185 static int ssl_tls13_parse_finished_message(mbedtls_ssl_context *ssl,
1186                                             const unsigned char *buf,
1187                                             const unsigned char *end)
1188 {
1189     /*
1190      * struct {
1191      *     opaque verify_data[Hash.length];
1192      * } Finished;
1193      */
1194     const unsigned char *expected_verify_data =
1195         ssl->handshake->state_local.finished_in.digest;
1196     size_t expected_verify_data_len =
1197         ssl->handshake->state_local.finished_in.digest_len;
1198     /* Structural validation */
1199     if ((size_t) (end - buf) != expected_verify_data_len) {
1200         MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
1201 
1202         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
1203                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
1204         return MBEDTLS_ERR_SSL_DECODE_ERROR;
1205     }
1206 
1207     MBEDTLS_SSL_DEBUG_BUF(4, "verify_data (self-computed):",
1208                           expected_verify_data,
1209                           expected_verify_data_len);
1210     MBEDTLS_SSL_DEBUG_BUF(4, "verify_data (received message):", buf,
1211                           expected_verify_data_len);
1212 
1213     /* Semantic validation */
1214     if (mbedtls_ct_memcmp(buf,
1215                           expected_verify_data,
1216                           expected_verify_data_len) != 0) {
1217         MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
1218 
1219         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
1220                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
1221         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1222     }
1223     return 0;
1224 }
1225 
mbedtls_ssl_tls13_process_finished_message(mbedtls_ssl_context * ssl)1226 int mbedtls_ssl_tls13_process_finished_message(mbedtls_ssl_context *ssl)
1227 {
1228     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1229     unsigned char *buf;
1230     size_t buf_len;
1231 
1232     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse finished message"));
1233 
1234     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
1235                              ssl, MBEDTLS_SSL_HS_FINISHED, &buf, &buf_len));
1236 
1237     /* Preprocessing step: Compute handshake digest */
1238     MBEDTLS_SSL_PROC_CHK(ssl_tls13_preprocess_finished_message(ssl));
1239 
1240     MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_finished_message(
1241                              ssl, buf, buf + buf_len));
1242 
1243     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
1244                              ssl, MBEDTLS_SSL_HS_FINISHED, buf, buf_len));
1245 
1246 cleanup:
1247 
1248     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse finished message"));
1249     return ret;
1250 }
1251 
1252 /*
1253  *
1254  * STATE HANDLING: Write and send Finished message.
1255  *
1256  */
1257 /*
1258  * Implement
1259  */
1260 
1261 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_prepare_finished_message(mbedtls_ssl_context * ssl)1262 static int ssl_tls13_prepare_finished_message(mbedtls_ssl_context *ssl)
1263 {
1264     int ret;
1265 
1266     /* Compute transcript of handshake up to now. */
1267     ret = mbedtls_ssl_tls13_calculate_verify_data(ssl,
1268                                                   ssl->handshake->state_local.finished_out.digest,
1269                                                   sizeof(ssl->handshake->state_local.finished_out.
1270                                                          digest),
1271                                                   &ssl->handshake->state_local.finished_out.digest_len,
1272                                                   ssl->conf->endpoint);
1273 
1274     if (ret != 0) {
1275         MBEDTLS_SSL_DEBUG_RET(1, "calculate_verify_data failed", ret);
1276         return ret;
1277     }
1278 
1279     return 0;
1280 }
1281 
1282 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_finished_message_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)1283 static int ssl_tls13_write_finished_message_body(mbedtls_ssl_context *ssl,
1284                                                  unsigned char *buf,
1285                                                  unsigned char *end,
1286                                                  size_t *out_len)
1287 {
1288     size_t verify_data_len = ssl->handshake->state_local.finished_out.digest_len;
1289     /*
1290      * struct {
1291      *     opaque verify_data[Hash.length];
1292      * } Finished;
1293      */
1294     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, verify_data_len);
1295 
1296     memcpy(buf, ssl->handshake->state_local.finished_out.digest,
1297            verify_data_len);
1298 
1299     *out_len = verify_data_len;
1300     return 0;
1301 }
1302 
1303 /* Main entry point: orchestrates the other functions */
mbedtls_ssl_tls13_write_finished_message(mbedtls_ssl_context * ssl)1304 int mbedtls_ssl_tls13_write_finished_message(mbedtls_ssl_context *ssl)
1305 {
1306     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1307     unsigned char *buf;
1308     size_t buf_len, msg_len;
1309 
1310     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write finished message"));
1311 
1312     MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_finished_message(ssl));
1313 
1314     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(ssl,
1315                                                          MBEDTLS_SSL_HS_FINISHED, &buf, &buf_len));
1316 
1317     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_finished_message_body(
1318                              ssl, buf, buf + buf_len, &msg_len));
1319 
1320     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(ssl,
1321                                                             MBEDTLS_SSL_HS_FINISHED, buf, msg_len));
1322 
1323     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
1324                              ssl, buf_len, msg_len));
1325 cleanup:
1326 
1327     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write finished message"));
1328     return ret;
1329 }
1330 
mbedtls_ssl_tls13_handshake_wrapup(mbedtls_ssl_context * ssl)1331 void mbedtls_ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl)
1332 {
1333 
1334     MBEDTLS_SSL_DEBUG_MSG(3, ("=> handshake wrapup"));
1335 
1336     MBEDTLS_SSL_DEBUG_MSG(1, ("Switch to application keys for inbound traffic"));
1337     mbedtls_ssl_set_inbound_transform(ssl, ssl->transform_application);
1338 
1339     MBEDTLS_SSL_DEBUG_MSG(1, ("Switch to application keys for outbound traffic"));
1340     mbedtls_ssl_set_outbound_transform(ssl, ssl->transform_application);
1341 
1342     /*
1343      * Free the previous session and switch to the current one.
1344      */
1345     if (ssl->session) {
1346         mbedtls_ssl_session_free(ssl->session);
1347         mbedtls_free(ssl->session);
1348     }
1349     ssl->session = ssl->session_negotiate;
1350     ssl->session_negotiate = NULL;
1351 
1352     MBEDTLS_SSL_DEBUG_MSG(3, ("<= handshake wrapup"));
1353 }
1354 
1355 /*
1356  *
1357  * STATE HANDLING: Write ChangeCipherSpec
1358  *
1359  */
1360 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
1361 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_change_cipher_spec_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * olen)1362 static int ssl_tls13_write_change_cipher_spec_body(mbedtls_ssl_context *ssl,
1363                                                    unsigned char *buf,
1364                                                    unsigned char *end,
1365                                                    size_t *olen)
1366 {
1367     ((void) ssl);
1368 
1369     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 1);
1370     buf[0] = 1;
1371     *olen = 1;
1372 
1373     return 0;
1374 }
1375 
mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context * ssl)1376 int mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context *ssl)
1377 {
1378     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1379 
1380     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write change cipher spec"));
1381 
1382     /* Write CCS message */
1383     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_change_cipher_spec_body(
1384                              ssl, ssl->out_msg,
1385                              ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
1386                              &ssl->out_msglen));
1387 
1388     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
1389 
1390     /* Dispatch message */
1391     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_write_record(ssl, 0));
1392 
1393 cleanup:
1394 
1395     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write change cipher spec"));
1396     return ret;
1397 }
1398 
1399 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
1400 
1401 /* Early Data Indication Extension
1402  *
1403  * struct {
1404  *   select ( Handshake.msg_type ) {
1405  *     ...
1406  *     case client_hello:         Empty;
1407  *     case encrypted_extensions: Empty;
1408  *   };
1409  * } EarlyDataIndication;
1410  */
1411 #if defined(MBEDTLS_SSL_EARLY_DATA)
mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * out_len)1412 int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
1413                                            unsigned char *buf,
1414                                            const unsigned char *end,
1415                                            size_t *out_len)
1416 {
1417     unsigned char *p = buf;
1418     *out_len = 0;
1419     ((void) ssl);
1420 
1421     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
1422 
1423     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_EARLY_DATA, p, 0);
1424     MBEDTLS_PUT_UINT16_BE(0, p, 2);
1425 
1426     *out_len = 4;
1427 
1428     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_EARLY_DATA);
1429 
1430     return 0;
1431 }
1432 #endif /* MBEDTLS_SSL_EARLY_DATA */
1433 
1434 /* Reset SSL context and update hash for handling HRR.
1435  *
1436  * Replace Transcript-Hash(X) by
1437  * Transcript-Hash( message_hash     ||
1438  *                 00 00 Hash.length ||
1439  *                 X )
1440  * A few states of the handshake are preserved, including:
1441  *   - session ID
1442  *   - session ticket
1443  *   - negotiated ciphersuite
1444  */
mbedtls_ssl_reset_transcript_for_hrr(mbedtls_ssl_context * ssl)1445 int mbedtls_ssl_reset_transcript_for_hrr(mbedtls_ssl_context *ssl)
1446 {
1447     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1448     unsigned char hash_transcript[PSA_HASH_MAX_SIZE + 4];
1449     size_t hash_len;
1450     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
1451         ssl->handshake->ciphersuite_info;
1452 
1453     MBEDTLS_SSL_DEBUG_MSG(3, ("Reset SSL session for HRR"));
1454 
1455     ret = mbedtls_ssl_get_handshake_transcript(ssl, ciphersuite_info->mac,
1456                                                hash_transcript + 4,
1457                                                PSA_HASH_MAX_SIZE,
1458                                                &hash_len);
1459     if (ret != 0) {
1460         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_get_handshake_transcript", ret);
1461         return ret;
1462     }
1463 
1464     hash_transcript[0] = MBEDTLS_SSL_HS_MESSAGE_HASH;
1465     hash_transcript[1] = 0;
1466     hash_transcript[2] = 0;
1467     hash_transcript[3] = (unsigned char) hash_len;
1468 
1469     hash_len += 4;
1470 
1471     MBEDTLS_SSL_DEBUG_BUF(4, "Truncated handshake transcript",
1472                           hash_transcript, hash_len);
1473 
1474     /* Reset running hash and replace it with a hash of the transcript */
1475     ret = mbedtls_ssl_reset_checksum(ssl);
1476     if (ret != 0) {
1477         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_reset_checksum", ret);
1478         return ret;
1479     }
1480     ret = ssl->handshake->update_checksum(ssl, hash_transcript, hash_len);
1481     if (ret != 0) {
1482         MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
1483         return ret;
1484     }
1485 
1486     return ret;
1487 }
1488 
1489 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
1490 
mbedtls_ssl_tls13_read_public_xxdhe_share(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t buf_len)1491 int mbedtls_ssl_tls13_read_public_xxdhe_share(mbedtls_ssl_context *ssl,
1492                                               const unsigned char *buf,
1493                                               size_t buf_len)
1494 {
1495     uint8_t *p = (uint8_t *) buf;
1496     const uint8_t *end = buf + buf_len;
1497     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1498 
1499     /* Get size of the TLS opaque key_exchange field of the KeyShareEntry struct. */
1500     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
1501     uint16_t peerkey_len = MBEDTLS_GET_UINT16_BE(p, 0);
1502     p += 2;
1503 
1504     /* Check if key size is consistent with given buffer length. */
1505     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, peerkey_len);
1506 
1507     /* Store peer's ECDH/FFDH public key. */
1508     if (peerkey_len > sizeof(handshake->xxdh_psa_peerkey)) {
1509         MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid public key length: %u > %" MBEDTLS_PRINTF_SIZET,
1510                                   (unsigned) peerkey_len,
1511                                   sizeof(handshake->xxdh_psa_peerkey)));
1512         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1513     }
1514     memcpy(handshake->xxdh_psa_peerkey, p, peerkey_len);
1515     handshake->xxdh_psa_peerkey_len = peerkey_len;
1516 
1517     return 0;
1518 }
1519 
1520 #if defined(PSA_WANT_ALG_FFDH)
mbedtls_ssl_get_psa_ffdh_info_from_tls_id(uint16_t tls_id,size_t * bits,psa_key_type_t * key_type)1521 static psa_status_t  mbedtls_ssl_get_psa_ffdh_info_from_tls_id(
1522     uint16_t tls_id, size_t *bits, psa_key_type_t *key_type)
1523 {
1524     switch (tls_id) {
1525         case MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048:
1526             *bits = 2048;
1527             *key_type = PSA_KEY_TYPE_DH_KEY_PAIR(PSA_DH_FAMILY_RFC7919);
1528             return PSA_SUCCESS;
1529         case MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE3072:
1530             *bits = 3072;
1531             *key_type =  PSA_KEY_TYPE_DH_KEY_PAIR(PSA_DH_FAMILY_RFC7919);
1532             return PSA_SUCCESS;
1533         case MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE4096:
1534             *bits = 4096;
1535             *key_type =  PSA_KEY_TYPE_DH_KEY_PAIR(PSA_DH_FAMILY_RFC7919);
1536             return PSA_SUCCESS;
1537         case MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE6144:
1538             *bits = 6144;
1539             *key_type =  PSA_KEY_TYPE_DH_KEY_PAIR(PSA_DH_FAMILY_RFC7919);
1540             return PSA_SUCCESS;
1541         case MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192:
1542             *bits = 8192;
1543             *key_type =  PSA_KEY_TYPE_DH_KEY_PAIR(PSA_DH_FAMILY_RFC7919);
1544             return PSA_SUCCESS;
1545         default:
1546             return PSA_ERROR_NOT_SUPPORTED;
1547     }
1548 }
1549 #endif /* PSA_WANT_ALG_FFDH */
1550 
mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(mbedtls_ssl_context * ssl,uint16_t named_group,unsigned char * buf,unsigned char * end,size_t * out_len)1551 int mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
1552     mbedtls_ssl_context *ssl,
1553     uint16_t named_group,
1554     unsigned char *buf,
1555     unsigned char *end,
1556     size_t *out_len)
1557 {
1558     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
1559     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1560     psa_key_attributes_t key_attributes;
1561     size_t own_pubkey_len;
1562     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1563     size_t bits = 0;
1564     psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
1565     psa_algorithm_t alg = PSA_ALG_NONE;
1566     size_t buf_size = (size_t) (end - buf);
1567 
1568     MBEDTLS_SSL_DEBUG_MSG(1, ("Perform PSA-based ECDH/FFDH computation."));
1569 
1570     /* Convert EC's TLS ID to PSA key type. */
1571 #if defined(PSA_WANT_ALG_ECDH)
1572     if (mbedtls_ssl_get_psa_curve_info_from_tls_id(
1573             named_group, &key_type, &bits) == PSA_SUCCESS) {
1574         alg = PSA_ALG_ECDH;
1575     }
1576 #endif
1577 #if defined(PSA_WANT_ALG_FFDH)
1578     if (mbedtls_ssl_get_psa_ffdh_info_from_tls_id(named_group, &bits,
1579                                                   &key_type) == PSA_SUCCESS) {
1580         alg = PSA_ALG_FFDH;
1581     }
1582 #endif
1583 
1584     if (key_type == PSA_KEY_TYPE_NONE) {
1585         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1586     }
1587 
1588     if (buf_size < PSA_BITS_TO_BYTES(bits)) {
1589         return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1590     }
1591 
1592     handshake->xxdh_psa_type = key_type;
1593     ssl->handshake->xxdh_psa_bits = bits;
1594 
1595     key_attributes = psa_key_attributes_init();
1596     psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
1597     psa_set_key_algorithm(&key_attributes, alg);
1598     psa_set_key_type(&key_attributes, handshake->xxdh_psa_type);
1599     psa_set_key_bits(&key_attributes, handshake->xxdh_psa_bits);
1600 
1601     /* Generate ECDH/FFDH private key. */
1602     status = psa_generate_key(&key_attributes,
1603                               &handshake->xxdh_psa_privkey);
1604     if (status != PSA_SUCCESS) {
1605         ret = PSA_TO_MBEDTLS_ERR(status);
1606         MBEDTLS_SSL_DEBUG_RET(1, "psa_generate_key", ret);
1607         return ret;
1608 
1609     }
1610 
1611     /* Export the public part of the ECDH/FFDH private key from PSA. */
1612     status = psa_export_public_key(handshake->xxdh_psa_privkey,
1613                                    buf, buf_size,
1614                                    &own_pubkey_len);
1615 
1616     if (status != PSA_SUCCESS) {
1617         ret = PSA_TO_MBEDTLS_ERR(status);
1618         MBEDTLS_SSL_DEBUG_RET(1, "psa_export_public_key", ret);
1619         return ret;
1620     }
1621 
1622     *out_len = own_pubkey_len;
1623 
1624     return 0;
1625 }
1626 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
1627 
1628 /* RFC 8446 section 4.2
1629  *
1630  * If an implementation receives an extension which it recognizes and which is
1631  * not specified for the message in which it appears, it MUST abort the handshake
1632  * with an "illegal_parameter" alert.
1633  *
1634  */
mbedtls_ssl_tls13_check_received_extension(mbedtls_ssl_context * ssl,int hs_msg_type,unsigned int received_extension_type,uint32_t hs_msg_allowed_extensions_mask)1635 int mbedtls_ssl_tls13_check_received_extension(
1636     mbedtls_ssl_context *ssl,
1637     int hs_msg_type,
1638     unsigned int received_extension_type,
1639     uint32_t hs_msg_allowed_extensions_mask)
1640 {
1641     uint32_t extension_mask = mbedtls_ssl_get_extension_mask(
1642         received_extension_type);
1643 
1644     MBEDTLS_SSL_PRINT_EXT(
1645         3, hs_msg_type, received_extension_type, "received");
1646 
1647     if ((extension_mask & hs_msg_allowed_extensions_mask) == 0) {
1648         MBEDTLS_SSL_PRINT_EXT(
1649             3, hs_msg_type, received_extension_type, "is illegal");
1650         MBEDTLS_SSL_PEND_FATAL_ALERT(
1651             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1652             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1653         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1654     }
1655 
1656     ssl->handshake->received_extensions |= extension_mask;
1657     /*
1658      * If it is a message containing extension responses, check that we
1659      * previously sent the extension.
1660      */
1661     switch (hs_msg_type) {
1662         case MBEDTLS_SSL_HS_SERVER_HELLO:
1663         case MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST:
1664         case MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS:
1665         case MBEDTLS_SSL_HS_CERTIFICATE:
1666             /* Check if the received extension is sent by peer message.*/
1667             if ((ssl->handshake->sent_extensions & extension_mask) != 0) {
1668                 return 0;
1669             }
1670             break;
1671         default:
1672             return 0;
1673     }
1674 
1675     MBEDTLS_SSL_PRINT_EXT(
1676         3, hs_msg_type, received_extension_type, "is unsupported");
1677     MBEDTLS_SSL_PEND_FATAL_ALERT(
1678         MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT,
1679         MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION);
1680     return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
1681 }
1682 
1683 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
1684 /* RFC 8449, section 4:
1685  *
1686  * The ExtensionData of the "record_size_limit" extension is
1687  * RecordSizeLimit:
1688  *     uint16 RecordSizeLimit;
1689  */
1690 MBEDTLS_CHECK_RETURN_CRITICAL
mbedtls_ssl_tls13_parse_record_size_limit_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1691 int mbedtls_ssl_tls13_parse_record_size_limit_ext(mbedtls_ssl_context *ssl,
1692                                                   const unsigned char *buf,
1693                                                   const unsigned char *end)
1694 {
1695     const unsigned char *p = buf;
1696     uint16_t record_size_limit;
1697     const size_t extension_data_len = end - buf;
1698 
1699     if (extension_data_len !=
1700         MBEDTLS_SSL_RECORD_SIZE_LIMIT_EXTENSION_DATA_LENGTH) {
1701         MBEDTLS_SSL_DEBUG_MSG(2,
1702                               ("record_size_limit extension has invalid length: %"
1703                                MBEDTLS_PRINTF_SIZET " Bytes",
1704                                extension_data_len));
1705 
1706         MBEDTLS_SSL_PEND_FATAL_ALERT(
1707             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1708             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1709         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1710     }
1711 
1712     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
1713     record_size_limit = MBEDTLS_GET_UINT16_BE(p, 0);
1714 
1715     MBEDTLS_SSL_DEBUG_MSG(2, ("RecordSizeLimit: %u Bytes", record_size_limit));
1716 
1717     /* RFC 8449, section 4
1718      *
1719      * Endpoints MUST NOT send a "record_size_limit" extension with a value
1720      * smaller than 64.  An endpoint MUST treat receipt of a smaller value
1721      * as a fatal error and generate an "illegal_parameter" alert.
1722      */
1723     if (record_size_limit < MBEDTLS_SSL_RECORD_SIZE_LIMIT_MIN) {
1724         MBEDTLS_SSL_PEND_FATAL_ALERT(
1725             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1726             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1727         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1728     }
1729 
1730     MBEDTLS_SSL_DEBUG_MSG(
1731         2, ("record_size_limit extension is still in development. Aborting handshake."));
1732 
1733     MBEDTLS_SSL_PEND_FATAL_ALERT(
1734         MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT,
1735         MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION);
1736     return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
1737 }
1738 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
1739 
1740 #endif /* MBEDTLS_SSL_TLS_C && MBEDTLS_SSL_PROTO_TLS1_3 */
1741