2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
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
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>
26 * Map error codes to TLS/SSL alart types.
28 typedef struct x509err2alert_st {
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
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,
45 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
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;
58 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
59 * SSL3_RT_CHANGE_CIPHER_SPEC)
61 int ssl3_do_write(SSL_CONNECTION *s, uint8_t type)
65 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
68 * If we're running the test suite then we may need to mutate the message
69 * we've been asked to write. Does not happen in normal operation.
71 if (s->statem.mutate_handshake_cb != NULL
72 && !s->statem.write_in_progress
73 && type == SSL3_RT_HANDSHAKE
74 && s->init_num >= SSL3_HM_HEADER_LENGTH) {
78 if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
83 if (msglen < SSL3_HM_HEADER_LENGTH
84 || !BUF_MEM_grow(s->init_buf, msglen))
86 memcpy(s->init_buf->data, msg, msglen);
88 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
89 s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
90 s->statem.write_in_progress = 1;
93 ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
94 s->init_num, &written);
97 if (type == SSL3_RT_HANDSHAKE)
99 * should not be done for 'Hello Request's, but in that case we'll
100 * ignore the result anyway
101 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
103 if (!SSL_CONNECTION_IS_TLS13(s)
104 || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
105 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
106 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
107 if (!ssl3_finish_mac(s,
108 (unsigned char *)&s->init_buf->data[s->init_off],
111 if (written == s->init_num) {
112 s->statem.write_in_progress = 0;
114 s->msg_callback(1, s->version, type, s->init_buf->data,
115 (size_t)(s->init_off + s->init_num), ssl,
116 s->msg_callback_arg);
119 s->init_off += written;
120 s->init_num -= written;
124 int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
128 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
129 || !WPACKET_get_length(pkt, &msglen)
132 s->init_num = (int)msglen;
138 int tls_setup_handshake(SSL_CONNECTION *s)
140 int ver_min, ver_max, ok;
141 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
142 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
144 if (!ssl3_init_finished_mac(s)) {
145 /* SSLfatal() already called */
149 /* Reset any extension flags */
150 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
152 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
153 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
157 /* Sanity check that we have MD5-SHA1 if we need it */
158 if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
159 int md5sha1_needed = 0;
161 /* We don't have MD5-SHA1 - do we need it? */
162 if (SSL_CONNECTION_IS_DTLS(s)) {
163 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
166 if (ver_max <= TLS1_1_VERSION)
169 if (md5sha1_needed) {
170 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
171 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
172 "The max supported SSL/TLS version needs the"
173 " MD5-SHA1 digest but it is not available"
174 " in the loaded providers. Use (D)TLSv1.2 or"
175 " above, or load different providers");
180 /* Don't allow TLSv1.1 or below to be negotiated */
181 if (SSL_CONNECTION_IS_DTLS(s)) {
182 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
183 ok = SSL_set_min_proto_version(ssl, DTLS1_2_VERSION);
185 if (ver_min < TLS1_2_VERSION)
186 ok = SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
189 /* Shouldn't happen */
190 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
197 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
201 * Sanity check that the maximum version we accept has ciphers
202 * enabled. For clients we do this check during construction of the
205 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
206 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
208 if (SSL_CONNECTION_IS_DTLS(s)) {
209 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
210 DTLS_VERSION_LE(ver_max, c->max_dtls))
212 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
219 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
220 SSL_R_NO_CIPHERS_AVAILABLE,
221 "No ciphers enabled for max supported "
225 if (SSL_IS_FIRST_HANDSHAKE(s)) {
226 /* N.B. s->session_ctx == s->ctx here */
227 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
229 /* N.B. s->ctx may not equal s->session_ctx */
230 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
232 s->s3.tmp.cert_request = 0;
235 if (SSL_IS_FIRST_HANDSHAKE(s))
236 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
238 ssl_tsan_counter(s->session_ctx,
239 &s->session_ctx->stats.sess_connect_renegotiate);
241 /* mark client_random uninitialized */
242 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
245 s->s3.tmp.cert_req = 0;
247 if (SSL_CONNECTION_IS_DTLS(s))
248 s->statem.use_timer = 1;
255 * Size of the to-be-signed TLS13 data, without the hash size itself:
256 * 64 bytes of value 32, 33 context bytes, 1 byte separator
258 #define TLS13_TBS_START_SIZE 64
259 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
261 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
262 void **hdata, size_t *hdatalen)
264 /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
265 static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
266 "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
267 /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
268 static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
269 "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
271 if (SSL_CONNECTION_IS_TLS13(s)) {
274 /* Set the first 64 bytes of to-be-signed data to octet 32 */
275 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
276 /* This copies the 33 bytes of context plus the 0 separator byte */
277 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
278 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
279 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
281 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
284 * If we're currently reading then we need to use the saved handshake
285 * hash value. We can't use the current handshake hash state because
286 * that includes the CertVerify itself.
288 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
289 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
290 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
291 s->cert_verify_hash_len);
292 hashlen = s->cert_verify_hash_len;
293 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
294 EVP_MAX_MD_SIZE, &hashlen)) {
295 /* SSLfatal() already called */
300 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
305 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
307 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
316 CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
318 EVP_PKEY *pkey = NULL;
319 const EVP_MD *md = NULL;
320 EVP_MD_CTX *mctx = NULL;
321 EVP_PKEY_CTX *pctx = NULL;
322 size_t hdatalen = 0, siglen = 0;
324 unsigned char *sig = NULL;
325 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
326 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
327 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
329 if (lu == NULL || s->s3.tmp.cert == NULL) {
330 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
333 pkey = s->s3.tmp.cert->privatekey;
335 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
336 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
340 mctx = EVP_MD_CTX_new();
342 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
346 /* Get the data to be signed */
347 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
348 /* SSLfatal() already called */
352 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
353 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
357 if (EVP_DigestSignInit_ex(mctx, &pctx,
358 md == NULL ? NULL : EVP_MD_get0_name(md),
359 sctx->libctx, sctx->propq, pkey,
361 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
365 if (lu->sig == EVP_PKEY_RSA_PSS) {
366 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
367 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
368 RSA_PSS_SALTLEN_DIGEST) <= 0) {
369 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
373 if (s->version == SSL3_VERSION) {
375 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
376 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
378 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
379 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
380 (int)s->session->master_key_length,
381 s->session->master_key) <= 0
382 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
384 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
387 sig = OPENSSL_malloc(siglen);
389 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
390 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
395 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
396 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
398 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
399 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
402 sig = OPENSSL_malloc(siglen);
404 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
405 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
410 #ifndef OPENSSL_NO_GOST
412 int pktype = lu->sig;
414 if (pktype == NID_id_GostR3410_2001
415 || pktype == NID_id_GostR3410_2012_256
416 || pktype == NID_id_GostR3410_2012_512)
417 BUF_reverse(sig, NULL, siglen);
421 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
422 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
426 /* Digest cached records and discard handshake buffer */
427 if (!ssl3_digest_cached_records(s, 0)) {
428 /* SSLfatal() already called */
433 EVP_MD_CTX_free(mctx);
434 return CON_FUNC_SUCCESS;
437 EVP_MD_CTX_free(mctx);
438 return CON_FUNC_ERROR;
441 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
443 EVP_PKEY *pkey = NULL;
444 const unsigned char *data;
445 #ifndef OPENSSL_NO_GOST
446 unsigned char *gost_data = NULL;
448 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
451 const EVP_MD *md = NULL;
454 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
455 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
456 EVP_PKEY_CTX *pctx = NULL;
457 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
460 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
464 pkey = tls_get_peer_pkey(s);
466 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
470 if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
471 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
472 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
476 if (SSL_USE_SIGALGS(s)) {
479 if (!PACKET_get_net_2(pkt, &sigalg)) {
480 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
483 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
484 /* SSLfatal() already called */
487 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
488 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
489 SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
493 if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
494 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
498 if (SSL_USE_SIGALGS(s))
499 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
500 md == NULL ? "n/a" : EVP_MD_get0_name(md));
502 /* Check for broken implementations of GOST ciphersuites */
504 * If key is GOST and len is exactly 64 or 128, it is signature without
505 * length field (CryptoPro implementations at least till TLS 1.2)
507 #ifndef OPENSSL_NO_GOST
508 if (!SSL_USE_SIGALGS(s)
509 && ((PACKET_remaining(pkt) == 64
510 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
511 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
512 || (PACKET_remaining(pkt) == 128
513 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
514 len = PACKET_remaining(pkt);
517 if (!PACKET_get_net_2(pkt, &len)) {
518 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
522 if (!PACKET_get_bytes(pkt, &data, len)) {
523 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
527 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
528 /* SSLfatal() already called */
532 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
533 md == NULL ? "n/a" : EVP_MD_get0_name(md));
535 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
536 md == NULL ? NULL : EVP_MD_get0_name(md),
537 sctx->libctx, sctx->propq, pkey,
539 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
542 #ifndef OPENSSL_NO_GOST
544 int pktype = EVP_PKEY_get_id(pkey);
545 if (pktype == NID_id_GostR3410_2001
546 || pktype == NID_id_GostR3410_2012_256
547 || pktype == NID_id_GostR3410_2012_512) {
548 if ((gost_data = OPENSSL_malloc(len)) == NULL)
550 BUF_reverse(gost_data, data, len);
556 if (SSL_USE_PSS(s)) {
557 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
558 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
559 RSA_PSS_SALTLEN_DIGEST) <= 0) {
560 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
564 if (s->version == SSL3_VERSION) {
565 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
566 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
567 (int)s->session->master_key_length,
568 s->session->master_key) <= 0) {
569 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
572 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
573 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
577 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
578 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
579 /* Ignore bad signatures when fuzzing */
580 if (SSL_IS_QUIC_HANDSHAKE(s))
584 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
590 * In TLSv1.3 on the client side we make sure we prepare the client
591 * certificate after the CertVerify instead of when we get the
592 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
593 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
594 * want to make sure that SSL_get1_peer_certificate() will return the actual
595 * server certificate from the client_cert_cb callback.
597 if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
598 ret = MSG_PROCESS_CONTINUE_PROCESSING;
600 ret = MSG_PROCESS_CONTINUE_READING;
602 BIO_free(s->s3.handshake_buffer);
603 s->s3.handshake_buffer = NULL;
604 EVP_MD_CTX_free(mctx);
605 #ifndef OPENSSL_NO_GOST
606 OPENSSL_free(gost_data);
611 CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
613 size_t finish_md_len;
616 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
618 /* This is a real handshake so make sure we clean it up at the end */
619 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
620 s->statem.cleanuphand = 1;
623 * If we attempted to write early data or we're in middlebox compat mode
624 * then we deferred changing the handshake write keys to the last possible
625 * moment. If we didn't already do this when we sent the client certificate
626 * then we need to do it now.
628 if (SSL_CONNECTION_IS_TLS13(s)
630 && (s->early_data_state != SSL_EARLY_DATA_NONE
631 || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
632 && s->s3.tmp.cert_req == 0
633 && (!ssl->method->ssl3_enc->change_cipher_state(s,
634 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
635 /* SSLfatal() already called */
636 return CON_FUNC_ERROR;
640 sender = ssl->method->ssl3_enc->server_finished_label;
641 slen = ssl->method->ssl3_enc->server_finished_label_len;
643 sender = ssl->method->ssl3_enc->client_finished_label;
644 slen = ssl->method->ssl3_enc->client_finished_label_len;
647 finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
649 s->s3.tmp.finish_md);
650 if (finish_md_len == 0) {
651 /* SSLfatal() already called */
652 return CON_FUNC_ERROR;
655 s->s3.tmp.finish_md_len = finish_md_len;
657 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
658 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
659 return CON_FUNC_ERROR;
663 * Log the master secret, if logging is enabled. We don't log it for
664 * TLSv1.3: there's a different key schedule for that.
666 if (!SSL_CONNECTION_IS_TLS13(s)
667 && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
668 s->session->master_key_length)) {
669 /* SSLfatal() already called */
670 return CON_FUNC_ERROR;
674 * Copy the finished so we can use it for renegotiation checks
676 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
677 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
678 return CON_FUNC_ERROR;
681 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
683 s->s3.previous_client_finished_len = finish_md_len;
685 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
687 s->s3.previous_server_finished_len = finish_md_len;
690 return CON_FUNC_SUCCESS;
693 CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
695 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
696 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
697 return CON_FUNC_ERROR;
700 s->key_update = SSL_KEY_UPDATE_NONE;
701 return CON_FUNC_SUCCESS;
704 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
706 unsigned int updatetype;
709 * A KeyUpdate message signals a key change so the end of the message must
710 * be on a record boundary.
712 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
713 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
714 return MSG_PROCESS_ERROR;
717 if (!PACKET_get_1(pkt, &updatetype)
718 || PACKET_remaining(pkt) != 0) {
719 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
720 return MSG_PROCESS_ERROR;
724 * There are only two defined key update types. Fail if we get a value we
727 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
728 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
729 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
730 return MSG_PROCESS_ERROR;
734 * If we get a request for us to update our sending keys too then, we need
735 * to additionally send a KeyUpdate message. However that message should
736 * not also request an update (otherwise we get into an infinite loop).
738 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
739 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
741 if (!tls13_update_key(s, 0)) {
742 /* SSLfatal() already called */
743 return MSG_PROCESS_ERROR;
746 return MSG_PROCESS_FINISHED_READING;
750 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
753 int ssl3_take_mac(SSL_CONNECTION *s)
757 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
760 sender = ssl->method->ssl3_enc->server_finished_label;
761 slen = ssl->method->ssl3_enc->server_finished_label_len;
763 sender = ssl->method->ssl3_enc->client_finished_label;
764 slen = ssl->method->ssl3_enc->client_finished_label_len;
767 s->s3.tmp.peer_finish_md_len =
768 ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
769 s->s3.tmp.peer_finish_md);
771 if (s->s3.tmp.peer_finish_md_len == 0) {
772 /* SSLfatal() already called */
779 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
784 remain = PACKET_remaining(pkt);
786 * 'Change Cipher Spec' is just a single byte, which should already have
787 * been consumed by ssl_get_message() so there should be no bytes left,
788 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
790 if (SSL_CONNECTION_IS_DTLS(s)) {
791 if ((s->version == DTLS1_BAD_VER
792 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
793 || (s->version != DTLS1_BAD_VER
794 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
795 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
796 return MSG_PROCESS_ERROR;
800 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
801 return MSG_PROCESS_ERROR;
805 /* Check we have a cipher to change to */
806 if (s->s3.tmp.new_cipher == NULL) {
807 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
808 return MSG_PROCESS_ERROR;
811 s->s3.change_cipher_spec = 1;
812 if (!ssl3_do_change_cipher_spec(s)) {
813 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
814 return MSG_PROCESS_ERROR;
817 if (SSL_CONNECTION_IS_DTLS(s)) {
818 dtls1_increment_epoch(s, SSL3_CC_READ);
820 if (s->version == DTLS1_BAD_VER)
821 s->d1->handshake_read_seq++;
823 #ifndef OPENSSL_NO_SCTP
825 * Remember that a CCS has been received, so that an old key of
826 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
829 BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
830 BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
834 return MSG_PROCESS_CONTINUE_READING;
837 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
840 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
841 int was_first = SSL_IS_FIRST_HANDSHAKE(s);
845 /* This is a real handshake so make sure we clean it up at the end */
848 * To get this far we must have read encrypted data from the client. We
849 * no longer tolerate unencrypted alerts. This is ignored if less than
852 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
853 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
854 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
855 s->statem.cleanuphand = 1;
856 if (SSL_CONNECTION_IS_TLS13(s)
857 && !tls13_save_handshake_digest_for_pha(s)) {
858 /* SSLfatal() already called */
859 return MSG_PROCESS_ERROR;
864 * In TLSv1.3 a Finished message signals a key change so the end of the
865 * message must be on a record boundary.
867 if (SSL_CONNECTION_IS_TLS13(s)
868 && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
869 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
870 return MSG_PROCESS_ERROR;
873 /* If this occurs, we have missed a message */
874 if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
875 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
876 return MSG_PROCESS_ERROR;
878 s->s3.change_cipher_spec = 0;
880 md_len = s->s3.tmp.peer_finish_md_len;
882 if (md_len != PACKET_remaining(pkt)) {
883 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
884 return MSG_PROCESS_ERROR;
887 ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
889 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
891 if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
897 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
898 return MSG_PROCESS_ERROR;
902 * Copy the finished so we can use it for renegotiation checks
904 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
905 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
906 return MSG_PROCESS_ERROR;
909 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
911 s->s3.previous_client_finished_len = md_len;
913 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
915 s->s3.previous_server_finished_len = md_len;
919 * In TLS1.3 we also have to change cipher state and do any final processing
920 * of the initial server flight (if we are a client)
922 if (SSL_CONNECTION_IS_TLS13(s)) {
924 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
925 !ssl->method->ssl3_enc->change_cipher_state(s,
926 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
927 /* SSLfatal() already called */
928 return MSG_PROCESS_ERROR;
931 /* TLS 1.3 gets the secret size from the handshake md */
933 if (!ssl->method->ssl3_enc->generate_master_secret(s,
934 s->master_secret, s->handshake_secret, 0,
936 /* SSLfatal() already called */
937 return MSG_PROCESS_ERROR;
939 if (!ssl->method->ssl3_enc->change_cipher_state(s,
940 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
941 /* SSLfatal() already called */
942 return MSG_PROCESS_ERROR;
944 if (!tls_process_initial_server_flight(s)) {
945 /* SSLfatal() already called */
946 return MSG_PROCESS_ERROR;
952 && !SSL_IS_FIRST_HANDSHAKE(s)
953 && s->rlayer.rrlmethod->set_first_handshake != NULL)
954 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
956 return MSG_PROCESS_FINISHED_READING;
959 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
961 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
962 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
963 return CON_FUNC_ERROR;
966 return CON_FUNC_SUCCESS;
969 /* Add a certificate to the WPACKET */
970 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
971 X509 *x, int chain, int for_comp)
974 unsigned char *outbytes;
975 int context = SSL_EXT_TLS1_3_CERTIFICATE;
978 context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
980 len = i2d_X509(x, NULL);
983 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
986 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
987 || i2d_X509(x, &outbytes) != len) {
989 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
993 if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
994 && !tls_construct_extensions(s, pkt, context, x, chain)) {
995 /* SSLfatal() already called */
1002 /* Add certificate chain to provided WPACKET */
1003 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
1007 STACK_OF(X509) *extra_certs;
1008 STACK_OF(X509) *chain = NULL;
1009 X509_STORE *chain_store;
1010 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1012 if (cpk == NULL || cpk->x509 == NULL)
1018 * If we have a certificate specific chain use it, else use parent ctx.
1020 if (cpk->chain != NULL)
1021 extra_certs = cpk->chain;
1023 extra_certs = sctx->extra_certs;
1025 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1027 else if (s->cert->chain_store)
1028 chain_store = s->cert->chain_store;
1030 chain_store = sctx->cert_store;
1032 if (chain_store != NULL) {
1033 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1036 if (xs_ctx == NULL) {
1038 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1041 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1042 X509_STORE_CTX_free(xs_ctx);
1044 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1048 * It is valid for the chain not to be complete (because normally we
1049 * don't include the root cert in the chain). Therefore we deliberately
1050 * ignore the error return from this call. We're not actually verifying
1051 * the cert - we're just building as much of the chain as we can
1053 (void)X509_verify_cert(xs_ctx);
1054 /* Don't leave errors in the queue */
1056 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1057 i = ssl_security_cert_chain(s, chain, NULL, 0);
1060 /* Dummy error calls so mkerr generates them */
1061 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1062 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1063 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1065 X509_STORE_CTX_free(xs_ctx);
1067 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1070 chain_count = sk_X509_num(chain);
1071 for (i = 0; i < chain_count; i++) {
1072 x = sk_X509_value(chain, i);
1074 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1075 /* SSLfatal() already called */
1076 X509_STORE_CTX_free(xs_ctx);
1080 X509_STORE_CTX_free(xs_ctx);
1082 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1085 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1088 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1089 /* SSLfatal() already called */
1092 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1093 x = sk_X509_value(extra_certs, i);
1094 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1095 /* SSLfatal() already called */
1103 EVP_PKEY* tls_get_peer_pkey(const SSL_CONNECTION *sc)
1105 if (sc->session->peer_rpk != NULL)
1106 return sc->session->peer_rpk;
1107 if (sc->session->peer != NULL)
1108 return X509_get0_pubkey(sc->session->peer);
1112 int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
1114 EVP_PKEY *pkey = NULL;
1116 RAW_EXTENSION *rawexts = NULL;
1119 unsigned long cert_len = 0, spki_len = 0;
1120 const unsigned char *spki, *spkistart;
1121 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
1124 * ----------------------------
1125 * TLS 1.3 Certificate message:
1126 * ----------------------------
1127 * https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
1133 * } CertificateType;
1136 * select (certificate_type) {
1137 * case RawPublicKey:
1138 * // From RFC 7250 ASN.1_subjectPublicKeyInfo
1139 * opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
1142 * opaque cert_data<1..2^24-1>;
1144 * Extension extensions<0..2^16-1>;
1145 * } CertificateEntry;
1148 * opaque certificate_request_context<0..2^8-1>;
1149 * CertificateEntry certificate_list<0..2^24-1>;
1152 * The client MUST send a Certificate message if and only if the server
1153 * has requested client authentication via a CertificateRequest message
1154 * (Section 4.3.2). If the server requests client authentication but no
1155 * suitable certificate is available, the client MUST send a Certificate
1156 * message containing no certificates (i.e., with the "certificate_list"
1157 * field having length 0).
1159 * ----------------------------
1160 * TLS 1.2 Certificate message:
1161 * ----------------------------
1162 * https://datatracker.ietf.org/doc/html/rfc7250#section-3
1164 * opaque ASN.1Cert<1..2^24-1>;
1167 * select(certificate_type){
1169 * // certificate type defined in this document.
1170 * case RawPublicKey:
1171 * opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
1173 * // X.509 certificate defined in RFC 5246
1175 * ASN.1Cert certificate_list<0..2^24-1>;
1177 * // Additional certificate type based on
1178 * // "TLS Certificate Types" subregistry
1185 * After the (TLS 1.3 only) context octet string (1 byte length + data) the
1186 * Certificate message has a 3-byte length that is zero in the client to
1187 * server message when the client has no RPK to send. In that case, there
1188 * are no (TLS 1.3 only) per-certificate extensions either, because the
1189 * [CertificateEntry] list is empty.
1191 * In the server to client direction, or when the client had an RPK to send,
1192 * the TLS 1.3 message just prepends the length of the RPK+extensions,
1193 * while TLS <= 1.2 sends just the RPK (octet-string).
1195 * The context must be zero-length in the server to client direction, and
1196 * must match the value recorded in the certificate request in the client
1197 * to server direction.
1199 if (SSL_CONNECTION_IS_TLS13(sc)) {
1200 if (!PACKET_get_length_prefixed_1(pkt, &context)) {
1201 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1205 if (sc->pha_context == NULL) {
1206 if (PACKET_remaining(&context) != 0) {
1207 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1211 if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
1212 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1217 if (PACKET_remaining(&context) != 0) {
1218 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1224 if (!PACKET_get_net_3(pkt, &cert_len)
1225 || PACKET_remaining(pkt) != cert_len) {
1226 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1231 * The list length may be zero when there is no RPK. In the case of TLS
1232 * 1.2 this is actually the RPK length, which cannot be zero as specified,
1233 * but that breaks the ability of the client to decline client auth. We
1234 * overload the 0 RPK length to mean "no RPK". This interpretation is
1235 * also used some other (reference?) implementations, but is not supported
1236 * by the verbatim RFC7250 text.
1241 if (SSL_CONNECTION_IS_TLS13(sc)) {
1243 * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
1244 * by a possibly empty extension block.
1246 if (!PACKET_get_net_3(pkt, &spki_len)) {
1247 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1250 if (spki_len == 0) {
1252 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
1256 spki_len = cert_len;
1259 if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
1260 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1264 if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
1265 || spki != (spkistart + spki_len)) {
1266 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1269 if (EVP_PKEY_missing_parameters(pkey)) {
1270 SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
1271 SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1275 /* Process the Extensions block */
1276 if (SSL_CONNECTION_IS_TLS13(sc)) {
1277 if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
1278 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1281 if (!PACKET_as_length_prefixed_2(pkt, &extensions)
1282 || PACKET_remaining(pkt) != 0) {
1283 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1286 if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1287 &rawexts, NULL, 1)) {
1288 /* SSLfatal already called */
1291 /* chain index is always zero and fin always 1 for RPK */
1292 if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1293 rawexts, NULL, 0, 1)) {
1294 /* SSLfatal already called */
1299 if (peer_rpk != NULL) {
1305 OPENSSL_free(rawexts);
1306 EVP_PKEY_free(pkey);
1310 unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
1313 unsigned char *pdata = NULL;
1314 X509_PUBKEY *xpk = NULL;
1315 unsigned long ret = 0;
1318 if (cpk != NULL && cpk->x509 != NULL) {
1320 /* Get the RPK from the certificate */
1321 xpk = X509_get_X509_PUBKEY(cpk->x509);
1323 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1326 pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
1327 } else if (cpk != NULL && cpk->privatekey != NULL) {
1328 /* Get the RPK from the private key */
1329 pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
1331 /* The server RPK is not optional */
1333 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1336 /* The client can send a zero length certificate list */
1337 if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1338 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1344 if (pdata_len <= 0) {
1345 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1350 * TLSv1.2 is _just_ the raw public key
1351 * TLSv1.3 includes extensions, so there's a length wrapper
1353 if (SSL_CONNECTION_IS_TLS13(sc)) {
1354 if (!WPACKET_start_sub_packet_u24(pkt)) {
1355 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1360 if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1361 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1365 if (SSL_CONNECTION_IS_TLS13(sc)) {
1367 * Only send extensions relevant to raw public keys. Until such
1368 * extensions are defined, this will be an empty set of extensions.
1369 * |x509| may be NULL, which raw public-key extensions need to handle.
1371 if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1373 /* SSLfatal() already called */
1376 if (!WPACKET_close(pkt)) {
1377 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1384 OPENSSL_free(pdata);
1388 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1389 CERT_PKEY *cpk, int for_comp)
1391 if (!WPACKET_start_sub_packet_u24(pkt)) {
1393 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1397 if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1400 if (!WPACKET_close(pkt)) {
1402 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1410 * Tidy up after the end of a handshake. In the case of SCTP this may result
1411 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1414 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1415 int clearbufs, int stop)
1417 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1418 int cleanuphand = s->statem.cleanuphand;
1419 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1420 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1423 if (!SSL_CONNECTION_IS_DTLS(s)
1424 #ifndef OPENSSL_NO_SCTP
1426 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1427 * messages that require it. Therefore, DTLS procedures for retransmissions
1429 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1431 || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1435 * We don't do this in DTLS over UDP because we may still need the init_buf
1436 * in case there are any unexpected retransmits
1438 BUF_MEM_free(s->init_buf);
1442 if (!ssl_free_wbio_buffer(s)) {
1443 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1449 if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1450 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1451 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1454 * Only set if there was a Finished message and this isn't after a TLSv1.3
1455 * post handshake exchange
1458 /* skipped if we just sent a HelloRequest */
1461 s->statem.cleanuphand = 0;
1462 s->ext.ticket_expected = 0;
1464 ssl3_cleanup_key_block(s);
1468 * In TLSv1.3 we update the cache as part of constructing the
1471 if (!SSL_CONNECTION_IS_TLS13(s))
1472 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1474 /* N.B. s->ctx may not equal s->session_ctx */
1475 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1476 s->handshake_func = ossl_statem_accept;
1478 if (SSL_CONNECTION_IS_TLS13(s)) {
1480 * We encourage applications to only use TLSv1.3 tickets once,
1481 * so we remove this one from the cache.
1483 if ((s->session_ctx->session_cache_mode
1484 & SSL_SESS_CACHE_CLIENT) != 0)
1485 SSL_CTX_remove_session(s->session_ctx, s->session);
1488 * In TLSv1.3 we update the cache as part of processing the
1491 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1494 ssl_tsan_counter(s->session_ctx,
1495 &s->session_ctx->stats.sess_hit);
1497 s->handshake_func = ossl_statem_connect;
1498 ssl_tsan_counter(s->session_ctx,
1499 &s->session_ctx->stats.sess_connect_good);
1502 if (SSL_CONNECTION_IS_DTLS(s)) {
1503 /* done with handshaking */
1504 s->d1->handshake_read_seq = 0;
1505 s->d1->handshake_write_seq = 0;
1506 s->d1->next_handshake_write_seq = 0;
1507 dtls1_clear_received_buffer(s);
1511 if (s->info_callback != NULL)
1512 cb = s->info_callback;
1513 else if (sctx->info_callback != NULL)
1514 cb = sctx->info_callback;
1516 /* The callback may expect us to not be in init at handshake done */
1517 ossl_statem_set_in_init(s, 0);
1521 || !SSL_CONNECTION_IS_TLS13(s)
1522 || SSL_IS_FIRST_HANDSHAKE(s))
1523 cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1527 /* If we've got more work to do we go back into init */
1528 ossl_statem_set_in_init(s, 1);
1529 return WORK_FINISHED_CONTINUE;
1532 return WORK_FINISHED_STOP;
1535 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1537 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1538 int skip_message, i;
1541 size_t l, readbytes;
1542 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1544 p = (unsigned char *)s->init_buf->data;
1547 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1548 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1550 SSL3_HM_HEADER_LENGTH - s->init_num,
1553 s->rwstate = SSL_READING;
1556 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1558 * A ChangeCipherSpec must be a single byte and may not occur
1559 * in the middle of a handshake message.
1561 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1562 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1563 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1566 if (s->statem.hand_state == TLS_ST_BEFORE
1567 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1569 * We are stateless and we received a CCS. Probably this is
1570 * from a client between the first and second ClientHellos.
1571 * We should ignore this, but return an error because we do
1572 * not return success until we see the second ClientHello
1573 * with a valid cookie.
1577 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1578 s->init_num = readbytes - 1;
1579 s->init_msg = s->init_buf->data;
1580 s->s3.tmp.message_size = readbytes;
1582 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1583 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1584 SSL_R_CCS_RECEIVED_EARLY);
1587 s->init_num += readbytes;
1592 if (s->statem.hand_state != TLS_ST_OK
1593 && p[0] == SSL3_MT_HELLO_REQUEST)
1595 * The server may always send 'Hello Request' messages --
1596 * we are doing a handshake anyway now, so ignore them if
1597 * their format is correct. Does not count for 'Finished'
1600 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1604 if (s->msg_callback)
1605 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1606 p, SSL3_HM_HEADER_LENGTH, ssl,
1607 s->msg_callback_arg);
1609 } while (skip_message);
1610 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1613 s->s3.tmp.message_type = *(p++);
1615 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1617 * Only happens with SSLv3+ in an SSLv2 backward compatible
1620 * Total message size is the remaining record bytes to read
1621 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1623 l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1624 s->s3.tmp.message_size = l;
1626 s->init_msg = s->init_buf->data;
1627 s->init_num = SSL3_HM_HEADER_LENGTH;
1630 /* BUF_MEM_grow takes an 'int' parameter */
1631 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1632 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1633 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1636 s->s3.tmp.message_size = l;
1638 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1645 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1647 size_t n, readbytes;
1650 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1652 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1653 /* We've already read everything in */
1654 *len = (unsigned long)s->init_num;
1659 n = s->s3.tmp.message_size - s->init_num;
1661 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1662 &p[s->init_num], n, 0, &readbytes);
1664 s->rwstate = SSL_READING;
1668 s->init_num += readbytes;
1673 * If receiving Finished, record MAC of prior handshake messages for
1674 * Finished verification.
1676 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1677 /* SSLfatal() already called */
1682 /* Feed this message into MAC computation. */
1683 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1684 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1686 /* SSLfatal() already called */
1690 if (s->msg_callback)
1691 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1692 (size_t)s->init_num, ssl, s->msg_callback_arg);
1695 * We defer feeding in the HRR until later. We'll do it as part of
1696 * processing the message
1697 * The TLsv1.3 handshake transcript stops at the ClientFinished
1700 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1701 /* KeyUpdate and NewSessionTicket do not need to be added */
1702 if (!SSL_CONNECTION_IS_TLS13(s)
1703 || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1704 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1705 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1706 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1707 || memcmp(hrrrandom,
1708 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1709 SSL3_RANDOM_SIZE) != 0) {
1710 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1711 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1712 /* SSLfatal() already called */
1718 if (s->msg_callback)
1719 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1720 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1721 s->msg_callback_arg);
1728 static const X509ERR2ALERT x509table[] = {
1729 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1730 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1731 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1732 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1733 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1734 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1735 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1736 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1737 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1738 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1739 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1740 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1741 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1742 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1743 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1744 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1745 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1746 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1747 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1748 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1749 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1750 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1751 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1752 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1753 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1754 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1755 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1756 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1757 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1758 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1759 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1760 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1761 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1762 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1763 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1764 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1765 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1766 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1767 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1768 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1770 /* Last entry; return this if we don't find the value above. */
1771 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1774 int ssl_x509err2alert(int x509err)
1776 const X509ERR2ALERT *tp;
1778 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1779 if (tp->x509err == x509err)
1784 int ssl_allow_compression(SSL_CONNECTION *s)
1786 if (s->options & SSL_OP_NO_COMPRESSION)
1788 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1791 static int version_cmp(const SSL_CONNECTION *s, int a, int b)
1793 int dtls = SSL_CONNECTION_IS_DTLS(s);
1798 return a < b ? -1 : 1;
1799 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1804 const SSL_METHOD *(*cmeth) (void);
1805 const SSL_METHOD *(*smeth) (void);
1808 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1809 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1812 /* Must be in order high to low */
1813 static const version_info tls_version_table[] = {
1814 #ifndef OPENSSL_NO_TLS1_3
1815 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1817 {TLS1_3_VERSION, NULL, NULL},
1819 #ifndef OPENSSL_NO_TLS1_2
1820 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1822 {TLS1_2_VERSION, NULL, NULL},
1824 #ifndef OPENSSL_NO_TLS1_1
1825 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1827 {TLS1_1_VERSION, NULL, NULL},
1829 #ifndef OPENSSL_NO_TLS1
1830 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1832 {TLS1_VERSION, NULL, NULL},
1834 #ifndef OPENSSL_NO_SSL3
1835 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1837 {SSL3_VERSION, NULL, NULL},
1842 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1843 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1846 /* Must be in order high to low */
1847 static const version_info dtls_version_table[] = {
1848 #ifndef OPENSSL_NO_DTLS1_2
1849 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1851 {DTLS1_2_VERSION, NULL, NULL},
1853 #ifndef OPENSSL_NO_DTLS1
1854 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1855 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1857 {DTLS1_VERSION, NULL, NULL},
1858 {DTLS1_BAD_VER, NULL, NULL},
1864 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1866 * @s: The SSL handle for the candidate method
1867 * @method: the intended method.
1869 * Returns 0 on success, or an SSL error reason on failure.
1871 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1873 int version = method->version;
1875 if ((s->min_proto_version != 0 &&
1876 version_cmp(s, version, s->min_proto_version) < 0) ||
1877 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1878 return SSL_R_VERSION_TOO_LOW;
1880 if (s->max_proto_version != 0 &&
1881 version_cmp(s, version, s->max_proto_version) > 0)
1882 return SSL_R_VERSION_TOO_HIGH;
1884 if ((s->options & method->mask) != 0)
1885 return SSL_R_UNSUPPORTED_PROTOCOL;
1886 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1887 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1893 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1894 * certificate type, or has PSK or a certificate callback configured, or has
1895 * a servername callback configure. Otherwise returns 0.
1897 static int is_tls13_capable(const SSL_CONNECTION *s)
1901 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1903 if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1907 * A servername callback can change the available certs, so if a servername
1908 * cb is set then we just assume TLSv1.3 will be ok
1910 if (sctx->ext.servername_cb != NULL
1911 || s->session_ctx->ext.servername_cb != NULL)
1914 #ifndef OPENSSL_NO_PSK
1915 if (s->psk_server_callback != NULL)
1919 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1922 /* All provider-based sig algs are required to support at least TLS1.3 */
1923 for (i = 0; i < s->ssl_pkey_num; i++) {
1924 /* Skip over certs disallowed for TLSv1.3 */
1926 case SSL_PKEY_DSA_SIGN:
1927 case SSL_PKEY_GOST01:
1928 case SSL_PKEY_GOST12_256:
1929 case SSL_PKEY_GOST12_512:
1934 if (!ssl_has_cert(s, i))
1936 if (i != SSL_PKEY_ECC)
1939 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1940 * more restrictive so check that our sig algs are consistent with this
1941 * EC cert. See section 4.2.3 of RFC8446.
1943 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1944 if (tls_check_sigalg_curve(s, curve))
1952 * ssl_version_supported - Check that the specified `version` is supported by
1955 * @s: The SSL handle for the candidate method
1956 * @version: Protocol version to test against
1958 * Returns 1 when supported, otherwise 0
1960 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1961 const SSL_METHOD **meth)
1963 const version_info *vent;
1964 const version_info *table;
1966 switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1968 /* Version should match method version for non-ANY method */
1969 return version_cmp(s, version, s->version) == 0;
1970 case TLS_ANY_VERSION:
1971 table = tls_version_table;
1973 case DTLS_ANY_VERSION:
1974 table = dtls_version_table;
1979 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1981 if (vent->cmeth != NULL
1982 && version_cmp(s, version, vent->version) == 0
1983 && ssl_method_error(s, vent->cmeth()) == 0
1985 || version != TLS1_3_VERSION
1986 || is_tls13_capable(s))) {
1988 *meth = vent->cmeth();
1996 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1997 * fallback indication from a client check whether we're using the highest
1998 * supported protocol version.
2000 * @s server SSL handle.
2002 * Returns 1 when using the highest enabled version, 0 otherwise.
2004 int ssl_check_version_downgrade(SSL_CONNECTION *s)
2006 const version_info *vent;
2007 const version_info *table;
2008 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2011 * Check that the current protocol is the highest enabled version
2012 * (according to ssl->defltmethod, as version negotiation may have changed
2015 if (s->version == ssl->defltmeth->version)
2019 * Apparently we're using a version-flexible SSL_METHOD (not at its
2020 * highest protocol version).
2022 if (ssl->defltmeth->version == TLS_method()->version)
2023 table = tls_version_table;
2024 else if (ssl->defltmeth->version == DTLS_method()->version)
2025 table = dtls_version_table;
2027 /* Unexpected state; fail closed. */
2031 for (vent = table; vent->version != 0; ++vent) {
2032 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
2033 return s->version == vent->version;
2039 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
2040 * protocols, provided the initial (D)TLS method is version-flexible. This
2041 * function sanity-checks the proposed value and makes sure the method is
2042 * version-flexible, then sets the limit if all is well.
2044 * @method_version: The version of the current SSL_METHOD.
2045 * @version: the intended limit.
2046 * @bound: pointer to limit to be updated.
2048 * Returns 1 on success, 0 on failure.
2050 int ssl_set_version_bound(int method_version, int version, int *bound)
2060 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
2062 /* We support client side pre-standardisation version of DTLS */
2063 (version == DTLS1_BAD_VER)
2064 || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
2065 && DTLS_VERSION_GE(version, DTLS1_VERSION));
2067 if (!valid_tls && !valid_dtls)
2071 * Restrict TLS methods to TLS protocol versions.
2072 * Restrict DTLS methods to DTLS protocol versions.
2073 * Note, DTLS version numbers are decreasing, use comparison macros.
2075 * Note that for both lower-bounds we use explicit versions, not
2076 * (D)TLS_MIN_VERSION. This is because we don't want to break user
2077 * configurations. If the MIN (supported) version ever rises, the user's
2078 * "floor" remains valid even if no longer available. We don't expect the
2079 * MAX ceiling to ever get lower, so making that variable makes sense.
2081 * We ignore attempts to set bounds on version-inflexible methods,
2082 * returning success.
2084 switch (method_version) {
2088 case TLS_ANY_VERSION:
2093 case DTLS_ANY_VERSION:
2101 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
2103 if (vers == TLS1_2_VERSION
2104 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
2105 *dgrd = DOWNGRADE_TO_1_2;
2106 } else if (!SSL_CONNECTION_IS_DTLS(s)
2107 && vers < TLS1_2_VERSION
2109 * We need to ensure that a server that disables TLSv1.2
2110 * (creating a hole between TLSv1.3 and TLSv1.1) can still
2111 * complete handshakes with clients that support TLSv1.2 and
2112 * below. Therefore we do not enable the sentinel if TLSv1.3 is
2113 * enabled and TLSv1.2 is not.
2115 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
2116 *dgrd = DOWNGRADE_TO_1_1;
2118 *dgrd = DOWNGRADE_NONE;
2123 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
2124 * client HELLO is received to select the final server protocol version and
2125 * the version specific method.
2127 * @s: server SSL handle.
2129 * Returns 0 on success or an SSL error reason number on failure.
2131 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
2135 * With version-flexible methods we have an initial state with:
2137 * s->method->version == (D)TLS_ANY_VERSION,
2138 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
2140 * So we detect version-flexible methods via the method version, not the
2143 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2144 int server_version = ssl->method->version;
2145 int client_version = hello->legacy_version;
2146 const version_info *vent;
2147 const version_info *table;
2149 RAW_EXTENSION *suppversions;
2151 s->client_version = client_version;
2153 switch (server_version) {
2155 if (!SSL_CONNECTION_IS_TLS13(s)) {
2156 if (version_cmp(s, client_version, s->version) < 0)
2157 return SSL_R_WRONG_SSL_VERSION;
2158 *dgrd = DOWNGRADE_NONE;
2160 * If this SSL handle is not from a version flexible method we don't
2161 * (and never did) check min/max FIPS or Suite B constraints. Hope
2162 * that's OK. It is up to the caller to not choose fixed protocol
2163 * versions they don't want. If not, then easy to fix, just return
2164 * ssl_method_error(s, s->method)
2169 * Fall through if we are TLSv1.3 already (this means we must be after
2170 * a HelloRetryRequest
2173 case TLS_ANY_VERSION:
2174 table = tls_version_table;
2176 case DTLS_ANY_VERSION:
2177 table = dtls_version_table;
2181 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
2183 /* If we did an HRR then supported versions is mandatory */
2184 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
2185 return SSL_R_UNSUPPORTED_PROTOCOL;
2187 if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
2188 unsigned int candidate_vers = 0;
2189 unsigned int best_vers = 0;
2190 const SSL_METHOD *best_method = NULL;
2191 PACKET versionslist;
2193 suppversions->parsed = 1;
2195 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
2196 /* Trailing or invalid data? */
2197 return SSL_R_LENGTH_MISMATCH;
2201 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
2202 * The spec only requires servers to check that it isn't SSLv3:
2203 * "Any endpoint receiving a Hello message with
2204 * ClientHello.legacy_version or ServerHello.legacy_version set to
2205 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
2206 * We are slightly stricter and require that it isn't SSLv3 or lower.
2207 * We tolerate TLSv1 and TLSv1.1.
2209 if (client_version <= SSL3_VERSION)
2210 return SSL_R_BAD_LEGACY_VERSION;
2212 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
2213 if (version_cmp(s, candidate_vers, best_vers) <= 0)
2215 if (ssl_version_supported(s, candidate_vers, &best_method))
2216 best_vers = candidate_vers;
2218 if (PACKET_remaining(&versionslist) != 0) {
2219 /* Trailing data? */
2220 return SSL_R_LENGTH_MISMATCH;
2223 if (best_vers > 0) {
2224 if (s->hello_retry_request != SSL_HRR_NONE) {
2226 * This is after a HelloRetryRequest so we better check that we
2227 * negotiated TLSv1.3
2229 if (best_vers != TLS1_3_VERSION)
2230 return SSL_R_UNSUPPORTED_PROTOCOL;
2233 check_for_downgrade(s, best_vers, dgrd);
2234 s->version = best_vers;
2235 ssl->method = best_method;
2236 if (!ssl_set_record_protocol_version(s, best_vers))
2237 return ERR_R_INTERNAL_ERROR;
2241 return SSL_R_UNSUPPORTED_PROTOCOL;
2245 * If the supported versions extension isn't present, then the highest
2246 * version we can negotiate is TLSv1.2
2248 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
2249 client_version = TLS1_2_VERSION;
2252 * No supported versions extension, so we just use the version supplied in
2255 for (vent = table; vent->version != 0; ++vent) {
2256 const SSL_METHOD *method;
2258 if (vent->smeth == NULL ||
2259 version_cmp(s, client_version, vent->version) < 0)
2261 method = vent->smeth();
2262 if (ssl_method_error(s, method) == 0) {
2263 check_for_downgrade(s, vent->version, dgrd);
2264 s->version = vent->version;
2265 ssl->method = method;
2266 if (!ssl_set_record_protocol_version(s, s->version))
2267 return ERR_R_INTERNAL_ERROR;
2273 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
2277 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
2278 * server HELLO is received to select the final client protocol version and
2279 * the version specific method.
2281 * @s: client SSL handle.
2282 * @version: The proposed version from the server's HELLO.
2283 * @extensions: The extensions received
2285 * Returns 1 on success or 0 on error.
2287 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
2288 RAW_EXTENSION *extensions)
2290 const version_info *vent;
2291 const version_info *table;
2292 int ret, ver_min, ver_max, real_max, origv;
2293 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2296 s->version = version;
2298 /* This will overwrite s->version if the extension is present */
2299 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2300 SSL_EXT_TLS1_2_SERVER_HELLO
2301 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
2307 if (s->hello_retry_request != SSL_HRR_NONE
2308 && s->version != TLS1_3_VERSION) {
2310 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2314 switch (ssl->method->version) {
2316 if (s->version != ssl->method->version) {
2318 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2322 * If this SSL handle is not from a version flexible method we don't
2323 * (and never did) check min/max, FIPS or Suite B constraints. Hope
2324 * that's OK. It is up to the caller to not choose fixed protocol
2325 * versions they don't want. If not, then easy to fix, just return
2326 * ssl_method_error(s, s->method)
2328 if (!ssl_set_record_protocol_version(s, s->version)) {
2329 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2333 case TLS_ANY_VERSION:
2334 table = tls_version_table;
2336 case DTLS_ANY_VERSION:
2337 table = dtls_version_table;
2341 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2344 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2347 if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2348 : s->version < ver_min) {
2350 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2352 } else if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2353 : s->version > ver_max) {
2355 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2359 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2362 /* Check for downgrades */
2363 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2364 if (memcmp(tls12downgrade,
2365 s->s3.server_random + SSL3_RANDOM_SIZE
2366 - sizeof(tls12downgrade),
2367 sizeof(tls12downgrade)) == 0) {
2369 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2370 SSL_R_INAPPROPRIATE_FALLBACK);
2373 } else if (!SSL_CONNECTION_IS_DTLS(s)
2374 && s->version < TLS1_2_VERSION
2375 && real_max > s->version) {
2376 if (memcmp(tls11downgrade,
2377 s->s3.server_random + SSL3_RANDOM_SIZE
2378 - sizeof(tls11downgrade),
2379 sizeof(tls11downgrade)) == 0) {
2381 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2382 SSL_R_INAPPROPRIATE_FALLBACK);
2387 for (vent = table; vent->version != 0; ++vent) {
2388 if (vent->cmeth == NULL || s->version != vent->version)
2391 ssl->method = vent->cmeth();
2392 if (!ssl_set_record_protocol_version(s, s->version)) {
2393 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2400 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2405 * ssl_get_min_max_version - get minimum and maximum protocol version
2406 * @s: The SSL connection
2407 * @min_version: The minimum supported version
2408 * @max_version: The maximum supported version
2409 * @real_max: The highest version below the lowest compile time version hole
2410 * where that hole lies above at least one run-time enabled
2413 * Work out what version we should be using for the initial ClientHello if the
2414 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2415 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2416 * constraints and any floor imposed by the security level here,
2417 * so we don't advertise the wrong protocol version to only reject the outcome later.
2419 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2420 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2421 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2423 * Returns 0 on success or an SSL error reason number on failure. On failure
2424 * min_version and max_version will also be set to 0.
2426 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2427 int *max_version, int *real_max)
2429 int version, tmp_real_max;
2431 const SSL_METHOD *method;
2432 const version_info *table;
2433 const version_info *vent;
2434 const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2436 switch (ssl->method->version) {
2439 * If this SSL handle is not from a version flexible method we don't
2440 * (and never did) check min/max FIPS or Suite B constraints. Hope
2441 * that's OK. It is up to the caller to not choose fixed protocol
2442 * versions they don't want. If not, then easy to fix, just return
2443 * ssl_method_error(s, s->method)
2445 *min_version = *max_version = s->version;
2447 * Providing a real_max only makes sense where we're using a version
2450 if (!ossl_assert(real_max == NULL))
2451 return ERR_R_INTERNAL_ERROR;
2453 case TLS_ANY_VERSION:
2454 table = tls_version_table;
2456 case DTLS_ANY_VERSION:
2457 table = dtls_version_table;
2462 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2463 * below X enabled. This is required in order to maintain the "version
2464 * capability" vector contiguous. Any versions with a NULL client method
2465 * (protocol version client is disabled at compile-time) is also a "hole".
2467 * Our initial state is hole == 1, version == 0. That is, versions above
2468 * the first version in the method table are disabled (a "hole" above
2469 * the valid protocol entries) and we don't have a selected version yet.
2471 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2472 * the selected version. We're no longer in a hole, so "hole" becomes 0.
2474 * If "hole == 0" and we hit an enabled method, we support a contiguous
2475 * range of at least two methods. If we hit a disabled method,
2476 * then hole becomes true again, but nothing else changes yet,
2477 * because all the remaining methods may be disabled too.
2478 * If we again hit an enabled method after the new hole, it becomes
2479 * selected, as we start from scratch.
2481 *min_version = version = 0;
2483 if (real_max != NULL)
2486 for (vent = table; vent->version != 0; ++vent) {
2488 * A table entry with a NULL client method is still a hole in the
2489 * "version capability" vector.
2491 if (vent->cmeth == NULL) {
2496 method = vent->cmeth();
2498 if (hole == 1 && tmp_real_max == 0)
2499 tmp_real_max = vent->version;
2501 if (ssl_method_error(s, method) != 0) {
2504 *min_version = method->version;
2506 if (real_max != NULL && tmp_real_max != 0)
2507 *real_max = tmp_real_max;
2508 version = method->version;
2509 *min_version = version;
2514 *max_version = version;
2516 /* Fail if everything is disabled */
2518 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2524 * ssl_set_client_hello_version - Work out what version we should be using for
2525 * the initial ClientHello.legacy_version field.
2527 * @s: client SSL handle.
2529 * Returns 0 on success or an SSL error reason number on failure.
2531 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2533 int ver_min, ver_max, ret;
2536 * In a renegotiation we always send the same client_version that we sent
2537 * last time, regardless of which version we eventually negotiated.
2539 if (!SSL_IS_FIRST_HANDSHAKE(s))
2542 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2547 s->version = ver_max;
2549 if (SSL_CONNECTION_IS_DTLS(s)) {
2550 if (ver_max == DTLS1_BAD_VER) {
2552 * Even though this is technically before version negotiation,
2553 * because we have asked for DTLS1_BAD_VER we will never negotiate
2554 * anything else, and this has impacts on the record layer for when
2555 * we read the ServerHello. So we need to tell the record layer
2556 * about this immediately.
2558 if (!ssl_set_record_protocol_version(s, ver_max))
2561 } else if (ver_max > TLS1_2_VERSION) {
2562 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2563 ver_max = TLS1_2_VERSION;
2566 s->client_version = ver_max;
2571 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2572 * and |checkallow| is 1 then additionally check if the group is allowed to be
2573 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2574 * 1) or 0 otherwise.
2576 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2577 size_t num_groups, int checkallow)
2581 if (groups == NULL || num_groups == 0)
2584 for (i = 0; i < num_groups; i++) {
2585 uint16_t group = groups[i];
2587 if (group_id == group
2589 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2597 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2598 int create_synthetic_message_hash(SSL_CONNECTION *s,
2599 const unsigned char *hashval,
2600 size_t hashlen, const unsigned char *hrr,
2603 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2604 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2606 memset(msghdr, 0, sizeof(msghdr));
2608 if (hashval == NULL) {
2609 hashval = hashvaltmp;
2611 /* Get the hash of the initial ClientHello */
2612 if (!ssl3_digest_cached_records(s, 0)
2613 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2615 /* SSLfatal() already called */
2620 /* Reinitialise the transcript hash */
2621 if (!ssl3_init_finished_mac(s)) {
2622 /* SSLfatal() already called */
2626 /* Inject the synthetic message_hash message */
2627 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2628 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2629 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2630 || !ssl3_finish_mac(s, hashval, hashlen)) {
2631 /* SSLfatal() already called */
2636 * Now re-inject the HRR and current message if appropriate (we just deleted
2637 * it when we reinitialised the transcript hash above). Only necessary after
2638 * receiving a ClientHello2 with a cookie.
2641 && (!ssl3_finish_mac(s, hrr, hrrlen)
2642 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2643 s->s3.tmp.message_size
2644 + SSL3_HM_HEADER_LENGTH))) {
2645 /* SSLfatal() already called */
2652 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2654 return X509_NAME_cmp(*a, *b);
2657 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2659 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2660 X509_NAME *xn = NULL;
2663 if (ca_sk == NULL) {
2664 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2667 /* get the CA RDNs */
2668 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2669 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2673 while (PACKET_remaining(&cadns)) {
2674 const unsigned char *namestart, *namebytes;
2675 unsigned int name_len;
2677 if (!PACKET_get_net_2(&cadns, &name_len)
2678 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2679 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2683 namestart = namebytes;
2684 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2685 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2688 if (namebytes != (namestart + name_len)) {
2689 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2693 if (!sk_X509_NAME_push(ca_sk, xn)) {
2694 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2700 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2701 s->s3.tmp.peer_ca_names = ca_sk;
2706 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2711 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2713 const STACK_OF(X509_NAME) *ca_sk = NULL;
2714 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2717 ca_sk = SSL_get_client_CA_list(ssl);
2718 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2723 ca_sk = SSL_get0_CA_list(ssl);
2728 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2731 /* Start sub-packet for client CA list */
2732 if (!WPACKET_start_sub_packet_u16(pkt)) {
2733 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2737 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2740 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2741 unsigned char *namebytes;
2742 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2746 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2747 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2749 || i2d_X509_NAME(name, &namebytes) != namelen) {
2750 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2756 if (!WPACKET_close(pkt)) {
2757 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2764 /* Create a buffer containing data to be signed for server key exchange */
2765 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2766 const void *param, size_t paramlen)
2768 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2769 unsigned char *tbs = OPENSSL_malloc(tbslen);
2772 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2775 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2776 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2778 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2785 * Saves the current handshake digest for Post-Handshake Auth,
2786 * Done after ClientFinished is processed, done exactly once
2788 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2790 if (s->pha_dgst == NULL) {
2791 if (!ssl3_digest_cached_records(s, 1))
2792 /* SSLfatal() already called */
2795 s->pha_dgst = EVP_MD_CTX_new();
2796 if (s->pha_dgst == NULL) {
2797 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2800 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2801 s->s3.handshake_dgst)) {
2802 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2803 EVP_MD_CTX_free(s->pha_dgst);
2812 * Restores the Post-Handshake Auth handshake digest
2813 * Done just before sending/processing the Cert Request
2815 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2817 if (s->pha_dgst == NULL) {
2818 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2821 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2823 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2829 #ifndef OPENSSL_NO_COMP_ALG
2830 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2835 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2837 COMP_METHOD *method = NULL;
2838 COMP_CTX *comp = NULL;
2839 size_t expected_length;
2845 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2848 if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2849 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2852 /* If we have a prefs list, make sure the algorithm is in it */
2853 if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2854 for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2855 if (sc->cert_comp_prefs[i] == comp_alg) {
2861 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2865 if (!ossl_comp_has_alg(comp_alg)) {
2866 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2870 case TLSEXT_comp_cert_zlib:
2871 method = COMP_zlib_oneshot();
2873 case TLSEXT_comp_cert_brotli:
2874 method = COMP_brotli_oneshot();
2876 case TLSEXT_comp_cert_zstd:
2877 method = COMP_zstd_oneshot();
2880 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2884 if ((comp = COMP_CTX_new(method)) == NULL
2885 || !PACKET_get_net_3_len(pkt, &expected_length)
2886 || !PACKET_get_net_3_len(pkt, &comp_length)
2887 || PACKET_remaining(pkt) != comp_length
2888 || !BUF_MEM_grow(buf, expected_length)
2889 || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2890 || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2891 (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2892 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2895 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2897 COMP_CTX_free(comp);