2 * Copyright 1995-2022 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>
25 * Map error codes to TLS/SSL alart types.
27 typedef struct x509err2alert_st {
32 /* Fixed value used in the ServerHello random field to identify an HRR */
33 const unsigned char hrrrandom[] = {
34 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
35 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
36 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
40 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
41 * SSL3_RT_CHANGE_CIPHER_SPEC)
43 int ssl3_do_write(SSL *s, int type)
48 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
49 s->init_num, &written);
52 if (type == SSL3_RT_HANDSHAKE)
54 * should not be done for 'Hello Request's, but in that case we'll
55 * ignore the result anyway
56 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
58 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
59 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
60 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
61 if (!ssl3_finish_mac(s,
62 (unsigned char *)&s->init_buf->data[s->init_off],
65 if (written == s->init_num) {
67 s->msg_callback(1, s->version, type, s->init_buf->data,
68 (size_t)(s->init_off + s->init_num), s,
72 s->init_off += written;
73 s->init_num -= written;
77 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
81 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
82 || !WPACKET_get_length(pkt, &msglen)
85 s->init_num = (int)msglen;
91 int tls_setup_handshake(SSL *s)
93 int ver_min, ver_max, ok;
95 if (!ssl3_init_finished_mac(s)) {
96 /* SSLfatal() already called */
100 /* Reset any extension flags */
101 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
103 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
104 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
108 /* Sanity check that we have MD5-SHA1 if we need it */
109 if (s->ctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
110 int md5sha1_needed = 0;
112 /* We don't have MD5-SHA1 - do we need it? */
113 if (SSL_IS_DTLS(s)) {
114 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
117 if (ver_max <= TLS1_1_VERSION)
120 if (md5sha1_needed) {
121 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
122 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
123 "The max supported SSL/TLS version needs the"
124 " MD5-SHA1 digest but it is not available"
125 " in the loaded providers. Use (D)TLSv1.2 or"
126 " above, or load different providers");
131 /* Don't allow TLSv1.1 or below to be negotiated */
132 if (SSL_IS_DTLS(s)) {
133 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
134 ok = SSL_set_min_proto_version(s, DTLS1_2_VERSION);
136 if (ver_min < TLS1_2_VERSION)
137 ok = SSL_set_min_proto_version(s, TLS1_2_VERSION);
140 /* Shouldn't happen */
141 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
148 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
152 * Sanity check that the maximum version we accept has ciphers
153 * enabled. For clients we do this check during construction of the
156 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
157 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
159 if (SSL_IS_DTLS(s)) {
160 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
161 DTLS_VERSION_LE(ver_max, c->max_dtls))
163 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
170 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
171 SSL_R_NO_CIPHERS_AVAILABLE,
172 "No ciphers enabled for max supported "
176 if (SSL_IS_FIRST_HANDSHAKE(s)) {
177 /* N.B. s->session_ctx == s->ctx here */
178 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
180 /* N.B. s->ctx may not equal s->session_ctx */
181 ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_renegotiate);
183 s->s3.tmp.cert_request = 0;
186 if (SSL_IS_FIRST_HANDSHAKE(s))
187 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
189 ssl_tsan_counter(s->session_ctx,
190 &s->session_ctx->stats.sess_connect_renegotiate);
192 /* mark client_random uninitialized */
193 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
196 s->s3.tmp.cert_req = 0;
199 s->statem.use_timer = 1;
206 * Size of the to-be-signed TLS13 data, without the hash size itself:
207 * 64 bytes of value 32, 33 context bytes, 1 byte separator
209 #define TLS13_TBS_START_SIZE 64
210 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
212 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
213 void **hdata, size_t *hdatalen)
215 #ifdef CHARSET_EBCDIC
216 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
217 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
218 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
219 0x69, 0x66, 0x79, 0x00 };
220 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
221 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
222 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
223 0x69, 0x66, 0x79, 0x00 };
225 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
226 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
228 if (SSL_IS_TLS13(s)) {
231 /* Set the first 64 bytes of to-be-signed data to octet 32 */
232 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
233 /* This copies the 33 bytes of context plus the 0 separator byte */
234 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
235 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
236 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
238 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
241 * If we're currently reading then we need to use the saved handshake
242 * hash value. We can't use the current handshake hash state because
243 * that includes the CertVerify itself.
245 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
246 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
247 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
248 s->cert_verify_hash_len);
249 hashlen = s->cert_verify_hash_len;
250 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
251 EVP_MAX_MD_SIZE, &hashlen)) {
252 /* SSLfatal() already called */
257 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
262 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
264 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
273 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
275 EVP_PKEY *pkey = NULL;
276 const EVP_MD *md = NULL;
277 EVP_MD_CTX *mctx = NULL;
278 EVP_PKEY_CTX *pctx = NULL;
279 size_t hdatalen = 0, siglen = 0;
281 unsigned char *sig = NULL;
282 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
283 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
285 if (lu == NULL || s->s3.tmp.cert == NULL) {
286 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
289 pkey = s->s3.tmp.cert->privatekey;
291 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
292 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
296 mctx = EVP_MD_CTX_new();
298 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
302 /* Get the data to be signed */
303 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
304 /* SSLfatal() already called */
308 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
309 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
313 if (EVP_DigestSignInit_ex(mctx, &pctx,
314 md == NULL ? NULL : EVP_MD_get0_name(md),
315 s->ctx->libctx, s->ctx->propq, pkey,
317 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
321 if (lu->sig == EVP_PKEY_RSA_PSS) {
322 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
323 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
324 RSA_PSS_SALTLEN_DIGEST) <= 0) {
325 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
329 if (s->version == SSL3_VERSION) {
331 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
332 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
334 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
335 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
336 (int)s->session->master_key_length,
337 s->session->master_key) <= 0
338 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
340 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
343 sig = OPENSSL_malloc(siglen);
345 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
346 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
351 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
352 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
354 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
355 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
358 sig = OPENSSL_malloc(siglen);
360 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
361 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
366 #ifndef OPENSSL_NO_GOST
368 int pktype = lu->sig;
370 if (pktype == NID_id_GostR3410_2001
371 || pktype == NID_id_GostR3410_2012_256
372 || pktype == NID_id_GostR3410_2012_512)
373 BUF_reverse(sig, NULL, siglen);
377 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
378 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
382 /* Digest cached records and discard handshake buffer */
383 if (!ssl3_digest_cached_records(s, 0)) {
384 /* SSLfatal() already called */
389 EVP_MD_CTX_free(mctx);
393 EVP_MD_CTX_free(mctx);
397 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
399 EVP_PKEY *pkey = NULL;
400 const unsigned char *data;
401 #ifndef OPENSSL_NO_GOST
402 unsigned char *gost_data = NULL;
404 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
408 const EVP_MD *md = NULL;
411 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
412 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
413 EVP_PKEY_CTX *pctx = NULL;
416 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
420 peer = s->session->peer;
421 pkey = X509_get0_pubkey(peer);
423 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
427 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
428 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
429 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
433 if (SSL_USE_SIGALGS(s)) {
436 if (!PACKET_get_net_2(pkt, &sigalg)) {
437 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
440 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
441 /* SSLfatal() already called */
444 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
445 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
449 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
450 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
454 if (SSL_USE_SIGALGS(s))
455 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
456 md == NULL ? "n/a" : EVP_MD_get0_name(md));
458 /* Check for broken implementations of GOST ciphersuites */
460 * If key is GOST and len is exactly 64 or 128, it is signature without
461 * length field (CryptoPro implementations at least till TLS 1.2)
463 #ifndef OPENSSL_NO_GOST
464 if (!SSL_USE_SIGALGS(s)
465 && ((PACKET_remaining(pkt) == 64
466 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
467 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
468 || (PACKET_remaining(pkt) == 128
469 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
470 len = PACKET_remaining(pkt);
473 if (!PACKET_get_net_2(pkt, &len)) {
474 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
478 if (!PACKET_get_bytes(pkt, &data, len)) {
479 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
483 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
484 /* SSLfatal() already called */
488 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
489 md == NULL ? "n/a" : EVP_MD_get0_name(md));
491 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
492 md == NULL ? NULL : EVP_MD_get0_name(md),
493 s->ctx->libctx, s->ctx->propq, pkey,
495 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
498 #ifndef OPENSSL_NO_GOST
500 int pktype = EVP_PKEY_get_id(pkey);
501 if (pktype == NID_id_GostR3410_2001
502 || pktype == NID_id_GostR3410_2012_256
503 || pktype == NID_id_GostR3410_2012_512) {
504 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
505 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
508 BUF_reverse(gost_data, data, len);
514 if (SSL_USE_PSS(s)) {
515 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
516 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
517 RSA_PSS_SALTLEN_DIGEST) <= 0) {
518 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
522 if (s->version == SSL3_VERSION) {
523 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
524 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
525 (int)s->session->master_key_length,
526 s->session->master_key) <= 0) {
527 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
530 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
531 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
535 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
537 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
543 * In TLSv1.3 on the client side we make sure we prepare the client
544 * certificate after the CertVerify instead of when we get the
545 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
546 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
547 * want to make sure that SSL_get1_peer_certificate() will return the actual
548 * server certificate from the client_cert_cb callback.
550 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
551 ret = MSG_PROCESS_CONTINUE_PROCESSING;
553 ret = MSG_PROCESS_CONTINUE_READING;
555 BIO_free(s->s3.handshake_buffer);
556 s->s3.handshake_buffer = NULL;
557 EVP_MD_CTX_free(mctx);
558 #ifndef OPENSSL_NO_GOST
559 OPENSSL_free(gost_data);
564 int tls_construct_finished(SSL *s, WPACKET *pkt)
566 size_t finish_md_len;
570 /* This is a real handshake so make sure we clean it up at the end */
571 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
572 s->statem.cleanuphand = 1;
575 * We only change the keys if we didn't already do this when we sent the
580 && s->s3.tmp.cert_req == 0
581 && (!s->method->ssl3_enc->change_cipher_state(s,
582 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
583 /* SSLfatal() already called */
588 sender = s->method->ssl3_enc->server_finished_label;
589 slen = s->method->ssl3_enc->server_finished_label_len;
591 sender = s->method->ssl3_enc->client_finished_label;
592 slen = s->method->ssl3_enc->client_finished_label_len;
595 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
597 s->s3.tmp.finish_md);
598 if (finish_md_len == 0) {
599 /* SSLfatal() already called */
603 s->s3.tmp.finish_md_len = finish_md_len;
605 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
606 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
611 * Log the master secret, if logging is enabled. We don't log it for
612 * TLSv1.3: there's a different key schedule for that.
614 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
615 s->session->master_key,
616 s->session->master_key_length)) {
617 /* SSLfatal() already called */
622 * Copy the finished so we can use it for renegotiation checks
624 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
625 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
629 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
631 s->s3.previous_client_finished_len = finish_md_len;
633 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
635 s->s3.previous_server_finished_len = finish_md_len;
641 int tls_construct_key_update(SSL *s, WPACKET *pkt)
643 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
644 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
648 s->key_update = SSL_KEY_UPDATE_NONE;
652 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
654 unsigned int updatetype;
657 * A KeyUpdate message signals a key change so the end of the message must
658 * be on a record boundary.
660 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
661 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
662 return MSG_PROCESS_ERROR;
665 if (!PACKET_get_1(pkt, &updatetype)
666 || PACKET_remaining(pkt) != 0) {
667 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
668 return MSG_PROCESS_ERROR;
672 * There are only two defined key update types. Fail if we get a value we
675 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
676 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
677 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
678 return MSG_PROCESS_ERROR;
682 * If we get a request for us to update our sending keys too then, we need
683 * to additionally send a KeyUpdate message. However that message should
684 * not also request an update (otherwise we get into an infinite loop).
686 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
687 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
689 if (!tls13_update_key(s, 0)) {
690 /* SSLfatal() already called */
691 return MSG_PROCESS_ERROR;
694 return MSG_PROCESS_FINISHED_READING;
698 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
701 int ssl3_take_mac(SSL *s)
707 sender = s->method->ssl3_enc->server_finished_label;
708 slen = s->method->ssl3_enc->server_finished_label_len;
710 sender = s->method->ssl3_enc->client_finished_label;
711 slen = s->method->ssl3_enc->client_finished_label_len;
714 s->s3.tmp.peer_finish_md_len =
715 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
716 s->s3.tmp.peer_finish_md);
718 if (s->s3.tmp.peer_finish_md_len == 0) {
719 /* SSLfatal() already called */
726 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
730 remain = PACKET_remaining(pkt);
732 * 'Change Cipher Spec' is just a single byte, which should already have
733 * been consumed by ssl_get_message() so there should be no bytes left,
734 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
736 if (SSL_IS_DTLS(s)) {
737 if ((s->version == DTLS1_BAD_VER
738 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
739 || (s->version != DTLS1_BAD_VER
740 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
741 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
742 return MSG_PROCESS_ERROR;
746 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
747 return MSG_PROCESS_ERROR;
751 /* Check we have a cipher to change to */
752 if (s->s3.tmp.new_cipher == NULL) {
753 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
754 return MSG_PROCESS_ERROR;
757 s->s3.change_cipher_spec = 1;
758 if (!ssl3_do_change_cipher_spec(s)) {
759 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
760 return MSG_PROCESS_ERROR;
763 if (SSL_IS_DTLS(s)) {
764 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
766 if (s->version == DTLS1_BAD_VER)
767 s->d1->handshake_read_seq++;
769 #ifndef OPENSSL_NO_SCTP
771 * Remember that a CCS has been received, so that an old key of
772 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
775 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
779 return MSG_PROCESS_CONTINUE_READING;
782 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
787 /* This is a real handshake so make sure we clean it up at the end */
790 * To get this far we must have read encrypted data from the client. We
791 * no longer tolerate unencrypted alerts. This value is ignored if less
794 s->statem.enc_read_state = ENC_READ_STATE_VALID;
795 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
796 s->statem.cleanuphand = 1;
797 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
798 /* SSLfatal() already called */
799 return MSG_PROCESS_ERROR;
804 * In TLSv1.3 a Finished message signals a key change so the end of the
805 * message must be on a record boundary.
807 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
808 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
809 return MSG_PROCESS_ERROR;
812 /* If this occurs, we have missed a message */
813 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
814 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
815 return MSG_PROCESS_ERROR;
817 s->s3.change_cipher_spec = 0;
819 md_len = s->s3.tmp.peer_finish_md_len;
821 if (md_len != PACKET_remaining(pkt)) {
822 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
823 return MSG_PROCESS_ERROR;
826 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
828 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
829 return MSG_PROCESS_ERROR;
833 * Copy the finished so we can use it for renegotiation checks
835 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
836 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
837 return MSG_PROCESS_ERROR;
840 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
842 s->s3.previous_client_finished_len = md_len;
844 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
846 s->s3.previous_server_finished_len = md_len;
850 * In TLS1.3 we also have to change cipher state and do any final processing
851 * of the initial server flight (if we are a client)
853 if (SSL_IS_TLS13(s)) {
855 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
856 !s->method->ssl3_enc->change_cipher_state(s,
857 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
858 /* SSLfatal() already called */
859 return MSG_PROCESS_ERROR;
862 /* TLS 1.3 gets the secret size from the handshake md */
864 if (!s->method->ssl3_enc->generate_master_secret(s,
865 s->master_secret, s->handshake_secret, 0,
867 /* SSLfatal() already called */
868 return MSG_PROCESS_ERROR;
870 if (!s->method->ssl3_enc->change_cipher_state(s,
871 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
872 /* SSLfatal() already called */
873 return MSG_PROCESS_ERROR;
875 if (!tls_process_initial_server_flight(s)) {
876 /* SSLfatal() already called */
877 return MSG_PROCESS_ERROR;
882 return MSG_PROCESS_FINISHED_READING;
885 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
887 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
888 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
895 /* Add a certificate to the WPACKET */
896 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
899 unsigned char *outbytes;
901 len = i2d_X509(x, NULL);
903 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
906 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
907 || i2d_X509(x, &outbytes) != len) {
908 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
913 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
915 /* SSLfatal() already called */
922 /* Add certificate chain to provided WPACKET */
923 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
927 STACK_OF(X509) *extra_certs;
928 STACK_OF(X509) *chain = NULL;
929 X509_STORE *chain_store;
931 if (cpk == NULL || cpk->x509 == NULL)
937 * If we have a certificate specific chain use it, else use parent ctx.
939 if (cpk->chain != NULL)
940 extra_certs = cpk->chain;
942 extra_certs = s->ctx->extra_certs;
944 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
946 else if (s->cert->chain_store)
947 chain_store = s->cert->chain_store;
949 chain_store = s->ctx->cert_store;
951 if (chain_store != NULL) {
952 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(s->ctx->libctx,
955 if (xs_ctx == NULL) {
956 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
959 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
960 X509_STORE_CTX_free(xs_ctx);
961 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
965 * It is valid for the chain not to be complete (because normally we
966 * don't include the root cert in the chain). Therefore we deliberately
967 * ignore the error return from this call. We're not actually verifying
968 * the cert - we're just building as much of the chain as we can
970 (void)X509_verify_cert(xs_ctx);
971 /* Don't leave errors in the queue */
973 chain = X509_STORE_CTX_get0_chain(xs_ctx);
974 i = ssl_security_cert_chain(s, chain, NULL, 0);
977 /* Dummy error calls so mkerr generates them */
978 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
979 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
980 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
982 X509_STORE_CTX_free(xs_ctx);
983 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
986 chain_count = sk_X509_num(chain);
987 for (i = 0; i < chain_count; i++) {
988 x = sk_X509_value(chain, i);
990 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
991 /* SSLfatal() already called */
992 X509_STORE_CTX_free(xs_ctx);
996 X509_STORE_CTX_free(xs_ctx);
998 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1000 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1003 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1004 /* SSLfatal() already called */
1007 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1008 x = sk_X509_value(extra_certs, i);
1009 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1010 /* SSLfatal() already called */
1018 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1020 if (!WPACKET_start_sub_packet_u24(pkt)) {
1021 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1025 if (!ssl_add_cert_chain(s, pkt, cpk))
1028 if (!WPACKET_close(pkt)) {
1029 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1037 * Tidy up after the end of a handshake. In the case of SCTP this may result
1038 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1041 WORK_STATE tls_finish_handshake(SSL *s, ossl_unused WORK_STATE wst,
1042 int clearbufs, int stop)
1044 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1045 int cleanuphand = s->statem.cleanuphand;
1049 #ifndef OPENSSL_NO_SCTP
1051 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1052 * messages that require it. Therefore, DTLS procedures for retransmissions
1054 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1056 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1060 * We don't do this in DTLS over UDP because we may still need the init_buf
1061 * in case there are any unexpected retransmits
1063 BUF_MEM_free(s->init_buf);
1067 if (!ssl_free_wbio_buffer(s)) {
1068 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1074 if (SSL_IS_TLS13(s) && !s->server
1075 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1076 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1079 * Only set if there was a Finished message and this isn't after a TLSv1.3
1080 * post handshake exchange
1083 /* skipped if we just sent a HelloRequest */
1086 s->statem.cleanuphand = 0;
1087 s->ext.ticket_expected = 0;
1089 ssl3_cleanup_key_block(s);
1093 * In TLSv1.3 we update the cache as part of constructing the
1096 if (!SSL_IS_TLS13(s))
1097 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1099 /* N.B. s->ctx may not equal s->session_ctx */
1100 ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept_good);
1101 s->handshake_func = ossl_statem_accept;
1103 if (SSL_IS_TLS13(s)) {
1105 * We encourage applications to only use TLSv1.3 tickets once,
1106 * so we remove this one from the cache.
1108 if ((s->session_ctx->session_cache_mode
1109 & SSL_SESS_CACHE_CLIENT) != 0)
1110 SSL_CTX_remove_session(s->session_ctx, s->session);
1113 * In TLSv1.3 we update the cache as part of processing the
1116 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1119 ssl_tsan_counter(s->session_ctx,
1120 &s->session_ctx->stats.sess_hit);
1122 s->handshake_func = ossl_statem_connect;
1123 ssl_tsan_counter(s->session_ctx,
1124 &s->session_ctx->stats.sess_connect_good);
1127 if (SSL_IS_DTLS(s)) {
1128 /* done with handshaking */
1129 s->d1->handshake_read_seq = 0;
1130 s->d1->handshake_write_seq = 0;
1131 s->d1->next_handshake_write_seq = 0;
1132 dtls1_clear_received_buffer(s);
1136 if (s->info_callback != NULL)
1137 cb = s->info_callback;
1138 else if (s->ctx->info_callback != NULL)
1139 cb = s->ctx->info_callback;
1141 /* The callback may expect us to not be in init at handshake done */
1142 ossl_statem_set_in_init(s, 0);
1147 || SSL_IS_FIRST_HANDSHAKE(s))
1148 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1152 /* If we've got more work to do we go back into init */
1153 ossl_statem_set_in_init(s, 1);
1154 return WORK_FINISHED_CONTINUE;
1157 return WORK_FINISHED_STOP;
1160 int tls_get_message_header(SSL *s, int *mt)
1162 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1163 int skip_message, i, recvd_type;
1165 size_t l, readbytes;
1167 p = (unsigned char *)s->init_buf->data;
1170 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1171 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1173 SSL3_HM_HEADER_LENGTH - s->init_num,
1176 s->rwstate = SSL_READING;
1179 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1181 * A ChangeCipherSpec must be a single byte and may not occur
1182 * in the middle of a handshake message.
1184 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1185 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1186 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1189 if (s->statem.hand_state == TLS_ST_BEFORE
1190 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1192 * We are stateless and we received a CCS. Probably this is
1193 * from a client between the first and second ClientHellos.
1194 * We should ignore this, but return an error because we do
1195 * not return success until we see the second ClientHello
1196 * with a valid cookie.
1200 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1201 s->init_num = readbytes - 1;
1202 s->init_msg = s->init_buf->data;
1203 s->s3.tmp.message_size = readbytes;
1205 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1206 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1207 SSL_R_CCS_RECEIVED_EARLY);
1210 s->init_num += readbytes;
1215 if (s->statem.hand_state != TLS_ST_OK
1216 && p[0] == SSL3_MT_HELLO_REQUEST)
1218 * The server may always send 'Hello Request' messages --
1219 * we are doing a handshake anyway now, so ignore them if
1220 * their format is correct. Does not count for 'Finished'
1223 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1227 if (s->msg_callback)
1228 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1229 p, SSL3_HM_HEADER_LENGTH, s,
1230 s->msg_callback_arg);
1232 } while (skip_message);
1233 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1236 s->s3.tmp.message_type = *(p++);
1238 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1240 * Only happens with SSLv3+ in an SSLv2 backward compatible
1243 * Total message size is the remaining record bytes to read
1244 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1246 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1247 + SSL3_HM_HEADER_LENGTH;
1248 s->s3.tmp.message_size = l;
1250 s->init_msg = s->init_buf->data;
1251 s->init_num = SSL3_HM_HEADER_LENGTH;
1254 /* BUF_MEM_grow takes an 'int' parameter */
1255 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1256 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1257 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1260 s->s3.tmp.message_size = l;
1262 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1269 int tls_get_message_body(SSL *s, size_t *len)
1271 size_t n, readbytes;
1275 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1276 /* We've already read everything in */
1277 *len = (unsigned long)s->init_num;
1282 n = s->s3.tmp.message_size - s->init_num;
1284 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1285 &p[s->init_num], n, 0, &readbytes);
1287 s->rwstate = SSL_READING;
1291 s->init_num += readbytes;
1296 * If receiving Finished, record MAC of prior handshake messages for
1297 * Finished verification.
1299 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1300 /* SSLfatal() already called */
1305 /* Feed this message into MAC computation. */
1306 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1307 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1309 /* SSLfatal() already called */
1313 if (s->msg_callback)
1314 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1315 (size_t)s->init_num, s, s->msg_callback_arg);
1318 * We defer feeding in the HRR until later. We'll do it as part of
1319 * processing the message
1320 * The TLsv1.3 handshake transcript stops at the ClientFinished
1323 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1324 /* KeyUpdate and NewSessionTicket do not need to be added */
1325 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1326 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1327 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1328 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1329 || memcmp(hrrrandom,
1330 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1331 SSL3_RANDOM_SIZE) != 0) {
1332 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1333 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1334 /* SSLfatal() already called */
1340 if (s->msg_callback)
1341 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1342 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1343 s->msg_callback_arg);
1350 static const X509ERR2ALERT x509table[] = {
1351 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1352 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1353 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1354 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1355 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1356 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1357 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1358 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1359 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1360 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1361 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1362 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1363 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1364 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1365 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1366 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1367 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1368 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1369 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1370 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1371 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1372 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1373 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1374 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1375 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1376 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1377 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1378 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1379 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1380 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1381 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1382 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1383 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1384 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1385 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1386 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1387 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1388 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1389 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1390 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1392 /* Last entry; return this if we don't find the value above. */
1393 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1396 int ssl_x509err2alert(int x509err)
1398 const X509ERR2ALERT *tp;
1400 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1401 if (tp->x509err == x509err)
1406 int ssl_allow_compression(SSL *s)
1408 if (s->options & SSL_OP_NO_COMPRESSION)
1410 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1413 static int version_cmp(const SSL *s, int a, int b)
1415 int dtls = SSL_IS_DTLS(s);
1420 return a < b ? -1 : 1;
1421 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1426 const SSL_METHOD *(*cmeth) (void);
1427 const SSL_METHOD *(*smeth) (void);
1430 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1431 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1434 /* Must be in order high to low */
1435 static const version_info tls_version_table[] = {
1436 #ifndef OPENSSL_NO_TLS1_3
1437 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1439 {TLS1_3_VERSION, NULL, NULL},
1441 #ifndef OPENSSL_NO_TLS1_2
1442 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1444 {TLS1_2_VERSION, NULL, NULL},
1446 #ifndef OPENSSL_NO_TLS1_1
1447 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1449 {TLS1_1_VERSION, NULL, NULL},
1451 #ifndef OPENSSL_NO_TLS1
1452 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1454 {TLS1_VERSION, NULL, NULL},
1456 #ifndef OPENSSL_NO_SSL3
1457 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1459 {SSL3_VERSION, NULL, NULL},
1464 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1465 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1468 /* Must be in order high to low */
1469 static const version_info dtls_version_table[] = {
1470 #ifndef OPENSSL_NO_DTLS1_2
1471 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1473 {DTLS1_2_VERSION, NULL, NULL},
1475 #ifndef OPENSSL_NO_DTLS1
1476 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1477 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1479 {DTLS1_VERSION, NULL, NULL},
1480 {DTLS1_BAD_VER, NULL, NULL},
1486 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1488 * @s: The SSL handle for the candidate method
1489 * @method: the intended method.
1491 * Returns 0 on success, or an SSL error reason on failure.
1493 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1495 int version = method->version;
1497 if ((s->min_proto_version != 0 &&
1498 version_cmp(s, version, s->min_proto_version) < 0) ||
1499 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1500 return SSL_R_VERSION_TOO_LOW;
1502 if (s->max_proto_version != 0 &&
1503 version_cmp(s, version, s->max_proto_version) > 0)
1504 return SSL_R_VERSION_TOO_HIGH;
1506 if ((s->options & method->mask) != 0)
1507 return SSL_R_UNSUPPORTED_PROTOCOL;
1508 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1509 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1515 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1516 * certificate type, or has PSK or a certificate callback configured, or has
1517 * a servername callback configure. Otherwise returns 0.
1519 static int is_tls13_capable(const SSL *s)
1524 if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1528 * A servername callback can change the available certs, so if a servername
1529 * cb is set then we just assume TLSv1.3 will be ok
1531 if (s->ctx->ext.servername_cb != NULL
1532 || s->session_ctx->ext.servername_cb != NULL)
1535 #ifndef OPENSSL_NO_PSK
1536 if (s->psk_server_callback != NULL)
1540 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1543 for (i = 0; i < SSL_PKEY_NUM; i++) {
1544 /* Skip over certs disallowed for TLSv1.3 */
1546 case SSL_PKEY_DSA_SIGN:
1547 case SSL_PKEY_GOST01:
1548 case SSL_PKEY_GOST12_256:
1549 case SSL_PKEY_GOST12_512:
1554 if (!ssl_has_cert(s, i))
1556 if (i != SSL_PKEY_ECC)
1559 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1560 * more restrictive so check that our sig algs are consistent with this
1561 * EC cert. See section 4.2.3 of RFC8446.
1563 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1564 if (tls_check_sigalg_curve(s, curve))
1572 * ssl_version_supported - Check that the specified `version` is supported by
1575 * @s: The SSL handle for the candidate method
1576 * @version: Protocol version to test against
1578 * Returns 1 when supported, otherwise 0
1580 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1582 const version_info *vent;
1583 const version_info *table;
1585 switch (s->method->version) {
1587 /* Version should match method version for non-ANY method */
1588 return version_cmp(s, version, s->version) == 0;
1589 case TLS_ANY_VERSION:
1590 table = tls_version_table;
1592 case DTLS_ANY_VERSION:
1593 table = dtls_version_table;
1598 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1600 if (vent->cmeth != NULL
1601 && version_cmp(s, version, vent->version) == 0
1602 && ssl_method_error(s, vent->cmeth()) == 0
1604 || version != TLS1_3_VERSION
1605 || is_tls13_capable(s))) {
1607 *meth = vent->cmeth();
1615 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1616 * fallback indication from a client check whether we're using the highest
1617 * supported protocol version.
1619 * @s server SSL handle.
1621 * Returns 1 when using the highest enabled version, 0 otherwise.
1623 int ssl_check_version_downgrade(SSL *s)
1625 const version_info *vent;
1626 const version_info *table;
1629 * Check that the current protocol is the highest enabled version
1630 * (according to s->ctx->method, as version negotiation may have changed
1633 if (s->version == s->ctx->method->version)
1637 * Apparently we're using a version-flexible SSL_METHOD (not at its
1638 * highest protocol version).
1640 if (s->ctx->method->version == TLS_method()->version)
1641 table = tls_version_table;
1642 else if (s->ctx->method->version == DTLS_method()->version)
1643 table = dtls_version_table;
1645 /* Unexpected state; fail closed. */
1649 for (vent = table; vent->version != 0; ++vent) {
1650 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1651 return s->version == vent->version;
1657 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1658 * protocols, provided the initial (D)TLS method is version-flexible. This
1659 * function sanity-checks the proposed value and makes sure the method is
1660 * version-flexible, then sets the limit if all is well.
1662 * @method_version: The version of the current SSL_METHOD.
1663 * @version: the intended limit.
1664 * @bound: pointer to limit to be updated.
1666 * Returns 1 on success, 0 on failure.
1668 int ssl_set_version_bound(int method_version, int version, int *bound)
1678 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1680 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1681 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1683 if (!valid_tls && !valid_dtls)
1687 * Restrict TLS methods to TLS protocol versions.
1688 * Restrict DTLS methods to DTLS protocol versions.
1689 * Note, DTLS version numbers are decreasing, use comparison macros.
1691 * Note that for both lower-bounds we use explicit versions, not
1692 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1693 * configurations. If the MIN (supported) version ever rises, the user's
1694 * "floor" remains valid even if no longer available. We don't expect the
1695 * MAX ceiling to ever get lower, so making that variable makes sense.
1697 * We ignore attempts to set bounds on version-inflexible methods,
1698 * returning success.
1700 switch (method_version) {
1704 case TLS_ANY_VERSION:
1709 case DTLS_ANY_VERSION:
1717 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1719 if (vers == TLS1_2_VERSION
1720 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1721 *dgrd = DOWNGRADE_TO_1_2;
1722 } else if (!SSL_IS_DTLS(s)
1723 && vers < TLS1_2_VERSION
1725 * We need to ensure that a server that disables TLSv1.2
1726 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1727 * complete handshakes with clients that support TLSv1.2 and
1728 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1729 * enabled and TLSv1.2 is not.
1731 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1732 *dgrd = DOWNGRADE_TO_1_1;
1734 *dgrd = DOWNGRADE_NONE;
1739 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1740 * client HELLO is received to select the final server protocol version and
1741 * the version specific method.
1743 * @s: server SSL handle.
1745 * Returns 0 on success or an SSL error reason number on failure.
1747 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1750 * With version-flexible methods we have an initial state with:
1752 * s->method->version == (D)TLS_ANY_VERSION,
1753 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1755 * So we detect version-flexible methods via the method version, not the
1758 int server_version = s->method->version;
1759 int client_version = hello->legacy_version;
1760 const version_info *vent;
1761 const version_info *table;
1763 RAW_EXTENSION *suppversions;
1765 s->client_version = client_version;
1767 switch (server_version) {
1769 if (!SSL_IS_TLS13(s)) {
1770 if (version_cmp(s, client_version, s->version) < 0)
1771 return SSL_R_WRONG_SSL_VERSION;
1772 *dgrd = DOWNGRADE_NONE;
1774 * If this SSL handle is not from a version flexible method we don't
1775 * (and never did) check min/max FIPS or Suite B constraints. Hope
1776 * that's OK. It is up to the caller to not choose fixed protocol
1777 * versions they don't want. If not, then easy to fix, just return
1778 * ssl_method_error(s, s->method)
1783 * Fall through if we are TLSv1.3 already (this means we must be after
1784 * a HelloRetryRequest
1787 case TLS_ANY_VERSION:
1788 table = tls_version_table;
1790 case DTLS_ANY_VERSION:
1791 table = dtls_version_table;
1795 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1797 /* If we did an HRR then supported versions is mandatory */
1798 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1799 return SSL_R_UNSUPPORTED_PROTOCOL;
1801 if (suppversions->present && !SSL_IS_DTLS(s)) {
1802 unsigned int candidate_vers = 0;
1803 unsigned int best_vers = 0;
1804 const SSL_METHOD *best_method = NULL;
1805 PACKET versionslist;
1807 suppversions->parsed = 1;
1809 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1810 /* Trailing or invalid data? */
1811 return SSL_R_LENGTH_MISMATCH;
1815 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1816 * The spec only requires servers to check that it isn't SSLv3:
1817 * "Any endpoint receiving a Hello message with
1818 * ClientHello.legacy_version or ServerHello.legacy_version set to
1819 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1820 * We are slightly stricter and require that it isn't SSLv3 or lower.
1821 * We tolerate TLSv1 and TLSv1.1.
1823 if (client_version <= SSL3_VERSION)
1824 return SSL_R_BAD_LEGACY_VERSION;
1826 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1827 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1829 if (ssl_version_supported(s, candidate_vers, &best_method))
1830 best_vers = candidate_vers;
1832 if (PACKET_remaining(&versionslist) != 0) {
1833 /* Trailing data? */
1834 return SSL_R_LENGTH_MISMATCH;
1837 if (best_vers > 0) {
1838 if (s->hello_retry_request != SSL_HRR_NONE) {
1840 * This is after a HelloRetryRequest so we better check that we
1841 * negotiated TLSv1.3
1843 if (best_vers != TLS1_3_VERSION)
1844 return SSL_R_UNSUPPORTED_PROTOCOL;
1847 check_for_downgrade(s, best_vers, dgrd);
1848 s->version = best_vers;
1849 s->method = best_method;
1852 return SSL_R_UNSUPPORTED_PROTOCOL;
1856 * If the supported versions extension isn't present, then the highest
1857 * version we can negotiate is TLSv1.2
1859 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1860 client_version = TLS1_2_VERSION;
1863 * No supported versions extension, so we just use the version supplied in
1866 for (vent = table; vent->version != 0; ++vent) {
1867 const SSL_METHOD *method;
1869 if (vent->smeth == NULL ||
1870 version_cmp(s, client_version, vent->version) < 0)
1872 method = vent->smeth();
1873 if (ssl_method_error(s, method) == 0) {
1874 check_for_downgrade(s, vent->version, dgrd);
1875 s->version = vent->version;
1881 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1885 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1886 * server HELLO is received to select the final client protocol version and
1887 * the version specific method.
1889 * @s: client SSL handle.
1890 * @version: The proposed version from the server's HELLO.
1891 * @extensions: The extensions received
1893 * Returns 1 on success or 0 on error.
1895 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1897 const version_info *vent;
1898 const version_info *table;
1899 int ret, ver_min, ver_max, real_max, origv;
1902 s->version = version;
1904 /* This will overwrite s->version if the extension is present */
1905 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1906 SSL_EXT_TLS1_2_SERVER_HELLO
1907 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1913 if (s->hello_retry_request != SSL_HRR_NONE
1914 && s->version != TLS1_3_VERSION) {
1916 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1920 switch (s->method->version) {
1922 if (s->version != s->method->version) {
1924 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1928 * If this SSL handle is not from a version flexible method we don't
1929 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1930 * that's OK. It is up to the caller to not choose fixed protocol
1931 * versions they don't want. If not, then easy to fix, just return
1932 * ssl_method_error(s, s->method)
1935 case TLS_ANY_VERSION:
1936 table = tls_version_table;
1938 case DTLS_ANY_VERSION:
1939 table = dtls_version_table;
1943 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1946 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
1949 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1950 : s->version < ver_min) {
1952 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1954 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1955 : s->version > ver_max) {
1957 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1961 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1964 /* Check for downgrades */
1965 if (s->version == TLS1_2_VERSION && real_max > s->version) {
1966 if (memcmp(tls12downgrade,
1967 s->s3.server_random + SSL3_RANDOM_SIZE
1968 - sizeof(tls12downgrade),
1969 sizeof(tls12downgrade)) == 0) {
1971 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1972 SSL_R_INAPPROPRIATE_FALLBACK);
1975 } else if (!SSL_IS_DTLS(s)
1976 && s->version < TLS1_2_VERSION
1977 && real_max > s->version) {
1978 if (memcmp(tls11downgrade,
1979 s->s3.server_random + SSL3_RANDOM_SIZE
1980 - sizeof(tls11downgrade),
1981 sizeof(tls11downgrade)) == 0) {
1983 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1984 SSL_R_INAPPROPRIATE_FALLBACK);
1989 for (vent = table; vent->version != 0; ++vent) {
1990 if (vent->cmeth == NULL || s->version != vent->version)
1993 s->method = vent->cmeth();
1998 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2003 * ssl_get_min_max_version - get minimum and maximum protocol version
2004 * @s: The SSL connection
2005 * @min_version: The minimum supported version
2006 * @max_version: The maximum supported version
2007 * @real_max: The highest version below the lowest compile time version hole
2008 * where that hole lies above at least one run-time enabled
2011 * Work out what version we should be using for the initial ClientHello if the
2012 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2013 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2014 * constraints and any floor imposed by the security level here,
2015 * so we don't advertise the wrong protocol version to only reject the outcome later.
2017 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2018 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2019 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2021 * Returns 0 on success or an SSL error reason number on failure. On failure
2022 * min_version and max_version will also be set to 0.
2024 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2027 int version, tmp_real_max;
2029 const SSL_METHOD *single = NULL;
2030 const SSL_METHOD *method;
2031 const version_info *table;
2032 const version_info *vent;
2034 switch (s->method->version) {
2037 * If this SSL handle is not from a version flexible method we don't
2038 * (and never did) check min/max FIPS or Suite B constraints. Hope
2039 * that's OK. It is up to the caller to not choose fixed protocol
2040 * versions they don't want. If not, then easy to fix, just return
2041 * ssl_method_error(s, s->method)
2043 *min_version = *max_version = s->version;
2045 * Providing a real_max only makes sense where we're using a version
2048 if (!ossl_assert(real_max == NULL))
2049 return ERR_R_INTERNAL_ERROR;
2051 case TLS_ANY_VERSION:
2052 table = tls_version_table;
2054 case DTLS_ANY_VERSION:
2055 table = dtls_version_table;
2060 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2061 * below X enabled. This is required in order to maintain the "version
2062 * capability" vector contiguous. Any versions with a NULL client method
2063 * (protocol version client is disabled at compile-time) is also a "hole".
2065 * Our initial state is hole == 1, version == 0. That is, versions above
2066 * the first version in the method table are disabled (a "hole" above
2067 * the valid protocol entries) and we don't have a selected version yet.
2069 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2070 * the selected version, and the method becomes a candidate "single"
2071 * method. We're no longer in a hole, so "hole" becomes 0.
2073 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2074 * as we support a contiguous range of at least two methods. If we hit
2075 * a disabled method, then hole becomes true again, but nothing else
2076 * changes yet, because all the remaining methods may be disabled too.
2077 * If we again hit an enabled method after the new hole, it becomes
2078 * selected, as we start from scratch.
2080 *min_version = version = 0;
2082 if (real_max != NULL)
2085 for (vent = table; vent->version != 0; ++vent) {
2087 * A table entry with a NULL client method is still a hole in the
2088 * "version capability" vector.
2090 if (vent->cmeth == NULL) {
2095 method = vent->cmeth();
2097 if (hole == 1 && tmp_real_max == 0)
2098 tmp_real_max = vent->version;
2100 if (ssl_method_error(s, method) != 0) {
2104 *min_version = method->version;
2106 if (real_max != NULL && tmp_real_max != 0)
2107 *real_max = tmp_real_max;
2108 version = (single = method)->version;
2109 *min_version = version;
2114 *max_version = version;
2116 /* Fail if everything is disabled */
2118 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2124 * ssl_set_client_hello_version - Work out what version we should be using for
2125 * the initial ClientHello.legacy_version field.
2127 * @s: client SSL handle.
2129 * Returns 0 on success or an SSL error reason number on failure.
2131 int ssl_set_client_hello_version(SSL *s)
2133 int ver_min, ver_max, ret;
2136 * In a renegotiation we always send the same client_version that we sent
2137 * last time, regardless of which version we eventually negotiated.
2139 if (!SSL_IS_FIRST_HANDSHAKE(s))
2142 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2147 s->version = ver_max;
2149 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2150 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2151 ver_max = TLS1_2_VERSION;
2153 s->client_version = ver_max;
2158 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2159 * and |checkallow| is 1 then additionally check if the group is allowed to be
2160 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2161 * 1) or 0 otherwise.
2163 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2164 size_t num_groups, int checkallow)
2168 if (groups == NULL || num_groups == 0)
2171 if (checkallow == 1)
2172 group_id = ssl_group_id_tls13_to_internal(group_id);
2174 for (i = 0; i < num_groups; i++) {
2175 uint16_t group = groups[i];
2177 if (checkallow == 2)
2178 group = ssl_group_id_tls13_to_internal(group);
2180 if (group_id == group
2182 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2190 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2191 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2192 size_t hashlen, const unsigned char *hrr,
2195 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2196 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2198 memset(msghdr, 0, sizeof(msghdr));
2200 if (hashval == NULL) {
2201 hashval = hashvaltmp;
2203 /* Get the hash of the initial ClientHello */
2204 if (!ssl3_digest_cached_records(s, 0)
2205 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2207 /* SSLfatal() already called */
2212 /* Reinitialise the transcript hash */
2213 if (!ssl3_init_finished_mac(s)) {
2214 /* SSLfatal() already called */
2218 /* Inject the synthetic message_hash message */
2219 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2220 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2221 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2222 || !ssl3_finish_mac(s, hashval, hashlen)) {
2223 /* SSLfatal() already called */
2228 * Now re-inject the HRR and current message if appropriate (we just deleted
2229 * it when we reinitialised the transcript hash above). Only necessary after
2230 * receiving a ClientHello2 with a cookie.
2233 && (!ssl3_finish_mac(s, hrr, hrrlen)
2234 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2235 s->s3.tmp.message_size
2236 + SSL3_HM_HEADER_LENGTH))) {
2237 /* SSLfatal() already called */
2244 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2246 return X509_NAME_cmp(*a, *b);
2249 int parse_ca_names(SSL *s, PACKET *pkt)
2251 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2252 X509_NAME *xn = NULL;
2255 if (ca_sk == NULL) {
2256 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2259 /* get the CA RDNs */
2260 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2261 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2265 while (PACKET_remaining(&cadns)) {
2266 const unsigned char *namestart, *namebytes;
2267 unsigned int name_len;
2269 if (!PACKET_get_net_2(&cadns, &name_len)
2270 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2271 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2275 namestart = namebytes;
2276 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2277 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2280 if (namebytes != (namestart + name_len)) {
2281 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2285 if (!sk_X509_NAME_push(ca_sk, xn)) {
2286 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2292 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2293 s->s3.tmp.peer_ca_names = ca_sk;
2298 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2303 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2305 const STACK_OF(X509_NAME) *ca_sk = NULL;
2308 ca_sk = SSL_get_client_CA_list(s);
2309 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2314 ca_sk = SSL_get0_CA_list(s);
2319 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2321 /* Start sub-packet for client CA list */
2322 if (!WPACKET_start_sub_packet_u16(pkt)) {
2323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2327 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2330 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2331 unsigned char *namebytes;
2332 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2336 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2337 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2339 || i2d_X509_NAME(name, &namebytes) != namelen) {
2340 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2346 if (!WPACKET_close(pkt)) {
2347 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2354 /* Create a buffer containing data to be signed for server key exchange */
2355 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2356 const void *param, size_t paramlen)
2358 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2359 unsigned char *tbs = OPENSSL_malloc(tbslen);
2362 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2365 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2366 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2368 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2375 * Saves the current handshake digest for Post-Handshake Auth,
2376 * Done after ClientFinished is processed, done exactly once
2378 int tls13_save_handshake_digest_for_pha(SSL *s)
2380 if (s->pha_dgst == NULL) {
2381 if (!ssl3_digest_cached_records(s, 1))
2382 /* SSLfatal() already called */
2385 s->pha_dgst = EVP_MD_CTX_new();
2386 if (s->pha_dgst == NULL) {
2387 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2390 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2391 s->s3.handshake_dgst)) {
2392 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2393 EVP_MD_CTX_free(s->pha_dgst);
2402 * Restores the Post-Handshake Auth handshake digest
2403 * Done just before sending/processing the Cert Request
2405 int tls13_restore_handshake_digest_for_pha(SSL *s)
2407 if (s->pha_dgst == NULL) {
2408 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2411 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2413 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);