2 * Copyright 1995-2020 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 "internal/evp.h"
18 #include <openssl/buffer.h>
19 #include <openssl/objects.h>
20 #include <openssl/evp.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_INTERNAL_ERROR, SSL_F_TLS_SETUP_HANDSHAKE,
105 ERR_R_INTERNAL_ERROR);
109 /* Sanity check that we have MD5-SHA1 if we need it */
110 if (s->ctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
111 int md5sha1_needed = 0;
113 /* We don't have MD5-SHA1 - do we need it? */
114 if (SSL_IS_DTLS(s)) {
115 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
118 if (ver_max <= TLS1_1_VERSION)
121 if (md5sha1_needed) {
122 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
123 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);
124 ERR_add_error_data(1, "The max supported SSL/TLS version needs the"
125 " MD5-SHA1 digest but it is not available"
126 " in the loaded providers. Use (D)TLSv1.2 or"
127 " above, or load different providers");
132 /* Don't allow TLSv1.1 or below to be negotiated */
133 if (SSL_IS_DTLS(s)) {
134 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
135 ok = SSL_set_min_proto_version(s, DTLS1_2_VERSION);
137 if (ver_min < TLS1_2_VERSION)
138 ok = SSL_set_min_proto_version(s, TLS1_2_VERSION);
141 /* Shouldn't happen */
142 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
143 ERR_R_INTERNAL_ERROR);
150 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
154 * Sanity check that the maximum version we accept has ciphers
155 * enabled. For clients we do this check during construction of the
158 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
159 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
161 if (SSL_IS_DTLS(s)) {
162 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
163 DTLS_VERSION_LE(ver_max, c->max_dtls))
165 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
172 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
173 SSL_R_NO_CIPHERS_AVAILABLE);
174 ERR_add_error_data(1, "No ciphers enabled for max supported "
178 if (SSL_IS_FIRST_HANDSHAKE(s)) {
179 /* N.B. s->session_ctx == s->ctx here */
180 tsan_counter(&s->session_ctx->stats.sess_accept);
182 /* N.B. s->ctx may not equal s->session_ctx */
183 tsan_counter(&s->ctx->stats.sess_accept_renegotiate);
185 s->s3.tmp.cert_request = 0;
188 if (SSL_IS_FIRST_HANDSHAKE(s))
189 tsan_counter(&s->session_ctx->stats.sess_connect);
191 tsan_counter(&s->session_ctx->stats.sess_connect_renegotiate);
193 /* mark client_random uninitialized */
194 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
197 s->s3.tmp.cert_req = 0;
200 s->statem.use_timer = 1;
207 * Size of the to-be-signed TLS13 data, without the hash size itself:
208 * 64 bytes of value 32, 33 context bytes, 1 byte separator
210 #define TLS13_TBS_START_SIZE 64
211 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
213 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
214 void **hdata, size_t *hdatalen)
216 #ifdef CHARSET_EBCDIC
217 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
218 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
219 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
220 0x69, 0x66, 0x79, 0x00 };
221 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
222 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
223 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
224 0x69, 0x66, 0x79, 0x00 };
226 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
227 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
229 if (SSL_IS_TLS13(s)) {
232 /* Set the first 64 bytes of to-be-signed data to octet 32 */
233 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
234 /* This copies the 33 bytes of context plus the 0 separator byte */
235 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
236 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
237 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
239 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
242 * If we're currently reading then we need to use the saved handshake
243 * hash value. We can't use the current handshake hash state because
244 * that includes the CertVerify itself.
246 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
247 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
248 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
249 s->cert_verify_hash_len);
250 hashlen = s->cert_verify_hash_len;
251 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
252 EVP_MAX_MD_SIZE, &hashlen)) {
253 /* SSLfatal() already called */
258 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
263 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
265 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
266 ERR_R_INTERNAL_ERROR);
275 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
277 EVP_PKEY *pkey = NULL;
278 const EVP_MD *md = NULL;
279 EVP_MD_CTX *mctx = NULL;
280 EVP_PKEY_CTX *pctx = NULL;
281 size_t hdatalen = 0, siglen = 0;
283 unsigned char *sig = NULL;
284 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
285 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
287 if (lu == NULL || s->s3.tmp.cert == NULL) {
288 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
289 ERR_R_INTERNAL_ERROR);
292 pkey = s->s3.tmp.cert->privatekey;
294 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
295 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
296 ERR_R_INTERNAL_ERROR);
300 mctx = EVP_MD_CTX_new();
302 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
303 ERR_R_MALLOC_FAILURE);
307 /* Get the data to be signed */
308 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
309 /* SSLfatal() already called */
313 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
314 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
315 ERR_R_INTERNAL_ERROR);
319 if (EVP_DigestSignInit_with_libctx(mctx, &pctx,
320 md == NULL ? NULL : EVP_MD_name(md),
321 s->ctx->libctx, s->ctx->propq,
323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
328 if (lu->sig == EVP_PKEY_RSA_PSS) {
329 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
330 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
331 RSA_PSS_SALTLEN_DIGEST) <= 0) {
332 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
337 if (s->version == SSL3_VERSION) {
339 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
340 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
342 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
344 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
345 * with a call to ssl3_digest_master_key_set_params()
347 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
348 (int)s->session->master_key_length,
349 s->session->master_key) <= 0
350 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
352 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
356 sig = OPENSSL_malloc(siglen);
358 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
359 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
365 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
366 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
368 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
369 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
373 sig = OPENSSL_malloc(siglen);
375 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
376 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
382 #ifndef OPENSSL_NO_GOST
384 int pktype = lu->sig;
386 if (pktype == NID_id_GostR3410_2001
387 || pktype == NID_id_GostR3410_2012_256
388 || pktype == NID_id_GostR3410_2012_512)
389 BUF_reverse(sig, NULL, siglen);
393 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
394 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
395 ERR_R_INTERNAL_ERROR);
399 /* Digest cached records and discard handshake buffer */
400 if (!ssl3_digest_cached_records(s, 0)) {
401 /* SSLfatal() already called */
406 EVP_MD_CTX_free(mctx);
410 EVP_MD_CTX_free(mctx);
414 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
416 EVP_PKEY *pkey = NULL;
417 const unsigned char *data;
418 #ifndef OPENSSL_NO_GOST
419 unsigned char *gost_data = NULL;
421 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
425 const EVP_MD *md = NULL;
428 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
429 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
430 EVP_PKEY_CTX *pctx = NULL;
433 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
434 ERR_R_MALLOC_FAILURE);
438 peer = s->session->peer;
439 pkey = X509_get0_pubkey(peer);
441 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
442 ERR_R_INTERNAL_ERROR);
446 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
447 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
448 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
452 if (SSL_USE_SIGALGS(s)) {
455 if (!PACKET_get_net_2(pkt, &sigalg)) {
456 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
460 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
461 /* SSLfatal() already called */
464 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
465 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
466 ERR_R_INTERNAL_ERROR);
470 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
471 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
472 ERR_R_INTERNAL_ERROR);
476 if (SSL_USE_SIGALGS(s))
477 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
478 md == NULL ? "n/a" : EVP_MD_name(md));
480 /* Check for broken implementations of GOST ciphersuites */
482 * If key is GOST and len is exactly 64 or 128, it is signature without
483 * length field (CryptoPro implementations at least till TLS 1.2)
485 #ifndef OPENSSL_NO_GOST
486 if (!SSL_USE_SIGALGS(s)
487 && ((PACKET_remaining(pkt) == 64
488 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
489 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
490 || (PACKET_remaining(pkt) == 128
491 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
492 len = PACKET_remaining(pkt);
495 if (!PACKET_get_net_2(pkt, &len)) {
496 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
497 SSL_R_LENGTH_MISMATCH);
501 if (!PACKET_get_bytes(pkt, &data, len)) {
502 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
503 SSL_R_LENGTH_MISMATCH);
507 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
508 /* SSLfatal() already called */
512 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
513 md == NULL ? "n/a" : EVP_MD_name(md));
515 if (EVP_DigestVerifyInit_with_libctx(mctx, &pctx,
516 md == NULL ? NULL : EVP_MD_name(md),
517 s->ctx->libctx, s->ctx->propq,
519 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
523 #ifndef OPENSSL_NO_GOST
525 int pktype = EVP_PKEY_id(pkey);
526 if (pktype == NID_id_GostR3410_2001
527 || pktype == NID_id_GostR3410_2012_256
528 || pktype == NID_id_GostR3410_2012_512) {
529 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
530 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
531 SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
534 BUF_reverse(gost_data, data, len);
540 if (SSL_USE_PSS(s)) {
541 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
542 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
543 RSA_PSS_SALTLEN_DIGEST) <= 0) {
544 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
549 if (s->version == SSL3_VERSION) {
551 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
552 * with a call to ssl3_digest_master_key_set_params()
554 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
555 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
556 (int)s->session->master_key_length,
557 s->session->master_key) <= 0) {
558 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
562 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
563 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
564 SSL_R_BAD_SIGNATURE);
568 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
570 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
571 SSL_R_BAD_SIGNATURE);
577 * In TLSv1.3 on the client side we make sure we prepare the client
578 * certificate after the CertVerify instead of when we get the
579 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
580 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
581 * want to make sure that SSL_get1_peer_certificate() will return the actual
582 * server certificate from the client_cert_cb callback.
584 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
585 ret = MSG_PROCESS_CONTINUE_PROCESSING;
587 ret = MSG_PROCESS_CONTINUE_READING;
589 BIO_free(s->s3.handshake_buffer);
590 s->s3.handshake_buffer = NULL;
591 EVP_MD_CTX_free(mctx);
592 #ifndef OPENSSL_NO_GOST
593 OPENSSL_free(gost_data);
598 int tls_construct_finished(SSL *s, WPACKET *pkt)
600 size_t finish_md_len;
604 /* This is a real handshake so make sure we clean it up at the end */
605 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
606 s->statem.cleanuphand = 1;
609 * We only change the keys if we didn't already do this when we sent the
614 && s->s3.tmp.cert_req == 0
615 && (!s->method->ssl3_enc->change_cipher_state(s,
616 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
617 /* SSLfatal() already called */
622 sender = s->method->ssl3_enc->server_finished_label;
623 slen = s->method->ssl3_enc->server_finished_label_len;
625 sender = s->method->ssl3_enc->client_finished_label;
626 slen = s->method->ssl3_enc->client_finished_label_len;
629 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
631 s->s3.tmp.finish_md);
632 if (finish_md_len == 0) {
633 /* SSLfatal() already called */
637 s->s3.tmp.finish_md_len = finish_md_len;
639 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
640 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
641 ERR_R_INTERNAL_ERROR);
646 * Log the master secret, if logging is enabled. We don't log it for
647 * TLSv1.3: there's a different key schedule for that.
649 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
650 s->session->master_key,
651 s->session->master_key_length)) {
652 /* SSLfatal() already called */
657 * Copy the finished so we can use it for renegotiation checks
659 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
660 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
661 ERR_R_INTERNAL_ERROR);
665 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
667 s->s3.previous_client_finished_len = finish_md_len;
669 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
671 s->s3.previous_server_finished_len = finish_md_len;
677 int tls_construct_key_update(SSL *s, WPACKET *pkt)
679 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
680 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
681 ERR_R_INTERNAL_ERROR);
685 s->key_update = SSL_KEY_UPDATE_NONE;
689 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
691 unsigned int updatetype;
694 * A KeyUpdate message signals a key change so the end of the message must
695 * be on a record boundary.
697 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
698 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
699 SSL_R_NOT_ON_RECORD_BOUNDARY);
700 return MSG_PROCESS_ERROR;
703 if (!PACKET_get_1(pkt, &updatetype)
704 || PACKET_remaining(pkt) != 0) {
705 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
706 SSL_R_BAD_KEY_UPDATE);
707 return MSG_PROCESS_ERROR;
711 * There are only two defined key update types. Fail if we get a value we
714 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
715 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
716 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
717 SSL_R_BAD_KEY_UPDATE);
718 return MSG_PROCESS_ERROR;
722 * If we get a request for us to update our sending keys too then, we need
723 * to additionally send a KeyUpdate message. However that message should
724 * not also request an update (otherwise we get into an infinite loop).
726 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
727 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
729 if (!tls13_update_key(s, 0)) {
730 /* SSLfatal() already called */
731 return MSG_PROCESS_ERROR;
734 return MSG_PROCESS_FINISHED_READING;
738 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
741 int ssl3_take_mac(SSL *s)
747 sender = s->method->ssl3_enc->server_finished_label;
748 slen = s->method->ssl3_enc->server_finished_label_len;
750 sender = s->method->ssl3_enc->client_finished_label;
751 slen = s->method->ssl3_enc->client_finished_label_len;
754 s->s3.tmp.peer_finish_md_len =
755 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
756 s->s3.tmp.peer_finish_md);
758 if (s->s3.tmp.peer_finish_md_len == 0) {
759 /* SSLfatal() already called */
766 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
770 remain = PACKET_remaining(pkt);
772 * 'Change Cipher Spec' is just a single byte, which should already have
773 * been consumed by ssl_get_message() so there should be no bytes left,
774 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
776 if (SSL_IS_DTLS(s)) {
777 if ((s->version == DTLS1_BAD_VER
778 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
779 || (s->version != DTLS1_BAD_VER
780 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
781 SSLfatal(s, SSL_AD_DECODE_ERROR,
782 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
783 SSL_R_BAD_CHANGE_CIPHER_SPEC);
784 return MSG_PROCESS_ERROR;
788 SSLfatal(s, SSL_AD_DECODE_ERROR,
789 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
790 SSL_R_BAD_CHANGE_CIPHER_SPEC);
791 return MSG_PROCESS_ERROR;
795 /* Check we have a cipher to change to */
796 if (s->s3.tmp.new_cipher == NULL) {
797 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
798 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
799 return MSG_PROCESS_ERROR;
802 s->s3.change_cipher_spec = 1;
803 if (!ssl3_do_change_cipher_spec(s)) {
804 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
805 ERR_R_INTERNAL_ERROR);
806 return MSG_PROCESS_ERROR;
809 if (SSL_IS_DTLS(s)) {
810 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
812 if (s->version == DTLS1_BAD_VER)
813 s->d1->handshake_read_seq++;
815 #ifndef OPENSSL_NO_SCTP
817 * Remember that a CCS has been received, so that an old key of
818 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
821 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
825 return MSG_PROCESS_CONTINUE_READING;
828 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
833 /* This is a real handshake so make sure we clean it up at the end */
836 * To get this far we must have read encrypted data from the client. We
837 * no longer tolerate unencrypted alerts. This value is ignored if less
840 s->statem.enc_read_state = ENC_READ_STATE_VALID;
841 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
842 s->statem.cleanuphand = 1;
843 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
844 /* SSLfatal() already called */
845 return MSG_PROCESS_ERROR;
850 * In TLSv1.3 a Finished message signals a key change so the end of the
851 * message must be on a record boundary.
853 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
854 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
855 SSL_R_NOT_ON_RECORD_BOUNDARY);
856 return MSG_PROCESS_ERROR;
859 /* If this occurs, we have missed a message */
860 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
861 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
862 SSL_R_GOT_A_FIN_BEFORE_A_CCS);
863 return MSG_PROCESS_ERROR;
865 s->s3.change_cipher_spec = 0;
867 md_len = s->s3.tmp.peer_finish_md_len;
869 if (md_len != PACKET_remaining(pkt)) {
870 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
871 SSL_R_BAD_DIGEST_LENGTH);
872 return MSG_PROCESS_ERROR;
875 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
877 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
878 SSL_R_DIGEST_CHECK_FAILED);
879 return MSG_PROCESS_ERROR;
883 * Copy the finished so we can use it for renegotiation checks
885 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
886 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
887 ERR_R_INTERNAL_ERROR);
888 return MSG_PROCESS_ERROR;
891 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
893 s->s3.previous_client_finished_len = md_len;
895 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
897 s->s3.previous_server_finished_len = md_len;
901 * In TLS1.3 we also have to change cipher state and do any final processing
902 * of the initial server flight (if we are a client)
904 if (SSL_IS_TLS13(s)) {
906 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
907 !s->method->ssl3_enc->change_cipher_state(s,
908 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
909 /* SSLfatal() already called */
910 return MSG_PROCESS_ERROR;
913 /* TLS 1.3 gets the secret size from the handshake md */
915 if (!s->method->ssl3_enc->generate_master_secret(s,
916 s->master_secret, s->handshake_secret, 0,
918 /* SSLfatal() already called */
919 return MSG_PROCESS_ERROR;
921 if (!s->method->ssl3_enc->change_cipher_state(s,
922 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
923 /* SSLfatal() already called */
924 return MSG_PROCESS_ERROR;
926 if (!tls_process_initial_server_flight(s)) {
927 /* SSLfatal() already called */
928 return MSG_PROCESS_ERROR;
933 return MSG_PROCESS_FINISHED_READING;
936 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
938 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
939 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
940 SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
947 /* Add a certificate to the WPACKET */
948 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
951 unsigned char *outbytes;
953 len = i2d_X509(x, NULL);
955 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
959 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
960 || i2d_X509(x, &outbytes) != len) {
961 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
962 ERR_R_INTERNAL_ERROR);
967 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
969 /* SSLfatal() already called */
976 /* Add certificate chain to provided WPACKET */
977 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
981 STACK_OF(X509) *extra_certs;
982 STACK_OF(X509) *chain = NULL;
983 X509_STORE *chain_store;
985 if (cpk == NULL || cpk->x509 == NULL)
991 * If we have a certificate specific chain use it, else use parent ctx.
993 if (cpk->chain != NULL)
994 extra_certs = cpk->chain;
996 extra_certs = s->ctx->extra_certs;
998 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1000 else if (s->cert->chain_store)
1001 chain_store = s->cert->chain_store;
1003 chain_store = s->ctx->cert_store;
1005 if (chain_store != NULL) {
1006 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_with_libctx(s->ctx->libctx,
1009 if (xs_ctx == NULL) {
1010 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
1011 ERR_R_MALLOC_FAILURE);
1014 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1015 X509_STORE_CTX_free(xs_ctx);
1016 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
1021 * It is valid for the chain not to be complete (because normally we
1022 * don't include the root cert in the chain). Therefore we deliberately
1023 * ignore the error return from this call. We're not actually verifying
1024 * the cert - we're just building as much of the chain as we can
1026 (void)X509_verify_cert(xs_ctx);
1027 /* Don't leave errors in the queue */
1029 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1030 i = ssl_security_cert_chain(s, chain, NULL, 0);
1033 /* Dummy error calls so mkerr generates them */
1034 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
1035 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
1036 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
1038 X509_STORE_CTX_free(xs_ctx);
1039 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1042 chain_count = sk_X509_num(chain);
1043 for (i = 0; i < chain_count; i++) {
1044 x = sk_X509_value(chain, i);
1046 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1047 /* SSLfatal() already called */
1048 X509_STORE_CTX_free(xs_ctx);
1052 X509_STORE_CTX_free(xs_ctx);
1054 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1056 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1059 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1060 /* SSLfatal() already called */
1063 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1064 x = sk_X509_value(extra_certs, i);
1065 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1066 /* SSLfatal() already called */
1074 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1076 if (!WPACKET_start_sub_packet_u24(pkt)) {
1077 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1078 ERR_R_INTERNAL_ERROR);
1082 if (!ssl_add_cert_chain(s, pkt, cpk))
1085 if (!WPACKET_close(pkt)) {
1086 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1087 ERR_R_INTERNAL_ERROR);
1095 * Tidy up after the end of a handshake. In the case of SCTP this may result
1096 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1099 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1101 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1102 int cleanuphand = s->statem.cleanuphand;
1106 #ifndef OPENSSL_NO_SCTP
1108 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1109 * messages that require it. Therefore, DTLS procedures for retransmissions
1111 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1113 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1117 * We don't do this in DTLS over UDP because we may still need the init_buf
1118 * in case there are any unexpected retransmits
1120 BUF_MEM_free(s->init_buf);
1124 if (!ssl_free_wbio_buffer(s)) {
1125 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_FINISH_HANDSHAKE,
1126 ERR_R_INTERNAL_ERROR);
1132 if (SSL_IS_TLS13(s) && !s->server
1133 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1134 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1137 * Only set if there was a Finished message and this isn't after a TLSv1.3
1138 * post handshake exchange
1141 /* skipped if we just sent a HelloRequest */
1144 s->statem.cleanuphand = 0;
1145 s->ext.ticket_expected = 0;
1147 ssl3_cleanup_key_block(s);
1151 * In TLSv1.3 we update the cache as part of constructing the
1154 if (!SSL_IS_TLS13(s))
1155 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1157 /* N.B. s->ctx may not equal s->session_ctx */
1158 tsan_counter(&s->ctx->stats.sess_accept_good);
1159 s->handshake_func = ossl_statem_accept;
1161 if (SSL_IS_TLS13(s)) {
1163 * We encourage applications to only use TLSv1.3 tickets once,
1164 * so we remove this one from the cache.
1166 if ((s->session_ctx->session_cache_mode
1167 & SSL_SESS_CACHE_CLIENT) != 0)
1168 SSL_CTX_remove_session(s->session_ctx, s->session);
1171 * In TLSv1.3 we update the cache as part of processing the
1174 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1177 tsan_counter(&s->session_ctx->stats.sess_hit);
1179 s->handshake_func = ossl_statem_connect;
1180 tsan_counter(&s->session_ctx->stats.sess_connect_good);
1183 if (SSL_IS_DTLS(s)) {
1184 /* done with handshaking */
1185 s->d1->handshake_read_seq = 0;
1186 s->d1->handshake_write_seq = 0;
1187 s->d1->next_handshake_write_seq = 0;
1188 dtls1_clear_received_buffer(s);
1192 if (s->info_callback != NULL)
1193 cb = s->info_callback;
1194 else if (s->ctx->info_callback != NULL)
1195 cb = s->ctx->info_callback;
1197 /* The callback may expect us to not be in init at handshake done */
1198 ossl_statem_set_in_init(s, 0);
1203 || SSL_IS_FIRST_HANDSHAKE(s))
1204 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1208 /* If we've got more work to do we go back into init */
1209 ossl_statem_set_in_init(s, 1);
1210 return WORK_FINISHED_CONTINUE;
1213 return WORK_FINISHED_STOP;
1216 int tls_get_message_header(SSL *s, int *mt)
1218 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1219 int skip_message, i, recvd_type;
1221 size_t l, readbytes;
1223 p = (unsigned char *)s->init_buf->data;
1226 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1227 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1229 SSL3_HM_HEADER_LENGTH - s->init_num,
1232 s->rwstate = SSL_READING;
1235 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1237 * A ChangeCipherSpec must be a single byte and may not occur
1238 * in the middle of a handshake message.
1240 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1241 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1242 SSL_F_TLS_GET_MESSAGE_HEADER,
1243 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1246 if (s->statem.hand_state == TLS_ST_BEFORE
1247 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1249 * We are stateless and we received a CCS. Probably this is
1250 * from a client between the first and second ClientHellos.
1251 * We should ignore this, but return an error because we do
1252 * not return success until we see the second ClientHello
1253 * with a valid cookie.
1257 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1258 s->init_num = readbytes - 1;
1259 s->init_msg = s->init_buf->data;
1260 s->s3.tmp.message_size = readbytes;
1262 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1263 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1264 SSL_F_TLS_GET_MESSAGE_HEADER,
1265 SSL_R_CCS_RECEIVED_EARLY);
1268 s->init_num += readbytes;
1273 if (s->statem.hand_state != TLS_ST_OK
1274 && p[0] == SSL3_MT_HELLO_REQUEST)
1276 * The server may always send 'Hello Request' messages --
1277 * we are doing a handshake anyway now, so ignore them if
1278 * their format is correct. Does not count for 'Finished'
1281 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1285 if (s->msg_callback)
1286 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1287 p, SSL3_HM_HEADER_LENGTH, s,
1288 s->msg_callback_arg);
1290 } while (skip_message);
1291 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1294 s->s3.tmp.message_type = *(p++);
1296 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1298 * Only happens with SSLv3+ in an SSLv2 backward compatible
1301 * Total message size is the remaining record bytes to read
1302 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1304 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1305 + SSL3_HM_HEADER_LENGTH;
1306 s->s3.tmp.message_size = l;
1308 s->init_msg = s->init_buf->data;
1309 s->init_num = SSL3_HM_HEADER_LENGTH;
1312 /* BUF_MEM_grow takes an 'int' parameter */
1313 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1314 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1315 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1318 s->s3.tmp.message_size = l;
1320 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1327 int tls_get_message_body(SSL *s, size_t *len)
1329 size_t n, readbytes;
1333 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1334 /* We've already read everything in */
1335 *len = (unsigned long)s->init_num;
1340 n = s->s3.tmp.message_size - s->init_num;
1342 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1343 &p[s->init_num], n, 0, &readbytes);
1345 s->rwstate = SSL_READING;
1349 s->init_num += readbytes;
1354 * If receiving Finished, record MAC of prior handshake messages for
1355 * Finished verification.
1357 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1358 /* SSLfatal() already called */
1363 /* Feed this message into MAC computation. */
1364 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1365 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1367 /* SSLfatal() already called */
1371 if (s->msg_callback)
1372 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1373 (size_t)s->init_num, s, s->msg_callback_arg);
1376 * We defer feeding in the HRR until later. We'll do it as part of
1377 * processing the message
1378 * The TLsv1.3 handshake transcript stops at the ClientFinished
1381 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1382 /* KeyUpdate and NewSessionTicket do not need to be added */
1383 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1384 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1385 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1386 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1387 || memcmp(hrrrandom,
1388 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1389 SSL3_RANDOM_SIZE) != 0) {
1390 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1391 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1392 /* SSLfatal() already called */
1398 if (s->msg_callback)
1399 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1400 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1401 s->msg_callback_arg);
1408 static const X509ERR2ALERT x509table[] = {
1409 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1410 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1411 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1412 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1413 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1414 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1415 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1416 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1417 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1418 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1419 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1420 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1421 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1422 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1423 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1424 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1425 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1426 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1427 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1428 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1429 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1430 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1431 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1432 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1433 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1434 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1435 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1436 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1437 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1438 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1439 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1440 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1441 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1442 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1443 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1444 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1445 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1446 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1447 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1448 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1450 /* Last entry; return this if we don't find the value above. */
1451 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1454 int ssl_x509err2alert(int x509err)
1456 const X509ERR2ALERT *tp;
1458 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1459 if (tp->x509err == x509err)
1464 int ssl_allow_compression(SSL *s)
1466 if (s->options & SSL_OP_NO_COMPRESSION)
1468 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1471 static int version_cmp(const SSL *s, int a, int b)
1473 int dtls = SSL_IS_DTLS(s);
1478 return a < b ? -1 : 1;
1479 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1484 const SSL_METHOD *(*cmeth) (void);
1485 const SSL_METHOD *(*smeth) (void);
1488 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1489 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1492 /* Must be in order high to low */
1493 static const version_info tls_version_table[] = {
1494 #ifndef OPENSSL_NO_TLS1_3
1495 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1497 {TLS1_3_VERSION, NULL, NULL},
1499 #ifndef OPENSSL_NO_TLS1_2
1500 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1502 {TLS1_2_VERSION, NULL, NULL},
1504 #ifndef OPENSSL_NO_TLS1_1
1505 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1507 {TLS1_1_VERSION, NULL, NULL},
1509 #ifndef OPENSSL_NO_TLS1
1510 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1512 {TLS1_VERSION, NULL, NULL},
1514 #ifndef OPENSSL_NO_SSL3
1515 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1517 {SSL3_VERSION, NULL, NULL},
1522 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1523 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1526 /* Must be in order high to low */
1527 static const version_info dtls_version_table[] = {
1528 #ifndef OPENSSL_NO_DTLS1_2
1529 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1531 {DTLS1_2_VERSION, NULL, NULL},
1533 #ifndef OPENSSL_NO_DTLS1
1534 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1535 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1537 {DTLS1_VERSION, NULL, NULL},
1538 {DTLS1_BAD_VER, NULL, NULL},
1544 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1546 * @s: The SSL handle for the candidate method
1547 * @method: the intended method.
1549 * Returns 0 on success, or an SSL error reason on failure.
1551 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1553 int version = method->version;
1555 if ((s->min_proto_version != 0 &&
1556 version_cmp(s, version, s->min_proto_version) < 0) ||
1557 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1558 return SSL_R_VERSION_TOO_LOW;
1560 if (s->max_proto_version != 0 &&
1561 version_cmp(s, version, s->max_proto_version) > 0)
1562 return SSL_R_VERSION_TOO_HIGH;
1564 if ((s->options & method->mask) != 0)
1565 return SSL_R_UNSUPPORTED_PROTOCOL;
1566 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1567 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1573 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1574 * certificate type, or has PSK or a certificate callback configured. Otherwise
1577 static int is_tls13_capable(const SSL *s)
1580 #ifndef OPENSSL_NO_EC
1584 #ifndef OPENSSL_NO_PSK
1585 if (s->psk_server_callback != NULL)
1589 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1592 for (i = 0; i < SSL_PKEY_NUM; i++) {
1593 /* Skip over certs disallowed for TLSv1.3 */
1595 case SSL_PKEY_DSA_SIGN:
1596 case SSL_PKEY_GOST01:
1597 case SSL_PKEY_GOST12_256:
1598 case SSL_PKEY_GOST12_512:
1603 if (!ssl_has_cert(s, i))
1605 #ifndef OPENSSL_NO_EC
1606 if (i != SSL_PKEY_ECC)
1609 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1610 * more restrictive so check that our sig algs are consistent with this
1611 * EC cert. See section 4.2.3 of RFC8446.
1613 curve = evp_pkey_get_EC_KEY_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
1615 if (tls_check_sigalg_curve(s, curve))
1626 * ssl_version_supported - Check that the specified `version` is supported by
1629 * @s: The SSL handle for the candidate method
1630 * @version: Protocol version to test against
1632 * Returns 1 when supported, otherwise 0
1634 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1636 const version_info *vent;
1637 const version_info *table;
1639 switch (s->method->version) {
1641 /* Version should match method version for non-ANY method */
1642 return version_cmp(s, version, s->version) == 0;
1643 case TLS_ANY_VERSION:
1644 table = tls_version_table;
1646 case DTLS_ANY_VERSION:
1647 table = dtls_version_table;
1652 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1654 if (vent->cmeth != NULL
1655 && version_cmp(s, version, vent->version) == 0
1656 && ssl_method_error(s, vent->cmeth()) == 0
1658 || version != TLS1_3_VERSION
1659 || is_tls13_capable(s))) {
1661 *meth = vent->cmeth();
1669 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1670 * fallback indication from a client check whether we're using the highest
1671 * supported protocol version.
1673 * @s server SSL handle.
1675 * Returns 1 when using the highest enabled version, 0 otherwise.
1677 int ssl_check_version_downgrade(SSL *s)
1679 const version_info *vent;
1680 const version_info *table;
1683 * Check that the current protocol is the highest enabled version
1684 * (according to s->ctx->method, as version negotiation may have changed
1687 if (s->version == s->ctx->method->version)
1691 * Apparently we're using a version-flexible SSL_METHOD (not at its
1692 * highest protocol version).
1694 if (s->ctx->method->version == TLS_method()->version)
1695 table = tls_version_table;
1696 else if (s->ctx->method->version == DTLS_method()->version)
1697 table = dtls_version_table;
1699 /* Unexpected state; fail closed. */
1703 for (vent = table; vent->version != 0; ++vent) {
1704 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1705 return s->version == vent->version;
1711 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1712 * protocols, provided the initial (D)TLS method is version-flexible. This
1713 * function sanity-checks the proposed value and makes sure the method is
1714 * version-flexible, then sets the limit if all is well.
1716 * @method_version: The version of the current SSL_METHOD.
1717 * @version: the intended limit.
1718 * @bound: pointer to limit to be updated.
1720 * Returns 1 on success, 0 on failure.
1722 int ssl_set_version_bound(int method_version, int version, int *bound)
1732 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1734 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1735 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1737 if (!valid_tls && !valid_dtls)
1741 * Restrict TLS methods to TLS protocol versions.
1742 * Restrict DTLS methods to DTLS protocol versions.
1743 * Note, DTLS version numbers are decreasing, use comparison macros.
1745 * Note that for both lower-bounds we use explicit versions, not
1746 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1747 * configurations. If the MIN (supported) version ever rises, the user's
1748 * "floor" remains valid even if no longer available. We don't expect the
1749 * MAX ceiling to ever get lower, so making that variable makes sense.
1751 * We ignore attempts to set bounds on version-inflexible methods,
1752 * returning success.
1754 switch (method_version) {
1758 case TLS_ANY_VERSION:
1763 case DTLS_ANY_VERSION:
1771 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1773 if (vers == TLS1_2_VERSION
1774 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1775 *dgrd = DOWNGRADE_TO_1_2;
1776 } else if (!SSL_IS_DTLS(s)
1777 && vers < TLS1_2_VERSION
1779 * We need to ensure that a server that disables TLSv1.2
1780 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1781 * complete handshakes with clients that support TLSv1.2 and
1782 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1783 * enabled and TLSv1.2 is not.
1785 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1786 *dgrd = DOWNGRADE_TO_1_1;
1788 *dgrd = DOWNGRADE_NONE;
1793 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1794 * client HELLO is received to select the final server protocol version and
1795 * the version specific method.
1797 * @s: server SSL handle.
1799 * Returns 0 on success or an SSL error reason number on failure.
1801 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1804 * With version-flexible methods we have an initial state with:
1806 * s->method->version == (D)TLS_ANY_VERSION,
1807 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1809 * So we detect version-flexible methods via the method version, not the
1812 int server_version = s->method->version;
1813 int client_version = hello->legacy_version;
1814 const version_info *vent;
1815 const version_info *table;
1817 RAW_EXTENSION *suppversions;
1819 s->client_version = client_version;
1821 switch (server_version) {
1823 if (!SSL_IS_TLS13(s)) {
1824 if (version_cmp(s, client_version, s->version) < 0)
1825 return SSL_R_WRONG_SSL_VERSION;
1826 *dgrd = DOWNGRADE_NONE;
1828 * If this SSL handle is not from a version flexible method we don't
1829 * (and never did) check min/max FIPS or Suite B constraints. Hope
1830 * that's OK. It is up to the caller to not choose fixed protocol
1831 * versions they don't want. If not, then easy to fix, just return
1832 * ssl_method_error(s, s->method)
1837 * Fall through if we are TLSv1.3 already (this means we must be after
1838 * a HelloRetryRequest
1841 case TLS_ANY_VERSION:
1842 table = tls_version_table;
1844 case DTLS_ANY_VERSION:
1845 table = dtls_version_table;
1849 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1851 /* If we did an HRR then supported versions is mandatory */
1852 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1853 return SSL_R_UNSUPPORTED_PROTOCOL;
1855 if (suppversions->present && !SSL_IS_DTLS(s)) {
1856 unsigned int candidate_vers = 0;
1857 unsigned int best_vers = 0;
1858 const SSL_METHOD *best_method = NULL;
1859 PACKET versionslist;
1861 suppversions->parsed = 1;
1863 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1864 /* Trailing or invalid data? */
1865 return SSL_R_LENGTH_MISMATCH;
1869 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1870 * The spec only requires servers to check that it isn't SSLv3:
1871 * "Any endpoint receiving a Hello message with
1872 * ClientHello.legacy_version or ServerHello.legacy_version set to
1873 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1874 * We are slightly stricter and require that it isn't SSLv3 or lower.
1875 * We tolerate TLSv1 and TLSv1.1.
1877 if (client_version <= SSL3_VERSION)
1878 return SSL_R_BAD_LEGACY_VERSION;
1880 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1881 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1883 if (ssl_version_supported(s, candidate_vers, &best_method))
1884 best_vers = candidate_vers;
1886 if (PACKET_remaining(&versionslist) != 0) {
1887 /* Trailing data? */
1888 return SSL_R_LENGTH_MISMATCH;
1891 if (best_vers > 0) {
1892 if (s->hello_retry_request != SSL_HRR_NONE) {
1894 * This is after a HelloRetryRequest so we better check that we
1895 * negotiated TLSv1.3
1897 if (best_vers != TLS1_3_VERSION)
1898 return SSL_R_UNSUPPORTED_PROTOCOL;
1901 check_for_downgrade(s, best_vers, dgrd);
1902 s->version = best_vers;
1903 s->method = best_method;
1906 return SSL_R_UNSUPPORTED_PROTOCOL;
1910 * If the supported versions extension isn't present, then the highest
1911 * version we can negotiate is TLSv1.2
1913 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1914 client_version = TLS1_2_VERSION;
1917 * No supported versions extension, so we just use the version supplied in
1920 for (vent = table; vent->version != 0; ++vent) {
1921 const SSL_METHOD *method;
1923 if (vent->smeth == NULL ||
1924 version_cmp(s, client_version, vent->version) < 0)
1926 method = vent->smeth();
1927 if (ssl_method_error(s, method) == 0) {
1928 check_for_downgrade(s, vent->version, dgrd);
1929 s->version = vent->version;
1935 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1939 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1940 * server HELLO is received to select the final client protocol version and
1941 * the version specific method.
1943 * @s: client SSL handle.
1944 * @version: The proposed version from the server's HELLO.
1945 * @extensions: The extensions received
1947 * Returns 1 on success or 0 on error.
1949 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1951 const version_info *vent;
1952 const version_info *table;
1953 int ret, ver_min, ver_max, real_max, origv;
1956 s->version = version;
1958 /* This will overwrite s->version if the extension is present */
1959 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1960 SSL_EXT_TLS1_2_SERVER_HELLO
1961 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1967 if (s->hello_retry_request != SSL_HRR_NONE
1968 && s->version != TLS1_3_VERSION) {
1970 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1971 SSL_R_WRONG_SSL_VERSION);
1975 switch (s->method->version) {
1977 if (s->version != s->method->version) {
1979 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1980 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1981 SSL_R_WRONG_SSL_VERSION);
1985 * If this SSL handle is not from a version flexible method we don't
1986 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1987 * that's OK. It is up to the caller to not choose fixed protocol
1988 * versions they don't want. If not, then easy to fix, just return
1989 * ssl_method_error(s, s->method)
1992 case TLS_ANY_VERSION:
1993 table = tls_version_table;
1995 case DTLS_ANY_VERSION:
1996 table = dtls_version_table;
2000 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2003 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2004 SSL_F_SSL_CHOOSE_CLIENT_VERSION, ret);
2007 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2008 : s->version < ver_min) {
2010 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2011 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2013 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2014 : s->version > ver_max) {
2016 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2017 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2021 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2024 /* Check for downgrades */
2025 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2026 if (memcmp(tls12downgrade,
2027 s->s3.server_random + SSL3_RANDOM_SIZE
2028 - sizeof(tls12downgrade),
2029 sizeof(tls12downgrade)) == 0) {
2031 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2032 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2033 SSL_R_INAPPROPRIATE_FALLBACK);
2036 } else if (!SSL_IS_DTLS(s)
2037 && s->version < TLS1_2_VERSION
2038 && real_max > s->version) {
2039 if (memcmp(tls11downgrade,
2040 s->s3.server_random + SSL3_RANDOM_SIZE
2041 - sizeof(tls11downgrade),
2042 sizeof(tls11downgrade)) == 0) {
2044 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2045 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2046 SSL_R_INAPPROPRIATE_FALLBACK);
2051 for (vent = table; vent->version != 0; ++vent) {
2052 if (vent->cmeth == NULL || s->version != vent->version)
2055 s->method = vent->cmeth();
2060 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2061 SSL_R_UNSUPPORTED_PROTOCOL);
2066 * ssl_get_min_max_version - get minimum and maximum protocol version
2067 * @s: The SSL connection
2068 * @min_version: The minimum supported version
2069 * @max_version: The maximum supported version
2070 * @real_max: The highest version below the lowest compile time version hole
2071 * where that hole lies above at least one run-time enabled
2074 * Work out what version we should be using for the initial ClientHello if the
2075 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2076 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2077 * constraints and any floor imposed by the security level here,
2078 * so we don't advertise the wrong protocol version to only reject the outcome later.
2080 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2081 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2082 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2084 * Returns 0 on success or an SSL error reason number on failure. On failure
2085 * min_version and max_version will also be set to 0.
2087 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2090 int version, tmp_real_max;
2092 const SSL_METHOD *single = NULL;
2093 const SSL_METHOD *method;
2094 const version_info *table;
2095 const version_info *vent;
2097 switch (s->method->version) {
2100 * If this SSL handle is not from a version flexible method we don't
2101 * (and never did) check min/max FIPS or Suite B constraints. Hope
2102 * that's OK. It is up to the caller to not choose fixed protocol
2103 * versions they don't want. If not, then easy to fix, just return
2104 * ssl_method_error(s, s->method)
2106 *min_version = *max_version = s->version;
2108 * Providing a real_max only makes sense where we're using a version
2111 if (!ossl_assert(real_max == NULL))
2112 return ERR_R_INTERNAL_ERROR;
2114 case TLS_ANY_VERSION:
2115 table = tls_version_table;
2117 case DTLS_ANY_VERSION:
2118 table = dtls_version_table;
2123 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2124 * below X enabled. This is required in order to maintain the "version
2125 * capability" vector contiguous. Any versions with a NULL client method
2126 * (protocol version client is disabled at compile-time) is also a "hole".
2128 * Our initial state is hole == 1, version == 0. That is, versions above
2129 * the first version in the method table are disabled (a "hole" above
2130 * the valid protocol entries) and we don't have a selected version yet.
2132 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2133 * the selected version, and the method becomes a candidate "single"
2134 * method. We're no longer in a hole, so "hole" becomes 0.
2136 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2137 * as we support a contiguous range of at least two methods. If we hit
2138 * a disabled method, then hole becomes true again, but nothing else
2139 * changes yet, because all the remaining methods may be disabled too.
2140 * If we again hit an enabled method after the new hole, it becomes
2141 * selected, as we start from scratch.
2143 *min_version = version = 0;
2145 if (real_max != NULL)
2148 for (vent = table; vent->version != 0; ++vent) {
2150 * A table entry with a NULL client method is still a hole in the
2151 * "version capability" vector.
2153 if (vent->cmeth == NULL) {
2158 method = vent->cmeth();
2160 if (hole == 1 && tmp_real_max == 0)
2161 tmp_real_max = vent->version;
2163 if (ssl_method_error(s, method) != 0) {
2167 *min_version = method->version;
2169 if (real_max != NULL && tmp_real_max != 0)
2170 *real_max = tmp_real_max;
2171 version = (single = method)->version;
2172 *min_version = version;
2177 *max_version = version;
2179 /* Fail if everything is disabled */
2181 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2187 * ssl_set_client_hello_version - Work out what version we should be using for
2188 * the initial ClientHello.legacy_version field.
2190 * @s: client SSL handle.
2192 * Returns 0 on success or an SSL error reason number on failure.
2194 int ssl_set_client_hello_version(SSL *s)
2196 int ver_min, ver_max, ret;
2199 * In a renegotiation we always send the same client_version that we sent
2200 * last time, regardless of which version we eventually negotiated.
2202 if (!SSL_IS_FIRST_HANDSHAKE(s))
2205 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2210 s->version = ver_max;
2212 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2213 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2214 ver_max = TLS1_2_VERSION;
2216 s->client_version = ver_max;
2221 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2222 * and |checkallow| is 1 then additionally check if the group is allowed to be
2223 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2224 * 1) or 0 otherwise.
2226 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2227 size_t num_groups, int checkallow)
2231 if (groups == NULL || num_groups == 0)
2234 for (i = 0; i < num_groups; i++) {
2235 uint16_t group = groups[i];
2237 if (group_id == group
2239 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2247 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2248 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2249 size_t hashlen, const unsigned char *hrr,
2252 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2253 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2255 memset(msghdr, 0, sizeof(msghdr));
2257 if (hashval == NULL) {
2258 hashval = hashvaltmp;
2260 /* Get the hash of the initial ClientHello */
2261 if (!ssl3_digest_cached_records(s, 0)
2262 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2264 /* SSLfatal() already called */
2269 /* Reinitialise the transcript hash */
2270 if (!ssl3_init_finished_mac(s)) {
2271 /* SSLfatal() already called */
2275 /* Inject the synthetic message_hash message */
2276 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2277 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2278 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2279 || !ssl3_finish_mac(s, hashval, hashlen)) {
2280 /* SSLfatal() already called */
2285 * Now re-inject the HRR and current message if appropriate (we just deleted
2286 * it when we reinitialised the transcript hash above). Only necessary after
2287 * receiving a ClientHello2 with a cookie.
2290 && (!ssl3_finish_mac(s, hrr, hrrlen)
2291 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2292 s->s3.tmp.message_size
2293 + SSL3_HM_HEADER_LENGTH))) {
2294 /* SSLfatal() already called */
2301 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2303 return X509_NAME_cmp(*a, *b);
2306 int parse_ca_names(SSL *s, PACKET *pkt)
2308 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2309 X509_NAME *xn = NULL;
2312 if (ca_sk == NULL) {
2313 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2314 ERR_R_MALLOC_FAILURE);
2317 /* get the CA RDNs */
2318 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2319 SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2320 SSL_R_LENGTH_MISMATCH);
2324 while (PACKET_remaining(&cadns)) {
2325 const unsigned char *namestart, *namebytes;
2326 unsigned int name_len;
2328 if (!PACKET_get_net_2(&cadns, &name_len)
2329 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2330 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2331 SSL_R_LENGTH_MISMATCH);
2335 namestart = namebytes;
2336 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2337 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2341 if (namebytes != (namestart + name_len)) {
2342 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2343 SSL_R_CA_DN_LENGTH_MISMATCH);
2347 if (!sk_X509_NAME_push(ca_sk, xn)) {
2348 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2349 ERR_R_MALLOC_FAILURE);
2355 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2356 s->s3.tmp.peer_ca_names = ca_sk;
2361 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2366 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2368 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2371 ca_sk = SSL_get_client_CA_list(s);
2372 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2377 ca_sk = SSL_get0_CA_list(s);
2382 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2384 /* Start sub-packet for client CA list */
2385 if (!WPACKET_start_sub_packet_u16(pkt)) {
2386 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2387 ERR_R_INTERNAL_ERROR);
2391 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2394 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2395 unsigned char *namebytes;
2396 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2400 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2401 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2403 || i2d_X509_NAME(name, &namebytes) != namelen) {
2404 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2405 ERR_R_INTERNAL_ERROR);
2411 if (!WPACKET_close(pkt)) {
2412 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2413 ERR_R_INTERNAL_ERROR);
2420 /* Create a buffer containing data to be signed for server key exchange */
2421 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2422 const void *param, size_t paramlen)
2424 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2425 unsigned char *tbs = OPENSSL_malloc(tbslen);
2428 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2429 ERR_R_MALLOC_FAILURE);
2432 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2433 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2435 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2442 * Saves the current handshake digest for Post-Handshake Auth,
2443 * Done after ClientFinished is processed, done exactly once
2445 int tls13_save_handshake_digest_for_pha(SSL *s)
2447 if (s->pha_dgst == NULL) {
2448 if (!ssl3_digest_cached_records(s, 1))
2449 /* SSLfatal() already called */
2452 s->pha_dgst = EVP_MD_CTX_new();
2453 if (s->pha_dgst == NULL) {
2454 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2455 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2456 ERR_R_INTERNAL_ERROR);
2459 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2460 s->s3.handshake_dgst)) {
2461 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2462 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2463 ERR_R_INTERNAL_ERROR);
2471 * Restores the Post-Handshake Auth handshake digest
2472 * Done just before sending/processing the Cert Request
2474 int tls13_restore_handshake_digest_for_pha(SSL *s)
2476 if (s->pha_dgst == NULL) {
2477 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2478 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2479 ERR_R_INTERNAL_ERROR);
2482 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2484 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2485 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2486 ERR_R_INTERNAL_ERROR);