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_CONNECTION *s, int type)
47 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
49 ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
50 s->init_num, &written);
53 if (type == SSL3_RT_HANDSHAKE)
55 * should not be done for 'Hello Request's, but in that case we'll
56 * ignore the result anyway
57 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
59 if (!SSL_CONNECTION_IS_TLS13(s)
60 || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
61 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
62 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
63 if (!ssl3_finish_mac(s,
64 (unsigned char *)&s->init_buf->data[s->init_off],
67 if (written == s->init_num) {
69 s->msg_callback(1, s->version, type, s->init_buf->data,
70 (size_t)(s->init_off + s->init_num), ssl,
74 s->init_off += written;
75 s->init_num -= written;
79 int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
83 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
84 || !WPACKET_get_length(pkt, &msglen)
87 s->init_num = (int)msglen;
93 int tls_setup_handshake(SSL_CONNECTION *s)
95 int ver_min, ver_max, ok;
96 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
97 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
99 if (!ssl3_init_finished_mac(s)) {
100 /* SSLfatal() already called */
104 /* Reset any extension flags */
105 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
107 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
108 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
112 /* Sanity check that we have MD5-SHA1 if we need it */
113 if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
114 int md5sha1_needed = 0;
116 /* We don't have MD5-SHA1 - do we need it? */
117 if (SSL_CONNECTION_IS_DTLS(s)) {
118 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
121 if (ver_max <= TLS1_1_VERSION)
124 if (md5sha1_needed) {
125 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
126 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
127 "The max supported SSL/TLS version needs the"
128 " MD5-SHA1 digest but it is not available"
129 " in the loaded providers. Use (D)TLSv1.2 or"
130 " above, or load different providers");
135 /* Don't allow TLSv1.1 or below to be negotiated */
136 if (SSL_CONNECTION_IS_DTLS(s)) {
137 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
138 ok = SSL_set_min_proto_version(ssl, DTLS1_2_VERSION);
140 if (ver_min < TLS1_2_VERSION)
141 ok = SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
144 /* Shouldn't happen */
145 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
152 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
156 * Sanity check that the maximum version we accept has ciphers
157 * enabled. For clients we do this check during construction of the
160 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
161 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
163 if (SSL_CONNECTION_IS_DTLS(s)) {
164 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
165 DTLS_VERSION_LE(ver_max, c->max_dtls))
167 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
174 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
175 SSL_R_NO_CIPHERS_AVAILABLE,
176 "No ciphers enabled for max supported "
180 if (SSL_IS_FIRST_HANDSHAKE(s)) {
181 /* N.B. s->session_ctx == s->ctx here */
182 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
184 /* N.B. s->ctx may not equal s->session_ctx */
185 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
187 s->s3.tmp.cert_request = 0;
190 if (SSL_IS_FIRST_HANDSHAKE(s))
191 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
193 ssl_tsan_counter(s->session_ctx,
194 &s->session_ctx->stats.sess_connect_renegotiate);
196 /* mark client_random uninitialized */
197 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
200 s->s3.tmp.cert_req = 0;
202 if (SSL_CONNECTION_IS_DTLS(s))
203 s->statem.use_timer = 1;
210 * Size of the to-be-signed TLS13 data, without the hash size itself:
211 * 64 bytes of value 32, 33 context bytes, 1 byte separator
213 #define TLS13_TBS_START_SIZE 64
214 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
216 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
217 void **hdata, size_t *hdatalen)
219 #ifdef CHARSET_EBCDIC
220 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
221 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
222 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
223 0x69, 0x66, 0x79, 0x00 };
224 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
225 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
226 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
227 0x69, 0x66, 0x79, 0x00 };
229 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
230 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
233 if (SSL_CONNECTION_IS_TLS13(s)) {
236 /* Set the first 64 bytes of to-be-signed data to octet 32 */
237 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
238 /* This copies the 33 bytes of context plus the 0 separator byte */
239 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
240 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
241 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
243 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
246 * If we're currently reading then we need to use the saved handshake
247 * hash value. We can't use the current handshake hash state because
248 * that includes the CertVerify itself.
250 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
251 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
252 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
253 s->cert_verify_hash_len);
254 hashlen = s->cert_verify_hash_len;
255 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
256 EVP_MAX_MD_SIZE, &hashlen)) {
257 /* SSLfatal() already called */
262 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
267 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
269 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
278 int tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
280 EVP_PKEY *pkey = NULL;
281 const EVP_MD *md = NULL;
282 EVP_MD_CTX *mctx = NULL;
283 EVP_PKEY_CTX *pctx = NULL;
284 size_t hdatalen = 0, siglen = 0;
286 unsigned char *sig = NULL;
287 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
288 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
289 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
291 if (lu == NULL || s->s3.tmp.cert == NULL) {
292 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
295 pkey = s->s3.tmp.cert->privatekey;
297 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
298 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
302 mctx = EVP_MD_CTX_new();
304 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
308 /* Get the data to be signed */
309 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
310 /* SSLfatal() already called */
314 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
315 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
319 if (EVP_DigestSignInit_ex(mctx, &pctx,
320 md == NULL ? NULL : EVP_MD_get0_name(md),
321 sctx->libctx, sctx->propq, pkey,
323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
327 if (lu->sig == EVP_PKEY_RSA_PSS) {
328 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
329 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
330 RSA_PSS_SALTLEN_DIGEST) <= 0) {
331 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
335 if (s->version == SSL3_VERSION) {
337 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
338 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
340 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
341 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
342 (int)s->session->master_key_length,
343 s->session->master_key) <= 0
344 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
346 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
349 sig = OPENSSL_malloc(siglen);
351 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
352 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
357 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
358 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
360 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
361 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
364 sig = OPENSSL_malloc(siglen);
366 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
367 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
372 #ifndef OPENSSL_NO_GOST
374 int pktype = lu->sig;
376 if (pktype == NID_id_GostR3410_2001
377 || pktype == NID_id_GostR3410_2012_256
378 || pktype == NID_id_GostR3410_2012_512)
379 BUF_reverse(sig, NULL, siglen);
383 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
384 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
388 /* Digest cached records and discard handshake buffer */
389 if (!ssl3_digest_cached_records(s, 0)) {
390 /* SSLfatal() already called */
395 EVP_MD_CTX_free(mctx);
399 EVP_MD_CTX_free(mctx);
403 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
405 EVP_PKEY *pkey = NULL;
406 const unsigned char *data;
407 #ifndef OPENSSL_NO_GOST
408 unsigned char *gost_data = NULL;
410 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
414 const EVP_MD *md = NULL;
417 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
418 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
419 EVP_PKEY_CTX *pctx = NULL;
420 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
423 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
427 peer = s->session->peer;
428 pkey = X509_get0_pubkey(peer);
430 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
434 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
435 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
436 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
440 if (SSL_USE_SIGALGS(s)) {
443 if (!PACKET_get_net_2(pkt, &sigalg)) {
444 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
447 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
448 /* SSLfatal() already called */
451 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
452 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
456 if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
457 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
461 if (SSL_USE_SIGALGS(s))
462 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
463 md == NULL ? "n/a" : EVP_MD_get0_name(md));
465 /* Check for broken implementations of GOST ciphersuites */
467 * If key is GOST and len is exactly 64 or 128, it is signature without
468 * length field (CryptoPro implementations at least till TLS 1.2)
470 #ifndef OPENSSL_NO_GOST
471 if (!SSL_USE_SIGALGS(s)
472 && ((PACKET_remaining(pkt) == 64
473 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
474 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
475 || (PACKET_remaining(pkt) == 128
476 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
477 len = PACKET_remaining(pkt);
480 if (!PACKET_get_net_2(pkt, &len)) {
481 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
485 if (!PACKET_get_bytes(pkt, &data, len)) {
486 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
490 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
491 /* SSLfatal() already called */
495 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
496 md == NULL ? "n/a" : EVP_MD_get0_name(md));
498 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
499 md == NULL ? NULL : EVP_MD_get0_name(md),
500 sctx->libctx, sctx->propq, pkey,
502 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
505 #ifndef OPENSSL_NO_GOST
507 int pktype = EVP_PKEY_get_id(pkey);
508 if (pktype == NID_id_GostR3410_2001
509 || pktype == NID_id_GostR3410_2012_256
510 || pktype == NID_id_GostR3410_2012_512) {
511 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
512 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
515 BUF_reverse(gost_data, data, len);
521 if (SSL_USE_PSS(s)) {
522 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
523 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
524 RSA_PSS_SALTLEN_DIGEST) <= 0) {
525 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
529 if (s->version == SSL3_VERSION) {
530 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
531 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
532 (int)s->session->master_key_length,
533 s->session->master_key) <= 0) {
534 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
537 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
538 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
542 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
544 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
550 * In TLSv1.3 on the client side we make sure we prepare the client
551 * certificate after the CertVerify instead of when we get the
552 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
553 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
554 * want to make sure that SSL_get1_peer_certificate() will return the actual
555 * server certificate from the client_cert_cb callback.
557 if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
558 ret = MSG_PROCESS_CONTINUE_PROCESSING;
560 ret = MSG_PROCESS_CONTINUE_READING;
562 BIO_free(s->s3.handshake_buffer);
563 s->s3.handshake_buffer = NULL;
564 EVP_MD_CTX_free(mctx);
565 #ifndef OPENSSL_NO_GOST
566 OPENSSL_free(gost_data);
571 int tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
573 size_t finish_md_len;
576 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
578 /* This is a real handshake so make sure we clean it up at the end */
579 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
580 s->statem.cleanuphand = 1;
583 * We only change the keys if we didn't already do this when we sent the
586 if (SSL_CONNECTION_IS_TLS13(s)
588 && s->s3.tmp.cert_req == 0
589 && (!ssl->method->ssl3_enc->change_cipher_state(s,
590 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
591 /* SSLfatal() already called */
596 sender = ssl->method->ssl3_enc->server_finished_label;
597 slen = ssl->method->ssl3_enc->server_finished_label_len;
599 sender = ssl->method->ssl3_enc->client_finished_label;
600 slen = ssl->method->ssl3_enc->client_finished_label_len;
603 finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
605 s->s3.tmp.finish_md);
606 if (finish_md_len == 0) {
607 /* SSLfatal() already called */
611 s->s3.tmp.finish_md_len = finish_md_len;
613 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
614 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
619 * Log the master secret, if logging is enabled. We don't log it for
620 * TLSv1.3: there's a different key schedule for that.
622 if (!SSL_CONNECTION_IS_TLS13(s)
623 && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
624 s->session->master_key_length)) {
625 /* SSLfatal() already called */
630 * Copy the finished so we can use it for renegotiation checks
632 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
633 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
637 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
639 s->s3.previous_client_finished_len = finish_md_len;
641 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
643 s->s3.previous_server_finished_len = finish_md_len;
649 int tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
651 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
652 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
656 s->key_update = SSL_KEY_UPDATE_NONE;
660 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
662 unsigned int updatetype;
665 * A KeyUpdate message signals a key change so the end of the message must
666 * be on a record boundary.
668 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
669 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
670 return MSG_PROCESS_ERROR;
673 if (!PACKET_get_1(pkt, &updatetype)
674 || PACKET_remaining(pkt) != 0) {
675 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
676 return MSG_PROCESS_ERROR;
680 * There are only two defined key update types. Fail if we get a value we
683 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
684 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
685 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
686 return MSG_PROCESS_ERROR;
690 * If we get a request for us to update our sending keys too then, we need
691 * to additionally send a KeyUpdate message. However that message should
692 * not also request an update (otherwise we get into an infinite loop).
694 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
695 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
697 if (!tls13_update_key(s, 0)) {
698 /* SSLfatal() already called */
699 return MSG_PROCESS_ERROR;
702 return MSG_PROCESS_FINISHED_READING;
706 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
709 int ssl3_take_mac(SSL_CONNECTION *s)
713 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
716 sender = ssl->method->ssl3_enc->server_finished_label;
717 slen = ssl->method->ssl3_enc->server_finished_label_len;
719 sender = ssl->method->ssl3_enc->client_finished_label;
720 slen = ssl->method->ssl3_enc->client_finished_label_len;
723 s->s3.tmp.peer_finish_md_len =
724 ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
725 s->s3.tmp.peer_finish_md);
727 if (s->s3.tmp.peer_finish_md_len == 0) {
728 /* SSLfatal() already called */
735 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
740 remain = PACKET_remaining(pkt);
742 * 'Change Cipher Spec' is just a single byte, which should already have
743 * been consumed by ssl_get_message() so there should be no bytes left,
744 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
746 if (SSL_CONNECTION_IS_DTLS(s)) {
747 if ((s->version == DTLS1_BAD_VER
748 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
749 || (s->version != DTLS1_BAD_VER
750 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
751 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
752 return MSG_PROCESS_ERROR;
756 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
757 return MSG_PROCESS_ERROR;
761 /* Check we have a cipher to change to */
762 if (s->s3.tmp.new_cipher == NULL) {
763 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
764 return MSG_PROCESS_ERROR;
767 s->s3.change_cipher_spec = 1;
768 if (!ssl3_do_change_cipher_spec(s)) {
769 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
770 return MSG_PROCESS_ERROR;
773 if (SSL_CONNECTION_IS_DTLS(s)) {
774 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
776 if (s->version == DTLS1_BAD_VER)
777 s->d1->handshake_read_seq++;
779 #ifndef OPENSSL_NO_SCTP
781 * Remember that a CCS has been received, so that an old key of
782 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
785 BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
786 BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
790 return MSG_PROCESS_CONTINUE_READING;
793 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
796 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
799 /* This is a real handshake so make sure we clean it up at the end */
802 * To get this far we must have read encrypted data from the client. We
803 * no longer tolerate unencrypted alerts. This value is ignored if less
806 s->statem.enc_read_state = ENC_READ_STATE_VALID;
807 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
808 s->statem.cleanuphand = 1;
809 if (SSL_CONNECTION_IS_TLS13(s)
810 && !tls13_save_handshake_digest_for_pha(s)) {
811 /* SSLfatal() already called */
812 return MSG_PROCESS_ERROR;
817 * In TLSv1.3 a Finished message signals a key change so the end of the
818 * message must be on a record boundary.
820 if (SSL_CONNECTION_IS_TLS13(s)
821 && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
822 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
823 return MSG_PROCESS_ERROR;
826 /* If this occurs, we have missed a message */
827 if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
828 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
829 return MSG_PROCESS_ERROR;
831 s->s3.change_cipher_spec = 0;
833 md_len = s->s3.tmp.peer_finish_md_len;
835 if (md_len != PACKET_remaining(pkt)) {
836 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
837 return MSG_PROCESS_ERROR;
840 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
842 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
843 return MSG_PROCESS_ERROR;
847 * Copy the finished so we can use it for renegotiation checks
849 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
850 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
851 return MSG_PROCESS_ERROR;
854 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
856 s->s3.previous_client_finished_len = md_len;
858 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
860 s->s3.previous_server_finished_len = md_len;
864 * In TLS1.3 we also have to change cipher state and do any final processing
865 * of the initial server flight (if we are a client)
867 if (SSL_CONNECTION_IS_TLS13(s)) {
869 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
870 !ssl->method->ssl3_enc->change_cipher_state(s,
871 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
872 /* SSLfatal() already called */
873 return MSG_PROCESS_ERROR;
876 /* TLS 1.3 gets the secret size from the handshake md */
878 if (!ssl->method->ssl3_enc->generate_master_secret(s,
879 s->master_secret, s->handshake_secret, 0,
881 /* SSLfatal() already called */
882 return MSG_PROCESS_ERROR;
884 if (!ssl->method->ssl3_enc->change_cipher_state(s,
885 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
886 /* SSLfatal() already called */
887 return MSG_PROCESS_ERROR;
889 if (!tls_process_initial_server_flight(s)) {
890 /* SSLfatal() already called */
891 return MSG_PROCESS_ERROR;
896 return MSG_PROCESS_FINISHED_READING;
899 int tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
901 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
902 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
909 /* Add a certificate to the WPACKET */
910 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
914 unsigned char *outbytes;
916 len = i2d_X509(x, NULL);
918 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
921 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
922 || i2d_X509(x, &outbytes) != len) {
923 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
927 if (SSL_CONNECTION_IS_TLS13(s)
928 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
930 /* SSLfatal() already called */
937 /* Add certificate chain to provided WPACKET */
938 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk)
942 STACK_OF(X509) *extra_certs;
943 STACK_OF(X509) *chain = NULL;
944 X509_STORE *chain_store;
945 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
947 if (cpk == NULL || cpk->x509 == NULL)
953 * If we have a certificate specific chain use it, else use parent ctx.
955 if (cpk->chain != NULL)
956 extra_certs = cpk->chain;
958 extra_certs = sctx->extra_certs;
960 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
962 else if (s->cert->chain_store)
963 chain_store = s->cert->chain_store;
965 chain_store = sctx->cert_store;
967 if (chain_store != NULL) {
968 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
971 if (xs_ctx == NULL) {
972 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
975 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
976 X509_STORE_CTX_free(xs_ctx);
977 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
981 * It is valid for the chain not to be complete (because normally we
982 * don't include the root cert in the chain). Therefore we deliberately
983 * ignore the error return from this call. We're not actually verifying
984 * the cert - we're just building as much of the chain as we can
986 (void)X509_verify_cert(xs_ctx);
987 /* Don't leave errors in the queue */
989 chain = X509_STORE_CTX_get0_chain(xs_ctx);
990 i = ssl_security_cert_chain(s, chain, NULL, 0);
993 /* Dummy error calls so mkerr generates them */
994 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
995 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
996 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
998 X509_STORE_CTX_free(xs_ctx);
999 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1002 chain_count = sk_X509_num(chain);
1003 for (i = 0; i < chain_count; i++) {
1004 x = sk_X509_value(chain, i);
1006 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1007 /* SSLfatal() already called */
1008 X509_STORE_CTX_free(xs_ctx);
1012 X509_STORE_CTX_free(xs_ctx);
1014 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1016 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1019 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1020 /* SSLfatal() already called */
1023 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1024 x = sk_X509_value(extra_certs, i);
1025 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1026 /* SSLfatal() already called */
1034 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1037 if (!WPACKET_start_sub_packet_u24(pkt)) {
1038 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1042 if (!ssl_add_cert_chain(s, pkt, cpk))
1045 if (!WPACKET_close(pkt)) {
1046 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1054 * Tidy up after the end of a handshake. In the case of SCTP this may result
1055 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1058 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1059 int clearbufs, int stop)
1061 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1062 int cleanuphand = s->statem.cleanuphand;
1063 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1064 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1067 if (!SSL_CONNECTION_IS_DTLS(s)
1068 #ifndef OPENSSL_NO_SCTP
1070 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1071 * messages that require it. Therefore, DTLS procedures for retransmissions
1073 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1075 || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1079 * We don't do this in DTLS over UDP because we may still need the init_buf
1080 * in case there are any unexpected retransmits
1082 BUF_MEM_free(s->init_buf);
1086 if (!ssl_free_wbio_buffer(s)) {
1087 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1093 if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1094 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1095 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1098 * Only set if there was a Finished message and this isn't after a TLSv1.3
1099 * post handshake exchange
1102 /* skipped if we just sent a HelloRequest */
1105 s->statem.cleanuphand = 0;
1106 s->ext.ticket_expected = 0;
1108 ssl3_cleanup_key_block(s);
1112 * In TLSv1.3 we update the cache as part of constructing the
1115 if (!SSL_CONNECTION_IS_TLS13(s))
1116 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1118 /* N.B. s->ctx may not equal s->session_ctx */
1119 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1120 s->handshake_func = ossl_statem_accept;
1122 if (SSL_CONNECTION_IS_TLS13(s)) {
1124 * We encourage applications to only use TLSv1.3 tickets once,
1125 * so we remove this one from the cache.
1127 if ((s->session_ctx->session_cache_mode
1128 & SSL_SESS_CACHE_CLIENT) != 0)
1129 SSL_CTX_remove_session(s->session_ctx, s->session);
1132 * In TLSv1.3 we update the cache as part of processing the
1135 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1138 ssl_tsan_counter(s->session_ctx,
1139 &s->session_ctx->stats.sess_hit);
1141 s->handshake_func = ossl_statem_connect;
1142 ssl_tsan_counter(s->session_ctx,
1143 &s->session_ctx->stats.sess_connect_good);
1146 if (SSL_CONNECTION_IS_DTLS(s)) {
1147 /* done with handshaking */
1148 s->d1->handshake_read_seq = 0;
1149 s->d1->handshake_write_seq = 0;
1150 s->d1->next_handshake_write_seq = 0;
1151 dtls1_clear_received_buffer(s);
1155 if (s->info_callback != NULL)
1156 cb = s->info_callback;
1157 else if (sctx->info_callback != NULL)
1158 cb = sctx->info_callback;
1160 /* The callback may expect us to not be in init at handshake done */
1161 ossl_statem_set_in_init(s, 0);
1165 || !SSL_CONNECTION_IS_TLS13(s)
1166 || SSL_IS_FIRST_HANDSHAKE(s))
1167 cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1171 /* If we've got more work to do we go back into init */
1172 ossl_statem_set_in_init(s, 1);
1173 return WORK_FINISHED_CONTINUE;
1176 return WORK_FINISHED_STOP;
1179 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1181 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1182 int skip_message, i, recvd_type;
1184 size_t l, readbytes;
1185 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1187 p = (unsigned char *)s->init_buf->data;
1190 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1191 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1193 SSL3_HM_HEADER_LENGTH - s->init_num,
1196 s->rwstate = SSL_READING;
1199 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1201 * A ChangeCipherSpec must be a single byte and may not occur
1202 * in the middle of a handshake message.
1204 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1205 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1206 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1209 if (s->statem.hand_state == TLS_ST_BEFORE
1210 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1212 * We are stateless and we received a CCS. Probably this is
1213 * from a client between the first and second ClientHellos.
1214 * We should ignore this, but return an error because we do
1215 * not return success until we see the second ClientHello
1216 * with a valid cookie.
1220 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1221 s->init_num = readbytes - 1;
1222 s->init_msg = s->init_buf->data;
1223 s->s3.tmp.message_size = readbytes;
1225 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1226 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1227 SSL_R_CCS_RECEIVED_EARLY);
1230 s->init_num += readbytes;
1235 if (s->statem.hand_state != TLS_ST_OK
1236 && p[0] == SSL3_MT_HELLO_REQUEST)
1238 * The server may always send 'Hello Request' messages --
1239 * we are doing a handshake anyway now, so ignore them if
1240 * their format is correct. Does not count for 'Finished'
1243 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1247 if (s->msg_callback)
1248 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1249 p, SSL3_HM_HEADER_LENGTH, ssl,
1250 s->msg_callback_arg);
1252 } while (skip_message);
1253 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1256 s->s3.tmp.message_type = *(p++);
1258 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1260 * Only happens with SSLv3+ in an SSLv2 backward compatible
1263 * Total message size is the remaining record bytes to read
1264 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1266 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1267 + SSL3_HM_HEADER_LENGTH;
1268 s->s3.tmp.message_size = l;
1270 s->init_msg = s->init_buf->data;
1271 s->init_num = SSL3_HM_HEADER_LENGTH;
1274 /* BUF_MEM_grow takes an 'int' parameter */
1275 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1276 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1277 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1280 s->s3.tmp.message_size = l;
1282 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1289 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1291 size_t n, readbytes;
1294 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1296 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1297 /* We've already read everything in */
1298 *len = (unsigned long)s->init_num;
1303 n = s->s3.tmp.message_size - s->init_num;
1305 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1306 &p[s->init_num], n, 0, &readbytes);
1308 s->rwstate = SSL_READING;
1312 s->init_num += readbytes;
1317 * If receiving Finished, record MAC of prior handshake messages for
1318 * Finished verification.
1320 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1321 /* SSLfatal() already called */
1326 /* Feed this message into MAC computation. */
1327 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1328 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1330 /* SSLfatal() already called */
1334 if (s->msg_callback)
1335 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1336 (size_t)s->init_num, ssl, s->msg_callback_arg);
1339 * We defer feeding in the HRR until later. We'll do it as part of
1340 * processing the message
1341 * The TLsv1.3 handshake transcript stops at the ClientFinished
1344 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1345 /* KeyUpdate and NewSessionTicket do not need to be added */
1346 if (!SSL_CONNECTION_IS_TLS13(s)
1347 || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1348 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1349 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1350 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1351 || memcmp(hrrrandom,
1352 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1353 SSL3_RANDOM_SIZE) != 0) {
1354 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1355 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1356 /* SSLfatal() already called */
1362 if (s->msg_callback)
1363 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1364 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1365 s->msg_callback_arg);
1372 static const X509ERR2ALERT x509table[] = {
1373 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1374 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1375 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1376 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1377 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1378 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1379 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1380 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1381 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1382 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1383 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1384 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1385 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1386 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1387 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1388 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1389 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1390 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1391 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1392 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1393 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1394 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1395 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1396 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1397 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1398 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1399 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1400 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1401 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1402 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1403 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1404 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1405 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1406 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1407 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1408 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1409 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1410 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1411 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1412 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1414 /* Last entry; return this if we don't find the value above. */
1415 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1418 int ssl_x509err2alert(int x509err)
1420 const X509ERR2ALERT *tp;
1422 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1423 if (tp->x509err == x509err)
1428 int ssl_allow_compression(SSL_CONNECTION *s)
1430 if (s->options & SSL_OP_NO_COMPRESSION)
1432 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1435 static int version_cmp(const SSL_CONNECTION *s, int a, int b)
1437 int dtls = SSL_CONNECTION_IS_DTLS(s);
1442 return a < b ? -1 : 1;
1443 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1448 const SSL_METHOD *(*cmeth) (void);
1449 const SSL_METHOD *(*smeth) (void);
1452 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1453 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1456 /* Must be in order high to low */
1457 static const version_info tls_version_table[] = {
1458 #ifndef OPENSSL_NO_TLS1_3
1459 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1461 {TLS1_3_VERSION, NULL, NULL},
1463 #ifndef OPENSSL_NO_TLS1_2
1464 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1466 {TLS1_2_VERSION, NULL, NULL},
1468 #ifndef OPENSSL_NO_TLS1_1
1469 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1471 {TLS1_1_VERSION, NULL, NULL},
1473 #ifndef OPENSSL_NO_TLS1
1474 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1476 {TLS1_VERSION, NULL, NULL},
1478 #ifndef OPENSSL_NO_SSL3
1479 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1481 {SSL3_VERSION, NULL, NULL},
1486 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1487 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1490 /* Must be in order high to low */
1491 static const version_info dtls_version_table[] = {
1492 #ifndef OPENSSL_NO_DTLS1_2
1493 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1495 {DTLS1_2_VERSION, NULL, NULL},
1497 #ifndef OPENSSL_NO_DTLS1
1498 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1499 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1501 {DTLS1_VERSION, NULL, NULL},
1502 {DTLS1_BAD_VER, NULL, NULL},
1508 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1510 * @s: The SSL handle for the candidate method
1511 * @method: the intended method.
1513 * Returns 0 on success, or an SSL error reason on failure.
1515 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1517 int version = method->version;
1519 if ((s->min_proto_version != 0 &&
1520 version_cmp(s, version, s->min_proto_version) < 0) ||
1521 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1522 return SSL_R_VERSION_TOO_LOW;
1524 if (s->max_proto_version != 0 &&
1525 version_cmp(s, version, s->max_proto_version) > 0)
1526 return SSL_R_VERSION_TOO_HIGH;
1528 if ((s->options & method->mask) != 0)
1529 return SSL_R_UNSUPPORTED_PROTOCOL;
1530 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1531 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1537 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1538 * certificate type, or has PSK or a certificate callback configured, or has
1539 * a servername callback configure. Otherwise returns 0.
1541 static int is_tls13_capable(const SSL_CONNECTION *s)
1545 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1547 if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1551 * A servername callback can change the available certs, so if a servername
1552 * cb is set then we just assume TLSv1.3 will be ok
1554 if (sctx->ext.servername_cb != NULL
1555 || s->session_ctx->ext.servername_cb != NULL)
1558 #ifndef OPENSSL_NO_PSK
1559 if (s->psk_server_callback != NULL)
1563 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1566 for (i = 0; i < SSL_PKEY_NUM; i++) {
1567 /* Skip over certs disallowed for TLSv1.3 */
1569 case SSL_PKEY_DSA_SIGN:
1570 case SSL_PKEY_GOST01:
1571 case SSL_PKEY_GOST12_256:
1572 case SSL_PKEY_GOST12_512:
1577 if (!ssl_has_cert(s, i))
1579 if (i != SSL_PKEY_ECC)
1582 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1583 * more restrictive so check that our sig algs are consistent with this
1584 * EC cert. See section 4.2.3 of RFC8446.
1586 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1587 if (tls_check_sigalg_curve(s, curve))
1595 * ssl_version_supported - Check that the specified `version` is supported by
1598 * @s: The SSL handle for the candidate method
1599 * @version: Protocol version to test against
1601 * Returns 1 when supported, otherwise 0
1603 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1604 const SSL_METHOD **meth)
1606 const version_info *vent;
1607 const version_info *table;
1609 switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1611 /* Version should match method version for non-ANY method */
1612 return version_cmp(s, version, s->version) == 0;
1613 case TLS_ANY_VERSION:
1614 table = tls_version_table;
1616 case DTLS_ANY_VERSION:
1617 table = dtls_version_table;
1622 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1624 if (vent->cmeth != NULL
1625 && version_cmp(s, version, vent->version) == 0
1626 && ssl_method_error(s, vent->cmeth()) == 0
1628 || version != TLS1_3_VERSION
1629 || is_tls13_capable(s))) {
1631 *meth = vent->cmeth();
1639 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1640 * fallback indication from a client check whether we're using the highest
1641 * supported protocol version.
1643 * @s server SSL handle.
1645 * Returns 1 when using the highest enabled version, 0 otherwise.
1647 int ssl_check_version_downgrade(SSL_CONNECTION *s)
1649 const version_info *vent;
1650 const version_info *table;
1651 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1654 * Check that the current protocol is the highest enabled version
1655 * (according to s->ctx->method, as version negotiation may have changed
1658 if (s->version == sctx->method->version)
1662 * Apparently we're using a version-flexible SSL_METHOD (not at its
1663 * highest protocol version).
1665 if (sctx->method->version == TLS_method()->version)
1666 table = tls_version_table;
1667 else if (sctx->method->version == DTLS_method()->version)
1668 table = dtls_version_table;
1670 /* Unexpected state; fail closed. */
1674 for (vent = table; vent->version != 0; ++vent) {
1675 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1676 return s->version == vent->version;
1682 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1683 * protocols, provided the initial (D)TLS method is version-flexible. This
1684 * function sanity-checks the proposed value and makes sure the method is
1685 * version-flexible, then sets the limit if all is well.
1687 * @method_version: The version of the current SSL_METHOD.
1688 * @version: the intended limit.
1689 * @bound: pointer to limit to be updated.
1691 * Returns 1 on success, 0 on failure.
1693 int ssl_set_version_bound(int method_version, int version, int *bound)
1703 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1705 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1706 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1708 if (!valid_tls && !valid_dtls)
1712 * Restrict TLS methods to TLS protocol versions.
1713 * Restrict DTLS methods to DTLS protocol versions.
1714 * Note, DTLS version numbers are decreasing, use comparison macros.
1716 * Note that for both lower-bounds we use explicit versions, not
1717 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1718 * configurations. If the MIN (supported) version ever rises, the user's
1719 * "floor" remains valid even if no longer available. We don't expect the
1720 * MAX ceiling to ever get lower, so making that variable makes sense.
1722 * We ignore attempts to set bounds on version-inflexible methods,
1723 * returning success.
1725 switch (method_version) {
1729 case TLS_ANY_VERSION:
1734 case DTLS_ANY_VERSION:
1742 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
1744 if (vers == TLS1_2_VERSION
1745 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1746 *dgrd = DOWNGRADE_TO_1_2;
1747 } else if (!SSL_CONNECTION_IS_DTLS(s)
1748 && vers < TLS1_2_VERSION
1750 * We need to ensure that a server that disables TLSv1.2
1751 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1752 * complete handshakes with clients that support TLSv1.2 and
1753 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1754 * enabled and TLSv1.2 is not.
1756 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1757 *dgrd = DOWNGRADE_TO_1_1;
1759 *dgrd = DOWNGRADE_NONE;
1764 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1765 * client HELLO is received to select the final server protocol version and
1766 * the version specific method.
1768 * @s: server SSL handle.
1770 * Returns 0 on success or an SSL error reason number on failure.
1772 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
1776 * With version-flexible methods we have an initial state with:
1778 * s->method->version == (D)TLS_ANY_VERSION,
1779 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1781 * So we detect version-flexible methods via the method version, not the
1784 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1785 int server_version = ssl->method->version;
1786 int client_version = hello->legacy_version;
1787 const version_info *vent;
1788 const version_info *table;
1790 RAW_EXTENSION *suppversions;
1792 s->client_version = client_version;
1794 switch (server_version) {
1796 if (!SSL_CONNECTION_IS_TLS13(s)) {
1797 if (version_cmp(s, client_version, s->version) < 0)
1798 return SSL_R_WRONG_SSL_VERSION;
1799 *dgrd = DOWNGRADE_NONE;
1801 * If this SSL handle is not from a version flexible method we don't
1802 * (and never did) check min/max FIPS or Suite B constraints. Hope
1803 * that's OK. It is up to the caller to not choose fixed protocol
1804 * versions they don't want. If not, then easy to fix, just return
1805 * ssl_method_error(s, s->method)
1810 * Fall through if we are TLSv1.3 already (this means we must be after
1811 * a HelloRetryRequest
1814 case TLS_ANY_VERSION:
1815 table = tls_version_table;
1817 case DTLS_ANY_VERSION:
1818 table = dtls_version_table;
1822 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1824 /* If we did an HRR then supported versions is mandatory */
1825 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1826 return SSL_R_UNSUPPORTED_PROTOCOL;
1828 if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
1829 unsigned int candidate_vers = 0;
1830 unsigned int best_vers = 0;
1831 const SSL_METHOD *best_method = NULL;
1832 PACKET versionslist;
1834 suppversions->parsed = 1;
1836 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1837 /* Trailing or invalid data? */
1838 return SSL_R_LENGTH_MISMATCH;
1842 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1843 * The spec only requires servers to check that it isn't SSLv3:
1844 * "Any endpoint receiving a Hello message with
1845 * ClientHello.legacy_version or ServerHello.legacy_version set to
1846 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1847 * We are slightly stricter and require that it isn't SSLv3 or lower.
1848 * We tolerate TLSv1 and TLSv1.1.
1850 if (client_version <= SSL3_VERSION)
1851 return SSL_R_BAD_LEGACY_VERSION;
1853 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1854 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1856 if (ssl_version_supported(s, candidate_vers, &best_method))
1857 best_vers = candidate_vers;
1859 if (PACKET_remaining(&versionslist) != 0) {
1860 /* Trailing data? */
1861 return SSL_R_LENGTH_MISMATCH;
1864 if (best_vers > 0) {
1865 if (s->hello_retry_request != SSL_HRR_NONE) {
1867 * This is after a HelloRetryRequest so we better check that we
1868 * negotiated TLSv1.3
1870 if (best_vers != TLS1_3_VERSION)
1871 return SSL_R_UNSUPPORTED_PROTOCOL;
1874 check_for_downgrade(s, best_vers, dgrd);
1875 s->version = best_vers;
1876 ssl->method = best_method;
1879 return SSL_R_UNSUPPORTED_PROTOCOL;
1883 * If the supported versions extension isn't present, then the highest
1884 * version we can negotiate is TLSv1.2
1886 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1887 client_version = TLS1_2_VERSION;
1890 * No supported versions extension, so we just use the version supplied in
1893 for (vent = table; vent->version != 0; ++vent) {
1894 const SSL_METHOD *method;
1896 if (vent->smeth == NULL ||
1897 version_cmp(s, client_version, vent->version) < 0)
1899 method = vent->smeth();
1900 if (ssl_method_error(s, method) == 0) {
1901 check_for_downgrade(s, vent->version, dgrd);
1902 s->version = vent->version;
1903 ssl->method = method;
1908 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1912 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1913 * server HELLO is received to select the final client protocol version and
1914 * the version specific method.
1916 * @s: client SSL handle.
1917 * @version: The proposed version from the server's HELLO.
1918 * @extensions: The extensions received
1920 * Returns 1 on success or 0 on error.
1922 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
1923 RAW_EXTENSION *extensions)
1925 const version_info *vent;
1926 const version_info *table;
1927 int ret, ver_min, ver_max, real_max, origv;
1928 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1931 s->version = version;
1933 /* This will overwrite s->version if the extension is present */
1934 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1935 SSL_EXT_TLS1_2_SERVER_HELLO
1936 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1942 if (s->hello_retry_request != SSL_HRR_NONE
1943 && s->version != TLS1_3_VERSION) {
1945 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1949 switch (ssl->method->version) {
1951 if (s->version != ssl->method->version) {
1953 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1957 * If this SSL handle is not from a version flexible method we don't
1958 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1959 * that's OK. It is up to the caller to not choose fixed protocol
1960 * versions they don't want. If not, then easy to fix, just return
1961 * ssl_method_error(s, s->method)
1964 case TLS_ANY_VERSION:
1965 table = tls_version_table;
1967 case DTLS_ANY_VERSION:
1968 table = dtls_version_table;
1972 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1975 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
1978 if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1979 : s->version < ver_min) {
1981 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1983 } else if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1984 : s->version > ver_max) {
1986 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1990 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1993 /* Check for downgrades */
1994 if (s->version == TLS1_2_VERSION && real_max > s->version) {
1995 if (memcmp(tls12downgrade,
1996 s->s3.server_random + SSL3_RANDOM_SIZE
1997 - sizeof(tls12downgrade),
1998 sizeof(tls12downgrade)) == 0) {
2000 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2001 SSL_R_INAPPROPRIATE_FALLBACK);
2004 } else if (!SSL_CONNECTION_IS_DTLS(s)
2005 && s->version < TLS1_2_VERSION
2006 && real_max > s->version) {
2007 if (memcmp(tls11downgrade,
2008 s->s3.server_random + SSL3_RANDOM_SIZE
2009 - sizeof(tls11downgrade),
2010 sizeof(tls11downgrade)) == 0) {
2012 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2013 SSL_R_INAPPROPRIATE_FALLBACK);
2018 for (vent = table; vent->version != 0; ++vent) {
2019 if (vent->cmeth == NULL || s->version != vent->version)
2022 ssl->method = vent->cmeth();
2027 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2032 * ssl_get_min_max_version - get minimum and maximum protocol version
2033 * @s: The SSL connection
2034 * @min_version: The minimum supported version
2035 * @max_version: The maximum supported version
2036 * @real_max: The highest version below the lowest compile time version hole
2037 * where that hole lies above at least one run-time enabled
2040 * Work out what version we should be using for the initial ClientHello if the
2041 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2042 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2043 * constraints and any floor imposed by the security level here,
2044 * so we don't advertise the wrong protocol version to only reject the outcome later.
2046 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2047 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2048 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2050 * Returns 0 on success or an SSL error reason number on failure. On failure
2051 * min_version and max_version will also be set to 0.
2053 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2054 int *max_version, int *real_max)
2056 int version, tmp_real_max;
2058 const SSL_METHOD *single = NULL;
2059 const SSL_METHOD *method;
2060 const version_info *table;
2061 const version_info *vent;
2062 const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2064 switch (ssl->method->version) {
2067 * If this SSL handle is not from a version flexible method we don't
2068 * (and never did) check min/max FIPS or Suite B constraints. Hope
2069 * that's OK. It is up to the caller to not choose fixed protocol
2070 * versions they don't want. If not, then easy to fix, just return
2071 * ssl_method_error(s, s->method)
2073 *min_version = *max_version = s->version;
2075 * Providing a real_max only makes sense where we're using a version
2078 if (!ossl_assert(real_max == NULL))
2079 return ERR_R_INTERNAL_ERROR;
2081 case TLS_ANY_VERSION:
2082 table = tls_version_table;
2084 case DTLS_ANY_VERSION:
2085 table = dtls_version_table;
2090 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2091 * below X enabled. This is required in order to maintain the "version
2092 * capability" vector contiguous. Any versions with a NULL client method
2093 * (protocol version client is disabled at compile-time) is also a "hole".
2095 * Our initial state is hole == 1, version == 0. That is, versions above
2096 * the first version in the method table are disabled (a "hole" above
2097 * the valid protocol entries) and we don't have a selected version yet.
2099 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2100 * the selected version, and the method becomes a candidate "single"
2101 * method. We're no longer in a hole, so "hole" becomes 0.
2103 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2104 * as we support a contiguous range of at least two methods. If we hit
2105 * a disabled method, then hole becomes true again, but nothing else
2106 * changes yet, because all the remaining methods may be disabled too.
2107 * If we again hit an enabled method after the new hole, it becomes
2108 * selected, as we start from scratch.
2110 *min_version = version = 0;
2112 if (real_max != NULL)
2115 for (vent = table; vent->version != 0; ++vent) {
2117 * A table entry with a NULL client method is still a hole in the
2118 * "version capability" vector.
2120 if (vent->cmeth == NULL) {
2125 method = vent->cmeth();
2127 if (hole == 1 && tmp_real_max == 0)
2128 tmp_real_max = vent->version;
2130 if (ssl_method_error(s, method) != 0) {
2134 *min_version = method->version;
2136 if (real_max != NULL && tmp_real_max != 0)
2137 *real_max = tmp_real_max;
2138 version = (single = method)->version;
2139 *min_version = version;
2144 *max_version = version;
2146 /* Fail if everything is disabled */
2148 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2154 * ssl_set_client_hello_version - Work out what version we should be using for
2155 * the initial ClientHello.legacy_version field.
2157 * @s: client SSL handle.
2159 * Returns 0 on success or an SSL error reason number on failure.
2161 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2163 int ver_min, ver_max, ret;
2166 * In a renegotiation we always send the same client_version that we sent
2167 * last time, regardless of which version we eventually negotiated.
2169 if (!SSL_IS_FIRST_HANDSHAKE(s))
2172 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2177 s->version = ver_max;
2179 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2180 if (!SSL_CONNECTION_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2181 ver_max = TLS1_2_VERSION;
2183 s->client_version = ver_max;
2188 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2189 * and |checkallow| is 1 then additionally check if the group is allowed to be
2190 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2191 * 1) or 0 otherwise.
2193 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2194 size_t num_groups, int checkallow)
2198 if (groups == NULL || num_groups == 0)
2201 if (checkallow == 1)
2202 group_id = ssl_group_id_tls13_to_internal(group_id);
2204 for (i = 0; i < num_groups; i++) {
2205 uint16_t group = groups[i];
2207 if (checkallow == 2)
2208 group = ssl_group_id_tls13_to_internal(group);
2210 if (group_id == group
2212 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2220 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2221 int create_synthetic_message_hash(SSL_CONNECTION *s,
2222 const unsigned char *hashval,
2223 size_t hashlen, const unsigned char *hrr,
2226 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2227 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2229 memset(msghdr, 0, sizeof(msghdr));
2231 if (hashval == NULL) {
2232 hashval = hashvaltmp;
2234 /* Get the hash of the initial ClientHello */
2235 if (!ssl3_digest_cached_records(s, 0)
2236 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2238 /* SSLfatal() already called */
2243 /* Reinitialise the transcript hash */
2244 if (!ssl3_init_finished_mac(s)) {
2245 /* SSLfatal() already called */
2249 /* Inject the synthetic message_hash message */
2250 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2251 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2252 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2253 || !ssl3_finish_mac(s, hashval, hashlen)) {
2254 /* SSLfatal() already called */
2259 * Now re-inject the HRR and current message if appropriate (we just deleted
2260 * it when we reinitialised the transcript hash above). Only necessary after
2261 * receiving a ClientHello2 with a cookie.
2264 && (!ssl3_finish_mac(s, hrr, hrrlen)
2265 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2266 s->s3.tmp.message_size
2267 + SSL3_HM_HEADER_LENGTH))) {
2268 /* SSLfatal() already called */
2275 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2277 return X509_NAME_cmp(*a, *b);
2280 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2282 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2283 X509_NAME *xn = NULL;
2286 if (ca_sk == NULL) {
2287 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2290 /* get the CA RDNs */
2291 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2292 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2296 while (PACKET_remaining(&cadns)) {
2297 const unsigned char *namestart, *namebytes;
2298 unsigned int name_len;
2300 if (!PACKET_get_net_2(&cadns, &name_len)
2301 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2302 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2306 namestart = namebytes;
2307 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2308 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2311 if (namebytes != (namestart + name_len)) {
2312 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2316 if (!sk_X509_NAME_push(ca_sk, xn)) {
2317 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2323 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2324 s->s3.tmp.peer_ca_names = ca_sk;
2329 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2334 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2336 const STACK_OF(X509_NAME) *ca_sk = NULL;
2337 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2340 ca_sk = SSL_get_client_CA_list(ssl);
2341 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2346 ca_sk = SSL_get0_CA_list(ssl);
2351 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2354 /* Start sub-packet for client CA list */
2355 if (!WPACKET_start_sub_packet_u16(pkt)) {
2356 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2360 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2363 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2364 unsigned char *namebytes;
2365 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2369 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2370 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2372 || i2d_X509_NAME(name, &namebytes) != namelen) {
2373 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2379 if (!WPACKET_close(pkt)) {
2380 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2387 /* Create a buffer containing data to be signed for server key exchange */
2388 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2389 const void *param, size_t paramlen)
2391 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2392 unsigned char *tbs = OPENSSL_malloc(tbslen);
2395 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2398 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2399 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2401 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2408 * Saves the current handshake digest for Post-Handshake Auth,
2409 * Done after ClientFinished is processed, done exactly once
2411 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2413 if (s->pha_dgst == NULL) {
2414 if (!ssl3_digest_cached_records(s, 1))
2415 /* SSLfatal() already called */
2418 s->pha_dgst = EVP_MD_CTX_new();
2419 if (s->pha_dgst == NULL) {
2420 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2423 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2424 s->s3.handshake_dgst)) {
2425 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2426 EVP_MD_CTX_free(s->pha_dgst);
2435 * Restores the Post-Handshake Auth handshake digest
2436 * Done just before sending/processing the Cert Request
2438 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2440 if (s->pha_dgst == NULL) {
2441 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2444 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2446 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);