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
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_SSL_TLS_C)
23 
24 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
25 
26 #include <string.h>
27 
28 #include "mbedtls/error.h"
29 #include "mbedtls/debug.h"
30 #include "mbedtls/oid.h"
31 #include "mbedtls/platform.h"
32 
33 #include "ssl_misc.h"
34 #include "ssl_tls13_keys.h"
35 
mbedtls_ssl_tls1_3_fetch_handshake_msg(mbedtls_ssl_context * ssl,unsigned hs_type,unsigned char ** buf,size_t * buflen)36 int mbedtls_ssl_tls1_3_fetch_handshake_msg( mbedtls_ssl_context *ssl,
37                                             unsigned hs_type,
38                                             unsigned char **buf,
39                                             size_t *buflen )
40 {
41     int ret;
42 
43     if( ( ret = mbedtls_ssl_read_record( ssl, 0 ) ) != 0 )
44     {
45         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
46         goto cleanup;
47     }
48 
49     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
50         ssl->in_msg[0]  != hs_type )
51     {
52         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Receive unexpected handshake message." ) );
53         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
54                                       MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
55         ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
56         goto cleanup;
57     }
58 
59     /*
60      * Jump handshake header (4 bytes, see Section 4 of RFC 8446).
61      *    ...
62      *    HandshakeType msg_type;
63      *    uint24 length;
64      *    ...
65      */
66     *buf    = ssl->in_msg   + 4;
67     *buflen = ssl->in_hslen - 4;
68 
69 cleanup:
70 
71     return( ret );
72 }
73 
mbedtls_ssl_tls13_start_handshake_msg(mbedtls_ssl_context * ssl,unsigned hs_type,unsigned char ** buf,size_t * buf_len)74 int mbedtls_ssl_tls13_start_handshake_msg( mbedtls_ssl_context *ssl,
75                                            unsigned hs_type,
76                                            unsigned char **buf,
77                                            size_t *buf_len )
78 {
79     /*
80      * Reserve 4 bytes for hanshake header. ( Section 4,RFC 8446 )
81      *    ...
82      *    HandshakeType msg_type;
83      *    uint24 length;
84      *    ...
85      */
86     *buf = ssl->out_msg + 4;
87     *buf_len = MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
88 
89     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
90     ssl->out_msg[0]  = hs_type;
91 
92     return( 0 );
93 }
94 
mbedtls_ssl_tls13_finish_handshake_msg(mbedtls_ssl_context * ssl,size_t buf_len,size_t msg_len)95 int mbedtls_ssl_tls13_finish_handshake_msg( mbedtls_ssl_context *ssl,
96                                             size_t buf_len,
97                                             size_t msg_len )
98 {
99     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
100     size_t msg_len_with_header;
101     ((void) buf_len);
102 
103     /* Add reserved 4 bytes for handshake header */
104     msg_len_with_header = msg_len + 4;
105     ssl->out_msglen = msg_len_with_header;
106     MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_write_handshake_msg_ext( ssl, 0 ) );
107 
108 cleanup:
109     return( ret );
110 }
111 
mbedtls_ssl_tls1_3_add_hs_msg_to_checksum(mbedtls_ssl_context * ssl,unsigned hs_type,unsigned char const * msg,size_t msg_len)112 void mbedtls_ssl_tls1_3_add_hs_msg_to_checksum( mbedtls_ssl_context *ssl,
113                                                 unsigned hs_type,
114                                                 unsigned char const *msg,
115                                                 size_t msg_len )
116 {
117     mbedtls_ssl_tls13_add_hs_hdr_to_checksum( ssl, hs_type, msg_len );
118     ssl->handshake->update_checksum( ssl, msg, msg_len );
119 }
120 
mbedtls_ssl_tls13_add_hs_hdr_to_checksum(mbedtls_ssl_context * ssl,unsigned hs_type,size_t total_hs_len)121 void mbedtls_ssl_tls13_add_hs_hdr_to_checksum( mbedtls_ssl_context *ssl,
122                                                unsigned hs_type,
123                                                size_t total_hs_len )
124 {
125     unsigned char hs_hdr[4];
126 
127     /* Build HS header for checksum update. */
128     hs_hdr[0] = MBEDTLS_BYTE_0( hs_type );
129     hs_hdr[1] = MBEDTLS_BYTE_2( total_hs_len );
130     hs_hdr[2] = MBEDTLS_BYTE_1( total_hs_len );
131     hs_hdr[3] = MBEDTLS_BYTE_0( total_hs_len );
132 
133     ssl->handshake->update_checksum( ssl, hs_hdr, sizeof( hs_hdr ) );
134 }
135 
136 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
137 
138 /*
139  * mbedtls_ssl_tls13_write_sig_alg_ext( )
140  *
141  * enum {
142  *    ....
143  *   ecdsa_secp256r1_sha256( 0x0403 ),
144  *   ecdsa_secp384r1_sha384( 0x0503 ),
145  *   ecdsa_secp521r1_sha512( 0x0603 ),
146  *    ....
147  * } SignatureScheme;
148  *
149  * struct {
150  *    SignatureScheme supported_signature_algorithms<2..2^16-2>;
151  * } SignatureSchemeList;
152  *
153  * Only if we handle at least one key exchange that needs signatures.
154  */
mbedtls_ssl_tls13_write_sig_alg_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * olen)155 int mbedtls_ssl_tls13_write_sig_alg_ext( mbedtls_ssl_context *ssl,
156                                          unsigned char *buf,
157                                          unsigned char *end,
158                                          size_t *olen )
159 {
160     unsigned char *p = buf;
161     unsigned char *supported_sig_alg_ptr; /* Start of supported_signature_algorithms */
162     size_t supported_sig_alg_len = 0;     /* Length of supported_signature_algorithms */
163 
164     *olen = 0;
165 
166     /* Skip the extension on the client if all allowed key exchanges
167      * are PSK-based. */
168 #if defined(MBEDTLS_SSL_CLI_C)
169     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
170         !mbedtls_ssl_conf_tls13_some_ephemeral_enabled( ssl ) )
171     {
172         return( 0 );
173     }
174 #endif /* MBEDTLS_SSL_CLI_C */
175 
176     MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding signature_algorithms extension" ) );
177 
178     /* Check if we have space for header and length field:
179      * - extension_type         (2 bytes)
180      * - extension_data_length  (2 bytes)
181      * - supported_signature_algorithms_length   (2 bytes)
182      */
183     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 );
184     p += 6;
185 
186     /*
187      * Write supported_signature_algorithms
188      */
189     supported_sig_alg_ptr = p;
190     for( const uint16_t *sig_alg = ssl->conf->tls13_sig_algs;
191          *sig_alg != MBEDTLS_TLS13_SIG_NONE; sig_alg++ )
192     {
193         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
194         MBEDTLS_PUT_UINT16_BE( *sig_alg, p, 0 );
195         p += 2;
196         MBEDTLS_SSL_DEBUG_MSG( 3, ( "signature scheme [%x]", *sig_alg ) );
197     }
198 
199     /* Length of supported_signature_algorithms */
200     supported_sig_alg_len = p - supported_sig_alg_ptr;
201     if( supported_sig_alg_len == 0 )
202     {
203         MBEDTLS_SSL_DEBUG_MSG( 1, ( "No signature algorithms defined." ) );
204         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
205     }
206 
207     /* Write extension_type */
208     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SIG_ALG, buf, 0 );
209     /* Write extension_data_length */
210     MBEDTLS_PUT_UINT16_BE( supported_sig_alg_len + 2, buf, 2 );
211     /* Write length of supported_signature_algorithms */
212     MBEDTLS_PUT_UINT16_BE( supported_sig_alg_len, buf, 4 );
213 
214     /* Output the total length of signature algorithms extension. */
215     *olen = p - buf;
216 
217     ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SIG_ALG;
218     return( 0 );
219 }
220 
221 /*
222  * STATE HANDLING: Read CertificateVerify
223  */
224 /* Macro to express the maximum length of the verify structure.
225  *
226  * The structure is computed per TLS 1.3 specification as:
227  *   - 64 bytes of octet 32,
228  *   - 33 bytes for the context string
229  *        (which is either "TLS 1.3, client CertificateVerify"
230  *         or "TLS 1.3, server CertificateVerify"),
231  *   - 1 byte for the octet 0x0, which serves as a separator,
232  *   - 32 or 48 bytes for the Transcript-Hash(Handshake Context, Certificate)
233  *     (depending on the size of the transcript_hash)
234  *
235  * This results in a total size of
236  * - 130 bytes for a SHA256-based transcript hash, or
237  *   (64 + 33 + 1 + 32 bytes)
238  * - 146 bytes for a SHA384-based transcript hash.
239  *   (64 + 33 + 1 + 48 bytes)
240  *
241  */
242 #define SSL_VERIFY_STRUCT_MAX_SIZE  ( 64 +                          \
243                                       33 +                          \
244                                        1 +                          \
245                                       MBEDTLS_TLS1_3_MD_MAX_SIZE    \
246                                     )
247 
248 /*
249  * The ssl_tls13_create_verify_structure() creates the verify structure.
250  * As input, it requires the transcript hash.
251  *
252  * The caller has to ensure that the buffer has size at least
253  * SSL_VERIFY_STRUCT_MAX_SIZE bytes.
254  */
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)255 static void ssl_tls13_create_verify_structure( const unsigned char *transcript_hash,
256                                                size_t transcript_hash_len,
257                                                unsigned char *verify_buffer,
258                                                size_t *verify_buffer_len,
259                                                int from )
260 {
261     size_t idx;
262 
263     /* RFC 8446, Section 4.4.3:
264      *
265      * The digital signature [in the CertificateVerify message] is then
266      * computed over the concatenation of:
267      * -  A string that consists of octet 32 (0x20) repeated 64 times
268      * -  The context string
269      * -  A single 0 byte which serves as the separator
270      * -  The content to be signed
271      */
272     memset( verify_buffer, 0x20, 64 );
273     idx = 64;
274 
275     if( from == MBEDTLS_SSL_IS_CLIENT )
276     {
277         memcpy( verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( client_cv ) );
278         idx += MBEDTLS_SSL_TLS1_3_LBL_LEN( client_cv );
279     }
280     else
281     { /* from == MBEDTLS_SSL_IS_SERVER */
282         memcpy( verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( server_cv ) );
283         idx += MBEDTLS_SSL_TLS1_3_LBL_LEN( server_cv );
284     }
285 
286     verify_buffer[idx++] = 0x0;
287 
288     memcpy( verify_buffer + idx, transcript_hash, transcript_hash_len );
289     idx += transcript_hash_len;
290 
291     *verify_buffer_len = idx;
292 }
293 
ssl_tls13_sig_alg_is_offered(const mbedtls_ssl_context * ssl,uint16_t sig_alg)294 static int ssl_tls13_sig_alg_is_offered( const mbedtls_ssl_context *ssl,
295                                          uint16_t sig_alg )
296 {
297     const uint16_t *tls13_sig_alg = ssl->conf->tls13_sig_algs;
298 
299     for( ; *tls13_sig_alg != MBEDTLS_TLS13_SIG_NONE ; tls13_sig_alg++ )
300     {
301         if( *tls13_sig_alg == sig_alg )
302             return( 1 );
303     }
304     return( 0 );
305 }
306 
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)307 static int ssl_tls13_parse_certificate_verify( mbedtls_ssl_context *ssl,
308                                                const unsigned char *buf,
309                                                const unsigned char *end,
310                                                const unsigned char *verify_buffer,
311                                                size_t verify_buffer_len )
312 {
313     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
314     const unsigned char *p = buf;
315     uint16_t algorithm;
316     size_t signature_len;
317     mbedtls_pk_type_t sig_alg;
318     mbedtls_md_type_t md_alg;
319     unsigned char verify_hash[MBEDTLS_MD_MAX_SIZE];
320     size_t verify_hash_len;
321 
322     /*
323      * struct {
324      *     SignatureScheme algorithm;
325      *     opaque signature<0..2^16-1>;
326      * } CertificateVerify;
327      */
328     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
329     algorithm = MBEDTLS_GET_UINT16_BE( p, 0 );
330     p += 2;
331 
332     /* RFC 8446 section 4.4.3
333      *
334      * If the CertificateVerify message is sent by a server, the signature algorithm
335      * MUST be one offered in the client's "signature_algorithms" extension unless
336      * no valid certificate chain can be produced without unsupported algorithms
337      *
338      * RFC 8446 section 4.4.2.2
339      *
340      * If the client cannot construct an acceptable chain using the provided
341      * certificates and decides to abort the handshake, then it MUST abort the handshake
342      * with an appropriate certificate-related alert (by default, "unsupported_certificate").
343      *
344      * Check if algorithm is an offered signature algorithm.
345      */
346     if( ! ssl_tls13_sig_alg_is_offered( ssl, algorithm ) )
347     {
348         /* algorithm not in offered signature algorithms list */
349         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Received signature algorithm(%04x) is not "
350                                     "offered.",
351                                     ( unsigned int ) algorithm ) );
352         goto error;
353     }
354 
355     /* We currently only support ECDSA-based signatures */
356     switch( algorithm )
357     {
358         case MBEDTLS_TLS13_SIG_ECDSA_SECP256R1_SHA256:
359             md_alg = MBEDTLS_MD_SHA256;
360             sig_alg = MBEDTLS_PK_ECDSA;
361             break;
362         case MBEDTLS_TLS13_SIG_ECDSA_SECP384R1_SHA384:
363             md_alg = MBEDTLS_MD_SHA384;
364             sig_alg = MBEDTLS_PK_ECDSA;
365             break;
366         case MBEDTLS_TLS13_SIG_ECDSA_SECP521R1_SHA512:
367             md_alg = MBEDTLS_MD_SHA512;
368             sig_alg = MBEDTLS_PK_ECDSA;
369             break;
370         default:
371             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Certificate Verify: Unknown signature algorithm." ) );
372             goto error;
373     }
374 
375     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate Verify: Signature algorithm ( %04x )",
376                                 ( unsigned int ) algorithm ) );
377 
378     /*
379      * Check the certificate's key type matches the signature alg
380      */
381     if( !mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, sig_alg ) )
382     {
383         MBEDTLS_SSL_DEBUG_MSG( 1, ( "signature algorithm doesn't match cert key" ) );
384         goto error;
385     }
386 
387     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
388     signature_len = MBEDTLS_GET_UINT16_BE( p, 0 );
389     p += 2;
390     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, signature_len );
391 
392     /* Hash verify buffer with indicated hash function */
393     switch( md_alg )
394     {
395 #if defined(MBEDTLS_SHA256_C)
396         case MBEDTLS_MD_SHA256:
397             verify_hash_len = 32;
398             ret = mbedtls_sha256( verify_buffer, verify_buffer_len, verify_hash, 0 );
399             break;
400 #endif /* MBEDTLS_SHA256_C */
401 
402 #if defined(MBEDTLS_SHA384_C)
403         case MBEDTLS_MD_SHA384:
404             verify_hash_len = 48;
405             ret = mbedtls_sha512( verify_buffer, verify_buffer_len, verify_hash, 1 );
406             break;
407 #endif /* MBEDTLS_SHA384_C */
408 
409 #if defined(MBEDTLS_SHA512_C)
410         case MBEDTLS_MD_SHA512:
411             verify_hash_len = 64;
412             ret = mbedtls_sha512( verify_buffer, verify_buffer_len, verify_hash, 0 );
413             break;
414 #endif /* MBEDTLS_SHA512_C */
415 
416         default:
417             ret = MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
418             break;
419     }
420 
421     if( ret != 0 )
422     {
423         MBEDTLS_SSL_DEBUG_RET( 1, "hash computation error", ret );
424         goto error;
425     }
426 
427     MBEDTLS_SSL_DEBUG_BUF( 3, "verify hash", verify_hash, verify_hash_len );
428 
429     if( ( ret = mbedtls_pk_verify_ext( sig_alg, NULL,
430                                        &ssl->session_negotiate->peer_cert->pk,
431                                        md_alg, verify_hash, verify_hash_len,
432                                        p, signature_len ) ) == 0 )
433     {
434         return( 0 );
435     }
436     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify_ext", ret );
437 
438 error:
439     /* RFC 8446 section 4.4.3
440      *
441      * If the verification fails, the receiver MUST terminate the handshake
442      * with a "decrypt_error" alert.
443     */
444     MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
445                                   MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
446     return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
447 
448 }
449 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
450 
mbedtls_ssl_tls13_process_certificate_verify(mbedtls_ssl_context * ssl)451 int mbedtls_ssl_tls13_process_certificate_verify( mbedtls_ssl_context *ssl )
452 {
453 
454 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
455     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
456     unsigned char verify_buffer[SSL_VERIFY_STRUCT_MAX_SIZE];
457     size_t verify_buffer_len;
458     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
459     size_t transcript_len;
460     unsigned char *buf;
461     size_t buf_len;
462 
463     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
464 
465     MBEDTLS_SSL_PROC_CHK(
466         mbedtls_ssl_tls1_3_fetch_handshake_msg( ssl,
467                 MBEDTLS_SSL_HS_CERTIFICATE_VERIFY, &buf, &buf_len ) );
468 
469     /* Need to calculate the hash of the transcript first
470      * before reading the message since otherwise it gets
471      * included in the transcript
472      */
473     ret = mbedtls_ssl_get_handshake_transcript( ssl,
474                             ssl->handshake->ciphersuite_info->mac,
475                             transcript, sizeof( transcript ),
476                             &transcript_len );
477     if( ret != 0 )
478     {
479         MBEDTLS_SSL_PEND_FATAL_ALERT(
480             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
481             MBEDTLS_ERR_SSL_INTERNAL_ERROR );
482         return( ret );
483     }
484 
485     MBEDTLS_SSL_DEBUG_BUF( 3, "handshake hash", transcript, transcript_len );
486 
487     /* Create verify structure */
488     ssl_tls13_create_verify_structure( transcript,
489                                        transcript_len,
490                                        verify_buffer,
491                                        &verify_buffer_len,
492                                        ( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ?
493                                          MBEDTLS_SSL_IS_SERVER :
494                                          MBEDTLS_SSL_IS_CLIENT );
495 
496     /* Process the message contents */
497     MBEDTLS_SSL_PROC_CHK( ssl_tls13_parse_certificate_verify( ssl, buf,
498                             buf + buf_len, verify_buffer, verify_buffer_len ) );
499 
500     mbedtls_ssl_tls1_3_add_hs_msg_to_checksum( ssl,
501                         MBEDTLS_SSL_HS_CERTIFICATE_VERIFY, buf, buf_len );
502 
503 cleanup:
504 
505     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
506     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_tls13_process_certificate_verify", ret );
507     return( ret );
508 #else
509     ((void) ssl);
510     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
511     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
512 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
513 }
514 
515 /*
516  *
517  * STATE HANDLING: Incoming Certificate, client-side only currently.
518  *
519  */
520 
521 /*
522  * Implementation
523  */
524 
525 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
526 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
527 /*
528  * Structure of Certificate message:
529  *
530  * enum {
531  *     X509(0),
532  *     RawPublicKey(2),
533  *     (255)
534  * } CertificateType;
535  *
536  * struct {
537  *     select (certificate_type) {
538  *         case RawPublicKey:
539  *           * From RFC 7250 ASN.1_subjectPublicKeyInfo *
540  *           opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
541  *         case X509:
542  *           opaque cert_data<1..2^24-1>;
543  *     };
544  *     Extension extensions<0..2^16-1>;
545  * } CertificateEntry;
546  *
547  * struct {
548  *     opaque certificate_request_context<0..2^8-1>;
549  *     CertificateEntry certificate_list<0..2^24-1>;
550  * } Certificate;
551  *
552  */
553 
554 /* Parse certificate chain send by the server. */
ssl_tls13_parse_certificate(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)555 static int ssl_tls13_parse_certificate( mbedtls_ssl_context *ssl,
556                                         const unsigned char *buf,
557                                         const unsigned char *end )
558 {
559     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
560     size_t certificate_request_context_len = 0;
561     size_t certificate_list_len = 0;
562     const unsigned char *p = buf;
563     const unsigned char *certificate_list_end;
564 
565     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 4 );
566     certificate_request_context_len = p[0];
567     certificate_list_len = MBEDTLS_GET_UINT24_BE( p, 1 );
568     p += 4;
569 
570     /* In theory, the certificate list can be up to 2^24 Bytes, but we don't
571      * support anything beyond 2^16 = 64K.
572      */
573     if( ( certificate_request_context_len != 0 ) ||
574         ( certificate_list_len >= 0x10000 ) )
575     {
576         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
577         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
578                                       MBEDTLS_ERR_SSL_DECODE_ERROR );
579         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
580     }
581 
582     /* In case we tried to reuse a session but it failed */
583     if( ssl->session_negotiate->peer_cert != NULL )
584     {
585         mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
586         mbedtls_free( ssl->session_negotiate->peer_cert );
587     }
588 
589     if( ( ssl->session_negotiate->peer_cert =
590           mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ) ) == NULL )
591     {
592         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc( %" MBEDTLS_PRINTF_SIZET " bytes ) failed",
593                                     sizeof( mbedtls_x509_crt ) ) );
594         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
595                                       MBEDTLS_ERR_SSL_ALLOC_FAILED );
596         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
597     }
598 
599     mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
600 
601     certificate_list_end = p + certificate_list_len;
602     while( p < certificate_list_end )
603     {
604         size_t cert_data_len, extensions_len;
605 
606         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, 3 );
607         cert_data_len = MBEDTLS_GET_UINT24_BE( p, 0 );
608         p += 3;
609 
610         /* In theory, the CRT can be up to 2^24 Bytes, but we don't support
611          * anything beyond 2^16 = 64K. Otherwise as in the TLS 1.2 code,
612          * check that we have a minimum of 128 bytes of data, this is not
613          * clear why we need that though.
614          */
615         if( ( cert_data_len < 128 ) || ( cert_data_len >= 0x10000 ) )
616         {
617             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad Certificate message" ) );
618             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
619                                           MBEDTLS_ERR_SSL_DECODE_ERROR );
620             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
621         }
622 
623         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, cert_data_len );
624         ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
625                                           p, cert_data_len );
626 
627         switch( ret )
628         {
629             case 0: /*ok*/
630                 break;
631             case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
632                 /* Ignore certificate with an unknown algorithm: maybe a
633                    prior certificate was already trusted. */
634                 break;
635 
636             case MBEDTLS_ERR_X509_ALLOC_FAILED:
637                 MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
638                                               MBEDTLS_ERR_X509_ALLOC_FAILED );
639                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
640                 return( ret );
641 
642             case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
643                 MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT,
644                                               MBEDTLS_ERR_X509_UNKNOWN_VERSION );
645                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
646                 return( ret );
647 
648             default:
649                 MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_BAD_CERT,
650                                               ret );
651                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
652                 return( ret );
653         }
654 
655         p += cert_data_len;
656 
657         /* Certificate extensions length */
658         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, 2 );
659         extensions_len = MBEDTLS_GET_UINT16_BE( p, 0 );
660         p += 2;
661         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, extensions_len );
662         p += extensions_len;
663     }
664 
665     /* Check that all the message is consumed. */
666     if( p != end )
667     {
668         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad Certificate message" ) );
669         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR, \
670                                       MBEDTLS_ERR_SSL_DECODE_ERROR );
671         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
672     }
673 
674     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
675 
676     return( ret );
677 }
678 #else
ssl_tls13_parse_certificate(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)679 static int ssl_tls13_parse_certificate( mbedtls_ssl_context *ssl,
680                                         const unsigned char *buf,
681                                         const unsigned char *end )
682 {
683     ((void) ssl);
684     ((void) buf);
685     ((void) end);
686     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
687 }
688 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
689 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
690 
691 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
692 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
693 /* Validate certificate chain sent by the server. */
ssl_tls13_validate_certificate(mbedtls_ssl_context * ssl)694 static int ssl_tls13_validate_certificate( mbedtls_ssl_context *ssl )
695 {
696     int ret = 0;
697     mbedtls_x509_crt *ca_chain;
698     mbedtls_x509_crl *ca_crl;
699     uint32_t verify_result = 0;
700 
701 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
702     if( ssl->handshake->sni_ca_chain != NULL )
703     {
704         ca_chain = ssl->handshake->sni_ca_chain;
705         ca_crl = ssl->handshake->sni_ca_crl;
706     }
707     else
708 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
709     {
710         ca_chain = ssl->conf->ca_chain;
711         ca_crl = ssl->conf->ca_crl;
712     }
713 
714     /*
715      * Main check: verify certificate
716      */
717     ret = mbedtls_x509_crt_verify_with_profile(
718         ssl->session_negotiate->peer_cert,
719         ca_chain, ca_crl,
720         ssl->conf->cert_profile,
721         ssl->hostname,
722         &verify_result,
723         ssl->conf->f_vrfy, ssl->conf->p_vrfy );
724 
725     if( ret != 0 )
726     {
727         MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
728     }
729 
730     /*
731      * Secondary checks: always done, but change 'ret' only if it was 0
732      */
733 
734 #if defined(MBEDTLS_ECP_C)
735     {
736         const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
737 
738         /* If certificate uses an EC key, make sure the curve is OK */
739         if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
740             mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
741         {
742             verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
743 
744             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate ( EC key curve )" ) );
745             if( ret == 0 )
746                 ret = MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
747         }
748     }
749 #endif /* MBEDTLS_ECP_C */
750 
751     if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
752                                       ssl->handshake->ciphersuite_info,
753                                       !ssl->conf->endpoint,
754                                       &verify_result ) != 0 )
755     {
756         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate ( usage extensions )" ) );
757         if( ret == 0 )
758             ret = MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
759     }
760 
761 
762     if( ca_chain == NULL )
763     {
764         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
765         ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
766     }
767 
768     if( ret != 0 )
769     {
770         /* The certificate may have been rejected for several reasons.
771            Pick one and send the corresponding alert. Which alert to send
772            may be a subject of debate in some cases. */
773         if( verify_result & MBEDTLS_X509_BADCERT_OTHER )
774             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED, ret );
775         else if( verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
776             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_BAD_CERT, ret );
777         else if( verify_result & ( MBEDTLS_X509_BADCERT_KEY_USAGE |
778                                    MBEDTLS_X509_BADCERT_EXT_KEY_USAGE |
779                                    MBEDTLS_X509_BADCERT_NS_CERT_TYPE |
780                                    MBEDTLS_X509_BADCERT_BAD_PK |
781                                    MBEDTLS_X509_BADCERT_BAD_KEY ) )
782             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT, ret );
783         else if( verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
784             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED, ret );
785         else if( verify_result & MBEDTLS_X509_BADCERT_REVOKED )
786             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED, ret );
787         else if( verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
788             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA, ret );
789         else
790             MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN, ret );
791     }
792 
793 #if defined(MBEDTLS_DEBUG_C)
794     if( verify_result != 0 )
795     {
796         MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %08x",
797                                     (unsigned int) verify_result ) );
798     }
799     else
800     {
801         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
802     }
803 #endif /* MBEDTLS_DEBUG_C */
804 
805     ssl->session_negotiate->verify_result = verify_result;
806     return( ret );
807 }
808 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
ssl_tls13_validate_certificate(mbedtls_ssl_context * ssl)809 static int ssl_tls13_validate_certificate( mbedtls_ssl_context *ssl )
810 {
811     ((void) ssl);
812     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
813 }
814 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
815 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
816 
mbedtls_ssl_tls13_process_certificate(mbedtls_ssl_context * ssl)817 int mbedtls_ssl_tls13_process_certificate( mbedtls_ssl_context *ssl )
818 {
819     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
820     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
821 
822 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
823     unsigned char *buf;
824     size_t buf_len;
825 
826     MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_tls1_3_fetch_handshake_msg(
827                           ssl, MBEDTLS_SSL_HS_CERTIFICATE,
828                           &buf, &buf_len ) );
829 
830     /* Parse the certificate chain sent by the peer. */
831     MBEDTLS_SSL_PROC_CHK( ssl_tls13_parse_certificate( ssl, buf, buf + buf_len ) );
832     /* Validate the certificate chain and set the verification results. */
833     MBEDTLS_SSL_PROC_CHK( ssl_tls13_validate_certificate( ssl ) );
834 
835     mbedtls_ssl_tls1_3_add_hs_msg_to_checksum( ssl, MBEDTLS_SSL_HS_CERTIFICATE,
836                                                buf, buf_len );
837 
838 cleanup:
839 
840     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
841 #else
842     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
843     ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
844 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
845     return( ret );
846 }
847 
848 /*
849  *
850  * STATE HANDLING: Incoming Finished message.
851  */
852 /*
853  * Implementation
854  */
855 
ssl_tls13_preprocess_finished_message(mbedtls_ssl_context * ssl)856 static int ssl_tls13_preprocess_finished_message( mbedtls_ssl_context *ssl )
857 {
858     int ret;
859 
860     ret = mbedtls_ssl_tls13_calculate_verify_data( ssl,
861                     ssl->handshake->state_local.finished_in.digest,
862                     sizeof( ssl->handshake->state_local.finished_in.digest ),
863                     &ssl->handshake->state_local.finished_in.digest_len,
864                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ?
865                         MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT );
866     if( ret != 0 )
867     {
868         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_tls13_calculate_verify_data", ret );
869         return( ret );
870     }
871 
872     return( 0 );
873 }
874 
ssl_tls13_parse_finished_message(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)875 static int ssl_tls13_parse_finished_message( mbedtls_ssl_context *ssl,
876                                              const unsigned char *buf,
877                                              const unsigned char *end )
878 {
879     /*
880      * struct {
881      *     opaque verify_data[Hash.length];
882      * } Finished;
883      */
884     const unsigned char *expected_verify_data =
885         ssl->handshake->state_local.finished_in.digest;
886     size_t expected_verify_data_len =
887         ssl->handshake->state_local.finished_in.digest_len;
888     /* Structural validation */
889     if( (size_t)( end - buf ) != expected_verify_data_len )
890     {
891         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
892 
893         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
894                                       MBEDTLS_ERR_SSL_DECODE_ERROR );
895         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
896     }
897 
898     MBEDTLS_SSL_DEBUG_BUF( 4, "verify_data (self-computed):",
899                            expected_verify_data,
900                            expected_verify_data_len );
901     MBEDTLS_SSL_DEBUG_BUF( 4, "verify_data (received message):", buf,
902                            expected_verify_data_len );
903 
904     /* Semantic validation */
905     if( mbedtls_ssl_safer_memcmp( buf,
906                                   expected_verify_data,
907                                   expected_verify_data_len ) != 0 )
908     {
909         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
910 
911         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
912                                       MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
913         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
914     }
915     return( 0 );
916 }
917 
918 #if defined(MBEDTLS_SSL_CLI_C)
ssl_tls13_postprocess_server_finished_message(mbedtls_ssl_context * ssl)919 static int ssl_tls13_postprocess_server_finished_message( mbedtls_ssl_context *ssl )
920 {
921     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
922     mbedtls_ssl_key_set traffic_keys;
923     mbedtls_ssl_transform *transform_application = NULL;
924 
925     ret = mbedtls_ssl_tls13_key_schedule_stage_application( ssl );
926     if( ret != 0 )
927     {
928         MBEDTLS_SSL_DEBUG_RET( 1,
929            "mbedtls_ssl_tls13_key_schedule_stage_application", ret );
930         goto cleanup;
931     }
932 
933     ret = mbedtls_ssl_tls13_generate_application_keys( ssl, &traffic_keys );
934     if( ret != 0 )
935     {
936         MBEDTLS_SSL_DEBUG_RET( 1,
937             "mbedtls_ssl_tls13_generate_application_keys", ret );
938         goto cleanup;
939     }
940 
941     transform_application =
942         mbedtls_calloc( 1, sizeof( mbedtls_ssl_transform ) );
943     if( transform_application == NULL )
944     {
945         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
946         goto cleanup;
947     }
948 
949     ret = mbedtls_ssl_tls13_populate_transform(
950                                     transform_application,
951                                     ssl->conf->endpoint,
952                                     ssl->session_negotiate->ciphersuite,
953                                     &traffic_keys,
954                                     ssl );
955     if( ret != 0 )
956     {
957         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_tls13_populate_transform", ret );
958         goto cleanup;
959     }
960 
961     ssl->transform_application = transform_application;
962 
963 cleanup:
964 
965     mbedtls_platform_zeroize( &traffic_keys, sizeof( traffic_keys ) );
966     if( ret != 0 )
967     {
968         mbedtls_free( transform_application );
969         MBEDTLS_SSL_PEND_FATAL_ALERT(
970                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
971                 MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
972     }
973     return( ret );
974 }
975 #endif /* MBEDTLS_SSL_CLI_C */
976 
ssl_tls13_postprocess_finished_message(mbedtls_ssl_context * ssl)977 static int ssl_tls13_postprocess_finished_message( mbedtls_ssl_context* ssl )
978 {
979 
980 #if defined(MBEDTLS_SSL_CLI_C)
981     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
982     {
983         return( ssl_tls13_postprocess_server_finished_message( ssl ) );
984     }
985 #else
986     ((void) ssl);
987 #endif /* MBEDTLS_SSL_CLI_C */
988 
989     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
990 }
991 
mbedtls_ssl_tls13_process_finished_message(mbedtls_ssl_context * ssl)992 int mbedtls_ssl_tls13_process_finished_message( mbedtls_ssl_context *ssl )
993 {
994     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
995     unsigned char *buf;
996     size_t buflen;
997 
998     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished message" ) );
999 
1000     /* Preprocessing step: Compute handshake digest */
1001     MBEDTLS_SSL_PROC_CHK( ssl_tls13_preprocess_finished_message( ssl ) );
1002 
1003     MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_tls1_3_fetch_handshake_msg( ssl,
1004                                               MBEDTLS_SSL_HS_FINISHED,
1005                                               &buf, &buflen ) );
1006     MBEDTLS_SSL_PROC_CHK( ssl_tls13_parse_finished_message( ssl, buf, buf + buflen ) );
1007     mbedtls_ssl_tls1_3_add_hs_msg_to_checksum(
1008         ssl, MBEDTLS_SSL_HS_FINISHED, buf, buflen );
1009     MBEDTLS_SSL_PROC_CHK( ssl_tls13_postprocess_finished_message( ssl ) );
1010 
1011 cleanup:
1012 
1013     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished message" ) );
1014     return( ret );
1015 }
1016 
1017 
1018 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
1019 
1020 #endif /* MBEDTLS_SSL_TLS_C */
1021