2 * Copyright 1995-2024 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 negotiated_minversion;
160 int md5sha1_needed_maxversion = SSL_CONNECTION_IS_DTLS(s)
161 ? DTLS1_VERSION : TLS1_1_VERSION;
163 /* We don't have MD5-SHA1 - do we need it? */
164 if (ssl_version_cmp(s, ver_max, md5sha1_needed_maxversion) <= 0) {
165 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
166 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
167 "The max supported SSL/TLS version needs the"
168 " MD5-SHA1 digest but it is not available"
169 " in the loaded providers. Use (D)TLSv1.2 or"
170 " above, or load different providers");
176 /* Don't allow TLSv1.1 or below to be negotiated */
177 negotiated_minversion = SSL_CONNECTION_IS_DTLS(s) ?
178 DTLS1_2_VERSION : TLS1_2_VERSION;
179 if (ssl_version_cmp(s, ver_min, negotiated_minversion) < 0)
180 ok = SSL_set_min_proto_version(ssl, negotiated_minversion);
182 /* Shouldn't happen */
183 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
190 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
194 * Sanity check that the maximum version we accept has ciphers
195 * enabled. For clients we do this check during construction of the
198 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
199 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
200 int cipher_minprotover = SSL_CONNECTION_IS_DTLS(s)
201 ? c->min_dtls : c->min_tls;
202 int cipher_maxprotover = SSL_CONNECTION_IS_DTLS(s)
203 ? c->max_dtls : c->max_tls;
205 if (ssl_version_cmp(s, ver_max, cipher_minprotover) >= 0
206 && ssl_version_cmp(s, ver_max, cipher_maxprotover) <= 0) {
212 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
213 SSL_R_NO_CIPHERS_AVAILABLE,
214 "No ciphers enabled for max supported "
218 if (SSL_IS_FIRST_HANDSHAKE(s)) {
219 /* N.B. s->session_ctx == s->ctx here */
220 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
222 /* N.B. s->ctx may not equal s->session_ctx */
223 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
225 s->s3.tmp.cert_request = 0;
228 if (SSL_IS_FIRST_HANDSHAKE(s))
229 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
231 ssl_tsan_counter(s->session_ctx,
232 &s->session_ctx->stats.sess_connect_renegotiate);
234 /* mark client_random uninitialized */
235 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
238 s->s3.tmp.cert_req = 0;
240 if (SSL_CONNECTION_IS_DTLS(s))
241 s->statem.use_timer = 1;
248 * Size of the to-be-signed TLS13 data, without the hash size itself:
249 * 64 bytes of value 32, 33 context bytes, 1 byte separator
251 #define TLS13_TBS_START_SIZE 64
252 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
254 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
255 void **hdata, size_t *hdatalen)
257 /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
258 static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
259 "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
260 /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
261 static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
262 "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
264 if (SSL_CONNECTION_IS_TLS13(s)) {
267 /* Set the first 64 bytes of to-be-signed data to octet 32 */
268 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
269 /* This copies the 33 bytes of context plus the 0 separator byte */
270 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
271 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
272 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
274 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
277 * If we're currently reading then we need to use the saved handshake
278 * hash value. We can't use the current handshake hash state because
279 * that includes the CertVerify itself.
281 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
282 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
283 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
284 s->cert_verify_hash_len);
285 hashlen = s->cert_verify_hash_len;
286 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
287 EVP_MAX_MD_SIZE, &hashlen)) {
288 /* SSLfatal() already called */
293 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
298 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
300 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
309 CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
311 EVP_PKEY *pkey = NULL;
312 const EVP_MD *md = NULL;
313 EVP_MD_CTX *mctx = NULL;
314 EVP_PKEY_CTX *pctx = NULL;
315 size_t hdatalen = 0, siglen = 0;
317 unsigned char *sig = NULL;
318 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
319 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
320 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
322 if (lu == NULL || s->s3.tmp.cert == NULL) {
323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
326 pkey = s->s3.tmp.cert->privatekey;
328 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
329 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
333 mctx = EVP_MD_CTX_new();
335 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
339 /* Get the data to be signed */
340 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
341 /* SSLfatal() already called */
345 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
346 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
350 if (EVP_DigestSignInit_ex(mctx, &pctx,
351 md == NULL ? NULL : EVP_MD_get0_name(md),
352 sctx->libctx, sctx->propq, pkey,
354 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
358 if (lu->sig == EVP_PKEY_RSA_PSS) {
359 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
360 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
361 RSA_PSS_SALTLEN_DIGEST) <= 0) {
362 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
366 if (s->version == SSL3_VERSION) {
368 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
369 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
371 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
372 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
373 (int)s->session->master_key_length,
374 s->session->master_key) <= 0
375 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
377 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
380 sig = OPENSSL_malloc(siglen);
382 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
383 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
388 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
389 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
391 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
392 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
395 sig = OPENSSL_malloc(siglen);
397 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
398 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
403 #ifndef OPENSSL_NO_GOST
405 int pktype = lu->sig;
407 if (pktype == NID_id_GostR3410_2001
408 || pktype == NID_id_GostR3410_2012_256
409 || pktype == NID_id_GostR3410_2012_512)
410 BUF_reverse(sig, NULL, siglen);
414 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
415 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
419 /* Digest cached records and discard handshake buffer */
420 if (!ssl3_digest_cached_records(s, 0)) {
421 /* SSLfatal() already called */
426 EVP_MD_CTX_free(mctx);
427 return CON_FUNC_SUCCESS;
430 EVP_MD_CTX_free(mctx);
431 return CON_FUNC_ERROR;
434 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
436 EVP_PKEY *pkey = NULL;
437 const unsigned char *data;
438 #ifndef OPENSSL_NO_GOST
439 unsigned char *gost_data = NULL;
441 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
444 const EVP_MD *md = NULL;
447 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
448 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
449 EVP_PKEY_CTX *pctx = NULL;
450 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
453 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
457 pkey = tls_get_peer_pkey(s);
459 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
463 if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
464 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
465 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
469 if (SSL_USE_SIGALGS(s)) {
472 if (!PACKET_get_net_2(pkt, &sigalg)) {
473 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
476 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
477 /* SSLfatal() already called */
480 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
481 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
482 SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
486 if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
487 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
491 if (SSL_USE_SIGALGS(s))
492 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
493 md == NULL ? "n/a" : EVP_MD_get0_name(md));
495 /* Check for broken implementations of GOST ciphersuites */
497 * If key is GOST and len is exactly 64 or 128, it is signature without
498 * length field (CryptoPro implementations at least till TLS 1.2)
500 #ifndef OPENSSL_NO_GOST
501 if (!SSL_USE_SIGALGS(s)
502 && ((PACKET_remaining(pkt) == 64
503 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
504 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
505 || (PACKET_remaining(pkt) == 128
506 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
507 len = PACKET_remaining(pkt);
510 if (!PACKET_get_net_2(pkt, &len)) {
511 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
515 if (!PACKET_get_bytes(pkt, &data, len)) {
516 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
520 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
521 /* SSLfatal() already called */
525 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
526 md == NULL ? "n/a" : EVP_MD_get0_name(md));
528 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
529 md == NULL ? NULL : EVP_MD_get0_name(md),
530 sctx->libctx, sctx->propq, pkey,
532 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
535 #ifndef OPENSSL_NO_GOST
537 int pktype = EVP_PKEY_get_id(pkey);
538 if (pktype == NID_id_GostR3410_2001
539 || pktype == NID_id_GostR3410_2012_256
540 || pktype == NID_id_GostR3410_2012_512) {
541 if ((gost_data = OPENSSL_malloc(len)) == NULL)
543 BUF_reverse(gost_data, data, len);
549 if (SSL_USE_PSS(s)) {
550 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
551 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
552 RSA_PSS_SALTLEN_DIGEST) <= 0) {
553 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
557 if (s->version == SSL3_VERSION) {
558 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
559 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
560 (int)s->session->master_key_length,
561 s->session->master_key) <= 0) {
562 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
565 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
566 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
570 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
571 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
572 /* Ignore bad signatures when fuzzing */
573 if (SSL_IS_QUIC_HANDSHAKE(s))
577 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
583 * In TLSv1.3 on the client side we make sure we prepare the client
584 * certificate after the CertVerify instead of when we get the
585 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
586 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
587 * want to make sure that SSL_get1_peer_certificate() will return the actual
588 * server certificate from the client_cert_cb callback.
590 if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
591 ret = MSG_PROCESS_CONTINUE_PROCESSING;
593 ret = MSG_PROCESS_CONTINUE_READING;
595 BIO_free(s->s3.handshake_buffer);
596 s->s3.handshake_buffer = NULL;
597 EVP_MD_CTX_free(mctx);
598 #ifndef OPENSSL_NO_GOST
599 OPENSSL_free(gost_data);
604 CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
606 size_t finish_md_len;
609 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
611 /* This is a real handshake so make sure we clean it up at the end */
612 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
613 s->statem.cleanuphand = 1;
616 * If we attempted to write early data or we're in middlebox compat mode
617 * then we deferred changing the handshake write keys to the last possible
618 * moment. If we didn't already do this when we sent the client certificate
619 * then we need to do it now.
621 if (SSL_CONNECTION_IS_TLS13(s)
623 && (s->early_data_state != SSL_EARLY_DATA_NONE
624 || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
625 && s->s3.tmp.cert_req == 0
626 && (!ssl->method->ssl3_enc->change_cipher_state(s,
627 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
628 /* SSLfatal() already called */
629 return CON_FUNC_ERROR;
633 sender = ssl->method->ssl3_enc->server_finished_label;
634 slen = ssl->method->ssl3_enc->server_finished_label_len;
636 sender = ssl->method->ssl3_enc->client_finished_label;
637 slen = ssl->method->ssl3_enc->client_finished_label_len;
640 finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
642 s->s3.tmp.finish_md);
643 if (finish_md_len == 0) {
644 /* SSLfatal() already called */
645 return CON_FUNC_ERROR;
648 s->s3.tmp.finish_md_len = finish_md_len;
650 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
651 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
652 return CON_FUNC_ERROR;
656 * Log the master secret, if logging is enabled. We don't log it for
657 * TLSv1.3: there's a different key schedule for that.
659 if (!SSL_CONNECTION_IS_TLS13(s)
660 && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
661 s->session->master_key_length)) {
662 /* SSLfatal() already called */
663 return CON_FUNC_ERROR;
667 * Copy the finished so we can use it for renegotiation checks
669 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
670 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
671 return CON_FUNC_ERROR;
674 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
676 s->s3.previous_client_finished_len = finish_md_len;
678 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
680 s->s3.previous_server_finished_len = finish_md_len;
683 return CON_FUNC_SUCCESS;
686 CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
688 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
689 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
690 return CON_FUNC_ERROR;
693 s->key_update = SSL_KEY_UPDATE_NONE;
694 return CON_FUNC_SUCCESS;
697 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
699 unsigned int updatetype;
702 * A KeyUpdate message signals a key change so the end of the message must
703 * be on a record boundary.
705 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
706 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
707 return MSG_PROCESS_ERROR;
710 if (!PACKET_get_1(pkt, &updatetype)
711 || PACKET_remaining(pkt) != 0) {
712 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
713 return MSG_PROCESS_ERROR;
717 * There are only two defined key update types. Fail if we get a value we
720 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
721 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
722 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
723 return MSG_PROCESS_ERROR;
727 * If we get a request for us to update our sending keys too then, we need
728 * to additionally send a KeyUpdate message. However that message should
729 * not also request an update (otherwise we get into an infinite loop).
731 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
732 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
734 if (!tls13_update_key(s, 0)) {
735 /* SSLfatal() already called */
736 return MSG_PROCESS_ERROR;
739 return MSG_PROCESS_FINISHED_READING;
743 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
746 int ssl3_take_mac(SSL_CONNECTION *s)
750 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
753 sender = ssl->method->ssl3_enc->server_finished_label;
754 slen = ssl->method->ssl3_enc->server_finished_label_len;
756 sender = ssl->method->ssl3_enc->client_finished_label;
757 slen = ssl->method->ssl3_enc->client_finished_label_len;
760 s->s3.tmp.peer_finish_md_len =
761 ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
762 s->s3.tmp.peer_finish_md);
764 if (s->s3.tmp.peer_finish_md_len == 0) {
765 /* SSLfatal() already called */
772 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
777 remain = PACKET_remaining(pkt);
779 * 'Change Cipher Spec' is just a single byte, which should already have
780 * been consumed by ssl_get_message() so there should be no bytes left,
781 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
783 if (SSL_CONNECTION_IS_DTLS(s)) {
784 if ((s->version == DTLS1_BAD_VER
785 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
786 || (s->version != DTLS1_BAD_VER
787 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
788 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
789 return MSG_PROCESS_ERROR;
793 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
794 return MSG_PROCESS_ERROR;
798 /* Check we have a cipher to change to */
799 if (s->s3.tmp.new_cipher == NULL) {
800 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
801 return MSG_PROCESS_ERROR;
804 s->s3.change_cipher_spec = 1;
805 if (!ssl3_do_change_cipher_spec(s)) {
806 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
807 return MSG_PROCESS_ERROR;
810 if (SSL_CONNECTION_IS_DTLS(s)) {
811 if (s->version == DTLS1_BAD_VER)
812 s->d1->handshake_read_seq++;
814 #ifndef OPENSSL_NO_SCTP
816 * Remember that a CCS has been received, so that an old key of
817 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
820 BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
821 BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
825 return MSG_PROCESS_CONTINUE_READING;
828 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
831 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
832 int was_first = SSL_IS_FIRST_HANDSHAKE(s);
836 /* This is a real handshake so make sure we clean it up at the end */
839 * To get this far we must have read encrypted data from the client. We
840 * no longer tolerate unencrypted alerts. This is ignored if less than
843 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
844 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
845 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
846 s->statem.cleanuphand = 1;
847 if (SSL_CONNECTION_IS_TLS13(s)
848 && !tls13_save_handshake_digest_for_pha(s)) {
849 /* SSLfatal() already called */
850 return MSG_PROCESS_ERROR;
855 * In TLSv1.3 a Finished message signals a key change so the end of the
856 * message must be on a record boundary.
858 if (SSL_CONNECTION_IS_TLS13(s)
859 && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
860 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
861 return MSG_PROCESS_ERROR;
864 /* If this occurs, we have missed a message */
865 if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
866 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
867 return MSG_PROCESS_ERROR;
869 s->s3.change_cipher_spec = 0;
871 md_len = s->s3.tmp.peer_finish_md_len;
873 if (md_len != PACKET_remaining(pkt)) {
874 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
875 return MSG_PROCESS_ERROR;
878 ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
880 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
882 if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
888 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
889 return MSG_PROCESS_ERROR;
893 * Copy the finished so we can use it for renegotiation checks
895 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
896 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
897 return MSG_PROCESS_ERROR;
900 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
902 s->s3.previous_client_finished_len = md_len;
904 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
906 s->s3.previous_server_finished_len = md_len;
910 * In TLS1.3 we also have to change cipher state and do any final processing
911 * of the initial server flight (if we are a client)
913 if (SSL_CONNECTION_IS_TLS13(s)) {
915 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
916 !ssl->method->ssl3_enc->change_cipher_state(s,
917 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
918 /* SSLfatal() already called */
919 return MSG_PROCESS_ERROR;
922 /* TLS 1.3 gets the secret size from the handshake md */
924 if (!ssl->method->ssl3_enc->generate_master_secret(s,
925 s->master_secret, s->handshake_secret, 0,
927 /* SSLfatal() already called */
928 return MSG_PROCESS_ERROR;
930 if (!ssl->method->ssl3_enc->change_cipher_state(s,
931 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
932 /* SSLfatal() already called */
933 return MSG_PROCESS_ERROR;
935 if (!tls_process_initial_server_flight(s)) {
936 /* SSLfatal() already called */
937 return MSG_PROCESS_ERROR;
943 && !SSL_IS_FIRST_HANDSHAKE(s)
944 && s->rlayer.rrlmethod->set_first_handshake != NULL)
945 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
947 return MSG_PROCESS_FINISHED_READING;
950 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
952 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
953 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
954 return CON_FUNC_ERROR;
957 return CON_FUNC_SUCCESS;
960 /* Add a certificate to the WPACKET */
961 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
962 X509 *x, int chain, int for_comp)
965 unsigned char *outbytes;
966 int context = SSL_EXT_TLS1_3_CERTIFICATE;
969 context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
971 len = i2d_X509(x, NULL);
974 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
977 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
978 || i2d_X509(x, &outbytes) != len) {
980 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
984 if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
985 && !tls_construct_extensions(s, pkt, context, x, chain)) {
986 /* SSLfatal() already called */
993 /* Add certificate chain to provided WPACKET */
994 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
998 STACK_OF(X509) *extra_certs;
999 STACK_OF(X509) *chain = NULL;
1000 X509_STORE *chain_store;
1001 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1003 if (cpk == NULL || cpk->x509 == NULL)
1009 * If we have a certificate specific chain use it, else use parent ctx.
1011 if (cpk->chain != NULL)
1012 extra_certs = cpk->chain;
1014 extra_certs = sctx->extra_certs;
1016 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1018 else if (s->cert->chain_store)
1019 chain_store = s->cert->chain_store;
1021 chain_store = sctx->cert_store;
1023 if (chain_store != NULL) {
1024 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1027 if (xs_ctx == NULL) {
1029 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1032 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1033 X509_STORE_CTX_free(xs_ctx);
1035 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1039 * It is valid for the chain not to be complete (because normally we
1040 * don't include the root cert in the chain). Therefore we deliberately
1041 * ignore the error return from this call. We're not actually verifying
1042 * the cert - we're just building as much of the chain as we can
1044 (void)X509_verify_cert(xs_ctx);
1045 /* Don't leave errors in the queue */
1047 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1048 i = ssl_security_cert_chain(s, chain, NULL, 0);
1051 /* Dummy error calls so mkerr generates them */
1052 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1053 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1054 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1056 X509_STORE_CTX_free(xs_ctx);
1058 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1061 chain_count = sk_X509_num(chain);
1062 for (i = 0; i < chain_count; i++) {
1063 x = sk_X509_value(chain, i);
1065 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1066 /* SSLfatal() already called */
1067 X509_STORE_CTX_free(xs_ctx);
1071 X509_STORE_CTX_free(xs_ctx);
1073 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1076 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1079 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1080 /* SSLfatal() already called */
1083 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1084 x = sk_X509_value(extra_certs, i);
1085 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1086 /* SSLfatal() already called */
1094 EVP_PKEY* tls_get_peer_pkey(const SSL_CONNECTION *sc)
1096 if (sc->session->peer_rpk != NULL)
1097 return sc->session->peer_rpk;
1098 if (sc->session->peer != NULL)
1099 return X509_get0_pubkey(sc->session->peer);
1103 int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
1105 EVP_PKEY *pkey = NULL;
1107 RAW_EXTENSION *rawexts = NULL;
1110 unsigned long cert_len = 0, spki_len = 0;
1111 const unsigned char *spki, *spkistart;
1112 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
1115 * ----------------------------
1116 * TLS 1.3 Certificate message:
1117 * ----------------------------
1118 * https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
1124 * } CertificateType;
1127 * select (certificate_type) {
1128 * case RawPublicKey:
1129 * // From RFC 7250 ASN.1_subjectPublicKeyInfo
1130 * opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
1133 * opaque cert_data<1..2^24-1>;
1135 * Extension extensions<0..2^16-1>;
1136 * } CertificateEntry;
1139 * opaque certificate_request_context<0..2^8-1>;
1140 * CertificateEntry certificate_list<0..2^24-1>;
1143 * The client MUST send a Certificate message if and only if the server
1144 * has requested client authentication via a CertificateRequest message
1145 * (Section 4.3.2). If the server requests client authentication but no
1146 * suitable certificate is available, the client MUST send a Certificate
1147 * message containing no certificates (i.e., with the "certificate_list"
1148 * field having length 0).
1150 * ----------------------------
1151 * TLS 1.2 Certificate message:
1152 * ----------------------------
1153 * https://datatracker.ietf.org/doc/html/rfc7250#section-3
1155 * opaque ASN.1Cert<1..2^24-1>;
1158 * select(certificate_type){
1160 * // certificate type defined in this document.
1161 * case RawPublicKey:
1162 * opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
1164 * // X.509 certificate defined in RFC 5246
1166 * ASN.1Cert certificate_list<0..2^24-1>;
1168 * // Additional certificate type based on
1169 * // "TLS Certificate Types" subregistry
1176 * After the (TLS 1.3 only) context octet string (1 byte length + data) the
1177 * Certificate message has a 3-byte length that is zero in the client to
1178 * server message when the client has no RPK to send. In that case, there
1179 * are no (TLS 1.3 only) per-certificate extensions either, because the
1180 * [CertificateEntry] list is empty.
1182 * In the server to client direction, or when the client had an RPK to send,
1183 * the TLS 1.3 message just prepends the length of the RPK+extensions,
1184 * while TLS <= 1.2 sends just the RPK (octet-string).
1186 * The context must be zero-length in the server to client direction, and
1187 * must match the value recorded in the certificate request in the client
1188 * to server direction.
1190 if (SSL_CONNECTION_IS_TLS13(sc)) {
1191 if (!PACKET_get_length_prefixed_1(pkt, &context)) {
1192 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1196 if (sc->pha_context == NULL) {
1197 if (PACKET_remaining(&context) != 0) {
1198 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1202 if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
1203 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1208 if (PACKET_remaining(&context) != 0) {
1209 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1215 if (!PACKET_get_net_3(pkt, &cert_len)
1216 || PACKET_remaining(pkt) != cert_len) {
1217 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1222 * The list length may be zero when there is no RPK. In the case of TLS
1223 * 1.2 this is actually the RPK length, which cannot be zero as specified,
1224 * but that breaks the ability of the client to decline client auth. We
1225 * overload the 0 RPK length to mean "no RPK". This interpretation is
1226 * also used some other (reference?) implementations, but is not supported
1227 * by the verbatim RFC7250 text.
1232 if (SSL_CONNECTION_IS_TLS13(sc)) {
1234 * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
1235 * by a possibly empty extension block.
1237 if (!PACKET_get_net_3(pkt, &spki_len)) {
1238 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1241 if (spki_len == 0) {
1243 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
1247 spki_len = cert_len;
1250 if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
1251 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1255 if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
1256 || spki != (spkistart + spki_len)) {
1257 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1260 if (EVP_PKEY_missing_parameters(pkey)) {
1261 SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
1262 SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1266 /* Process the Extensions block */
1267 if (SSL_CONNECTION_IS_TLS13(sc)) {
1268 if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
1269 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1272 if (!PACKET_as_length_prefixed_2(pkt, &extensions)
1273 || PACKET_remaining(pkt) != 0) {
1274 SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1277 if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1278 &rawexts, NULL, 1)) {
1279 /* SSLfatal already called */
1282 /* chain index is always zero and fin always 1 for RPK */
1283 if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1284 rawexts, NULL, 0, 1)) {
1285 /* SSLfatal already called */
1290 if (peer_rpk != NULL) {
1296 OPENSSL_free(rawexts);
1297 EVP_PKEY_free(pkey);
1301 unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
1304 unsigned char *pdata = NULL;
1305 X509_PUBKEY *xpk = NULL;
1306 unsigned long ret = 0;
1309 if (cpk != NULL && cpk->x509 != NULL) {
1311 /* Get the RPK from the certificate */
1312 xpk = X509_get_X509_PUBKEY(cpk->x509);
1314 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1317 pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
1318 } else if (cpk != NULL && cpk->privatekey != NULL) {
1319 /* Get the RPK from the private key */
1320 pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
1322 /* The server RPK is not optional */
1324 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1327 /* The client can send a zero length certificate list */
1328 if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1329 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1335 if (pdata_len <= 0) {
1336 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1341 * TLSv1.2 is _just_ the raw public key
1342 * TLSv1.3 includes extensions, so there's a length wrapper
1344 if (SSL_CONNECTION_IS_TLS13(sc)) {
1345 if (!WPACKET_start_sub_packet_u24(pkt)) {
1346 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1351 if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1352 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1356 if (SSL_CONNECTION_IS_TLS13(sc)) {
1358 * Only send extensions relevant to raw public keys. Until such
1359 * extensions are defined, this will be an empty set of extensions.
1360 * |x509| may be NULL, which raw public-key extensions need to handle.
1362 if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1364 /* SSLfatal() already called */
1367 if (!WPACKET_close(pkt)) {
1368 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1375 OPENSSL_free(pdata);
1379 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1380 CERT_PKEY *cpk, int for_comp)
1382 if (!WPACKET_start_sub_packet_u24(pkt)) {
1384 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1388 if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1391 if (!WPACKET_close(pkt)) {
1393 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1401 * Tidy up after the end of a handshake. In the case of SCTP this may result
1402 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1405 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1406 int clearbufs, int stop)
1408 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1409 int cleanuphand = s->statem.cleanuphand;
1410 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1411 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1414 if (!SSL_CONNECTION_IS_DTLS(s)
1415 #ifndef OPENSSL_NO_SCTP
1417 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1418 * messages that require it. Therefore, DTLS procedures for retransmissions
1420 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1422 || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1426 * We don't do this in DTLS over UDP because we may still need the init_buf
1427 * in case there are any unexpected retransmits
1429 BUF_MEM_free(s->init_buf);
1433 if (!ssl_free_wbio_buffer(s)) {
1434 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1440 if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1441 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1442 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1445 * Only set if there was a Finished message and this isn't after a TLSv1.3
1446 * post handshake exchange
1449 /* skipped if we just sent a HelloRequest */
1452 s->statem.cleanuphand = 0;
1453 s->ext.ticket_expected = 0;
1455 ssl3_cleanup_key_block(s);
1459 * In TLSv1.3 we update the cache as part of constructing the
1462 if (!SSL_CONNECTION_IS_TLS13(s))
1463 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1465 /* N.B. s->ctx may not equal s->session_ctx */
1466 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1467 s->handshake_func = ossl_statem_accept;
1469 if (SSL_CONNECTION_IS_TLS13(s)) {
1471 * We encourage applications to only use TLSv1.3 tickets once,
1472 * so we remove this one from the cache.
1474 if ((s->session_ctx->session_cache_mode
1475 & SSL_SESS_CACHE_CLIENT) != 0)
1476 SSL_CTX_remove_session(s->session_ctx, s->session);
1479 * In TLSv1.3 we update the cache as part of processing the
1482 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1485 ssl_tsan_counter(s->session_ctx,
1486 &s->session_ctx->stats.sess_hit);
1488 s->handshake_func = ossl_statem_connect;
1489 ssl_tsan_counter(s->session_ctx,
1490 &s->session_ctx->stats.sess_connect_good);
1493 if (SSL_CONNECTION_IS_DTLS(s)) {
1494 /* done with handshaking */
1495 s->d1->handshake_read_seq = 0;
1496 s->d1->handshake_write_seq = 0;
1497 s->d1->next_handshake_write_seq = 0;
1498 dtls1_clear_received_buffer(s);
1502 if (s->info_callback != NULL)
1503 cb = s->info_callback;
1504 else if (sctx->info_callback != NULL)
1505 cb = sctx->info_callback;
1507 /* The callback may expect us to not be in init at handshake done */
1508 ossl_statem_set_in_init(s, 0);
1512 || !SSL_CONNECTION_IS_TLS13(s)
1513 || SSL_IS_FIRST_HANDSHAKE(s))
1514 cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1518 /* If we've got more work to do we go back into init */
1519 ossl_statem_set_in_init(s, 1);
1520 return WORK_FINISHED_CONTINUE;
1523 return WORK_FINISHED_STOP;
1526 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1528 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1529 int skip_message, i;
1532 size_t l, readbytes;
1533 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1535 p = (unsigned char *)s->init_buf->data;
1538 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1539 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1541 SSL3_HM_HEADER_LENGTH - s->init_num,
1544 s->rwstate = SSL_READING;
1547 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1549 * A ChangeCipherSpec must be a single byte and may not occur
1550 * in the middle of a handshake message.
1552 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1553 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1554 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1557 if (s->statem.hand_state == TLS_ST_BEFORE
1558 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1560 * We are stateless and we received a CCS. Probably this is
1561 * from a client between the first and second ClientHellos.
1562 * We should ignore this, but return an error because we do
1563 * not return success until we see the second ClientHello
1564 * with a valid cookie.
1568 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1569 s->init_num = readbytes - 1;
1570 s->init_msg = s->init_buf->data;
1571 s->s3.tmp.message_size = readbytes;
1573 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1574 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1575 SSL_R_CCS_RECEIVED_EARLY);
1578 s->init_num += readbytes;
1583 if (s->statem.hand_state != TLS_ST_OK
1584 && p[0] == SSL3_MT_HELLO_REQUEST)
1586 * The server may always send 'Hello Request' messages --
1587 * we are doing a handshake anyway now, so ignore them if
1588 * their format is correct. Does not count for 'Finished'
1591 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1595 if (s->msg_callback)
1596 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1597 p, SSL3_HM_HEADER_LENGTH, ssl,
1598 s->msg_callback_arg);
1600 } while (skip_message);
1601 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1604 s->s3.tmp.message_type = *(p++);
1606 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1608 * Only happens with SSLv3+ in an SSLv2 backward compatible
1611 * Total message size is the remaining record bytes to read
1612 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1614 l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1615 s->s3.tmp.message_size = l;
1617 s->init_msg = s->init_buf->data;
1618 s->init_num = SSL3_HM_HEADER_LENGTH;
1621 /* BUF_MEM_grow takes an 'int' parameter */
1622 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1623 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1624 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1627 s->s3.tmp.message_size = l;
1629 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1636 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1638 size_t n, readbytes;
1641 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1643 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1644 /* We've already read everything in */
1645 *len = (unsigned long)s->init_num;
1650 n = s->s3.tmp.message_size - s->init_num;
1652 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1653 &p[s->init_num], n, 0, &readbytes);
1655 s->rwstate = SSL_READING;
1659 s->init_num += readbytes;
1664 * If receiving Finished, record MAC of prior handshake messages for
1665 * Finished verification.
1667 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1668 /* SSLfatal() already called */
1673 /* Feed this message into MAC computation. */
1674 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1675 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1677 /* SSLfatal() already called */
1681 if (s->msg_callback)
1682 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1683 (size_t)s->init_num, ssl, s->msg_callback_arg);
1686 * We defer feeding in the HRR until later. We'll do it as part of
1687 * processing the message
1688 * The TLsv1.3 handshake transcript stops at the ClientFinished
1691 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1692 /* KeyUpdate and NewSessionTicket do not need to be added */
1693 if (!SSL_CONNECTION_IS_TLS13(s)
1694 || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1695 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1696 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1697 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1698 || memcmp(hrrrandom,
1699 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1700 SSL3_RANDOM_SIZE) != 0) {
1701 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1702 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1703 /* SSLfatal() already called */
1709 if (s->msg_callback)
1710 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1711 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1712 s->msg_callback_arg);
1719 static const X509ERR2ALERT x509table[] = {
1720 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1721 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1722 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1723 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1724 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1725 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1726 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1727 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1728 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1729 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1730 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1731 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1732 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1733 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1734 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1735 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1736 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1737 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1738 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1739 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1740 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1741 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1742 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1743 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1744 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1745 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1746 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1747 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1748 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1749 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1750 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1751 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1752 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1753 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1754 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1755 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1756 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1757 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1758 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1759 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1761 /* Last entry; return this if we don't find the value above. */
1762 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1765 int ssl_x509err2alert(int x509err)
1767 const X509ERR2ALERT *tp;
1769 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1770 if (tp->x509err == x509err)
1775 int ssl_allow_compression(SSL_CONNECTION *s)
1777 if (s->options & SSL_OP_NO_COMPRESSION)
1779 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1783 * SSL/TLS/DTLS version comparison
1786 * 0 if versiona is equal to versionb
1787 * 1 if versiona is greater than versionb
1788 * -1 if versiona is less than versionb
1790 int ssl_version_cmp(const SSL_CONNECTION *s, int versiona, int versionb)
1792 int dtls = SSL_CONNECTION_IS_DTLS(s);
1794 if (versiona == versionb)
1797 return versiona < versionb ? -1 : 1;
1798 return DTLS_VERSION_LT(versiona, versionb) ? -1 : 1;
1803 const SSL_METHOD *(*cmeth) (void);
1804 const SSL_METHOD *(*smeth) (void);
1807 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1808 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1811 /* Must be in order high to low */
1812 static const version_info tls_version_table[] = {
1813 #ifndef OPENSSL_NO_TLS1_3
1814 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1816 {TLS1_3_VERSION, NULL, NULL},
1818 #ifndef OPENSSL_NO_TLS1_2
1819 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1821 {TLS1_2_VERSION, NULL, NULL},
1823 #ifndef OPENSSL_NO_TLS1_1
1824 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1826 {TLS1_1_VERSION, NULL, NULL},
1828 #ifndef OPENSSL_NO_TLS1
1829 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1831 {TLS1_VERSION, NULL, NULL},
1833 #ifndef OPENSSL_NO_SSL3
1834 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1836 {SSL3_VERSION, NULL, NULL},
1841 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1842 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1845 /* Must be in order high to low */
1846 static const version_info dtls_version_table[] = {
1847 #ifndef OPENSSL_NO_DTLS1_2
1848 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1850 {DTLS1_2_VERSION, NULL, NULL},
1852 #ifndef OPENSSL_NO_DTLS1
1853 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1854 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1856 {DTLS1_VERSION, NULL, NULL},
1857 {DTLS1_BAD_VER, NULL, NULL},
1863 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1865 * @s: The SSL handle for the candidate method
1866 * @method: the intended method.
1868 * Returns 0 on success, or an SSL error reason on failure.
1870 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1872 int version = method->version;
1874 if ((s->min_proto_version != 0 &&
1875 ssl_version_cmp(s, version, s->min_proto_version) < 0) ||
1876 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1877 return SSL_R_VERSION_TOO_LOW;
1879 if (s->max_proto_version != 0 &&
1880 ssl_version_cmp(s, version, s->max_proto_version) > 0)
1881 return SSL_R_VERSION_TOO_HIGH;
1883 if ((s->options & method->mask) != 0)
1884 return SSL_R_UNSUPPORTED_PROTOCOL;
1885 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1886 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1892 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1893 * certificate type, or has PSK or a certificate callback configured, or has
1894 * a servername callback configure. Otherwise returns 0.
1896 static int is_tls13_capable(const SSL_CONNECTION *s)
1900 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1902 if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1906 * A servername callback can change the available certs, so if a servername
1907 * cb is set then we just assume TLSv1.3 will be ok
1909 if (sctx->ext.servername_cb != NULL
1910 || s->session_ctx->ext.servername_cb != NULL)
1913 #ifndef OPENSSL_NO_PSK
1914 if (s->psk_server_callback != NULL)
1918 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1921 /* All provider-based sig algs are required to support at least TLS1.3 */
1922 for (i = 0; i < s->ssl_pkey_num; i++) {
1923 /* Skip over certs disallowed for TLSv1.3 */
1925 case SSL_PKEY_DSA_SIGN:
1926 case SSL_PKEY_GOST01:
1927 case SSL_PKEY_GOST12_256:
1928 case SSL_PKEY_GOST12_512:
1933 if (!ssl_has_cert(s, i))
1935 if (i != SSL_PKEY_ECC)
1938 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1939 * more restrictive so check that our sig algs are consistent with this
1940 * EC cert. See section 4.2.3 of RFC8446.
1942 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1943 if (tls_check_sigalg_curve(s, curve))
1951 * ssl_version_supported - Check that the specified `version` is supported by
1954 * @s: The SSL handle for the candidate method
1955 * @version: Protocol version to test against
1957 * Returns 1 when supported, otherwise 0
1959 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1960 const SSL_METHOD **meth)
1962 const version_info *vent;
1963 const version_info *table;
1965 switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1967 /* Version should match method version for non-ANY method */
1968 return ssl_version_cmp(s, version, s->version) == 0;
1969 case TLS_ANY_VERSION:
1970 table = tls_version_table;
1972 case DTLS_ANY_VERSION:
1973 table = dtls_version_table;
1978 vent->version != 0 && ssl_version_cmp(s, version, vent->version) <= 0;
1980 const SSL_METHOD *(*thismeth)(void) = s->server ? vent->smeth
1983 if (thismeth != NULL
1984 && ssl_version_cmp(s, version, vent->version) == 0
1985 && ssl_method_error(s, thismeth()) == 0
1987 || version != TLS1_3_VERSION
1988 || is_tls13_capable(s))) {
1998 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1999 * fallback indication from a client check whether we're using the highest
2000 * supported protocol version.
2002 * @s server SSL handle.
2004 * Returns 1 when using the highest enabled version, 0 otherwise.
2006 int ssl_check_version_downgrade(SSL_CONNECTION *s)
2008 const version_info *vent;
2009 const version_info *table;
2010 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2013 * Check that the current protocol is the highest enabled version
2014 * (according to ssl->defltmethod, as version negotiation may have changed
2017 if (s->version == ssl->defltmeth->version)
2021 * Apparently we're using a version-flexible SSL_METHOD (not at its
2022 * highest protocol version).
2024 if (ssl->defltmeth->version == TLS_method()->version)
2025 table = tls_version_table;
2026 else if (ssl->defltmeth->version == DTLS_method()->version)
2027 table = dtls_version_table;
2029 /* Unexpected state; fail closed. */
2033 for (vent = table; vent->version != 0; ++vent) {
2034 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
2035 return s->version == vent->version;
2041 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
2042 * protocols, provided the initial (D)TLS method is version-flexible. This
2043 * function sanity-checks the proposed value and makes sure the method is
2044 * version-flexible, then sets the limit if all is well.
2046 * @method_version: The version of the current SSL_METHOD.
2047 * @version: the intended limit.
2048 * @bound: pointer to limit to be updated.
2050 * Returns 1 on success, 0 on failure.
2052 int ssl_set_version_bound(int method_version, int version, int *bound)
2062 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
2064 /* We support client side pre-standardisation version of DTLS */
2065 (version == DTLS1_BAD_VER)
2066 || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
2067 && DTLS_VERSION_GE(version, DTLS1_VERSION));
2069 if (!valid_tls && !valid_dtls)
2073 * Restrict TLS methods to TLS protocol versions.
2074 * Restrict DTLS methods to DTLS protocol versions.
2075 * Note, DTLS version numbers are decreasing, use comparison macros.
2077 * Note that for both lower-bounds we use explicit versions, not
2078 * (D)TLS_MIN_VERSION. This is because we don't want to break user
2079 * configurations. If the MIN (supported) version ever rises, the user's
2080 * "floor" remains valid even if no longer available. We don't expect the
2081 * MAX ceiling to ever get lower, so making that variable makes sense.
2083 * We ignore attempts to set bounds on version-inflexible methods,
2084 * returning success.
2086 switch (method_version) {
2090 case TLS_ANY_VERSION:
2095 case DTLS_ANY_VERSION:
2103 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
2105 if (vers == TLS1_2_VERSION
2106 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
2107 *dgrd = DOWNGRADE_TO_1_2;
2108 } else if (!SSL_CONNECTION_IS_DTLS(s)
2109 && vers < TLS1_2_VERSION
2111 * We need to ensure that a server that disables TLSv1.2
2112 * (creating a hole between TLSv1.3 and TLSv1.1) can still
2113 * complete handshakes with clients that support TLSv1.2 and
2114 * below. Therefore we do not enable the sentinel if TLSv1.3 is
2115 * enabled and TLSv1.2 is not.
2117 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
2118 *dgrd = DOWNGRADE_TO_1_1;
2120 *dgrd = DOWNGRADE_NONE;
2125 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
2126 * client HELLO is received to select the final server protocol version and
2127 * the version specific method.
2129 * @s: server SSL handle.
2131 * Returns 0 on success or an SSL error reason number on failure.
2133 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
2137 * With version-flexible methods we have an initial state with:
2139 * s->method->version == (D)TLS_ANY_VERSION,
2140 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
2142 * So we detect version-flexible methods via the method version, not the
2145 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2146 int server_version = ssl->method->version;
2147 int client_version = hello->legacy_version;
2148 const version_info *vent;
2149 const version_info *table;
2151 RAW_EXTENSION *suppversions;
2153 s->client_version = client_version;
2155 switch (server_version) {
2157 if (!SSL_CONNECTION_IS_TLS13(s)) {
2158 if (ssl_version_cmp(s, client_version, s->version) < 0)
2159 return SSL_R_WRONG_SSL_VERSION;
2160 *dgrd = DOWNGRADE_NONE;
2162 * If this SSL handle is not from a version flexible method we don't
2163 * (and never did) check min/max FIPS or Suite B constraints. Hope
2164 * that's OK. It is up to the caller to not choose fixed protocol
2165 * versions they don't want. If not, then easy to fix, just return
2166 * ssl_method_error(s, s->method)
2171 * Fall through if we are TLSv1.3 already (this means we must be after
2172 * a HelloRetryRequest
2175 case TLS_ANY_VERSION:
2176 table = tls_version_table;
2178 case DTLS_ANY_VERSION:
2179 table = dtls_version_table;
2183 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
2185 /* If we did an HRR then supported versions is mandatory */
2186 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
2187 return SSL_R_UNSUPPORTED_PROTOCOL;
2189 if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
2190 unsigned int candidate_vers = 0;
2191 unsigned int best_vers = 0;
2192 const SSL_METHOD *best_method = NULL;
2193 PACKET versionslist;
2195 suppversions->parsed = 1;
2197 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
2198 /* Trailing or invalid data? */
2199 return SSL_R_LENGTH_MISMATCH;
2203 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
2204 * The spec only requires servers to check that it isn't SSLv3:
2205 * "Any endpoint receiving a Hello message with
2206 * ClientHello.legacy_version or ServerHello.legacy_version set to
2207 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
2208 * We are slightly stricter and require that it isn't SSLv3 or lower.
2209 * We tolerate TLSv1 and TLSv1.1.
2211 if (client_version <= SSL3_VERSION)
2212 return SSL_R_BAD_LEGACY_VERSION;
2214 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
2215 if (ssl_version_cmp(s, candidate_vers, best_vers) <= 0)
2217 if (ssl_version_supported(s, candidate_vers, &best_method))
2218 best_vers = candidate_vers;
2220 if (PACKET_remaining(&versionslist) != 0) {
2221 /* Trailing data? */
2222 return SSL_R_LENGTH_MISMATCH;
2225 if (best_vers > 0) {
2226 if (s->hello_retry_request != SSL_HRR_NONE) {
2228 * This is after a HelloRetryRequest so we better check that we
2229 * negotiated TLSv1.3
2231 if (best_vers != TLS1_3_VERSION)
2232 return SSL_R_UNSUPPORTED_PROTOCOL;
2235 check_for_downgrade(s, best_vers, dgrd);
2236 s->version = best_vers;
2237 ssl->method = best_method;
2238 if (!ssl_set_record_protocol_version(s, best_vers))
2239 return ERR_R_INTERNAL_ERROR;
2243 return SSL_R_UNSUPPORTED_PROTOCOL;
2247 * If the supported versions extension isn't present, then the highest
2248 * version we can negotiate is TLSv1.2
2250 if (ssl_version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
2251 client_version = TLS1_2_VERSION;
2254 * No supported versions extension, so we just use the version supplied in
2257 for (vent = table; vent->version != 0; ++vent) {
2258 const SSL_METHOD *method;
2260 if (vent->smeth == NULL ||
2261 ssl_version_cmp(s, client_version, vent->version) < 0)
2263 method = vent->smeth();
2264 if (ssl_method_error(s, method) == 0) {
2265 check_for_downgrade(s, vent->version, dgrd);
2266 s->version = vent->version;
2267 ssl->method = method;
2268 if (!ssl_set_record_protocol_version(s, s->version))
2269 return ERR_R_INTERNAL_ERROR;
2275 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
2279 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
2280 * server HELLO is received to select the final client protocol version and
2281 * the version specific method.
2283 * @s: client SSL handle.
2284 * @version: The proposed version from the server's HELLO.
2285 * @extensions: The extensions received
2287 * Returns 1 on success or 0 on error.
2289 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
2290 RAW_EXTENSION *extensions)
2292 const version_info *vent;
2293 const version_info *table;
2294 int ret, ver_min, ver_max, real_max, origv;
2295 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2298 s->version = version;
2300 /* This will overwrite s->version if the extension is present */
2301 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2302 SSL_EXT_TLS1_2_SERVER_HELLO
2303 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
2309 if (s->hello_retry_request != SSL_HRR_NONE
2310 && s->version != TLS1_3_VERSION) {
2312 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2316 switch (ssl->method->version) {
2318 if (s->version != ssl->method->version) {
2320 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2324 * If this SSL handle is not from a version flexible method we don't
2325 * (and never did) check min/max, FIPS or Suite B constraints. Hope
2326 * that's OK. It is up to the caller to not choose fixed protocol
2327 * versions they don't want. If not, then easy to fix, just return
2328 * ssl_method_error(s, s->method)
2330 if (!ssl_set_record_protocol_version(s, s->version)) {
2331 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2335 case TLS_ANY_VERSION:
2336 table = tls_version_table;
2338 case DTLS_ANY_VERSION:
2339 table = dtls_version_table;
2343 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2346 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2349 if (ssl_version_cmp(s, s->version, ver_min) < 0
2350 || ssl_version_cmp(s, s->version, ver_max) > 0) {
2352 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2356 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2359 /* Check for downgrades */
2360 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2361 if (memcmp(tls12downgrade,
2362 s->s3.server_random + SSL3_RANDOM_SIZE
2363 - sizeof(tls12downgrade),
2364 sizeof(tls12downgrade)) == 0) {
2366 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2367 SSL_R_INAPPROPRIATE_FALLBACK);
2370 } else if (!SSL_CONNECTION_IS_DTLS(s)
2371 && s->version < TLS1_2_VERSION
2372 && real_max > s->version) {
2373 if (memcmp(tls11downgrade,
2374 s->s3.server_random + SSL3_RANDOM_SIZE
2375 - sizeof(tls11downgrade),
2376 sizeof(tls11downgrade)) == 0) {
2378 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2379 SSL_R_INAPPROPRIATE_FALLBACK);
2384 for (vent = table; vent->version != 0; ++vent) {
2385 if (vent->cmeth == NULL || s->version != vent->version)
2388 ssl->method = vent->cmeth();
2389 if (!ssl_set_record_protocol_version(s, s->version)) {
2390 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2397 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2402 * ssl_get_min_max_version - get minimum and maximum protocol version
2403 * @s: The SSL connection
2404 * @min_version: The minimum supported version
2405 * @max_version: The maximum supported version
2406 * @real_max: The highest version below the lowest compile time version hole
2407 * where that hole lies above at least one run-time enabled
2410 * Work out what version we should be using for the initial ClientHello if the
2411 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2412 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2413 * constraints and any floor imposed by the security level here,
2414 * so we don't advertise the wrong protocol version to only reject the outcome later.
2416 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2417 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2418 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2420 * Returns 0 on success or an SSL error reason number on failure. On failure
2421 * min_version and max_version will also be set to 0.
2423 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2424 int *max_version, int *real_max)
2426 int version, tmp_real_max;
2428 const SSL_METHOD *method;
2429 const version_info *table;
2430 const version_info *vent;
2431 const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2433 switch (ssl->method->version) {
2436 * If this SSL handle is not from a version flexible method we don't
2437 * (and never did) check min/max FIPS or Suite B constraints. Hope
2438 * that's OK. It is up to the caller to not choose fixed protocol
2439 * versions they don't want. If not, then easy to fix, just return
2440 * ssl_method_error(s, s->method)
2442 *min_version = *max_version = s->version;
2444 * Providing a real_max only makes sense where we're using a version
2447 if (!ossl_assert(real_max == NULL))
2448 return ERR_R_INTERNAL_ERROR;
2450 case TLS_ANY_VERSION:
2451 table = tls_version_table;
2453 case DTLS_ANY_VERSION:
2454 table = dtls_version_table;
2459 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2460 * below X enabled. This is required in order to maintain the "version
2461 * capability" vector contiguous. Any versions with a NULL client method
2462 * (protocol version client is disabled at compile-time) is also a "hole".
2464 * Our initial state is hole == 1, version == 0. That is, versions above
2465 * the first version in the method table are disabled (a "hole" above
2466 * the valid protocol entries) and we don't have a selected version yet.
2468 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2469 * the selected version. We're no longer in a hole, so "hole" becomes 0.
2471 * If "hole == 0" and we hit an enabled method, we support a contiguous
2472 * range of at least two methods. If we hit a disabled method,
2473 * then hole becomes true again, but nothing else changes yet,
2474 * because all the remaining methods may be disabled too.
2475 * If we again hit an enabled method after the new hole, it becomes
2476 * selected, as we start from scratch.
2478 *min_version = version = 0;
2480 if (real_max != NULL)
2483 for (vent = table; vent->version != 0; ++vent) {
2485 * A table entry with a NULL client method is still a hole in the
2486 * "version capability" vector.
2488 if (vent->cmeth == NULL) {
2493 method = vent->cmeth();
2495 if (hole == 1 && tmp_real_max == 0)
2496 tmp_real_max = vent->version;
2498 if (ssl_method_error(s, method) != 0) {
2501 *min_version = method->version;
2503 if (real_max != NULL && tmp_real_max != 0)
2504 *real_max = tmp_real_max;
2505 version = method->version;
2506 *min_version = version;
2511 *max_version = version;
2513 /* Fail if everything is disabled */
2515 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2521 * ssl_set_client_hello_version - Work out what version we should be using for
2522 * the initial ClientHello.legacy_version field.
2524 * @s: client SSL handle.
2526 * Returns 0 on success or an SSL error reason number on failure.
2528 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2530 int ver_min, ver_max, ret;
2533 * In a renegotiation we always send the same client_version that we sent
2534 * last time, regardless of which version we eventually negotiated.
2536 if (!SSL_IS_FIRST_HANDSHAKE(s))
2539 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2544 s->version = ver_max;
2546 if (SSL_CONNECTION_IS_DTLS(s)) {
2547 if (ver_max == DTLS1_BAD_VER) {
2549 * Even though this is technically before version negotiation,
2550 * because we have asked for DTLS1_BAD_VER we will never negotiate
2551 * anything else, and this has impacts on the record layer for when
2552 * we read the ServerHello. So we need to tell the record layer
2553 * about this immediately.
2555 if (!ssl_set_record_protocol_version(s, ver_max))
2558 } else if (ver_max > TLS1_2_VERSION) {
2559 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2560 ver_max = TLS1_2_VERSION;
2563 s->client_version = ver_max;
2568 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2569 * and |checkallow| is 1 then additionally check if the group is allowed to be
2570 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2571 * 1) or 0 otherwise.
2573 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2574 size_t num_groups, int checkallow)
2578 if (groups == NULL || num_groups == 0)
2581 for (i = 0; i < num_groups; i++) {
2582 uint16_t group = groups[i];
2584 if (group_id == group
2586 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2594 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2595 int create_synthetic_message_hash(SSL_CONNECTION *s,
2596 const unsigned char *hashval,
2597 size_t hashlen, const unsigned char *hrr,
2600 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2601 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2603 memset(msghdr, 0, sizeof(msghdr));
2605 if (hashval == NULL) {
2606 hashval = hashvaltmp;
2608 /* Get the hash of the initial ClientHello */
2609 if (!ssl3_digest_cached_records(s, 0)
2610 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2612 /* SSLfatal() already called */
2617 /* Reinitialise the transcript hash */
2618 if (!ssl3_init_finished_mac(s)) {
2619 /* SSLfatal() already called */
2623 /* Inject the synthetic message_hash message */
2624 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2625 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2626 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2627 || !ssl3_finish_mac(s, hashval, hashlen)) {
2628 /* SSLfatal() already called */
2633 * Now re-inject the HRR and current message if appropriate (we just deleted
2634 * it when we reinitialised the transcript hash above). Only necessary after
2635 * receiving a ClientHello2 with a cookie.
2638 && (!ssl3_finish_mac(s, hrr, hrrlen)
2639 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2640 s->s3.tmp.message_size
2641 + SSL3_HM_HEADER_LENGTH))) {
2642 /* SSLfatal() already called */
2649 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2651 return X509_NAME_cmp(*a, *b);
2654 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2656 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2657 X509_NAME *xn = NULL;
2660 if (ca_sk == NULL) {
2661 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2664 /* get the CA RDNs */
2665 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2666 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2670 while (PACKET_remaining(&cadns)) {
2671 const unsigned char *namestart, *namebytes;
2672 unsigned int name_len;
2674 if (!PACKET_get_net_2(&cadns, &name_len)
2675 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2676 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2680 namestart = namebytes;
2681 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2682 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2685 if (namebytes != (namestart + name_len)) {
2686 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2690 if (!sk_X509_NAME_push(ca_sk, xn)) {
2691 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2697 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2698 s->s3.tmp.peer_ca_names = ca_sk;
2703 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2708 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2710 const STACK_OF(X509_NAME) *ca_sk = NULL;
2711 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2714 ca_sk = SSL_get_client_CA_list(ssl);
2715 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2720 ca_sk = SSL_get0_CA_list(ssl);
2725 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2728 /* Start sub-packet for client CA list */
2729 if (!WPACKET_start_sub_packet_u16(pkt)) {
2730 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2734 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2737 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2738 unsigned char *namebytes;
2739 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2743 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2744 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2746 || i2d_X509_NAME(name, &namebytes) != namelen) {
2747 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2753 if (!WPACKET_close(pkt)) {
2754 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2761 /* Create a buffer containing data to be signed for server key exchange */
2762 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2763 const void *param, size_t paramlen)
2765 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2766 unsigned char *tbs = OPENSSL_malloc(tbslen);
2769 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2772 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2773 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2775 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2782 * Saves the current handshake digest for Post-Handshake Auth,
2783 * Done after ClientFinished is processed, done exactly once
2785 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2787 if (s->pha_dgst == NULL) {
2788 if (!ssl3_digest_cached_records(s, 1))
2789 /* SSLfatal() already called */
2792 s->pha_dgst = EVP_MD_CTX_new();
2793 if (s->pha_dgst == NULL) {
2794 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2797 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2798 s->s3.handshake_dgst)) {
2799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2800 EVP_MD_CTX_free(s->pha_dgst);
2809 * Restores the Post-Handshake Auth handshake digest
2810 * Done just before sending/processing the Cert Request
2812 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2814 if (s->pha_dgst == NULL) {
2815 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2818 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2820 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2826 #ifndef OPENSSL_NO_COMP_ALG
2827 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2832 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2834 COMP_METHOD *method = NULL;
2835 COMP_CTX *comp = NULL;
2836 size_t expected_length;
2842 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2845 if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2846 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2849 /* If we have a prefs list, make sure the algorithm is in it */
2850 if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2851 for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2852 if (sc->cert_comp_prefs[i] == comp_alg) {
2858 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2862 if (!ossl_comp_has_alg(comp_alg)) {
2863 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2867 case TLSEXT_comp_cert_zlib:
2868 method = COMP_zlib_oneshot();
2870 case TLSEXT_comp_cert_brotli:
2871 method = COMP_brotli_oneshot();
2873 case TLSEXT_comp_cert_zstd:
2874 method = COMP_zstd_oneshot();
2877 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2881 if ((comp = COMP_CTX_new(method)) == NULL
2882 || !PACKET_get_net_3_len(pkt, &expected_length)
2883 || !PACKET_get_net_3_len(pkt, &comp_length)
2884 || PACKET_remaining(pkt) != comp_length
2885 || !BUF_MEM_grow(buf, expected_length)
2886 || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2887 || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2888 (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2889 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2892 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2894 COMP_CTX_free(comp);