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 DEFINE_STACK_OF(X509_NAME)
28 * Map error codes to TLS/SSL alart types.
30 typedef struct x509err2alert_st {
35 /* Fixed value used in the ServerHello random field to identify an HRR */
36 const unsigned char hrrrandom[] = {
37 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
38 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
39 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
43 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
44 * SSL3_RT_CHANGE_CIPHER_SPEC)
46 int ssl3_do_write(SSL *s, int type)
51 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
52 s->init_num, &written);
55 if (type == SSL3_RT_HANDSHAKE)
57 * should not be done for 'Hello Request's, but in that case we'll
58 * ignore the result anyway
59 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
61 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
62 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
63 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
64 if (!ssl3_finish_mac(s,
65 (unsigned char *)&s->init_buf->data[s->init_off],
68 if (written == s->init_num) {
70 s->msg_callback(1, s->version, type, s->init_buf->data,
71 (size_t)(s->init_off + s->init_num), s,
75 s->init_off += written;
76 s->init_num -= written;
80 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
84 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
85 || !WPACKET_get_length(pkt, &msglen)
88 s->init_num = (int)msglen;
94 int tls_setup_handshake(SSL *s)
96 int ver_min, ver_max, ok;
98 if (!ssl3_init_finished_mac(s)) {
99 /* SSLfatal() already called */
103 /* Reset any extension flags */
104 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
106 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
107 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_SETUP_HANDSHAKE,
108 ERR_R_INTERNAL_ERROR);
112 /* Sanity check that we have MD5-SHA1 if we need it */
113 if (s->ctx->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_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(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
126 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);
127 ERR_add_error_data(1, "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_IS_DTLS(s)) {
137 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
138 ok = SSL_set_min_proto_version(s, DTLS1_2_VERSION);
140 if (ver_min < TLS1_2_VERSION)
141 ok = SSL_set_min_proto_version(s, TLS1_2_VERSION);
144 /* Shouldn't happen */
145 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
146 ERR_R_INTERNAL_ERROR);
153 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
157 * Sanity check that the maximum version we accept has ciphers
158 * enabled. For clients we do this check during construction of the
161 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
162 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
164 if (SSL_IS_DTLS(s)) {
165 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
166 DTLS_VERSION_LE(ver_max, c->max_dtls))
168 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
175 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
176 SSL_R_NO_CIPHERS_AVAILABLE);
177 ERR_add_error_data(1, "No ciphers enabled for max supported "
181 if (SSL_IS_FIRST_HANDSHAKE(s)) {
182 /* N.B. s->session_ctx == s->ctx here */
183 tsan_counter(&s->session_ctx->stats.sess_accept);
185 /* N.B. s->ctx may not equal s->session_ctx */
186 tsan_counter(&s->ctx->stats.sess_accept_renegotiate);
188 s->s3.tmp.cert_request = 0;
191 if (SSL_IS_FIRST_HANDSHAKE(s))
192 tsan_counter(&s->session_ctx->stats.sess_connect);
194 tsan_counter(&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;
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 *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";
232 if (SSL_IS_TLS13(s)) {
235 /* Set the first 64 bytes of to-be-signed data to octet 32 */
236 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
237 /* This copies the 33 bytes of context plus the 0 separator byte */
238 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
239 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
240 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
242 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
245 * If we're currently reading then we need to use the saved handshake
246 * hash value. We can't use the current handshake hash state because
247 * that includes the CertVerify itself.
249 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
250 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
251 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
252 s->cert_verify_hash_len);
253 hashlen = s->cert_verify_hash_len;
254 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
255 EVP_MAX_MD_SIZE, &hashlen)) {
256 /* SSLfatal() already called */
261 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
266 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
268 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
269 ERR_R_INTERNAL_ERROR);
278 int tls_construct_cert_verify(SSL *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;
290 if (lu == NULL || s->s3.tmp.cert == NULL) {
291 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
292 ERR_R_INTERNAL_ERROR);
295 pkey = s->s3.tmp.cert->privatekey;
297 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
298 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
299 ERR_R_INTERNAL_ERROR);
303 mctx = EVP_MD_CTX_new();
305 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
306 ERR_R_MALLOC_FAILURE);
310 /* Get the data to be signed */
311 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
312 /* SSLfatal() already called */
316 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
317 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
318 ERR_R_INTERNAL_ERROR);
322 if (EVP_DigestSignInit_with_libctx(mctx, &pctx,
323 md == NULL ? NULL : EVP_MD_name(md),
324 s->ctx->libctx, s->ctx->propq,
326 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
331 if (lu->sig == EVP_PKEY_RSA_PSS) {
332 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
333 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
334 RSA_PSS_SALTLEN_DIGEST) <= 0) {
335 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
340 if (s->version == SSL3_VERSION) {
342 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
343 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
345 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
347 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
348 * with a call to ssl3_digest_master_key_set_params()
350 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
351 (int)s->session->master_key_length,
352 s->session->master_key) <= 0
353 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
355 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
359 sig = OPENSSL_malloc(siglen);
361 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
362 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
368 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
369 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
371 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
372 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
376 sig = OPENSSL_malloc(siglen);
378 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
379 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
385 #ifndef OPENSSL_NO_GOST
387 int pktype = lu->sig;
389 if (pktype == NID_id_GostR3410_2001
390 || pktype == NID_id_GostR3410_2012_256
391 || pktype == NID_id_GostR3410_2012_512)
392 BUF_reverse(sig, NULL, siglen);
396 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
397 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
398 ERR_R_INTERNAL_ERROR);
402 /* Digest cached records and discard handshake buffer */
403 if (!ssl3_digest_cached_records(s, 0)) {
404 /* SSLfatal() already called */
409 EVP_MD_CTX_free(mctx);
413 EVP_MD_CTX_free(mctx);
417 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
419 EVP_PKEY *pkey = NULL;
420 const unsigned char *data;
421 #ifndef OPENSSL_NO_GOST
422 unsigned char *gost_data = NULL;
424 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
428 const EVP_MD *md = NULL;
431 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
432 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
433 EVP_PKEY_CTX *pctx = NULL;
436 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
437 ERR_R_MALLOC_FAILURE);
441 peer = s->session->peer;
442 pkey = X509_get0_pubkey(peer);
444 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
445 ERR_R_INTERNAL_ERROR);
449 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
450 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
451 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
455 if (SSL_USE_SIGALGS(s)) {
458 if (!PACKET_get_net_2(pkt, &sigalg)) {
459 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
463 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
464 /* SSLfatal() already called */
467 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
468 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
469 ERR_R_INTERNAL_ERROR);
473 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
474 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
475 ERR_R_INTERNAL_ERROR);
479 if (SSL_USE_SIGALGS(s))
480 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
481 md == NULL ? "n/a" : EVP_MD_name(md));
483 /* Check for broken implementations of GOST ciphersuites */
485 * If key is GOST and len is exactly 64 or 128, it is signature without
486 * length field (CryptoPro implementations at least till TLS 1.2)
488 #ifndef OPENSSL_NO_GOST
489 if (!SSL_USE_SIGALGS(s)
490 && ((PACKET_remaining(pkt) == 64
491 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
492 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
493 || (PACKET_remaining(pkt) == 128
494 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
495 len = PACKET_remaining(pkt);
498 if (!PACKET_get_net_2(pkt, &len)) {
499 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
500 SSL_R_LENGTH_MISMATCH);
504 if (!PACKET_get_bytes(pkt, &data, len)) {
505 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
506 SSL_R_LENGTH_MISMATCH);
510 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
511 /* SSLfatal() already called */
515 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
516 md == NULL ? "n/a" : EVP_MD_name(md));
518 if (EVP_DigestVerifyInit_with_libctx(mctx, &pctx,
519 md == NULL ? NULL : EVP_MD_name(md),
520 s->ctx->libctx, s->ctx->propq,
522 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
526 #ifndef OPENSSL_NO_GOST
528 int pktype = EVP_PKEY_id(pkey);
529 if (pktype == NID_id_GostR3410_2001
530 || pktype == NID_id_GostR3410_2012_256
531 || pktype == NID_id_GostR3410_2012_512) {
532 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
533 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
534 SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
537 BUF_reverse(gost_data, data, len);
543 if (SSL_USE_PSS(s)) {
544 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
545 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
546 RSA_PSS_SALTLEN_DIGEST) <= 0) {
547 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
552 if (s->version == SSL3_VERSION) {
554 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
555 * with a call to ssl3_digest_master_key_set_params()
557 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
558 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
559 (int)s->session->master_key_length,
560 s->session->master_key) <= 0) {
561 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
565 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
566 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
567 SSL_R_BAD_SIGNATURE);
571 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
573 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
574 SSL_R_BAD_SIGNATURE);
580 * In TLSv1.3 on the client side we make sure we prepare the client
581 * certificate after the CertVerify instead of when we get the
582 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
583 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
584 * want to make sure that SSL_get1_peer_certificate() will return the actual
585 * server certificate from the client_cert_cb callback.
587 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
588 ret = MSG_PROCESS_CONTINUE_PROCESSING;
590 ret = MSG_PROCESS_CONTINUE_READING;
592 BIO_free(s->s3.handshake_buffer);
593 s->s3.handshake_buffer = NULL;
594 EVP_MD_CTX_free(mctx);
595 #ifndef OPENSSL_NO_GOST
596 OPENSSL_free(gost_data);
601 int tls_construct_finished(SSL *s, WPACKET *pkt)
603 size_t finish_md_len;
607 /* This is a real handshake so make sure we clean it up at the end */
608 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
609 s->statem.cleanuphand = 1;
612 * We only change the keys if we didn't already do this when we sent the
617 && s->s3.tmp.cert_req == 0
618 && (!s->method->ssl3_enc->change_cipher_state(s,
619 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
620 /* SSLfatal() already called */
625 sender = s->method->ssl3_enc->server_finished_label;
626 slen = s->method->ssl3_enc->server_finished_label_len;
628 sender = s->method->ssl3_enc->client_finished_label;
629 slen = s->method->ssl3_enc->client_finished_label_len;
632 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
634 s->s3.tmp.finish_md);
635 if (finish_md_len == 0) {
636 /* SSLfatal() already called */
640 s->s3.tmp.finish_md_len = finish_md_len;
642 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
643 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
644 ERR_R_INTERNAL_ERROR);
649 * Log the master secret, if logging is enabled. We don't log it for
650 * TLSv1.3: there's a different key schedule for that.
652 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
653 s->session->master_key,
654 s->session->master_key_length)) {
655 /* SSLfatal() already called */
660 * Copy the finished so we can use it for renegotiation checks
662 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
663 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
664 ERR_R_INTERNAL_ERROR);
668 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
670 s->s3.previous_client_finished_len = finish_md_len;
672 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
674 s->s3.previous_server_finished_len = finish_md_len;
680 int tls_construct_key_update(SSL *s, WPACKET *pkt)
682 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
683 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
684 ERR_R_INTERNAL_ERROR);
688 s->key_update = SSL_KEY_UPDATE_NONE;
692 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
694 unsigned int updatetype;
697 * A KeyUpdate message signals a key change so the end of the message must
698 * be on a record boundary.
700 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
701 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
702 SSL_R_NOT_ON_RECORD_BOUNDARY);
703 return MSG_PROCESS_ERROR;
706 if (!PACKET_get_1(pkt, &updatetype)
707 || PACKET_remaining(pkt) != 0) {
708 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
709 SSL_R_BAD_KEY_UPDATE);
710 return MSG_PROCESS_ERROR;
714 * There are only two defined key update types. Fail if we get a value we
717 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
718 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
719 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
720 SSL_R_BAD_KEY_UPDATE);
721 return MSG_PROCESS_ERROR;
725 * If we get a request for us to update our sending keys too then, we need
726 * to additionally send a KeyUpdate message. However that message should
727 * not also request an update (otherwise we get into an infinite loop).
729 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
730 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
732 if (!tls13_update_key(s, 0)) {
733 /* SSLfatal() already called */
734 return MSG_PROCESS_ERROR;
737 return MSG_PROCESS_FINISHED_READING;
741 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
744 int ssl3_take_mac(SSL *s)
750 sender = s->method->ssl3_enc->server_finished_label;
751 slen = s->method->ssl3_enc->server_finished_label_len;
753 sender = s->method->ssl3_enc->client_finished_label;
754 slen = s->method->ssl3_enc->client_finished_label_len;
757 s->s3.tmp.peer_finish_md_len =
758 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
759 s->s3.tmp.peer_finish_md);
761 if (s->s3.tmp.peer_finish_md_len == 0) {
762 /* SSLfatal() already called */
769 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
773 remain = PACKET_remaining(pkt);
775 * 'Change Cipher Spec' is just a single byte, which should already have
776 * been consumed by ssl_get_message() so there should be no bytes left,
777 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
779 if (SSL_IS_DTLS(s)) {
780 if ((s->version == DTLS1_BAD_VER
781 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
782 || (s->version != DTLS1_BAD_VER
783 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
784 SSLfatal(s, SSL_AD_DECODE_ERROR,
785 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
786 SSL_R_BAD_CHANGE_CIPHER_SPEC);
787 return MSG_PROCESS_ERROR;
791 SSLfatal(s, SSL_AD_DECODE_ERROR,
792 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
793 SSL_R_BAD_CHANGE_CIPHER_SPEC);
794 return MSG_PROCESS_ERROR;
798 /* Check we have a cipher to change to */
799 if (s->s3.tmp.new_cipher == NULL) {
800 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
801 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
802 return MSG_PROCESS_ERROR;
805 s->s3.change_cipher_spec = 1;
806 if (!ssl3_do_change_cipher_spec(s)) {
807 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
808 ERR_R_INTERNAL_ERROR);
809 return MSG_PROCESS_ERROR;
812 if (SSL_IS_DTLS(s)) {
813 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
815 if (s->version == DTLS1_BAD_VER)
816 s->d1->handshake_read_seq++;
818 #ifndef OPENSSL_NO_SCTP
820 * Remember that a CCS has been received, so that an old key of
821 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
824 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
828 return MSG_PROCESS_CONTINUE_READING;
831 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
836 /* This is a real handshake so make sure we clean it up at the end */
839 * To get this far we must have read encrypted data from the client. We
840 * no longer tolerate unencrypted alerts. This value is ignored if less
843 s->statem.enc_read_state = ENC_READ_STATE_VALID;
844 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
845 s->statem.cleanuphand = 1;
846 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
847 /* SSLfatal() already called */
848 return MSG_PROCESS_ERROR;
853 * In TLSv1.3 a Finished message signals a key change so the end of the
854 * message must be on a record boundary.
856 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
857 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
858 SSL_R_NOT_ON_RECORD_BOUNDARY);
859 return MSG_PROCESS_ERROR;
862 /* If this occurs, we have missed a message */
863 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
864 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
865 SSL_R_GOT_A_FIN_BEFORE_A_CCS);
866 return MSG_PROCESS_ERROR;
868 s->s3.change_cipher_spec = 0;
870 md_len = s->s3.tmp.peer_finish_md_len;
872 if (md_len != PACKET_remaining(pkt)) {
873 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
874 SSL_R_BAD_DIGEST_LENGTH);
875 return MSG_PROCESS_ERROR;
878 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
880 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
881 SSL_R_DIGEST_CHECK_FAILED);
882 return MSG_PROCESS_ERROR;
886 * Copy the finished so we can use it for renegotiation checks
888 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
889 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
890 ERR_R_INTERNAL_ERROR);
891 return MSG_PROCESS_ERROR;
894 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
896 s->s3.previous_client_finished_len = md_len;
898 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
900 s->s3.previous_server_finished_len = md_len;
904 * In TLS1.3 we also have to change cipher state and do any final processing
905 * of the initial server flight (if we are a client)
907 if (SSL_IS_TLS13(s)) {
909 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
910 !s->method->ssl3_enc->change_cipher_state(s,
911 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
912 /* SSLfatal() already called */
913 return MSG_PROCESS_ERROR;
916 /* TLS 1.3 gets the secret size from the handshake md */
918 if (!s->method->ssl3_enc->generate_master_secret(s,
919 s->master_secret, s->handshake_secret, 0,
921 /* SSLfatal() already called */
922 return MSG_PROCESS_ERROR;
924 if (!s->method->ssl3_enc->change_cipher_state(s,
925 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
926 /* SSLfatal() already called */
927 return MSG_PROCESS_ERROR;
929 if (!tls_process_initial_server_flight(s)) {
930 /* SSLfatal() already called */
931 return MSG_PROCESS_ERROR;
936 return MSG_PROCESS_FINISHED_READING;
939 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
941 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
942 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
943 SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
950 /* Add a certificate to the WPACKET */
951 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
954 unsigned char *outbytes;
956 len = i2d_X509(x, NULL);
958 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
962 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
963 || i2d_X509(x, &outbytes) != len) {
964 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
965 ERR_R_INTERNAL_ERROR);
970 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
972 /* SSLfatal() already called */
979 /* Add certificate chain to provided WPACKET */
980 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
984 STACK_OF(X509) *extra_certs;
985 STACK_OF(X509) *chain = NULL;
986 X509_STORE *chain_store;
988 if (cpk == NULL || cpk->x509 == NULL)
994 * If we have a certificate specific chain use it, else use parent ctx.
996 if (cpk->chain != NULL)
997 extra_certs = cpk->chain;
999 extra_certs = s->ctx->extra_certs;
1001 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1003 else if (s->cert->chain_store)
1004 chain_store = s->cert->chain_store;
1006 chain_store = s->ctx->cert_store;
1008 if (chain_store != NULL) {
1009 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_with_libctx(s->ctx->libctx,
1012 if (xs_ctx == NULL) {
1013 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
1014 ERR_R_MALLOC_FAILURE);
1017 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1018 X509_STORE_CTX_free(xs_ctx);
1019 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
1024 * It is valid for the chain not to be complete (because normally we
1025 * don't include the root cert in the chain). Therefore we deliberately
1026 * ignore the error return from this call. We're not actually verifying
1027 * the cert - we're just building as much of the chain as we can
1029 (void)X509_verify_cert(xs_ctx);
1030 /* Don't leave errors in the queue */
1032 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1033 i = ssl_security_cert_chain(s, chain, NULL, 0);
1036 /* Dummy error calls so mkerr generates them */
1037 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
1038 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
1039 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
1041 X509_STORE_CTX_free(xs_ctx);
1042 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1045 chain_count = sk_X509_num(chain);
1046 for (i = 0; i < chain_count; i++) {
1047 x = sk_X509_value(chain, i);
1049 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1050 /* SSLfatal() already called */
1051 X509_STORE_CTX_free(xs_ctx);
1055 X509_STORE_CTX_free(xs_ctx);
1057 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1059 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1062 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1063 /* SSLfatal() already called */
1066 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1067 x = sk_X509_value(extra_certs, i);
1068 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1069 /* SSLfatal() already called */
1077 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1079 if (!WPACKET_start_sub_packet_u24(pkt)) {
1080 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1081 ERR_R_INTERNAL_ERROR);
1085 if (!ssl_add_cert_chain(s, pkt, cpk))
1088 if (!WPACKET_close(pkt)) {
1089 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1090 ERR_R_INTERNAL_ERROR);
1098 * Tidy up after the end of a handshake. In the case of SCTP this may result
1099 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1102 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1104 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1105 int cleanuphand = s->statem.cleanuphand;
1109 #ifndef OPENSSL_NO_SCTP
1111 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1112 * messages that require it. Therefore, DTLS procedures for retransmissions
1114 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1116 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1120 * We don't do this in DTLS over UDP because we may still need the init_buf
1121 * in case there are any unexpected retransmits
1123 BUF_MEM_free(s->init_buf);
1127 if (!ssl_free_wbio_buffer(s)) {
1128 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_FINISH_HANDSHAKE,
1129 ERR_R_INTERNAL_ERROR);
1135 if (SSL_IS_TLS13(s) && !s->server
1136 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1137 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1140 * Only set if there was a Finished message and this isn't after a TLSv1.3
1141 * post handshake exchange
1144 /* skipped if we just sent a HelloRequest */
1147 s->statem.cleanuphand = 0;
1148 s->ext.ticket_expected = 0;
1150 ssl3_cleanup_key_block(s);
1154 * In TLSv1.3 we update the cache as part of constructing the
1157 if (!SSL_IS_TLS13(s))
1158 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1160 /* N.B. s->ctx may not equal s->session_ctx */
1161 tsan_counter(&s->ctx->stats.sess_accept_good);
1162 s->handshake_func = ossl_statem_accept;
1164 if (SSL_IS_TLS13(s)) {
1166 * We encourage applications to only use TLSv1.3 tickets once,
1167 * so we remove this one from the cache.
1169 if ((s->session_ctx->session_cache_mode
1170 & SSL_SESS_CACHE_CLIENT) != 0)
1171 SSL_CTX_remove_session(s->session_ctx, s->session);
1174 * In TLSv1.3 we update the cache as part of processing the
1177 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1180 tsan_counter(&s->session_ctx->stats.sess_hit);
1182 s->handshake_func = ossl_statem_connect;
1183 tsan_counter(&s->session_ctx->stats.sess_connect_good);
1186 if (SSL_IS_DTLS(s)) {
1187 /* done with handshaking */
1188 s->d1->handshake_read_seq = 0;
1189 s->d1->handshake_write_seq = 0;
1190 s->d1->next_handshake_write_seq = 0;
1191 dtls1_clear_received_buffer(s);
1195 if (s->info_callback != NULL)
1196 cb = s->info_callback;
1197 else if (s->ctx->info_callback != NULL)
1198 cb = s->ctx->info_callback;
1200 /* The callback may expect us to not be in init at handshake done */
1201 ossl_statem_set_in_init(s, 0);
1206 || SSL_IS_FIRST_HANDSHAKE(s))
1207 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1211 /* If we've got more work to do we go back into init */
1212 ossl_statem_set_in_init(s, 1);
1213 return WORK_FINISHED_CONTINUE;
1216 return WORK_FINISHED_STOP;
1219 int tls_get_message_header(SSL *s, int *mt)
1221 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1222 int skip_message, i, recvd_type;
1224 size_t l, readbytes;
1226 p = (unsigned char *)s->init_buf->data;
1229 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1230 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1232 SSL3_HM_HEADER_LENGTH - s->init_num,
1235 s->rwstate = SSL_READING;
1238 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1240 * A ChangeCipherSpec must be a single byte and may not occur
1241 * in the middle of a handshake message.
1243 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1244 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1245 SSL_F_TLS_GET_MESSAGE_HEADER,
1246 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1249 if (s->statem.hand_state == TLS_ST_BEFORE
1250 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1252 * We are stateless and we received a CCS. Probably this is
1253 * from a client between the first and second ClientHellos.
1254 * We should ignore this, but return an error because we do
1255 * not return success until we see the second ClientHello
1256 * with a valid cookie.
1260 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1261 s->init_num = readbytes - 1;
1262 s->init_msg = s->init_buf->data;
1263 s->s3.tmp.message_size = readbytes;
1265 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1266 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1267 SSL_F_TLS_GET_MESSAGE_HEADER,
1268 SSL_R_CCS_RECEIVED_EARLY);
1271 s->init_num += readbytes;
1276 if (s->statem.hand_state != TLS_ST_OK
1277 && p[0] == SSL3_MT_HELLO_REQUEST)
1279 * The server may always send 'Hello Request' messages --
1280 * we are doing a handshake anyway now, so ignore them if
1281 * their format is correct. Does not count for 'Finished'
1284 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1288 if (s->msg_callback)
1289 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1290 p, SSL3_HM_HEADER_LENGTH, s,
1291 s->msg_callback_arg);
1293 } while (skip_message);
1294 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1297 s->s3.tmp.message_type = *(p++);
1299 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1301 * Only happens with SSLv3+ in an SSLv2 backward compatible
1304 * Total message size is the remaining record bytes to read
1305 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1307 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1308 + SSL3_HM_HEADER_LENGTH;
1309 s->s3.tmp.message_size = l;
1311 s->init_msg = s->init_buf->data;
1312 s->init_num = SSL3_HM_HEADER_LENGTH;
1315 /* BUF_MEM_grow takes an 'int' parameter */
1316 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1317 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1318 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1321 s->s3.tmp.message_size = l;
1323 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1330 int tls_get_message_body(SSL *s, size_t *len)
1332 size_t n, readbytes;
1336 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1337 /* We've already read everything in */
1338 *len = (unsigned long)s->init_num;
1343 n = s->s3.tmp.message_size - s->init_num;
1345 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1346 &p[s->init_num], n, 0, &readbytes);
1348 s->rwstate = SSL_READING;
1352 s->init_num += readbytes;
1357 * If receiving Finished, record MAC of prior handshake messages for
1358 * Finished verification.
1360 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1361 /* SSLfatal() already called */
1366 /* Feed this message into MAC computation. */
1367 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1368 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1370 /* SSLfatal() already called */
1374 if (s->msg_callback)
1375 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1376 (size_t)s->init_num, s, s->msg_callback_arg);
1379 * We defer feeding in the HRR until later. We'll do it as part of
1380 * processing the message
1381 * The TLsv1.3 handshake transcript stops at the ClientFinished
1384 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1385 /* KeyUpdate and NewSessionTicket do not need to be added */
1386 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1387 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1388 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1389 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1390 || memcmp(hrrrandom,
1391 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1392 SSL3_RANDOM_SIZE) != 0) {
1393 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1394 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1395 /* SSLfatal() already called */
1401 if (s->msg_callback)
1402 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1403 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1404 s->msg_callback_arg);
1411 static const X509ERR2ALERT x509table[] = {
1412 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1413 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1414 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1415 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1416 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1417 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1418 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1419 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1420 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1421 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1422 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1423 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1424 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1425 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1426 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1427 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1428 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1429 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1430 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1431 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1432 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1433 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1434 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1435 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1436 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1437 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1438 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1439 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1440 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1441 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1442 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1443 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1444 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1445 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1446 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1447 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1448 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1449 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1450 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1452 /* Last entry; return this if we don't find the value above. */
1453 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1456 int ssl_x509err2alert(int x509err)
1458 const X509ERR2ALERT *tp;
1460 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1461 if (tp->x509err == x509err)
1466 int ssl_allow_compression(SSL *s)
1468 if (s->options & SSL_OP_NO_COMPRESSION)
1470 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1473 static int version_cmp(const SSL *s, int a, int b)
1475 int dtls = SSL_IS_DTLS(s);
1480 return a < b ? -1 : 1;
1481 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1486 const SSL_METHOD *(*cmeth) (void);
1487 const SSL_METHOD *(*smeth) (void);
1490 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1491 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1494 /* Must be in order high to low */
1495 static const version_info tls_version_table[] = {
1496 #ifndef OPENSSL_NO_TLS1_3
1497 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1499 {TLS1_3_VERSION, NULL, NULL},
1501 #ifndef OPENSSL_NO_TLS1_2
1502 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1504 {TLS1_2_VERSION, NULL, NULL},
1506 #ifndef OPENSSL_NO_TLS1_1
1507 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1509 {TLS1_1_VERSION, NULL, NULL},
1511 #ifndef OPENSSL_NO_TLS1
1512 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1514 {TLS1_VERSION, NULL, NULL},
1516 #ifndef OPENSSL_NO_SSL3
1517 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1519 {SSL3_VERSION, NULL, NULL},
1524 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1525 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1528 /* Must be in order high to low */
1529 static const version_info dtls_version_table[] = {
1530 #ifndef OPENSSL_NO_DTLS1_2
1531 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1533 {DTLS1_2_VERSION, NULL, NULL},
1535 #ifndef OPENSSL_NO_DTLS1
1536 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1537 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1539 {DTLS1_VERSION, NULL, NULL},
1540 {DTLS1_BAD_VER, NULL, NULL},
1546 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1548 * @s: The SSL handle for the candidate method
1549 * @method: the intended method.
1551 * Returns 0 on success, or an SSL error reason on failure.
1553 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1555 int version = method->version;
1557 if ((s->min_proto_version != 0 &&
1558 version_cmp(s, version, s->min_proto_version) < 0) ||
1559 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1560 return SSL_R_VERSION_TOO_LOW;
1562 if (s->max_proto_version != 0 &&
1563 version_cmp(s, version, s->max_proto_version) > 0)
1564 return SSL_R_VERSION_TOO_HIGH;
1566 if ((s->options & method->mask) != 0)
1567 return SSL_R_UNSUPPORTED_PROTOCOL;
1568 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1569 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1575 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1576 * certificate type, or has PSK or a certificate callback configured. Otherwise
1579 static int is_tls13_capable(const SSL *s)
1582 #ifndef OPENSSL_NO_EC
1586 #ifndef OPENSSL_NO_PSK
1587 if (s->psk_server_callback != NULL)
1591 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1594 for (i = 0; i < SSL_PKEY_NUM; i++) {
1595 /* Skip over certs disallowed for TLSv1.3 */
1597 case SSL_PKEY_DSA_SIGN:
1598 case SSL_PKEY_GOST01:
1599 case SSL_PKEY_GOST12_256:
1600 case SSL_PKEY_GOST12_512:
1605 if (!ssl_has_cert(s, i))
1607 #ifndef OPENSSL_NO_EC
1608 if (i != SSL_PKEY_ECC)
1611 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1612 * more restrictive so check that our sig algs are consistent with this
1613 * EC cert. See section 4.2.3 of RFC8446.
1615 curve = evp_pkey_get_EC_KEY_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
1617 if (tls_check_sigalg_curve(s, curve))
1628 * ssl_version_supported - Check that the specified `version` is supported by
1631 * @s: The SSL handle for the candidate method
1632 * @version: Protocol version to test against
1634 * Returns 1 when supported, otherwise 0
1636 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1638 const version_info *vent;
1639 const version_info *table;
1641 switch (s->method->version) {
1643 /* Version should match method version for non-ANY method */
1644 return version_cmp(s, version, s->version) == 0;
1645 case TLS_ANY_VERSION:
1646 table = tls_version_table;
1648 case DTLS_ANY_VERSION:
1649 table = dtls_version_table;
1654 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1656 if (vent->cmeth != NULL
1657 && version_cmp(s, version, vent->version) == 0
1658 && ssl_method_error(s, vent->cmeth()) == 0
1660 || version != TLS1_3_VERSION
1661 || is_tls13_capable(s))) {
1663 *meth = vent->cmeth();
1671 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1672 * fallback indication from a client check whether we're using the highest
1673 * supported protocol version.
1675 * @s server SSL handle.
1677 * Returns 1 when using the highest enabled version, 0 otherwise.
1679 int ssl_check_version_downgrade(SSL *s)
1681 const version_info *vent;
1682 const version_info *table;
1685 * Check that the current protocol is the highest enabled version
1686 * (according to s->ctx->method, as version negotiation may have changed
1689 if (s->version == s->ctx->method->version)
1693 * Apparently we're using a version-flexible SSL_METHOD (not at its
1694 * highest protocol version).
1696 if (s->ctx->method->version == TLS_method()->version)
1697 table = tls_version_table;
1698 else if (s->ctx->method->version == DTLS_method()->version)
1699 table = dtls_version_table;
1701 /* Unexpected state; fail closed. */
1705 for (vent = table; vent->version != 0; ++vent) {
1706 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1707 return s->version == vent->version;
1713 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1714 * protocols, provided the initial (D)TLS method is version-flexible. This
1715 * function sanity-checks the proposed value and makes sure the method is
1716 * version-flexible, then sets the limit if all is well.
1718 * @method_version: The version of the current SSL_METHOD.
1719 * @version: the intended limit.
1720 * @bound: pointer to limit to be updated.
1722 * Returns 1 on success, 0 on failure.
1724 int ssl_set_version_bound(int method_version, int version, int *bound)
1734 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1736 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1737 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1739 if (!valid_tls && !valid_dtls)
1743 * Restrict TLS methods to TLS protocol versions.
1744 * Restrict DTLS methods to DTLS protocol versions.
1745 * Note, DTLS version numbers are decreasing, use comparison macros.
1747 * Note that for both lower-bounds we use explicit versions, not
1748 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1749 * configurations. If the MIN (supported) version ever rises, the user's
1750 * "floor" remains valid even if no longer available. We don't expect the
1751 * MAX ceiling to ever get lower, so making that variable makes sense.
1753 * We ignore attempts to set bounds on version-inflexible methods,
1754 * returning success.
1756 switch (method_version) {
1760 case TLS_ANY_VERSION:
1765 case DTLS_ANY_VERSION:
1773 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1775 if (vers == TLS1_2_VERSION
1776 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1777 *dgrd = DOWNGRADE_TO_1_2;
1778 } else if (!SSL_IS_DTLS(s)
1779 && vers < TLS1_2_VERSION
1781 * We need to ensure that a server that disables TLSv1.2
1782 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1783 * complete handshakes with clients that support TLSv1.2 and
1784 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1785 * enabled and TLSv1.2 is not.
1787 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1788 *dgrd = DOWNGRADE_TO_1_1;
1790 *dgrd = DOWNGRADE_NONE;
1795 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1796 * client HELLO is received to select the final server protocol version and
1797 * the version specific method.
1799 * @s: server SSL handle.
1801 * Returns 0 on success or an SSL error reason number on failure.
1803 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1806 * With version-flexible methods we have an initial state with:
1808 * s->method->version == (D)TLS_ANY_VERSION,
1809 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1811 * So we detect version-flexible methods via the method version, not the
1814 int server_version = s->method->version;
1815 int client_version = hello->legacy_version;
1816 const version_info *vent;
1817 const version_info *table;
1819 RAW_EXTENSION *suppversions;
1821 s->client_version = client_version;
1823 switch (server_version) {
1825 if (!SSL_IS_TLS13(s)) {
1826 if (version_cmp(s, client_version, s->version) < 0)
1827 return SSL_R_WRONG_SSL_VERSION;
1828 *dgrd = DOWNGRADE_NONE;
1830 * If this SSL handle is not from a version flexible method we don't
1831 * (and never did) check min/max FIPS or Suite B constraints. Hope
1832 * that's OK. It is up to the caller to not choose fixed protocol
1833 * versions they don't want. If not, then easy to fix, just return
1834 * ssl_method_error(s, s->method)
1839 * Fall through if we are TLSv1.3 already (this means we must be after
1840 * a HelloRetryRequest
1843 case TLS_ANY_VERSION:
1844 table = tls_version_table;
1846 case DTLS_ANY_VERSION:
1847 table = dtls_version_table;
1851 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1853 /* If we did an HRR then supported versions is mandatory */
1854 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1855 return SSL_R_UNSUPPORTED_PROTOCOL;
1857 if (suppversions->present && !SSL_IS_DTLS(s)) {
1858 unsigned int candidate_vers = 0;
1859 unsigned int best_vers = 0;
1860 const SSL_METHOD *best_method = NULL;
1861 PACKET versionslist;
1863 suppversions->parsed = 1;
1865 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1866 /* Trailing or invalid data? */
1867 return SSL_R_LENGTH_MISMATCH;
1871 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1872 * The spec only requires servers to check that it isn't SSLv3:
1873 * "Any endpoint receiving a Hello message with
1874 * ClientHello.legacy_version or ServerHello.legacy_version set to
1875 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1876 * We are slightly stricter and require that it isn't SSLv3 or lower.
1877 * We tolerate TLSv1 and TLSv1.1.
1879 if (client_version <= SSL3_VERSION)
1880 return SSL_R_BAD_LEGACY_VERSION;
1882 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1883 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1885 if (ssl_version_supported(s, candidate_vers, &best_method))
1886 best_vers = candidate_vers;
1888 if (PACKET_remaining(&versionslist) != 0) {
1889 /* Trailing data? */
1890 return SSL_R_LENGTH_MISMATCH;
1893 if (best_vers > 0) {
1894 if (s->hello_retry_request != SSL_HRR_NONE) {
1896 * This is after a HelloRetryRequest so we better check that we
1897 * negotiated TLSv1.3
1899 if (best_vers != TLS1_3_VERSION)
1900 return SSL_R_UNSUPPORTED_PROTOCOL;
1903 check_for_downgrade(s, best_vers, dgrd);
1904 s->version = best_vers;
1905 s->method = best_method;
1908 return SSL_R_UNSUPPORTED_PROTOCOL;
1912 * If the supported versions extension isn't present, then the highest
1913 * version we can negotiate is TLSv1.2
1915 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1916 client_version = TLS1_2_VERSION;
1919 * No supported versions extension, so we just use the version supplied in
1922 for (vent = table; vent->version != 0; ++vent) {
1923 const SSL_METHOD *method;
1925 if (vent->smeth == NULL ||
1926 version_cmp(s, client_version, vent->version) < 0)
1928 method = vent->smeth();
1929 if (ssl_method_error(s, method) == 0) {
1930 check_for_downgrade(s, vent->version, dgrd);
1931 s->version = vent->version;
1937 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1941 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1942 * server HELLO is received to select the final client protocol version and
1943 * the version specific method.
1945 * @s: client SSL handle.
1946 * @version: The proposed version from the server's HELLO.
1947 * @extensions: The extensions received
1949 * Returns 1 on success or 0 on error.
1951 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1953 const version_info *vent;
1954 const version_info *table;
1955 int ret, ver_min, ver_max, real_max, origv;
1958 s->version = version;
1960 /* This will overwrite s->version if the extension is present */
1961 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1962 SSL_EXT_TLS1_2_SERVER_HELLO
1963 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1969 if (s->hello_retry_request != SSL_HRR_NONE
1970 && s->version != TLS1_3_VERSION) {
1972 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1973 SSL_R_WRONG_SSL_VERSION);
1977 switch (s->method->version) {
1979 if (s->version != s->method->version) {
1981 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1982 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1983 SSL_R_WRONG_SSL_VERSION);
1987 * If this SSL handle is not from a version flexible method we don't
1988 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1989 * that's OK. It is up to the caller to not choose fixed protocol
1990 * versions they don't want. If not, then easy to fix, just return
1991 * ssl_method_error(s, s->method)
1994 case TLS_ANY_VERSION:
1995 table = tls_version_table;
1997 case DTLS_ANY_VERSION:
1998 table = dtls_version_table;
2002 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2005 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2006 SSL_F_SSL_CHOOSE_CLIENT_VERSION, ret);
2009 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2010 : s->version < ver_min) {
2012 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2013 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2015 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2016 : s->version > ver_max) {
2018 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
2019 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2023 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2026 /* Check for downgrades */
2027 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2028 if (memcmp(tls12downgrade,
2029 s->s3.server_random + SSL3_RANDOM_SIZE
2030 - sizeof(tls12downgrade),
2031 sizeof(tls12downgrade)) == 0) {
2033 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2034 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2035 SSL_R_INAPPROPRIATE_FALLBACK);
2038 } else if (!SSL_IS_DTLS(s)
2039 && s->version < TLS1_2_VERSION
2040 && real_max > s->version) {
2041 if (memcmp(tls11downgrade,
2042 s->s3.server_random + SSL3_RANDOM_SIZE
2043 - sizeof(tls11downgrade),
2044 sizeof(tls11downgrade)) == 0) {
2046 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2047 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2048 SSL_R_INAPPROPRIATE_FALLBACK);
2053 for (vent = table; vent->version != 0; ++vent) {
2054 if (vent->cmeth == NULL || s->version != vent->version)
2057 s->method = vent->cmeth();
2062 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2063 SSL_R_UNSUPPORTED_PROTOCOL);
2068 * ssl_get_min_max_version - get minimum and maximum protocol version
2069 * @s: The SSL connection
2070 * @min_version: The minimum supported version
2071 * @max_version: The maximum supported version
2072 * @real_max: The highest version below the lowest compile time version hole
2073 * where that hole lies above at least one run-time enabled
2076 * Work out what version we should be using for the initial ClientHello if the
2077 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2078 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2079 * constraints and any floor imposed by the security level here,
2080 * so we don't advertise the wrong protocol version to only reject the outcome later.
2082 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2083 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2084 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2086 * Returns 0 on success or an SSL error reason number on failure. On failure
2087 * min_version and max_version will also be set to 0.
2089 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2092 int version, tmp_real_max;
2094 const SSL_METHOD *single = NULL;
2095 const SSL_METHOD *method;
2096 const version_info *table;
2097 const version_info *vent;
2099 switch (s->method->version) {
2102 * If this SSL handle is not from a version flexible method we don't
2103 * (and never did) check min/max FIPS or Suite B constraints. Hope
2104 * that's OK. It is up to the caller to not choose fixed protocol
2105 * versions they don't want. If not, then easy to fix, just return
2106 * ssl_method_error(s, s->method)
2108 *min_version = *max_version = s->version;
2110 * Providing a real_max only makes sense where we're using a version
2113 if (!ossl_assert(real_max == NULL))
2114 return ERR_R_INTERNAL_ERROR;
2116 case TLS_ANY_VERSION:
2117 table = tls_version_table;
2119 case DTLS_ANY_VERSION:
2120 table = dtls_version_table;
2125 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2126 * below X enabled. This is required in order to maintain the "version
2127 * capability" vector contiguous. Any versions with a NULL client method
2128 * (protocol version client is disabled at compile-time) is also a "hole".
2130 * Our initial state is hole == 1, version == 0. That is, versions above
2131 * the first version in the method table are disabled (a "hole" above
2132 * the valid protocol entries) and we don't have a selected version yet.
2134 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2135 * the selected version, and the method becomes a candidate "single"
2136 * method. We're no longer in a hole, so "hole" becomes 0.
2138 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2139 * as we support a contiguous range of at least two methods. If we hit
2140 * a disabled method, then hole becomes true again, but nothing else
2141 * changes yet, because all the remaining methods may be disabled too.
2142 * If we again hit an enabled method after the new hole, it becomes
2143 * selected, as we start from scratch.
2145 *min_version = version = 0;
2147 if (real_max != NULL)
2150 for (vent = table; vent->version != 0; ++vent) {
2152 * A table entry with a NULL client method is still a hole in the
2153 * "version capability" vector.
2155 if (vent->cmeth == NULL) {
2160 method = vent->cmeth();
2162 if (hole == 1 && tmp_real_max == 0)
2163 tmp_real_max = vent->version;
2165 if (ssl_method_error(s, method) != 0) {
2169 *min_version = method->version;
2171 if (real_max != NULL && tmp_real_max != 0)
2172 *real_max = tmp_real_max;
2173 version = (single = method)->version;
2174 *min_version = version;
2179 *max_version = version;
2181 /* Fail if everything is disabled */
2183 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2189 * ssl_set_client_hello_version - Work out what version we should be using for
2190 * the initial ClientHello.legacy_version field.
2192 * @s: client SSL handle.
2194 * Returns 0 on success or an SSL error reason number on failure.
2196 int ssl_set_client_hello_version(SSL *s)
2198 int ver_min, ver_max, ret;
2201 * In a renegotiation we always send the same client_version that we sent
2202 * last time, regardless of which version we eventually negotiated.
2204 if (!SSL_IS_FIRST_HANDSHAKE(s))
2207 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2212 s->version = ver_max;
2214 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2215 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2216 ver_max = TLS1_2_VERSION;
2218 s->client_version = ver_max;
2223 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2224 * and |checkallow| is 1 then additionally check if the group is allowed to be
2225 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2226 * 1) or 0 otherwise.
2228 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2229 size_t num_groups, int checkallow)
2233 if (groups == NULL || num_groups == 0)
2236 for (i = 0; i < num_groups; i++) {
2237 uint16_t group = groups[i];
2239 if (group_id == group
2241 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2249 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2250 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2251 size_t hashlen, const unsigned char *hrr,
2254 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2255 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2257 memset(msghdr, 0, sizeof(msghdr));
2259 if (hashval == NULL) {
2260 hashval = hashvaltmp;
2262 /* Get the hash of the initial ClientHello */
2263 if (!ssl3_digest_cached_records(s, 0)
2264 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2266 /* SSLfatal() already called */
2271 /* Reinitialise the transcript hash */
2272 if (!ssl3_init_finished_mac(s)) {
2273 /* SSLfatal() already called */
2277 /* Inject the synthetic message_hash message */
2278 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2279 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2280 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2281 || !ssl3_finish_mac(s, hashval, hashlen)) {
2282 /* SSLfatal() already called */
2287 * Now re-inject the HRR and current message if appropriate (we just deleted
2288 * it when we reinitialised the transcript hash above). Only necessary after
2289 * receiving a ClientHello2 with a cookie.
2292 && (!ssl3_finish_mac(s, hrr, hrrlen)
2293 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2294 s->s3.tmp.message_size
2295 + SSL3_HM_HEADER_LENGTH))) {
2296 /* SSLfatal() already called */
2303 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2305 return X509_NAME_cmp(*a, *b);
2308 int parse_ca_names(SSL *s, PACKET *pkt)
2310 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2311 X509_NAME *xn = NULL;
2314 if (ca_sk == NULL) {
2315 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2316 ERR_R_MALLOC_FAILURE);
2319 /* get the CA RDNs */
2320 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2321 SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2322 SSL_R_LENGTH_MISMATCH);
2326 while (PACKET_remaining(&cadns)) {
2327 const unsigned char *namestart, *namebytes;
2328 unsigned int name_len;
2330 if (!PACKET_get_net_2(&cadns, &name_len)
2331 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2332 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2333 SSL_R_LENGTH_MISMATCH);
2337 namestart = namebytes;
2338 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2339 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2343 if (namebytes != (namestart + name_len)) {
2344 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2345 SSL_R_CA_DN_LENGTH_MISMATCH);
2349 if (!sk_X509_NAME_push(ca_sk, xn)) {
2350 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2351 ERR_R_MALLOC_FAILURE);
2357 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2358 s->s3.tmp.peer_ca_names = ca_sk;
2363 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2368 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2370 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2373 ca_sk = SSL_get_client_CA_list(s);
2374 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2379 ca_sk = SSL_get0_CA_list(s);
2384 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2386 /* Start sub-packet for client CA list */
2387 if (!WPACKET_start_sub_packet_u16(pkt)) {
2388 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2389 ERR_R_INTERNAL_ERROR);
2393 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2396 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2397 unsigned char *namebytes;
2398 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2402 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2403 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2405 || i2d_X509_NAME(name, &namebytes) != namelen) {
2406 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2407 ERR_R_INTERNAL_ERROR);
2413 if (!WPACKET_close(pkt)) {
2414 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2415 ERR_R_INTERNAL_ERROR);
2422 /* Create a buffer containing data to be signed for server key exchange */
2423 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2424 const void *param, size_t paramlen)
2426 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2427 unsigned char *tbs = OPENSSL_malloc(tbslen);
2430 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2431 ERR_R_MALLOC_FAILURE);
2434 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2435 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2437 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2444 * Saves the current handshake digest for Post-Handshake Auth,
2445 * Done after ClientFinished is processed, done exactly once
2447 int tls13_save_handshake_digest_for_pha(SSL *s)
2449 if (s->pha_dgst == NULL) {
2450 if (!ssl3_digest_cached_records(s, 1))
2451 /* SSLfatal() already called */
2454 s->pha_dgst = EVP_MD_CTX_new();
2455 if (s->pha_dgst == NULL) {
2456 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2457 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2458 ERR_R_INTERNAL_ERROR);
2461 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2462 s->s3.handshake_dgst)) {
2463 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2464 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2465 ERR_R_INTERNAL_ERROR);
2473 * Restores the Post-Handshake Auth handshake digest
2474 * Done just before sending/processing the Cert Request
2476 int tls13_restore_handshake_digest_for_pha(SSL *s)
2478 if (s->pha_dgst == NULL) {
2479 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2480 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2481 ERR_R_INTERNAL_ERROR);
2484 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2486 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2487 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2488 ERR_R_INTERNAL_ERROR);