xref: /openssl/ssl/statem/statem_lib.c (revision dc84829c)
1 /*
2  * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 #include <limits.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/rsa.h>
21 #include <openssl/x509.h>
22 #include <openssl/trace.h>
23 #include <openssl/encoder.h>
24 
25 /*
26  * Map error codes to TLS/SSL alart types.
27  */
28 typedef struct x509err2alert_st {
29     int x509err;
30     int alert;
31 } X509ERR2ALERT;
32 
33 /* Fixed value used in the ServerHello random field to identify an HRR */
34 const unsigned char hrrrandom[] = {
35     0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
36     0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
37     0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
38 };
39 
ossl_statem_set_mutator(SSL * s,ossl_statem_mutate_handshake_cb mutate_handshake_cb,ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,void * mutatearg)40 int ossl_statem_set_mutator(SSL *s,
41                             ossl_statem_mutate_handshake_cb mutate_handshake_cb,
42                             ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
43                             void *mutatearg)
44 {
45     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
46 
47     if (sc == NULL)
48         return 0;
49 
50     sc->statem.mutate_handshake_cb = mutate_handshake_cb;
51     sc->statem.mutatearg = mutatearg;
52     sc->statem.finish_mutate_handshake_cb = finish_mutate_handshake_cb;
53 
54     return 1;
55 }
56 
57 /*
58  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
59  * SSL3_RT_CHANGE_CIPHER_SPEC)
60  */
ssl3_do_write(SSL_CONNECTION * s,uint8_t type)61 int ssl3_do_write(SSL_CONNECTION *s, uint8_t type)
62 {
63     int ret;
64     size_t written = 0;
65     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
66     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
67 
68     /*
69      * If we're running the test suite then we may need to mutate the message
70      * we've been asked to write. Does not happen in normal operation.
71      */
72     if (s->statem.mutate_handshake_cb != NULL
73             && !s->statem.write_in_progress
74             && type == SSL3_RT_HANDSHAKE
75             && s->init_num >= SSL3_HM_HEADER_LENGTH) {
76         unsigned char *msg;
77         size_t msglen;
78 
79         if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
80                                            s->init_num,
81                                            &msg, &msglen,
82                                            s->statem.mutatearg))
83             return -1;
84         if (msglen < SSL3_HM_HEADER_LENGTH
85                 || !BUF_MEM_grow(s->init_buf, msglen))
86             return -1;
87         memcpy(s->init_buf->data, msg, msglen);
88         s->init_num = msglen;
89         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
90         s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
91         s->statem.write_in_progress = 1;
92     }
93 
94     ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
95                            s->init_num, &written);
96     if (ret <= 0)
97         return -1;
98     if (type == SSL3_RT_HANDSHAKE)
99         /*
100          * should not be done for 'Hello Request's, but in that case we'll
101          * ignore the result anyway
102          * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
103          */
104         if (!SSL_CONNECTION_IS_TLS13(s)
105             || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
106                                  && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
107                                  && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
108             if (!ssl3_finish_mac(s,
109                                  (unsigned char *)&s->init_buf->data[s->init_off],
110                                  written))
111                 return -1;
112     if (written == s->init_num) {
113         s->statem.write_in_progress = 0;
114         if (s->msg_callback)
115             s->msg_callback(1, s->version, type, s->init_buf->data,
116                             (size_t)(s->init_off + s->init_num), ussl,
117                             s->msg_callback_arg);
118         return 1;
119     }
120     s->init_off += written;
121     s->init_num -= written;
122     return 0;
123 }
124 
tls_close_construct_packet(SSL_CONNECTION * s,WPACKET * pkt,int htype)125 int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
126 {
127     size_t msglen;
128 
129     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
130             || !WPACKET_get_length(pkt, &msglen)
131             || msglen > INT_MAX)
132         return 0;
133     s->init_num = (int)msglen;
134     s->init_off = 0;
135 
136     return 1;
137 }
138 
tls_setup_handshake(SSL_CONNECTION * s)139 int tls_setup_handshake(SSL_CONNECTION *s)
140 {
141     int ver_min, ver_max, ok;
142     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
143     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
144 
145     if (!ssl3_init_finished_mac(s)) {
146         /* SSLfatal() already called */
147         return 0;
148     }
149 
150     /* Reset any extension flags */
151     memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
152 
153     if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
154         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
155         return 0;
156     }
157 
158     /* Sanity check that we have MD5-SHA1 if we need it */
159     if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
160         int negotiated_minversion;
161         int md5sha1_needed_maxversion = SSL_CONNECTION_IS_DTLS(s)
162                                         ? DTLS1_VERSION : TLS1_1_VERSION;
163 
164         /* We don't have MD5-SHA1 - do we need it? */
165         if (ssl_version_cmp(s, ver_max, md5sha1_needed_maxversion) <= 0) {
166             SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
167                           SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
168                           "The max supported SSL/TLS version needs the"
169                           " MD5-SHA1 digest but it is not available"
170                           " in the loaded providers. Use (D)TLSv1.2 or"
171                           " above, or load different providers");
172             return 0;
173         }
174 
175         ok = 1;
176 
177         /* Don't allow TLSv1.1 or below to be negotiated */
178         negotiated_minversion = SSL_CONNECTION_IS_DTLS(s) ?
179                                 DTLS1_2_VERSION : TLS1_2_VERSION;
180         if (ssl_version_cmp(s, ver_min, negotiated_minversion) < 0)
181                 ok = SSL_set_min_proto_version(ssl, negotiated_minversion);
182         if (!ok) {
183             /* Shouldn't happen */
184             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
185             return 0;
186         }
187     }
188 
189     ok = 0;
190     if (s->server) {
191         STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
192         int i;
193 
194         /*
195          * Sanity check that the maximum version we accept has ciphers
196          * enabled. For clients we do this check during construction of the
197          * ClientHello.
198          */
199         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
200             const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
201             int cipher_minprotover = SSL_CONNECTION_IS_DTLS(s)
202                                      ? c->min_dtls : c->min_tls;
203             int cipher_maxprotover = SSL_CONNECTION_IS_DTLS(s)
204                                      ? c->max_dtls : c->max_tls;
205 
206             if (ssl_version_cmp(s, ver_max, cipher_minprotover) >= 0
207                     && ssl_version_cmp(s, ver_max, cipher_maxprotover) <= 0) {
208                 ok = 1;
209                 break;
210             }
211         }
212         if (!ok) {
213             SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
214                           SSL_R_NO_CIPHERS_AVAILABLE,
215                           "No ciphers enabled for max supported "
216                           "SSL/TLS version");
217             return 0;
218         }
219         if (SSL_IS_FIRST_HANDSHAKE(s)) {
220             /* N.B. s->session_ctx == s->ctx here */
221             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
222         } else {
223             /* N.B. s->ctx may not equal s->session_ctx */
224             ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
225 
226             s->s3.tmp.cert_request = 0;
227         }
228     } else {
229         if (SSL_IS_FIRST_HANDSHAKE(s))
230             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
231         else
232             ssl_tsan_counter(s->session_ctx,
233                          &s->session_ctx->stats.sess_connect_renegotiate);
234 
235         /* mark client_random uninitialized */
236         memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
237         s->hit = 0;
238 
239         s->s3.tmp.cert_req = 0;
240 
241         if (SSL_CONNECTION_IS_DTLS(s))
242             s->statem.use_timer = 1;
243     }
244 
245     return 1;
246 }
247 
248 /*
249  * Size of the to-be-signed TLS13 data, without the hash size itself:
250  * 64 bytes of value 32, 33 context bytes, 1 byte separator
251  */
252 #define TLS13_TBS_START_SIZE            64
253 #define TLS13_TBS_PREAMBLE_SIZE         (TLS13_TBS_START_SIZE + 33 + 1)
254 
get_cert_verify_tbs_data(SSL_CONNECTION * s,unsigned char * tls13tbs,void ** hdata,size_t * hdatalen)255 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
256                                     void **hdata, size_t *hdatalen)
257 {
258     /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
259     static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
260         "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
261     /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
262     static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
263         "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
264 
265     if (SSL_CONNECTION_IS_TLS13(s)) {
266         size_t hashlen;
267 
268         /* Set the first 64 bytes of to-be-signed data to octet 32 */
269         memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
270         /* This copies the 33 bytes of context plus the 0 separator byte */
271         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
272                  || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
273             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
274         else
275             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
276 
277         /*
278          * If we're currently reading then we need to use the saved handshake
279          * hash value. We can't use the current handshake hash state because
280          * that includes the CertVerify itself.
281          */
282         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
283                 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
284             memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
285                    s->cert_verify_hash_len);
286             hashlen = s->cert_verify_hash_len;
287         } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
288                                        EVP_MAX_MD_SIZE, &hashlen)) {
289             /* SSLfatal() already called */
290             return 0;
291         }
292 
293         *hdata = tls13tbs;
294         *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
295     } else {
296         size_t retlen;
297         long retlen_l;
298 
299         retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
300         if (retlen_l <= 0) {
301             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
302             return 0;
303         }
304         *hdatalen = retlen;
305     }
306 
307     return 1;
308 }
309 
tls_construct_cert_verify(SSL_CONNECTION * s,WPACKET * pkt)310 CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
311 {
312     EVP_PKEY *pkey = NULL;
313     const EVP_MD *md = NULL;
314     EVP_MD_CTX *mctx = NULL;
315     EVP_PKEY_CTX *pctx = NULL;
316     size_t hdatalen = 0, siglen = 0;
317     void *hdata;
318     unsigned char *sig = NULL;
319     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
320     const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
321     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
322 
323     if (lu == NULL || s->s3.tmp.cert == NULL) {
324         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
325         goto err;
326     }
327     pkey = s->s3.tmp.cert->privatekey;
328 
329     if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
330         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
331         goto err;
332     }
333 
334     mctx = EVP_MD_CTX_new();
335     if (mctx == NULL) {
336         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
337         goto err;
338     }
339 
340     /* Get the data to be signed */
341     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
342         /* SSLfatal() already called */
343         goto err;
344     }
345 
346     if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
347         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
348         goto err;
349     }
350 
351     if (EVP_DigestSignInit_ex(mctx, &pctx,
352                               md == NULL ? NULL : EVP_MD_get0_name(md),
353                               sctx->libctx, sctx->propq, pkey,
354                               NULL) <= 0) {
355         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
356         goto err;
357     }
358 
359     if (lu->sig == EVP_PKEY_RSA_PSS) {
360         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
361             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
362                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
363             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
364             goto err;
365         }
366     }
367     if (s->version == SSL3_VERSION) {
368         /*
369          * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
370          * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
371          */
372         if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
373             || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
374                                (int)s->session->master_key_length,
375                                s->session->master_key) <= 0
376             || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
377 
378             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
379             goto err;
380         }
381         sig = OPENSSL_malloc(siglen);
382         if (sig == NULL
383                 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
384             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
385             goto err;
386         }
387     } else {
388         /*
389          * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
390          * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
391          */
392         if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
393             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
394             goto err;
395         }
396         sig = OPENSSL_malloc(siglen);
397         if (sig == NULL
398                 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
399             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
400             goto err;
401         }
402     }
403 
404 #ifndef OPENSSL_NO_GOST
405     {
406         int pktype = lu->sig;
407 
408         if (pktype == NID_id_GostR3410_2001
409             || pktype == NID_id_GostR3410_2012_256
410             || pktype == NID_id_GostR3410_2012_512)
411             BUF_reverse(sig, NULL, siglen);
412     }
413 #endif
414 
415     if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
416         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
417         goto err;
418     }
419 
420     /* Digest cached records and discard handshake buffer */
421     if (!ssl3_digest_cached_records(s, 0)) {
422         /* SSLfatal() already called */
423         goto err;
424     }
425 
426     OPENSSL_free(sig);
427     EVP_MD_CTX_free(mctx);
428     return CON_FUNC_SUCCESS;
429  err:
430     OPENSSL_free(sig);
431     EVP_MD_CTX_free(mctx);
432     return CON_FUNC_ERROR;
433 }
434 
tls_process_cert_verify(SSL_CONNECTION * s,PACKET * pkt)435 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
436 {
437     EVP_PKEY *pkey = NULL;
438     const unsigned char *data;
439 #ifndef OPENSSL_NO_GOST
440     unsigned char *gost_data = NULL;
441 #endif
442     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
443     int j;
444     unsigned int len;
445     const EVP_MD *md = NULL;
446     size_t hdatalen = 0;
447     void *hdata;
448     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
449     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
450     EVP_PKEY_CTX *pctx = NULL;
451     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
452 
453     if (mctx == NULL) {
454         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
455         goto err;
456     }
457 
458     pkey = tls_get_peer_pkey(s);
459     if (pkey == NULL) {
460         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
461         goto err;
462     }
463 
464     if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
465         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
466                  SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
467         goto err;
468     }
469 
470     if (SSL_USE_SIGALGS(s)) {
471         unsigned int sigalg;
472 
473         if (!PACKET_get_net_2(pkt, &sigalg)) {
474             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
475             goto err;
476         }
477         if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
478             /* SSLfatal() already called */
479             goto err;
480         }
481     } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
482             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
483                      SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
484             goto err;
485     }
486 
487     if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
488         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
489         goto err;
490     }
491 
492     if (SSL_USE_SIGALGS(s))
493         OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
494                     md == NULL ? "n/a" : EVP_MD_get0_name(md));
495 
496     /* Check for broken implementations of GOST ciphersuites */
497     /*
498      * If key is GOST and len is exactly 64 or 128, it is signature without
499      * length field (CryptoPro implementations at least till TLS 1.2)
500      */
501 #ifndef OPENSSL_NO_GOST
502     if (!SSL_USE_SIGALGS(s)
503         && ((PACKET_remaining(pkt) == 64
504              && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
505                  || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
506             || (PACKET_remaining(pkt) == 128
507                 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
508         len = PACKET_remaining(pkt);
509     } else
510 #endif
511     if (!PACKET_get_net_2(pkt, &len)) {
512         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
513         goto err;
514     }
515 
516     if (!PACKET_get_bytes(pkt, &data, len)) {
517         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
518         goto err;
519     }
520     if (PACKET_remaining(pkt) != 0) {
521         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
522         goto err;
523     }
524 
525     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
526         /* SSLfatal() already called */
527         goto err;
528     }
529 
530     OSSL_TRACE1(TLS, "Using client verify alg %s\n",
531                 md == NULL ? "n/a" : EVP_MD_get0_name(md));
532 
533     if (EVP_DigestVerifyInit_ex(mctx, &pctx,
534                                 md == NULL ? NULL : EVP_MD_get0_name(md),
535                                 sctx->libctx, sctx->propq, pkey,
536                                 NULL) <= 0) {
537         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
538         goto err;
539     }
540 #ifndef OPENSSL_NO_GOST
541     {
542         int pktype = EVP_PKEY_get_id(pkey);
543         if (pktype == NID_id_GostR3410_2001
544             || pktype == NID_id_GostR3410_2012_256
545             || pktype == NID_id_GostR3410_2012_512) {
546             if ((gost_data = OPENSSL_malloc(len)) == NULL)
547                 goto err;
548             BUF_reverse(gost_data, data, len);
549             data = gost_data;
550         }
551     }
552 #endif
553 
554     if (SSL_USE_PSS(s)) {
555         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
556             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
557                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
558             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
559             goto err;
560         }
561     }
562     if (s->version == SSL3_VERSION) {
563         if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
564                 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
565                                    (int)s->session->master_key_length,
566                                     s->session->master_key) <= 0) {
567             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
568             goto err;
569         }
570         if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
571             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
572             goto err;
573         }
574     } else {
575         j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
576 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
577         /* Ignore bad signatures when fuzzing */
578         if (SSL_IS_QUIC_HANDSHAKE(s))
579             j = 1;
580 #endif
581         if (j <= 0) {
582             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
583             goto err;
584         }
585     }
586 
587     /*
588      * In TLSv1.3 on the client side we make sure we prepare the client
589      * certificate after the CertVerify instead of when we get the
590      * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
591      * comes *before* the Certificate message. In TLSv1.2 it comes after. We
592      * want to make sure that SSL_get1_peer_certificate() will return the actual
593      * server certificate from the client_cert_cb callback.
594      */
595     if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
596         ret = MSG_PROCESS_CONTINUE_PROCESSING;
597     else
598         ret = MSG_PROCESS_CONTINUE_READING;
599  err:
600     BIO_free(s->s3.handshake_buffer);
601     s->s3.handshake_buffer = NULL;
602     EVP_MD_CTX_free(mctx);
603 #ifndef OPENSSL_NO_GOST
604     OPENSSL_free(gost_data);
605 #endif
606     return ret;
607 }
608 
tls_construct_finished(SSL_CONNECTION * s,WPACKET * pkt)609 CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
610 {
611     size_t finish_md_len;
612     const char *sender;
613     size_t slen;
614     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
615 
616     /* This is a real handshake so make sure we clean it up at the end */
617     if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
618         s->statem.cleanuphand = 1;
619 
620     /*
621      * If we attempted to write early data or we're in middlebox compat mode
622      * then we deferred changing the handshake write keys to the last possible
623      * moment. If we didn't already do this when we sent the client certificate
624      * then we need to do it now.
625      */
626     if (SSL_CONNECTION_IS_TLS13(s)
627             && !s->server
628             && (s->early_data_state != SSL_EARLY_DATA_NONE
629                 || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
630             && s->s3.tmp.cert_req == 0
631             && (!ssl->method->ssl3_enc->change_cipher_state(s,
632                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
633         /* SSLfatal() already called */
634         return CON_FUNC_ERROR;
635     }
636 
637     if (s->server) {
638         sender = ssl->method->ssl3_enc->server_finished_label;
639         slen = ssl->method->ssl3_enc->server_finished_label_len;
640     } else {
641         sender = ssl->method->ssl3_enc->client_finished_label;
642         slen = ssl->method->ssl3_enc->client_finished_label_len;
643     }
644 
645     finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
646                                                             sender, slen,
647                                                             s->s3.tmp.finish_md);
648     if (finish_md_len == 0) {
649         /* SSLfatal() already called */
650         return CON_FUNC_ERROR;
651     }
652 
653     s->s3.tmp.finish_md_len = finish_md_len;
654 
655     if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
656         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
657         return CON_FUNC_ERROR;
658     }
659 
660     /*
661      * Log the master secret, if logging is enabled. We don't log it for
662      * TLSv1.3: there's a different key schedule for that.
663      */
664     if (!SSL_CONNECTION_IS_TLS13(s)
665         && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
666                            s->session->master_key_length)) {
667         /* SSLfatal() already called */
668         return CON_FUNC_ERROR;
669     }
670 
671     /*
672      * Copy the finished so we can use it for renegotiation checks
673      */
674     if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
675         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
676         return CON_FUNC_ERROR;
677     }
678     if (!s->server) {
679         memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
680                finish_md_len);
681         s->s3.previous_client_finished_len = finish_md_len;
682     } else {
683         memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
684                finish_md_len);
685         s->s3.previous_server_finished_len = finish_md_len;
686     }
687 
688     return CON_FUNC_SUCCESS;
689 }
690 
tls_construct_key_update(SSL_CONNECTION * s,WPACKET * pkt)691 CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
692 {
693     if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
694         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
695         return CON_FUNC_ERROR;
696     }
697 
698     s->key_update = SSL_KEY_UPDATE_NONE;
699     return CON_FUNC_SUCCESS;
700 }
701 
tls_process_key_update(SSL_CONNECTION * s,PACKET * pkt)702 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
703 {
704     unsigned int updatetype;
705 
706     /*
707      * A KeyUpdate message signals a key change so the end of the message must
708      * be on a record boundary.
709      */
710     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
711         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
712         return MSG_PROCESS_ERROR;
713     }
714 
715     if (!PACKET_get_1(pkt, &updatetype)
716             || PACKET_remaining(pkt) != 0) {
717         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
718         return MSG_PROCESS_ERROR;
719     }
720 
721     /*
722      * There are only two defined key update types. Fail if we get a value we
723      * didn't recognise.
724      */
725     if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
726             && updatetype != SSL_KEY_UPDATE_REQUESTED) {
727         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
728         return MSG_PROCESS_ERROR;
729     }
730 
731     /*
732      * If we get a request for us to update our sending keys too then, we need
733      * to additionally send a KeyUpdate message. However that message should
734      * not also request an update (otherwise we get into an infinite loop).
735      */
736     if (updatetype == SSL_KEY_UPDATE_REQUESTED)
737         s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
738 
739     if (!tls13_update_key(s, 0)) {
740         /* SSLfatal() already called */
741         return MSG_PROCESS_ERROR;
742     }
743 
744     return MSG_PROCESS_FINISHED_READING;
745 }
746 
747 /*
748  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
749  * to far.
750  */
ssl3_take_mac(SSL_CONNECTION * s)751 int ssl3_take_mac(SSL_CONNECTION *s)
752 {
753     const char *sender;
754     size_t slen;
755     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
756 
757     if (!s->server) {
758         sender = ssl->method->ssl3_enc->server_finished_label;
759         slen = ssl->method->ssl3_enc->server_finished_label_len;
760     } else {
761         sender = ssl->method->ssl3_enc->client_finished_label;
762         slen = ssl->method->ssl3_enc->client_finished_label_len;
763     }
764 
765     s->s3.tmp.peer_finish_md_len =
766         ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
767                                                 s->s3.tmp.peer_finish_md);
768 
769     if (s->s3.tmp.peer_finish_md_len == 0) {
770         /* SSLfatal() already called */
771         return 0;
772     }
773 
774     return 1;
775 }
776 
tls_process_change_cipher_spec(SSL_CONNECTION * s,PACKET * pkt)777 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
778                                                   PACKET *pkt)
779 {
780     size_t remain;
781 
782     remain = PACKET_remaining(pkt);
783     /*
784      * 'Change Cipher Spec' is just a single byte, which should already have
785      * been consumed by ssl_get_message() so there should be no bytes left,
786      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
787      */
788     if (SSL_CONNECTION_IS_DTLS(s)) {
789         if ((s->version == DTLS1_BAD_VER
790              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
791             || (s->version != DTLS1_BAD_VER
792                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
793             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
794             return MSG_PROCESS_ERROR;
795         }
796     } else {
797         if (remain != 0) {
798             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
799             return MSG_PROCESS_ERROR;
800         }
801     }
802 
803     /* Check we have a cipher to change to */
804     if (s->s3.tmp.new_cipher == NULL) {
805         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
806         return MSG_PROCESS_ERROR;
807     }
808 
809     s->s3.change_cipher_spec = 1;
810     if (!ssl3_do_change_cipher_spec(s)) {
811         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
812         return MSG_PROCESS_ERROR;
813     }
814 
815     if (SSL_CONNECTION_IS_DTLS(s)) {
816         if (s->version == DTLS1_BAD_VER)
817             s->d1->handshake_read_seq++;
818 
819 #ifndef OPENSSL_NO_SCTP
820         /*
821          * Remember that a CCS has been received, so that an old key of
822          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
823          * SCTP is used
824          */
825         BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
826                  BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
827 #endif
828     }
829 
830     return MSG_PROCESS_CONTINUE_READING;
831 }
832 
tls_process_finished(SSL_CONNECTION * s,PACKET * pkt)833 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
834 {
835     size_t md_len;
836     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
837     int was_first = SSL_IS_FIRST_HANDSHAKE(s);
838     int ok;
839 
840 
841     /* This is a real handshake so make sure we clean it up at the end */
842     if (s->server) {
843         /*
844         * To get this far we must have read encrypted data from the client. We
845         * no longer tolerate unencrypted alerts. This is ignored if less than
846         * TLSv1.3
847         */
848         if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
849             s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
850         if (s->post_handshake_auth != SSL_PHA_REQUESTED)
851             s->statem.cleanuphand = 1;
852         if (SSL_CONNECTION_IS_TLS13(s)
853             && !tls13_save_handshake_digest_for_pha(s)) {
854                 /* SSLfatal() already called */
855                 return MSG_PROCESS_ERROR;
856         }
857     }
858 
859     /*
860      * In TLSv1.3 a Finished message signals a key change so the end of the
861      * message must be on a record boundary.
862      */
863     if (SSL_CONNECTION_IS_TLS13(s)
864         && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
865         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
866         return MSG_PROCESS_ERROR;
867     }
868 
869     /* If this occurs, we have missed a message */
870     if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
871         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
872         return MSG_PROCESS_ERROR;
873     }
874     s->s3.change_cipher_spec = 0;
875 
876     md_len = s->s3.tmp.peer_finish_md_len;
877 
878     if (md_len != PACKET_remaining(pkt)) {
879         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
880         return MSG_PROCESS_ERROR;
881     }
882 
883     ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
884                        md_len);
885 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
886     if (ok != 0) {
887         if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
888             ok = 0;
889         }
890     }
891 #endif
892     if (ok != 0) {
893         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
894         return MSG_PROCESS_ERROR;
895     }
896 
897     /*
898      * Copy the finished so we can use it for renegotiation checks
899      */
900     if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
901         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
902         return MSG_PROCESS_ERROR;
903     }
904     if (s->server) {
905         memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
906                md_len);
907         s->s3.previous_client_finished_len = md_len;
908     } else {
909         memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
910                md_len);
911         s->s3.previous_server_finished_len = md_len;
912     }
913 
914     /*
915      * In TLS1.3 we also have to change cipher state and do any final processing
916      * of the initial server flight (if we are a client)
917      */
918     if (SSL_CONNECTION_IS_TLS13(s)) {
919         if (s->server) {
920             if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
921                     !ssl->method->ssl3_enc->change_cipher_state(s,
922                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
923                 /* SSLfatal() already called */
924                 return MSG_PROCESS_ERROR;
925             }
926         } else {
927             /* TLS 1.3 gets the secret size from the handshake md */
928             size_t dummy;
929             if (!ssl->method->ssl3_enc->generate_master_secret(s,
930                     s->master_secret, s->handshake_secret, 0,
931                     &dummy)) {
932                 /* SSLfatal() already called */
933                 return MSG_PROCESS_ERROR;
934             }
935             if (!ssl->method->ssl3_enc->change_cipher_state(s,
936                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
937                 /* SSLfatal() already called */
938                 return MSG_PROCESS_ERROR;
939             }
940             if (!tls_process_initial_server_flight(s)) {
941                 /* SSLfatal() already called */
942                 return MSG_PROCESS_ERROR;
943             }
944         }
945     }
946 
947     if (was_first
948             && !SSL_IS_FIRST_HANDSHAKE(s)
949             && s->rlayer.rrlmethod->set_first_handshake != NULL)
950         s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
951 
952     return MSG_PROCESS_FINISHED_READING;
953 }
954 
tls_construct_change_cipher_spec(SSL_CONNECTION * s,WPACKET * pkt)955 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
956 {
957     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
958         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
959         return CON_FUNC_ERROR;
960     }
961 
962     return CON_FUNC_SUCCESS;
963 }
964 
965 /* Add a certificate to the WPACKET */
ssl_add_cert_to_wpacket(SSL_CONNECTION * s,WPACKET * pkt,X509 * x,int chain,int for_comp)966 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
967                                    X509 *x, int chain, int for_comp)
968 {
969     int len;
970     unsigned char *outbytes;
971     int context = SSL_EXT_TLS1_3_CERTIFICATE;
972 
973     if (for_comp)
974         context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
975 
976     len = i2d_X509(x, NULL);
977     if (len < 0) {
978         if (!for_comp)
979             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
980         return 0;
981     }
982     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
983             || i2d_X509(x, &outbytes) != len) {
984         if (!for_comp)
985             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
986         return 0;
987     }
988 
989     if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
990             && !tls_construct_extensions(s, pkt, context, x, chain)) {
991         /* SSLfatal() already called */
992         return 0;
993     }
994 
995     return 1;
996 }
997 
998 /* Add certificate chain to provided WPACKET */
ssl_add_cert_chain(SSL_CONNECTION * s,WPACKET * pkt,CERT_PKEY * cpk,int for_comp)999 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
1000 {
1001     int i, chain_count;
1002     X509 *x;
1003     STACK_OF(X509) *extra_certs;
1004     STACK_OF(X509) *chain = NULL;
1005     X509_STORE *chain_store;
1006     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1007 
1008     if (cpk == NULL || cpk->x509 == NULL)
1009         return 1;
1010 
1011     x = cpk->x509;
1012 
1013     /*
1014      * If we have a certificate specific chain use it, else use parent ctx.
1015      */
1016     if (cpk->chain != NULL)
1017         extra_certs = cpk->chain;
1018     else
1019         extra_certs = sctx->extra_certs;
1020 
1021     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1022         chain_store = NULL;
1023     else if (s->cert->chain_store)
1024         chain_store = s->cert->chain_store;
1025     else
1026         chain_store = sctx->cert_store;
1027 
1028     if (chain_store != NULL) {
1029         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1030                                                        sctx->propq);
1031 
1032         if (xs_ctx == NULL) {
1033             if (!for_comp)
1034                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1035             return 0;
1036         }
1037         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1038             X509_STORE_CTX_free(xs_ctx);
1039             if (!for_comp)
1040                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1041             return 0;
1042         }
1043         /*
1044          * It is valid for the chain not to be complete (because normally we
1045          * don't include the root cert in the chain). Therefore we deliberately
1046          * ignore the error return from this call. We're not actually verifying
1047          * the cert - we're just building as much of the chain as we can
1048          */
1049         (void)X509_verify_cert(xs_ctx);
1050         /* Don't leave errors in the queue */
1051         ERR_clear_error();
1052         chain = X509_STORE_CTX_get0_chain(xs_ctx);
1053         i = ssl_security_cert_chain(s, chain, NULL, 0);
1054         if (i != 1) {
1055 #if 0
1056             /* Dummy error calls so mkerr generates them */
1057             ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1058             ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1059             ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1060 #endif
1061             X509_STORE_CTX_free(xs_ctx);
1062             if (!for_comp)
1063                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1064             return 0;
1065         }
1066         chain_count = sk_X509_num(chain);
1067         for (i = 0; i < chain_count; i++) {
1068             x = sk_X509_value(chain, i);
1069 
1070             if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1071                 /* SSLfatal() already called */
1072                 X509_STORE_CTX_free(xs_ctx);
1073                 return 0;
1074             }
1075         }
1076         X509_STORE_CTX_free(xs_ctx);
1077     } else {
1078         i = ssl_security_cert_chain(s, extra_certs, x, 0);
1079         if (i != 1) {
1080             if (!for_comp)
1081                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1082             return 0;
1083         }
1084         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1085             /* SSLfatal() already called */
1086             return 0;
1087         }
1088         for (i = 0; i < sk_X509_num(extra_certs); i++) {
1089             x = sk_X509_value(extra_certs, i);
1090             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1091                 /* SSLfatal() already called */
1092                 return 0;
1093             }
1094         }
1095     }
1096     return 1;
1097 }
1098 
tls_get_peer_pkey(const SSL_CONNECTION * sc)1099 EVP_PKEY* tls_get_peer_pkey(const SSL_CONNECTION *sc)
1100 {
1101     if (sc->session->peer_rpk != NULL)
1102         return sc->session->peer_rpk;
1103     if (sc->session->peer != NULL)
1104         return X509_get0_pubkey(sc->session->peer);
1105     return NULL;
1106 }
1107 
tls_process_rpk(SSL_CONNECTION * sc,PACKET * pkt,EVP_PKEY ** peer_rpk)1108 int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
1109 {
1110     EVP_PKEY *pkey = NULL;
1111     int ret = 0;
1112     RAW_EXTENSION *rawexts = NULL;
1113     PACKET extensions;
1114     PACKET context;
1115     unsigned long cert_len = 0, spki_len = 0;
1116     const unsigned char *spki, *spkistart;
1117     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
1118 
1119     /*-
1120      * ----------------------------
1121      * TLS 1.3 Certificate message:
1122      * ----------------------------
1123      * https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
1124      *
1125      *   enum {
1126      *       X509(0),
1127      *       RawPublicKey(2),
1128      *       (255)
1129      *   } CertificateType;
1130      *
1131      *   struct {
1132      *       select (certificate_type) {
1133      *           case RawPublicKey:
1134      *             // From RFC 7250 ASN.1_subjectPublicKeyInfo
1135      *             opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
1136      *
1137      *           case X509:
1138      *             opaque cert_data<1..2^24-1>;
1139      *       };
1140      *       Extension extensions<0..2^16-1>;
1141      *   } CertificateEntry;
1142      *
1143      *   struct {
1144      *       opaque certificate_request_context<0..2^8-1>;
1145      *       CertificateEntry certificate_list<0..2^24-1>;
1146      *   } Certificate;
1147      *
1148      * The client MUST send a Certificate message if and only if the server
1149      * has requested client authentication via a CertificateRequest message
1150      * (Section 4.3.2).  If the server requests client authentication but no
1151      * suitable certificate is available, the client MUST send a Certificate
1152      * message containing no certificates (i.e., with the "certificate_list"
1153      * field having length 0).
1154      *
1155      * ----------------------------
1156      * TLS 1.2 Certificate message:
1157      * ----------------------------
1158      * https://datatracker.ietf.org/doc/html/rfc7250#section-3
1159      *
1160      *   opaque ASN.1Cert<1..2^24-1>;
1161      *
1162      *   struct {
1163      *       select(certificate_type){
1164      *
1165      *            // certificate type defined in this document.
1166      *            case RawPublicKey:
1167      *              opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
1168      *
1169      *           // X.509 certificate defined in RFC 5246
1170      *           case X.509:
1171      *             ASN.1Cert certificate_list<0..2^24-1>;
1172      *
1173      *           // Additional certificate type based on
1174      *           // "TLS Certificate Types" subregistry
1175      *       };
1176      *   } Certificate;
1177      *
1178      * -------------
1179      * Consequently:
1180      * -------------
1181      * After the (TLS 1.3 only) context octet string (1 byte length + data) the
1182      * Certificate message has a 3-byte length that is zero in the client to
1183      * server message when the client has no RPK to send.  In that case, there
1184      * are no (TLS 1.3 only) per-certificate extensions either, because the
1185      * [CertificateEntry] list is empty.
1186      *
1187      * In the server to client direction, or when the client had an RPK to send,
1188      * the TLS 1.3 message just prepends the length of the RPK+extensions,
1189      * while TLS <= 1.2 sends just the RPK (octet-string).
1190      *
1191      * The context must be zero-length in the server to client direction, and
1192      * must match the value recorded in the certificate request in the client
1193      * to server direction.
1194      */
1195     if (SSL_CONNECTION_IS_TLS13(sc)) {
1196         if (!PACKET_get_length_prefixed_1(pkt, &context)) {
1197             SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1198             goto err;
1199         }
1200         if (sc->server) {
1201             if (sc->pha_context == NULL) {
1202                 if (PACKET_remaining(&context) != 0) {
1203                     SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1204                     goto err;
1205                 }
1206             } else {
1207                 if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
1208                     SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1209                     goto err;
1210                 }
1211             }
1212         } else {
1213             if (PACKET_remaining(&context) != 0) {
1214                 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1215                 goto err;
1216             }
1217         }
1218     }
1219 
1220     if (!PACKET_get_net_3(pkt, &cert_len)
1221         || PACKET_remaining(pkt) != cert_len) {
1222         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1223         goto err;
1224     }
1225 
1226     /*
1227      * The list length may be zero when there is no RPK.  In the case of TLS
1228      * 1.2 this is actually the RPK length, which cannot be zero as specified,
1229      * but that breaks the ability of the client to decline client auth. We
1230      * overload the 0 RPK length to mean "no RPK".  This interpretation is
1231      * also used some other (reference?) implementations, but is not supported
1232      * by the verbatim RFC7250 text.
1233      */
1234     if (cert_len == 0)
1235         return 1;
1236 
1237     if (SSL_CONNECTION_IS_TLS13(sc)) {
1238         /*
1239          * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
1240          * by a possibly empty extension block.
1241          */
1242         if (!PACKET_get_net_3(pkt, &spki_len)) {
1243             SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1244             goto err;
1245         }
1246         if (spki_len == 0) {
1247             /* empty RPK */
1248             SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
1249             goto err;
1250         }
1251     } else {
1252         spki_len = cert_len;
1253     }
1254 
1255     if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
1256         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1257         goto err;
1258     }
1259     spkistart = spki;
1260     if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
1261             || spki != (spkistart + spki_len)) {
1262         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1263         goto err;
1264     }
1265     if (EVP_PKEY_missing_parameters(pkey)) {
1266         SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
1267                  SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1268         goto err;
1269     }
1270 
1271     /* Process the Extensions block */
1272     if (SSL_CONNECTION_IS_TLS13(sc)) {
1273         if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
1274             SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1275             goto err;
1276         }
1277         if (!PACKET_as_length_prefixed_2(pkt, &extensions)
1278                 || PACKET_remaining(pkt) != 0) {
1279             SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1280             goto err;
1281         }
1282         if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1283                                     &rawexts, NULL, 1)) {
1284             /* SSLfatal already called */
1285             goto err;
1286         }
1287         /* chain index is always zero and fin always 1 for RPK */
1288         if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1289                                       rawexts, NULL, 0, 1)) {
1290             /* SSLfatal already called */
1291             goto err;
1292         }
1293     }
1294     ret = 1;
1295     if (peer_rpk != NULL) {
1296         *peer_rpk = pkey;
1297         pkey = NULL;
1298     }
1299 
1300  err:
1301     OPENSSL_free(rawexts);
1302     EVP_PKEY_free(pkey);
1303     return ret;
1304 }
1305 
tls_output_rpk(SSL_CONNECTION * sc,WPACKET * pkt,CERT_PKEY * cpk)1306 unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
1307 {
1308     int pdata_len = 0;
1309     unsigned char *pdata = NULL;
1310     X509_PUBKEY *xpk = NULL;
1311     unsigned long ret = 0;
1312     X509 *x509 = NULL;
1313 
1314     if (cpk != NULL && cpk->x509 != NULL) {
1315         x509 = cpk->x509;
1316         /* Get the RPK from the certificate */
1317         xpk = X509_get_X509_PUBKEY(cpk->x509);
1318         if (xpk == NULL) {
1319             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1320             goto err;
1321         }
1322         pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
1323     } else if (cpk != NULL && cpk->privatekey != NULL) {
1324         /* Get the RPK from the private key */
1325         pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
1326     } else {
1327         /* The server RPK is not optional */
1328         if (sc->server) {
1329             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1330             goto err;
1331         }
1332         /* The client can send a zero length certificate list */
1333         if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1334             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1335             goto err;
1336         }
1337         return 1;
1338     }
1339 
1340     if (pdata_len <= 0) {
1341         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1342         goto err;
1343     }
1344 
1345     /*
1346      * TLSv1.2 is _just_ the raw public key
1347      * TLSv1.3 includes extensions, so there's a length wrapper
1348      */
1349     if (SSL_CONNECTION_IS_TLS13(sc)) {
1350         if (!WPACKET_start_sub_packet_u24(pkt)) {
1351             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1352             goto err;
1353         }
1354     }
1355 
1356     if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1357         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1358         goto err;
1359     }
1360 
1361     if (SSL_CONNECTION_IS_TLS13(sc)) {
1362         /*
1363          * Only send extensions relevant to raw public keys. Until such
1364          * extensions are defined, this will be an empty set of extensions.
1365          * |x509| may be NULL, which raw public-key extensions need to handle.
1366          */
1367         if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1368                                       x509, 0)) {
1369             /* SSLfatal() already called */
1370             goto err;
1371         }
1372         if (!WPACKET_close(pkt)) {
1373             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1374             goto err;
1375         }
1376     }
1377 
1378     ret = 1;
1379  err:
1380     OPENSSL_free(pdata);
1381     return ret;
1382 }
1383 
ssl3_output_cert_chain(SSL_CONNECTION * s,WPACKET * pkt,CERT_PKEY * cpk,int for_comp)1384 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1385                                      CERT_PKEY *cpk, int for_comp)
1386 {
1387     if (!WPACKET_start_sub_packet_u24(pkt)) {
1388         if (!for_comp)
1389             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1390         return 0;
1391     }
1392 
1393     if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1394         return 0;
1395 
1396     if (!WPACKET_close(pkt)) {
1397         if (!for_comp)
1398             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1399         return 0;
1400     }
1401 
1402     return 1;
1403 }
1404 
1405 /*
1406  * Tidy up after the end of a handshake. In the case of SCTP this may result
1407  * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1408  * freed up as well.
1409  */
tls_finish_handshake(SSL_CONNECTION * s,ossl_unused WORK_STATE wst,int clearbufs,int stop)1410 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1411                                 int clearbufs, int stop)
1412 {
1413     void (*cb) (const SSL *ssl, int type, int val) = NULL;
1414     int cleanuphand = s->statem.cleanuphand;
1415     SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
1416     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1417 
1418     if (clearbufs) {
1419         if (!SSL_CONNECTION_IS_DTLS(s)
1420 #ifndef OPENSSL_NO_SCTP
1421             /*
1422              * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1423              * messages that require it. Therefore, DTLS procedures for retransmissions
1424              * MUST NOT be used.
1425              * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1426              */
1427             || BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))
1428 #endif
1429             ) {
1430             /*
1431              * We don't do this in DTLS over UDP because we may still need the init_buf
1432              * in case there are any unexpected retransmits
1433              */
1434             BUF_MEM_free(s->init_buf);
1435             s->init_buf = NULL;
1436         }
1437 
1438         if (!ssl_free_wbio_buffer(s)) {
1439             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1440             return WORK_ERROR;
1441         }
1442         s->init_num = 0;
1443     }
1444 
1445     if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1446             && s->post_handshake_auth == SSL_PHA_REQUESTED)
1447         s->post_handshake_auth = SSL_PHA_EXT_SENT;
1448 
1449     /*
1450      * Only set if there was a Finished message and this isn't after a TLSv1.3
1451      * post handshake exchange
1452      */
1453     if (cleanuphand) {
1454         /* skipped if we just sent a HelloRequest */
1455         s->renegotiate = 0;
1456         s->new_session = 0;
1457         s->statem.cleanuphand = 0;
1458         s->ext.ticket_expected = 0;
1459 
1460         ssl3_cleanup_key_block(s);
1461 
1462         if (s->server) {
1463             /*
1464              * In TLSv1.3 we update the cache as part of constructing the
1465              * NewSessionTicket
1466              */
1467             if (!SSL_CONNECTION_IS_TLS13(s))
1468                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1469 
1470             /* N.B. s->ctx may not equal s->session_ctx */
1471             ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1472             s->handshake_func = ossl_statem_accept;
1473         } else {
1474             if (SSL_CONNECTION_IS_TLS13(s)) {
1475                 /*
1476                  * We encourage applications to only use TLSv1.3 tickets once,
1477                  * so we remove this one from the cache.
1478                  */
1479                 if ((s->session_ctx->session_cache_mode
1480                      & SSL_SESS_CACHE_CLIENT) != 0)
1481                     SSL_CTX_remove_session(s->session_ctx, s->session);
1482             } else {
1483                 /*
1484                  * In TLSv1.3 we update the cache as part of processing the
1485                  * NewSessionTicket
1486                  */
1487                 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1488             }
1489             if (s->hit)
1490                 ssl_tsan_counter(s->session_ctx,
1491                                  &s->session_ctx->stats.sess_hit);
1492 
1493             s->handshake_func = ossl_statem_connect;
1494             ssl_tsan_counter(s->session_ctx,
1495                              &s->session_ctx->stats.sess_connect_good);
1496         }
1497 
1498         if (SSL_CONNECTION_IS_DTLS(s)) {
1499             /* done with handshaking */
1500             s->d1->handshake_read_seq = 0;
1501             s->d1->handshake_write_seq = 0;
1502             s->d1->next_handshake_write_seq = 0;
1503             dtls1_clear_received_buffer(s);
1504         }
1505     }
1506 
1507     if (s->info_callback != NULL)
1508         cb = s->info_callback;
1509     else if (sctx->info_callback != NULL)
1510         cb = sctx->info_callback;
1511 
1512     /* The callback may expect us to not be in init at handshake done */
1513     ossl_statem_set_in_init(s, 0);
1514 
1515     if (cb != NULL) {
1516         if (cleanuphand
1517                 || !SSL_CONNECTION_IS_TLS13(s)
1518                 || SSL_IS_FIRST_HANDSHAKE(s))
1519             cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1520     }
1521 
1522     if (!stop) {
1523         /* If we've got more work to do we go back into init */
1524         ossl_statem_set_in_init(s, 1);
1525         return WORK_FINISHED_CONTINUE;
1526     }
1527 
1528     return WORK_FINISHED_STOP;
1529 }
1530 
tls_get_message_header(SSL_CONNECTION * s,int * mt)1531 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1532 {
1533     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1534     int skip_message, i;
1535     uint8_t recvd_type;
1536     unsigned char *p;
1537     size_t l, readbytes;
1538     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1539     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1540 
1541     p = (unsigned char *)s->init_buf->data;
1542 
1543     do {
1544         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1545             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1546                                             &p[s->init_num],
1547                                             SSL3_HM_HEADER_LENGTH - s->init_num,
1548                                             0, &readbytes);
1549             if (i <= 0) {
1550                 s->rwstate = SSL_READING;
1551                 return 0;
1552             }
1553             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1554                 /*
1555                  * A ChangeCipherSpec must be a single byte and may not occur
1556                  * in the middle of a handshake message.
1557                  */
1558                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1559                     SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1560                              SSL_R_BAD_CHANGE_CIPHER_SPEC);
1561                     return 0;
1562                 }
1563                 if (s->statem.hand_state == TLS_ST_BEFORE
1564                         && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1565                     /*
1566                      * We are stateless and we received a CCS. Probably this is
1567                      * from a client between the first and second ClientHellos.
1568                      * We should ignore this, but return an error because we do
1569                      * not return success until we see the second ClientHello
1570                      * with a valid cookie.
1571                      */
1572                     return 0;
1573                 }
1574                 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1575                 s->init_num = readbytes - 1;
1576                 s->init_msg = s->init_buf->data;
1577                 s->s3.tmp.message_size = readbytes;
1578                 return 1;
1579             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1580                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1581                          SSL_R_CCS_RECEIVED_EARLY);
1582                 return 0;
1583             }
1584             s->init_num += readbytes;
1585         }
1586 
1587         skip_message = 0;
1588         if (!s->server)
1589             if (s->statem.hand_state != TLS_ST_OK
1590                     && p[0] == SSL3_MT_HELLO_REQUEST)
1591                 /*
1592                  * The server may always send 'Hello Request' messages --
1593                  * we are doing a handshake anyway now, so ignore them if
1594                  * their format is correct. Does not count for 'Finished'
1595                  * MAC.
1596                  */
1597                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1598                     s->init_num = 0;
1599                     skip_message = 1;
1600 
1601                     if (s->msg_callback)
1602                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1603                                         p, SSL3_HM_HEADER_LENGTH, ussl,
1604                                         s->msg_callback_arg);
1605                 }
1606     } while (skip_message);
1607     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1608 
1609     *mt = *p;
1610     s->s3.tmp.message_type = *(p++);
1611 
1612     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1613         /*
1614          * Only happens with SSLv3+ in an SSLv2 backward compatible
1615          * ClientHello
1616          *
1617          * Total message size is the remaining record bytes to read
1618          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1619          */
1620         l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1621         s->s3.tmp.message_size = l;
1622 
1623         s->init_msg = s->init_buf->data;
1624         s->init_num = SSL3_HM_HEADER_LENGTH;
1625     } else {
1626         n2l3(p, l);
1627         /* BUF_MEM_grow takes an 'int' parameter */
1628         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1629             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1630                      SSL_R_EXCESSIVE_MESSAGE_SIZE);
1631             return 0;
1632         }
1633         s->s3.tmp.message_size = l;
1634 
1635         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1636         s->init_num = 0;
1637     }
1638 
1639     return 1;
1640 }
1641 
tls_get_message_body(SSL_CONNECTION * s,size_t * len)1642 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1643 {
1644     size_t n, readbytes;
1645     unsigned char *p;
1646     int i;
1647     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1648     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1649 
1650     if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1651         /* We've already read everything in */
1652         *len = (unsigned long)s->init_num;
1653         return 1;
1654     }
1655 
1656     p = s->init_msg;
1657     n = s->s3.tmp.message_size - s->init_num;
1658     while (n > 0) {
1659         i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1660                                         &p[s->init_num], n, 0, &readbytes);
1661         if (i <= 0) {
1662             s->rwstate = SSL_READING;
1663             *len = 0;
1664             return 0;
1665         }
1666         s->init_num += readbytes;
1667         n -= readbytes;
1668     }
1669 
1670     /*
1671      * If receiving Finished, record MAC of prior handshake messages for
1672      * Finished verification.
1673      */
1674     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1675         /* SSLfatal() already called */
1676         *len = 0;
1677         return 0;
1678     }
1679 
1680     /* Feed this message into MAC computation. */
1681     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1682         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1683                              s->init_num)) {
1684             /* SSLfatal() already called */
1685             *len = 0;
1686             return 0;
1687         }
1688         if (s->msg_callback)
1689             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1690                             (size_t)s->init_num, ussl, s->msg_callback_arg);
1691     } else {
1692         /*
1693          * We defer feeding in the HRR until later. We'll do it as part of
1694          * processing the message
1695          * The TLsv1.3 handshake transcript stops at the ClientFinished
1696          * message.
1697          */
1698 #define SERVER_HELLO_RANDOM_OFFSET  (SSL3_HM_HEADER_LENGTH + 2)
1699         /* KeyUpdate and NewSessionTicket do not need to be added */
1700         if (!SSL_CONNECTION_IS_TLS13(s)
1701             || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1702                          && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1703             if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1704                     || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1705                     || memcmp(hrrrandom,
1706                               s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1707                               SSL3_RANDOM_SIZE) != 0) {
1708                 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1709                                      s->init_num + SSL3_HM_HEADER_LENGTH)) {
1710                     /* SSLfatal() already called */
1711                     *len = 0;
1712                     return 0;
1713                 }
1714             }
1715         }
1716         if (s->msg_callback)
1717             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1718                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ussl,
1719                             s->msg_callback_arg);
1720     }
1721 
1722     *len = s->init_num;
1723     return 1;
1724 }
1725 
1726 static const X509ERR2ALERT x509table[] = {
1727     {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1728     {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1729     {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1730     {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1731     {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1732     {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1733     {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1734     {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1735     {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1736     {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1737     {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1738     {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1739     {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1740     {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1741     {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1742     {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1743     {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1744     {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1745     {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1746     {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1747     {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1748     {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1749     {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1750     {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1751     {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1752     {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1753     {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1754     {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1755     {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1756     {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1757     {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1758     {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1759     {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1760     {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1761     {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1762     {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1763     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1764     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1765     {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1766     {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1767 
1768     /* Last entry; return this if we don't find the value above. */
1769     {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1770 };
1771 
ssl_x509err2alert(int x509err)1772 int ssl_x509err2alert(int x509err)
1773 {
1774     const X509ERR2ALERT *tp;
1775 
1776     for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1777         if (tp->x509err == x509err)
1778             break;
1779     return tp->alert;
1780 }
1781 
ssl_allow_compression(SSL_CONNECTION * s)1782 int ssl_allow_compression(SSL_CONNECTION *s)
1783 {
1784     if (s->options & SSL_OP_NO_COMPRESSION)
1785         return 0;
1786     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1787 }
1788 
1789 /*
1790  * SSL/TLS/DTLS version comparison
1791  *
1792  * Returns
1793  *      0 if versiona is equal to versionb
1794  *      1 if versiona is greater than versionb
1795  *     -1 if versiona is less than versionb
1796  */
ssl_version_cmp(const SSL_CONNECTION * s,int versiona,int versionb)1797 int ssl_version_cmp(const SSL_CONNECTION *s, int versiona, int versionb)
1798 {
1799     int dtls = SSL_CONNECTION_IS_DTLS(s);
1800 
1801     if (versiona == versionb)
1802         return 0;
1803     if (!dtls)
1804         return versiona < versionb ? -1 : 1;
1805     return DTLS_VERSION_LT(versiona, versionb) ? -1 : 1;
1806 }
1807 
1808 typedef struct {
1809     int version;
1810     const SSL_METHOD *(*cmeth) (void);
1811     const SSL_METHOD *(*smeth) (void);
1812 } version_info;
1813 
1814 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1815 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1816 #endif
1817 
1818 /* Must be in order high to low */
1819 static const version_info tls_version_table[] = {
1820 #ifndef OPENSSL_NO_TLS1_3
1821     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1822 #else
1823     {TLS1_3_VERSION, NULL, NULL},
1824 #endif
1825 #ifndef OPENSSL_NO_TLS1_2
1826     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1827 #else
1828     {TLS1_2_VERSION, NULL, NULL},
1829 #endif
1830 #ifndef OPENSSL_NO_TLS1_1
1831     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1832 #else
1833     {TLS1_1_VERSION, NULL, NULL},
1834 #endif
1835 #ifndef OPENSSL_NO_TLS1
1836     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1837 #else
1838     {TLS1_VERSION, NULL, NULL},
1839 #endif
1840 #ifndef OPENSSL_NO_SSL3
1841     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1842 #else
1843     {SSL3_VERSION, NULL, NULL},
1844 #endif
1845     {0, NULL, NULL},
1846 };
1847 
1848 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1849 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1850 #endif
1851 
1852 /* Must be in order high to low */
1853 static const version_info dtls_version_table[] = {
1854 #ifndef OPENSSL_NO_DTLS1_2
1855     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1856 #else
1857     {DTLS1_2_VERSION, NULL, NULL},
1858 #endif
1859 #ifndef OPENSSL_NO_DTLS1
1860     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1861     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1862 #else
1863     {DTLS1_VERSION, NULL, NULL},
1864     {DTLS1_BAD_VER, NULL, NULL},
1865 #endif
1866     {0, NULL, NULL},
1867 };
1868 
1869 /*
1870  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1871  *
1872  * @s: The SSL handle for the candidate method
1873  * @method: the intended method.
1874  *
1875  * Returns 0 on success, or an SSL error reason on failure.
1876  */
ssl_method_error(const SSL_CONNECTION * s,const SSL_METHOD * method)1877 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1878 {
1879     int version = method->version;
1880 
1881     if ((s->min_proto_version != 0 &&
1882         ssl_version_cmp(s, version, s->min_proto_version) < 0) ||
1883         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1884         return SSL_R_VERSION_TOO_LOW;
1885 
1886     if (s->max_proto_version != 0 &&
1887         ssl_version_cmp(s, version, s->max_proto_version) > 0)
1888         return SSL_R_VERSION_TOO_HIGH;
1889 
1890     if ((s->options & method->mask) != 0)
1891         return SSL_R_UNSUPPORTED_PROTOCOL;
1892     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1893         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1894 
1895     return 0;
1896 }
1897 
1898 /*
1899  * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1900  * certificate type, or has PSK or a certificate callback configured, or has
1901  * a servername callback configure. Otherwise returns 0.
1902  */
is_tls13_capable(const SSL_CONNECTION * s)1903 static int is_tls13_capable(const SSL_CONNECTION *s)
1904 {
1905     size_t i;
1906     int curve;
1907     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1908 
1909     if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1910         return 0;
1911 
1912     /*
1913      * A servername callback can change the available certs, so if a servername
1914      * cb is set then we just assume TLSv1.3 will be ok
1915      */
1916     if (sctx->ext.servername_cb != NULL
1917             || s->session_ctx->ext.servername_cb != NULL)
1918         return 1;
1919 
1920 #ifndef OPENSSL_NO_PSK
1921     if (s->psk_server_callback != NULL)
1922         return 1;
1923 #endif
1924 
1925     if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1926         return 1;
1927 
1928     /* All provider-based sig algs are required to support at least TLS1.3 */
1929     for (i = 0; i < s->ssl_pkey_num; i++) {
1930         /* Skip over certs disallowed for TLSv1.3 */
1931         switch (i) {
1932         case SSL_PKEY_DSA_SIGN:
1933         case SSL_PKEY_GOST01:
1934         case SSL_PKEY_GOST12_256:
1935         case SSL_PKEY_GOST12_512:
1936             continue;
1937         default:
1938             break;
1939         }
1940         if (!ssl_has_cert(s, i))
1941             continue;
1942         if (i != SSL_PKEY_ECC)
1943             return 1;
1944         /*
1945          * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1946          * more restrictive so check that our sig algs are consistent with this
1947          * EC cert. See section 4.2.3 of RFC8446.
1948          */
1949         curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1950         if (tls_check_sigalg_curve(s, curve))
1951             return 1;
1952     }
1953 
1954     return 0;
1955 }
1956 
1957 /*
1958  * ssl_version_supported - Check that the specified `version` is supported by
1959  * `SSL *` instance
1960  *
1961  * @s: The SSL handle for the candidate method
1962  * @version: Protocol version to test against
1963  *
1964  * Returns 1 when supported, otherwise 0
1965  */
ssl_version_supported(const SSL_CONNECTION * s,int version,const SSL_METHOD ** meth)1966 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1967                           const SSL_METHOD **meth)
1968 {
1969     const version_info *vent;
1970     const version_info *table;
1971 
1972     switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1973     default:
1974         /* Version should match method version for non-ANY method */
1975         return ssl_version_cmp(s, version, s->version) == 0;
1976     case TLS_ANY_VERSION:
1977         table = tls_version_table;
1978         break;
1979     case DTLS_ANY_VERSION:
1980         table = dtls_version_table;
1981         break;
1982     }
1983 
1984     for (vent = table;
1985          vent->version != 0 && ssl_version_cmp(s, version, vent->version) <= 0;
1986          ++vent) {
1987         const SSL_METHOD *(*thismeth)(void) = s->server ? vent->smeth
1988                                                         : vent->cmeth;
1989 
1990         if (thismeth != NULL
1991                 && ssl_version_cmp(s, version, vent->version) == 0
1992                 && ssl_method_error(s, thismeth()) == 0
1993                 && (!s->server
1994                     || version != TLS1_3_VERSION
1995                     || is_tls13_capable(s))) {
1996             if (meth != NULL)
1997                 *meth = thismeth();
1998             return 1;
1999         }
2000     }
2001     return 0;
2002 }
2003 
2004 /*
2005  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
2006  * fallback indication from a client check whether we're using the highest
2007  * supported protocol version.
2008  *
2009  * @s server SSL handle.
2010  *
2011  * Returns 1 when using the highest enabled version, 0 otherwise.
2012  */
ssl_check_version_downgrade(SSL_CONNECTION * s)2013 int ssl_check_version_downgrade(SSL_CONNECTION *s)
2014 {
2015     const version_info *vent;
2016     const version_info *table;
2017     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2018 
2019     /*
2020      * Check that the current protocol is the highest enabled version
2021      * (according to ssl->defltmethod, as version negotiation may have changed
2022      * s->method).
2023      */
2024     if (s->version == ssl->defltmeth->version)
2025         return 1;
2026 
2027     /*
2028      * Apparently we're using a version-flexible SSL_METHOD (not at its
2029      * highest protocol version).
2030      */
2031     if (ssl->defltmeth->version == TLS_method()->version)
2032         table = tls_version_table;
2033     else if (ssl->defltmeth->version == DTLS_method()->version)
2034         table = dtls_version_table;
2035     else {
2036         /* Unexpected state; fail closed. */
2037         return 0;
2038     }
2039 
2040     for (vent = table; vent->version != 0; ++vent) {
2041         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
2042             return s->version == vent->version;
2043     }
2044     return 0;
2045 }
2046 
2047 /*
2048  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
2049  * protocols, provided the initial (D)TLS method is version-flexible.  This
2050  * function sanity-checks the proposed value and makes sure the method is
2051  * version-flexible, then sets the limit if all is well.
2052  *
2053  * @method_version: The version of the current SSL_METHOD.
2054  * @version: the intended limit.
2055  * @bound: pointer to limit to be updated.
2056  *
2057  * Returns 1 on success, 0 on failure.
2058  */
ssl_set_version_bound(int method_version,int version,int * bound)2059 int ssl_set_version_bound(int method_version, int version, int *bound)
2060 {
2061     int valid_tls;
2062     int valid_dtls;
2063 
2064     if (version == 0) {
2065         *bound = version;
2066         return 1;
2067     }
2068 
2069     valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
2070     valid_dtls =
2071         /* We support client side pre-standardisation version of DTLS */
2072         (version == DTLS1_BAD_VER)
2073         || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
2074             && DTLS_VERSION_GE(version, DTLS1_VERSION));
2075 
2076     if (!valid_tls && !valid_dtls)
2077         return 0;
2078 
2079     /*-
2080      * Restrict TLS methods to TLS protocol versions.
2081      * Restrict DTLS methods to DTLS protocol versions.
2082      * Note, DTLS version numbers are decreasing, use comparison macros.
2083      *
2084      * Note that for both lower-bounds we use explicit versions, not
2085      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
2086      * configurations.  If the MIN (supported) version ever rises, the user's
2087      * "floor" remains valid even if no longer available.  We don't expect the
2088      * MAX ceiling to ever get lower, so making that variable makes sense.
2089      *
2090      * We ignore attempts to set bounds on version-inflexible methods,
2091      * returning success.
2092      */
2093     switch (method_version) {
2094     default:
2095         break;
2096 
2097     case TLS_ANY_VERSION:
2098         if (valid_tls)
2099             *bound = version;
2100         break;
2101 
2102     case DTLS_ANY_VERSION:
2103         if (valid_dtls)
2104             *bound = version;
2105         break;
2106     }
2107     return 1;
2108 }
2109 
check_for_downgrade(SSL_CONNECTION * s,int vers,DOWNGRADE * dgrd)2110 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
2111 {
2112     if (vers == TLS1_2_VERSION
2113             && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
2114         *dgrd = DOWNGRADE_TO_1_2;
2115     } else if (!SSL_CONNECTION_IS_DTLS(s)
2116             && vers < TLS1_2_VERSION
2117                /*
2118                 * We need to ensure that a server that disables TLSv1.2
2119                 * (creating a hole between TLSv1.3 and TLSv1.1) can still
2120                 * complete handshakes with clients that support TLSv1.2 and
2121                 * below. Therefore we do not enable the sentinel if TLSv1.3 is
2122                 * enabled and TLSv1.2 is not.
2123                 */
2124             && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
2125         *dgrd = DOWNGRADE_TO_1_1;
2126     } else {
2127         *dgrd = DOWNGRADE_NONE;
2128     }
2129 }
2130 
2131 /*
2132  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
2133  * client HELLO is received to select the final server protocol version and
2134  * the version specific method.
2135  *
2136  * @s: server SSL handle.
2137  *
2138  * Returns 0 on success or an SSL error reason number on failure.
2139  */
ssl_choose_server_version(SSL_CONNECTION * s,CLIENTHELLO_MSG * hello,DOWNGRADE * dgrd)2140 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
2141                               DOWNGRADE *dgrd)
2142 {
2143     /*-
2144      * With version-flexible methods we have an initial state with:
2145      *
2146      *   s->method->version == (D)TLS_ANY_VERSION,
2147      *   s->version == (D)TLS_MAX_VERSION_INTERNAL.
2148      *
2149      * So we detect version-flexible methods via the method version, not the
2150      * handle version.
2151      */
2152     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2153     int server_version = ssl->method->version;
2154     int client_version = hello->legacy_version;
2155     const version_info *vent;
2156     const version_info *table;
2157     int disabled = 0;
2158     RAW_EXTENSION *suppversions;
2159 
2160     s->client_version = client_version;
2161 
2162     switch (server_version) {
2163     default:
2164         if (!SSL_CONNECTION_IS_TLS13(s)) {
2165             if (ssl_version_cmp(s, client_version, s->version) < 0)
2166                 return SSL_R_WRONG_SSL_VERSION;
2167             *dgrd = DOWNGRADE_NONE;
2168             /*
2169              * If this SSL handle is not from a version flexible method we don't
2170              * (and never did) check min/max FIPS or Suite B constraints.  Hope
2171              * that's OK.  It is up to the caller to not choose fixed protocol
2172              * versions they don't want.  If not, then easy to fix, just return
2173              * ssl_method_error(s, s->method)
2174              */
2175             return 0;
2176         }
2177         /*
2178          * Fall through if we are TLSv1.3 already (this means we must be after
2179          * a HelloRetryRequest
2180          */
2181         /* fall thru */
2182     case TLS_ANY_VERSION:
2183         table = tls_version_table;
2184         break;
2185     case DTLS_ANY_VERSION:
2186         table = dtls_version_table;
2187         break;
2188     }
2189 
2190     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
2191 
2192     /* If we did an HRR then supported versions is mandatory */
2193     if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
2194         return SSL_R_UNSUPPORTED_PROTOCOL;
2195 
2196     if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
2197         unsigned int candidate_vers = 0;
2198         unsigned int best_vers = 0;
2199         const SSL_METHOD *best_method = NULL;
2200         PACKET versionslist;
2201 
2202         suppversions->parsed = 1;
2203 
2204         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
2205             /* Trailing or invalid data? */
2206             return SSL_R_LENGTH_MISMATCH;
2207         }
2208 
2209         /*
2210          * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
2211          * The spec only requires servers to check that it isn't SSLv3:
2212          * "Any endpoint receiving a Hello message with
2213          * ClientHello.legacy_version or ServerHello.legacy_version set to
2214          * 0x0300 MUST abort the handshake with a "protocol_version" alert."
2215          * We are slightly stricter and require that it isn't SSLv3 or lower.
2216          * We tolerate TLSv1 and TLSv1.1.
2217          */
2218         if (client_version <= SSL3_VERSION)
2219             return SSL_R_BAD_LEGACY_VERSION;
2220 
2221         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
2222             if (ssl_version_cmp(s, candidate_vers, best_vers) <= 0)
2223                 continue;
2224             if (ssl_version_supported(s, candidate_vers, &best_method))
2225                 best_vers = candidate_vers;
2226         }
2227         if (PACKET_remaining(&versionslist) != 0) {
2228             /* Trailing data? */
2229             return SSL_R_LENGTH_MISMATCH;
2230         }
2231 
2232         if (best_vers > 0) {
2233             if (s->hello_retry_request != SSL_HRR_NONE) {
2234                 /*
2235                  * This is after a HelloRetryRequest so we better check that we
2236                  * negotiated TLSv1.3
2237                  */
2238                 if (best_vers != TLS1_3_VERSION)
2239                     return SSL_R_UNSUPPORTED_PROTOCOL;
2240                 return 0;
2241             }
2242             check_for_downgrade(s, best_vers, dgrd);
2243             s->version = best_vers;
2244             ssl->method = best_method;
2245             if (!ssl_set_record_protocol_version(s, best_vers))
2246                 return ERR_R_INTERNAL_ERROR;
2247 
2248             return 0;
2249         }
2250         return SSL_R_UNSUPPORTED_PROTOCOL;
2251     }
2252 
2253     /*
2254      * If the supported versions extension isn't present, then the highest
2255      * version we can negotiate is TLSv1.2
2256      */
2257     if (ssl_version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
2258         client_version = TLS1_2_VERSION;
2259 
2260     /*
2261      * No supported versions extension, so we just use the version supplied in
2262      * the ClientHello.
2263      */
2264     for (vent = table; vent->version != 0; ++vent) {
2265         const SSL_METHOD *method;
2266 
2267         if (vent->smeth == NULL ||
2268             ssl_version_cmp(s, client_version, vent->version) < 0)
2269             continue;
2270         method = vent->smeth();
2271         if (ssl_method_error(s, method) == 0) {
2272             check_for_downgrade(s, vent->version, dgrd);
2273             s->version = vent->version;
2274             ssl->method = method;
2275             if (!ssl_set_record_protocol_version(s, s->version))
2276                 return ERR_R_INTERNAL_ERROR;
2277 
2278             return 0;
2279         }
2280         disabled = 1;
2281     }
2282     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
2283 }
2284 
2285 /*
2286  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
2287  * server HELLO is received to select the final client protocol version and
2288  * the version specific method.
2289  *
2290  * @s: client SSL handle.
2291  * @version: The proposed version from the server's HELLO.
2292  * @extensions: The extensions received
2293  *
2294  * Returns 1 on success or 0 on error.
2295  */
ssl_choose_client_version(SSL_CONNECTION * s,int version,RAW_EXTENSION * extensions)2296 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
2297                               RAW_EXTENSION *extensions)
2298 {
2299     const version_info *vent;
2300     const version_info *table;
2301     int ret, ver_min, ver_max, real_max, origv;
2302     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2303 
2304     origv = s->version;
2305     s->version = version;
2306 
2307     /* This will overwrite s->version if the extension is present */
2308     if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2309                              SSL_EXT_TLS1_2_SERVER_HELLO
2310                              | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
2311                              NULL, 0)) {
2312         s->version = origv;
2313         return 0;
2314     }
2315 
2316     if (s->hello_retry_request != SSL_HRR_NONE
2317             && s->version != TLS1_3_VERSION) {
2318         s->version = origv;
2319         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2320         return 0;
2321     }
2322 
2323     switch (ssl->method->version) {
2324     default:
2325         if (s->version != ssl->method->version) {
2326             s->version = origv;
2327             SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2328             return 0;
2329         }
2330         /*
2331          * If this SSL handle is not from a version flexible method we don't
2332          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
2333          * that's OK.  It is up to the caller to not choose fixed protocol
2334          * versions they don't want.  If not, then easy to fix, just return
2335          * ssl_method_error(s, s->method)
2336          */
2337         if (!ssl_set_record_protocol_version(s, s->version)) {
2338             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2339             return 0;
2340         }
2341         return 1;
2342     case TLS_ANY_VERSION:
2343         table = tls_version_table;
2344         break;
2345     case DTLS_ANY_VERSION:
2346         table = dtls_version_table;
2347         break;
2348     }
2349 
2350     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2351     if (ret != 0) {
2352         s->version = origv;
2353         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2354         return 0;
2355     }
2356     if (ssl_version_cmp(s, s->version, ver_min) < 0
2357         || ssl_version_cmp(s, s->version, ver_max) > 0) {
2358         s->version = origv;
2359         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2360         return 0;
2361     }
2362 
2363     if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2364         real_max = ver_max;
2365 
2366     /* Check for downgrades */
2367     if (s->version == TLS1_2_VERSION && real_max > s->version) {
2368         if (memcmp(tls12downgrade,
2369                    s->s3.server_random + SSL3_RANDOM_SIZE
2370                                         - sizeof(tls12downgrade),
2371                    sizeof(tls12downgrade)) == 0) {
2372             s->version = origv;
2373             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2374                      SSL_R_INAPPROPRIATE_FALLBACK);
2375             return 0;
2376         }
2377     } else if (!SSL_CONNECTION_IS_DTLS(s)
2378                && s->version < TLS1_2_VERSION
2379                && real_max > s->version) {
2380         if (memcmp(tls11downgrade,
2381                    s->s3.server_random + SSL3_RANDOM_SIZE
2382                                         - sizeof(tls11downgrade),
2383                    sizeof(tls11downgrade)) == 0) {
2384             s->version = origv;
2385             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2386                      SSL_R_INAPPROPRIATE_FALLBACK);
2387             return 0;
2388         }
2389     }
2390 
2391     for (vent = table; vent->version != 0; ++vent) {
2392         if (vent->cmeth == NULL || s->version != vent->version)
2393             continue;
2394 
2395         ssl->method = vent->cmeth();
2396         if (!ssl_set_record_protocol_version(s, s->version)) {
2397             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2398             return 0;
2399         }
2400         return 1;
2401     }
2402 
2403     s->version = origv;
2404     SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2405     return 0;
2406 }
2407 
2408 /*
2409  * ssl_get_min_max_version - get minimum and maximum protocol version
2410  * @s: The SSL connection
2411  * @min_version: The minimum supported version
2412  * @max_version: The maximum supported version
2413  * @real_max:    The highest version below the lowest compile time version hole
2414  *               where that hole lies above at least one run-time enabled
2415  *               protocol.
2416  *
2417  * Work out what version we should be using for the initial ClientHello if the
2418  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
2419  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2420  * constraints and any floor imposed by the security level here,
2421  * so we don't advertise the wrong protocol version to only reject the outcome later.
2422  *
2423  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
2424  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
2425  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2426  *
2427  * Returns 0 on success or an SSL error reason number on failure.  On failure
2428  * min_version and max_version will also be set to 0.
2429  */
ssl_get_min_max_version(const SSL_CONNECTION * s,int * min_version,int * max_version,int * real_max)2430 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2431                             int *max_version, int *real_max)
2432 {
2433     int version, tmp_real_max;
2434     int hole;
2435     const SSL_METHOD *method;
2436     const version_info *table;
2437     const version_info *vent;
2438     const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2439 
2440     switch (ssl->method->version) {
2441     default:
2442         /*
2443          * If this SSL handle is not from a version flexible method we don't
2444          * (and never did) check min/max FIPS or Suite B constraints.  Hope
2445          * that's OK.  It is up to the caller to not choose fixed protocol
2446          * versions they don't want.  If not, then easy to fix, just return
2447          * ssl_method_error(s, s->method)
2448          */
2449         *min_version = *max_version = s->version;
2450         /*
2451          * Providing a real_max only makes sense where we're using a version
2452          * flexible method.
2453          */
2454         if (!ossl_assert(real_max == NULL))
2455             return ERR_R_INTERNAL_ERROR;
2456         return 0;
2457     case TLS_ANY_VERSION:
2458         table = tls_version_table;
2459         break;
2460     case DTLS_ANY_VERSION:
2461         table = dtls_version_table;
2462         break;
2463     }
2464 
2465     /*
2466      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2467      * below X enabled. This is required in order to maintain the "version
2468      * capability" vector contiguous. Any versions with a NULL client method
2469      * (protocol version client is disabled at compile-time) is also a "hole".
2470      *
2471      * Our initial state is hole == 1, version == 0.  That is, versions above
2472      * the first version in the method table are disabled (a "hole" above
2473      * the valid protocol entries) and we don't have a selected version yet.
2474      *
2475      * Whenever "hole == 1", and we hit an enabled method, its version becomes
2476      * the selected version.  We're no longer in a hole, so "hole" becomes 0.
2477      *
2478      * If "hole == 0" and we hit an enabled method, we support a contiguous
2479      * range of at least two methods.  If we hit a disabled method,
2480      * then hole becomes true again, but nothing else changes yet,
2481      * because all the remaining methods may be disabled too.
2482      * If we again hit an enabled method after the new hole, it becomes
2483      * selected, as we start from scratch.
2484      */
2485     *min_version = version = 0;
2486     hole = 1;
2487     if (real_max != NULL)
2488         *real_max = 0;
2489     tmp_real_max = 0;
2490     for (vent = table; vent->version != 0; ++vent) {
2491         /*
2492          * A table entry with a NULL client method is still a hole in the
2493          * "version capability" vector.
2494          */
2495         if (vent->cmeth == NULL) {
2496             hole = 1;
2497             tmp_real_max = 0;
2498             continue;
2499         }
2500         method = vent->cmeth();
2501 
2502         if (hole == 1 && tmp_real_max == 0)
2503             tmp_real_max = vent->version;
2504 
2505         if (ssl_method_error(s, method) != 0) {
2506             hole = 1;
2507         } else if (!hole) {
2508             *min_version = method->version;
2509         } else {
2510             if (real_max != NULL && tmp_real_max != 0)
2511                 *real_max = tmp_real_max;
2512             version = method->version;
2513             *min_version = version;
2514             hole = 0;
2515         }
2516     }
2517 
2518     *max_version = version;
2519 
2520     /* Fail if everything is disabled */
2521     if (version == 0)
2522         return SSL_R_NO_PROTOCOLS_AVAILABLE;
2523 
2524     return 0;
2525 }
2526 
2527 /*
2528  * ssl_set_client_hello_version - Work out what version we should be using for
2529  * the initial ClientHello.legacy_version field.
2530  *
2531  * @s: client SSL handle.
2532  *
2533  * Returns 0 on success or an SSL error reason number on failure.
2534  */
ssl_set_client_hello_version(SSL_CONNECTION * s)2535 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2536 {
2537     int ver_min, ver_max, ret;
2538 
2539     /*
2540      * In a renegotiation we always send the same client_version that we sent
2541      * last time, regardless of which version we eventually negotiated.
2542      */
2543     if (!SSL_IS_FIRST_HANDSHAKE(s))
2544         return 0;
2545 
2546     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2547 
2548     if (ret != 0)
2549         return ret;
2550 
2551     s->version = ver_max;
2552 
2553     if (SSL_CONNECTION_IS_DTLS(s)) {
2554         if (ver_max == DTLS1_BAD_VER) {
2555             /*
2556              * Even though this is technically before version negotiation,
2557              * because we have asked for DTLS1_BAD_VER we will never negotiate
2558              * anything else, and this has impacts on the record layer for when
2559              * we read the ServerHello. So we need to tell the record layer
2560              * about this immediately.
2561              */
2562             if (!ssl_set_record_protocol_version(s, ver_max))
2563                 return 0;
2564         }
2565     } else if (ver_max > TLS1_2_VERSION) {
2566         /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2567         ver_max = TLS1_2_VERSION;
2568     }
2569 
2570     s->client_version = ver_max;
2571     return 0;
2572 }
2573 
2574 /*
2575  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2576  * and |checkallow| is 1 then additionally check if the group is allowed to be
2577  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2578  * 1) or 0 otherwise.
2579  */
check_in_list(SSL_CONNECTION * s,uint16_t group_id,const uint16_t * groups,size_t num_groups,int checkallow)2580 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2581                   size_t num_groups, int checkallow)
2582 {
2583     size_t i;
2584 
2585     if (groups == NULL || num_groups == 0)
2586         return 0;
2587 
2588     for (i = 0; i < num_groups; i++) {
2589         uint16_t group = groups[i];
2590 
2591         if (group_id == group
2592                 && (!checkallow
2593                     || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2594             return 1;
2595         }
2596     }
2597 
2598     return 0;
2599 }
2600 
2601 /* Replace ClientHello1 in the transcript hash with a synthetic message */
create_synthetic_message_hash(SSL_CONNECTION * s,const unsigned char * hashval,size_t hashlen,const unsigned char * hrr,size_t hrrlen)2602 int create_synthetic_message_hash(SSL_CONNECTION *s,
2603                                   const unsigned char *hashval,
2604                                   size_t hashlen, const unsigned char *hrr,
2605                                   size_t hrrlen)
2606 {
2607     unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2608     unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2609 
2610     memset(msghdr, 0, sizeof(msghdr));
2611 
2612     if (hashval == NULL) {
2613         hashval = hashvaltmp;
2614         hashlen = 0;
2615         /* Get the hash of the initial ClientHello */
2616         if (!ssl3_digest_cached_records(s, 0)
2617                 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2618                                        &hashlen)) {
2619             /* SSLfatal() already called */
2620             return 0;
2621         }
2622     }
2623 
2624     /* Reinitialise the transcript hash */
2625     if (!ssl3_init_finished_mac(s)) {
2626         /* SSLfatal() already called */
2627         return 0;
2628     }
2629 
2630     /* Inject the synthetic message_hash message */
2631     msghdr[0] = SSL3_MT_MESSAGE_HASH;
2632     msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2633     if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2634             || !ssl3_finish_mac(s, hashval, hashlen)) {
2635         /* SSLfatal() already called */
2636         return 0;
2637     }
2638 
2639     /*
2640      * Now re-inject the HRR and current message if appropriate (we just deleted
2641      * it when we reinitialised the transcript hash above). Only necessary after
2642      * receiving a ClientHello2 with a cookie.
2643      */
2644     if (hrr != NULL
2645             && (!ssl3_finish_mac(s, hrr, hrrlen)
2646                 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2647                                     s->s3.tmp.message_size
2648                                     + SSL3_HM_HEADER_LENGTH))) {
2649         /* SSLfatal() already called */
2650         return 0;
2651     }
2652 
2653     return 1;
2654 }
2655 
ca_dn_cmp(const X509_NAME * const * a,const X509_NAME * const * b)2656 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2657 {
2658     return X509_NAME_cmp(*a, *b);
2659 }
2660 
parse_ca_names(SSL_CONNECTION * s,PACKET * pkt)2661 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2662 {
2663     STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2664     X509_NAME *xn = NULL;
2665     PACKET cadns;
2666 
2667     if (ca_sk == NULL) {
2668         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2669         goto err;
2670     }
2671     /* get the CA RDNs */
2672     if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2673         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2674         goto err;
2675     }
2676 
2677     while (PACKET_remaining(&cadns)) {
2678         const unsigned char *namestart, *namebytes;
2679         unsigned int name_len;
2680 
2681         if (!PACKET_get_net_2(&cadns, &name_len)
2682             || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2683             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2684             goto err;
2685         }
2686 
2687         namestart = namebytes;
2688         if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2689             SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2690             goto err;
2691         }
2692         if (namebytes != (namestart + name_len)) {
2693             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2694             goto err;
2695         }
2696 
2697         if (!sk_X509_NAME_push(ca_sk, xn)) {
2698             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2699             goto err;
2700         }
2701         xn = NULL;
2702     }
2703 
2704     sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2705     s->s3.tmp.peer_ca_names = ca_sk;
2706 
2707     return 1;
2708 
2709  err:
2710     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2711     X509_NAME_free(xn);
2712     return 0;
2713 }
2714 
STACK_OF(X509_NAME)2715 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2716 {
2717     const STACK_OF(X509_NAME) *ca_sk = NULL;
2718     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2719 
2720     if (s->server) {
2721         ca_sk = SSL_get_client_CA_list(ssl);
2722         if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2723             ca_sk = NULL;
2724     }
2725 
2726     if (ca_sk == NULL)
2727         ca_sk = SSL_get0_CA_list(ssl);
2728 
2729     return ca_sk;
2730 }
2731 
construct_ca_names(SSL_CONNECTION * s,const STACK_OF (X509_NAME)* ca_sk,WPACKET * pkt)2732 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2733                        WPACKET *pkt)
2734 {
2735     /* Start sub-packet for client CA list */
2736     if (!WPACKET_start_sub_packet_u16(pkt)) {
2737         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2738         return 0;
2739     }
2740 
2741     if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2742         int i;
2743 
2744         for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2745             unsigned char *namebytes;
2746             X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2747             int namelen;
2748 
2749             if (name == NULL
2750                     || (namelen = i2d_X509_NAME(name, NULL)) < 0
2751                     || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2752                                                        &namebytes)
2753                     || i2d_X509_NAME(name, &namebytes) != namelen) {
2754                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2755                 return 0;
2756             }
2757         }
2758     }
2759 
2760     if (!WPACKET_close(pkt)) {
2761         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2762         return 0;
2763     }
2764 
2765     return 1;
2766 }
2767 
2768 /* Create a buffer containing data to be signed for server key exchange */
construct_key_exchange_tbs(SSL_CONNECTION * s,unsigned char ** ptbs,const void * param,size_t paramlen)2769 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2770                                   const void *param, size_t paramlen)
2771 {
2772     size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2773     unsigned char *tbs = OPENSSL_malloc(tbslen);
2774 
2775     if (tbs == NULL) {
2776         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2777         return 0;
2778     }
2779     memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2780     memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2781 
2782     memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2783 
2784     *ptbs = tbs;
2785     return tbslen;
2786 }
2787 
2788 /*
2789  * Saves the current handshake digest for Post-Handshake Auth,
2790  * Done after ClientFinished is processed, done exactly once
2791  */
tls13_save_handshake_digest_for_pha(SSL_CONNECTION * s)2792 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2793 {
2794     if (s->pha_dgst == NULL) {
2795         if (!ssl3_digest_cached_records(s, 1))
2796             /* SSLfatal() already called */
2797             return 0;
2798 
2799         s->pha_dgst = EVP_MD_CTX_new();
2800         if (s->pha_dgst == NULL) {
2801             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2802             return 0;
2803         }
2804         if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2805                                 s->s3.handshake_dgst)) {
2806             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2807             EVP_MD_CTX_free(s->pha_dgst);
2808             s->pha_dgst = NULL;
2809             return 0;
2810         }
2811     }
2812     return 1;
2813 }
2814 
2815 /*
2816  * Restores the Post-Handshake Auth handshake digest
2817  * Done just before sending/processing the Cert Request
2818  */
tls13_restore_handshake_digest_for_pha(SSL_CONNECTION * s)2819 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2820 {
2821     if (s->pha_dgst == NULL) {
2822         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2823         return 0;
2824     }
2825     if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2826                             s->pha_dgst)) {
2827         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2828         return 0;
2829     }
2830     return 1;
2831 }
2832 
2833 #ifndef OPENSSL_NO_COMP_ALG
tls13_process_compressed_certificate(SSL_CONNECTION * sc,PACKET * pkt,PACKET * tmppkt,BUF_MEM * buf)2834 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2835                                                         PACKET *pkt,
2836                                                         PACKET *tmppkt,
2837                                                         BUF_MEM *buf)
2838 {
2839     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2840     int comp_alg;
2841     COMP_METHOD *method = NULL;
2842     COMP_CTX *comp = NULL;
2843     size_t expected_length;
2844     size_t comp_length;
2845     int i;
2846     int found = 0;
2847 
2848     if (buf == NULL) {
2849         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2850         goto err;
2851     }
2852     if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2853         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2854         goto err;
2855     }
2856     /* If we have a prefs list, make sure the algorithm is in it */
2857     if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2858         for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2859             if (sc->cert_comp_prefs[i] == comp_alg) {
2860                 found = 1;
2861                 break;
2862             }
2863         }
2864         if (!found) {
2865             SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_COMPRESSION_ALGORITHM);
2866             goto err;
2867         }
2868     }
2869     if (!ossl_comp_has_alg(comp_alg)) {
2870         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2871         goto err;
2872     }
2873     switch (comp_alg) {
2874     case TLSEXT_comp_cert_zlib:
2875         method = COMP_zlib_oneshot();
2876         break;
2877     case TLSEXT_comp_cert_brotli:
2878         method = COMP_brotli_oneshot();
2879         break;
2880     case TLSEXT_comp_cert_zstd:
2881         method = COMP_zstd_oneshot();
2882         break;
2883     default:
2884         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2885         goto err;
2886     }
2887 
2888     if ((comp = COMP_CTX_new(method)) == NULL
2889         || !PACKET_get_net_3_len(pkt, &expected_length)
2890         || !PACKET_get_net_3_len(pkt, &comp_length)) {
2891         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2892         goto err;
2893     }
2894 
2895     if (PACKET_remaining(pkt) != comp_length || comp_length == 0) {
2896         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_DECOMPRESSION);
2897         goto err;
2898     }
2899 
2900     if (!BUF_MEM_grow(buf, expected_length)
2901         || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2902         || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2903                              (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2904         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2905         goto err;
2906     }
2907     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2908  err:
2909     COMP_CTX_free(comp);
2910     return ret;
2911 }
2912 #endif
2913