2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/rsa.h>
21 #include <openssl/x509.h>
22 #include <openssl/trace.h>
25 * Map error codes to TLS/SSL alart types.
27 typedef struct x509err2alert_st {
32 /* Fixed value used in the ServerHello random field to identify an HRR */
33 const unsigned char hrrrandom[] = {
34 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
35 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
36 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
39 int ossl_statem_set_mutator(SSL *s,
40 ossl_statem_mutate_handshake_cb mutate_handshake_cb,
41 ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
44 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
49 sc->statem.mutate_handshake_cb = mutate_handshake_cb;
50 sc->statem.mutatearg = mutatearg;
51 sc->statem.finish_mutate_handshake_cb = finish_mutate_handshake_cb;
57 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
58 * SSL3_RT_CHANGE_CIPHER_SPEC)
60 int ssl3_do_write(SSL_CONNECTION *s, int type)
64 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
67 * If we're running the test suite then we may need to mutate the message
68 * we've been asked to write. Does not happen in normal operation.
70 if (s->statem.mutate_handshake_cb != NULL
71 && !s->statem.write_in_progress
72 && type == SSL3_RT_HANDSHAKE
73 && s->init_num >= SSL3_HM_HEADER_LENGTH) {
77 if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
82 if (msglen < SSL3_HM_HEADER_LENGTH
83 || !BUF_MEM_grow(s->init_buf, msglen))
85 memcpy(s->init_buf->data, msg, msglen);
87 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
88 s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
89 s->statem.write_in_progress = 1;
92 ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
93 s->init_num, &written);
96 if (type == SSL3_RT_HANDSHAKE)
98 * should not be done for 'Hello Request's, but in that case we'll
99 * ignore the result anyway
100 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
102 if (!SSL_CONNECTION_IS_TLS13(s)
103 || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
104 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
105 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
106 if (!ssl3_finish_mac(s,
107 (unsigned char *)&s->init_buf->data[s->init_off],
110 if (written == s->init_num) {
111 s->statem.write_in_progress = 0;
113 s->msg_callback(1, s->version, type, s->init_buf->data,
114 (size_t)(s->init_off + s->init_num), ssl,
115 s->msg_callback_arg);
118 s->init_off += written;
119 s->init_num -= written;
123 int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
127 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
128 || !WPACKET_get_length(pkt, &msglen)
131 s->init_num = (int)msglen;
137 int tls_setup_handshake(SSL_CONNECTION *s)
139 int ver_min, ver_max, ok;
140 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
141 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
143 if (!ssl3_init_finished_mac(s)) {
144 /* SSLfatal() already called */
148 /* Reset any extension flags */
149 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
151 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
152 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
156 /* Sanity check that we have MD5-SHA1 if we need it */
157 if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
158 int md5sha1_needed = 0;
160 /* We don't have MD5-SHA1 - do we need it? */
161 if (SSL_CONNECTION_IS_DTLS(s)) {
162 if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
165 if (ver_max <= TLS1_1_VERSION)
168 if (md5sha1_needed) {
169 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
170 SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
171 "The max supported SSL/TLS version needs the"
172 " MD5-SHA1 digest but it is not available"
173 " in the loaded providers. Use (D)TLSv1.2 or"
174 " above, or load different providers");
179 /* Don't allow TLSv1.1 or below to be negotiated */
180 if (SSL_CONNECTION_IS_DTLS(s)) {
181 if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
182 ok = SSL_set_min_proto_version(ssl, DTLS1_2_VERSION);
184 if (ver_min < TLS1_2_VERSION)
185 ok = SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
188 /* Shouldn't happen */
189 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
196 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
200 * Sanity check that the maximum version we accept has ciphers
201 * enabled. For clients we do this check during construction of the
204 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
205 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
207 if (SSL_CONNECTION_IS_DTLS(s)) {
208 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
209 DTLS_VERSION_LE(ver_max, c->max_dtls))
211 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
218 SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
219 SSL_R_NO_CIPHERS_AVAILABLE,
220 "No ciphers enabled for max supported "
224 if (SSL_IS_FIRST_HANDSHAKE(s)) {
225 /* N.B. s->session_ctx == s->ctx here */
226 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
228 /* N.B. s->ctx may not equal s->session_ctx */
229 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
231 s->s3.tmp.cert_request = 0;
234 if (SSL_IS_FIRST_HANDSHAKE(s))
235 ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
237 ssl_tsan_counter(s->session_ctx,
238 &s->session_ctx->stats.sess_connect_renegotiate);
240 /* mark client_random uninitialized */
241 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
244 s->s3.tmp.cert_req = 0;
246 if (SSL_CONNECTION_IS_DTLS(s))
247 s->statem.use_timer = 1;
254 * Size of the to-be-signed TLS13 data, without the hash size itself:
255 * 64 bytes of value 32, 33 context bytes, 1 byte separator
257 #define TLS13_TBS_START_SIZE 64
258 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
260 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
261 void **hdata, size_t *hdatalen)
263 /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
264 static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
265 "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
266 /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
267 static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
268 "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
270 if (SSL_CONNECTION_IS_TLS13(s)) {
273 /* Set the first 64 bytes of to-be-signed data to octet 32 */
274 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
275 /* This copies the 33 bytes of context plus the 0 separator byte */
276 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
277 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
278 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
280 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
283 * If we're currently reading then we need to use the saved handshake
284 * hash value. We can't use the current handshake hash state because
285 * that includes the CertVerify itself.
287 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
288 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
289 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
290 s->cert_verify_hash_len);
291 hashlen = s->cert_verify_hash_len;
292 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
293 EVP_MAX_MD_SIZE, &hashlen)) {
294 /* SSLfatal() already called */
299 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
304 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
306 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
315 CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
317 EVP_PKEY *pkey = NULL;
318 const EVP_MD *md = NULL;
319 EVP_MD_CTX *mctx = NULL;
320 EVP_PKEY_CTX *pctx = NULL;
321 size_t hdatalen = 0, siglen = 0;
323 unsigned char *sig = NULL;
324 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
325 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
326 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
328 if (lu == NULL || s->s3.tmp.cert == NULL) {
329 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
332 pkey = s->s3.tmp.cert->privatekey;
334 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
335 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
339 mctx = EVP_MD_CTX_new();
341 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
345 /* Get the data to be signed */
346 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
347 /* SSLfatal() already called */
351 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
352 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
356 if (EVP_DigestSignInit_ex(mctx, &pctx,
357 md == NULL ? NULL : EVP_MD_get0_name(md),
358 sctx->libctx, sctx->propq, pkey,
360 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
364 if (lu->sig == EVP_PKEY_RSA_PSS) {
365 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
366 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
367 RSA_PSS_SALTLEN_DIGEST) <= 0) {
368 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
372 if (s->version == SSL3_VERSION) {
374 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
375 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
377 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
378 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
379 (int)s->session->master_key_length,
380 s->session->master_key) <= 0
381 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
383 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
386 sig = OPENSSL_malloc(siglen);
388 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
389 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
394 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
395 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
397 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
398 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
401 sig = OPENSSL_malloc(siglen);
403 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
404 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
409 #ifndef OPENSSL_NO_GOST
411 int pktype = lu->sig;
413 if (pktype == NID_id_GostR3410_2001
414 || pktype == NID_id_GostR3410_2012_256
415 || pktype == NID_id_GostR3410_2012_512)
416 BUF_reverse(sig, NULL, siglen);
420 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
421 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
425 /* Digest cached records and discard handshake buffer */
426 if (!ssl3_digest_cached_records(s, 0)) {
427 /* SSLfatal() already called */
432 EVP_MD_CTX_free(mctx);
433 return CON_FUNC_SUCCESS;
436 EVP_MD_CTX_free(mctx);
437 return CON_FUNC_ERROR;
440 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
442 EVP_PKEY *pkey = NULL;
443 const unsigned char *data;
444 #ifndef OPENSSL_NO_GOST
445 unsigned char *gost_data = NULL;
447 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
451 const EVP_MD *md = NULL;
454 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
455 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
456 EVP_PKEY_CTX *pctx = NULL;
457 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
460 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
464 peer = s->session->peer;
465 pkey = X509_get0_pubkey(peer);
467 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
471 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
472 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
473 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
477 if (SSL_USE_SIGALGS(s)) {
480 if (!PACKET_get_net_2(pkt, &sigalg)) {
481 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
484 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
485 /* SSLfatal() already called */
488 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
489 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
490 SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
494 if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
495 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
499 if (SSL_USE_SIGALGS(s))
500 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
501 md == NULL ? "n/a" : EVP_MD_get0_name(md));
503 /* Check for broken implementations of GOST ciphersuites */
505 * If key is GOST and len is exactly 64 or 128, it is signature without
506 * length field (CryptoPro implementations at least till TLS 1.2)
508 #ifndef OPENSSL_NO_GOST
509 if (!SSL_USE_SIGALGS(s)
510 && ((PACKET_remaining(pkt) == 64
511 && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
512 || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
513 || (PACKET_remaining(pkt) == 128
514 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
515 len = PACKET_remaining(pkt);
518 if (!PACKET_get_net_2(pkt, &len)) {
519 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
523 if (!PACKET_get_bytes(pkt, &data, len)) {
524 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
528 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
529 /* SSLfatal() already called */
533 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
534 md == NULL ? "n/a" : EVP_MD_get0_name(md));
536 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
537 md == NULL ? NULL : EVP_MD_get0_name(md),
538 sctx->libctx, sctx->propq, pkey,
540 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
543 #ifndef OPENSSL_NO_GOST
545 int pktype = EVP_PKEY_get_id(pkey);
546 if (pktype == NID_id_GostR3410_2001
547 || pktype == NID_id_GostR3410_2012_256
548 || pktype == NID_id_GostR3410_2012_512) {
549 if ((gost_data = OPENSSL_malloc(len)) == NULL)
551 BUF_reverse(gost_data, data, len);
557 if (SSL_USE_PSS(s)) {
558 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
559 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
560 RSA_PSS_SALTLEN_DIGEST) <= 0) {
561 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
565 if (s->version == SSL3_VERSION) {
566 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
567 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
568 (int)s->session->master_key_length,
569 s->session->master_key) <= 0) {
570 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
573 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
574 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
578 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
580 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
586 * In TLSv1.3 on the client side we make sure we prepare the client
587 * certificate after the CertVerify instead of when we get the
588 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
589 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
590 * want to make sure that SSL_get1_peer_certificate() will return the actual
591 * server certificate from the client_cert_cb callback.
593 if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
594 ret = MSG_PROCESS_CONTINUE_PROCESSING;
596 ret = MSG_PROCESS_CONTINUE_READING;
598 BIO_free(s->s3.handshake_buffer);
599 s->s3.handshake_buffer = NULL;
600 EVP_MD_CTX_free(mctx);
601 #ifndef OPENSSL_NO_GOST
602 OPENSSL_free(gost_data);
607 CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
609 size_t finish_md_len;
612 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
614 /* This is a real handshake so make sure we clean it up at the end */
615 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
616 s->statem.cleanuphand = 1;
619 * We only change the keys if we didn't already do this when we sent the
622 if (SSL_CONNECTION_IS_TLS13(s)
624 && s->s3.tmp.cert_req == 0
625 && (!ssl->method->ssl3_enc->change_cipher_state(s,
626 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
627 /* SSLfatal() already called */
628 return CON_FUNC_ERROR;
632 sender = ssl->method->ssl3_enc->server_finished_label;
633 slen = ssl->method->ssl3_enc->server_finished_label_len;
635 sender = ssl->method->ssl3_enc->client_finished_label;
636 slen = ssl->method->ssl3_enc->client_finished_label_len;
639 finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
641 s->s3.tmp.finish_md);
642 if (finish_md_len == 0) {
643 /* SSLfatal() already called */
644 return CON_FUNC_ERROR;
647 s->s3.tmp.finish_md_len = finish_md_len;
649 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
650 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
651 return CON_FUNC_ERROR;
655 * Log the master secret, if logging is enabled. We don't log it for
656 * TLSv1.3: there's a different key schedule for that.
658 if (!SSL_CONNECTION_IS_TLS13(s)
659 && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
660 s->session->master_key_length)) {
661 /* SSLfatal() already called */
662 return CON_FUNC_ERROR;
666 * Copy the finished so we can use it for renegotiation checks
668 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
669 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
670 return CON_FUNC_ERROR;
673 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
675 s->s3.previous_client_finished_len = finish_md_len;
677 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
679 s->s3.previous_server_finished_len = finish_md_len;
682 return CON_FUNC_SUCCESS;
685 CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
687 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
688 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
689 return CON_FUNC_ERROR;
692 s->key_update = SSL_KEY_UPDATE_NONE;
693 return CON_FUNC_SUCCESS;
696 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
698 unsigned int updatetype;
701 * A KeyUpdate message signals a key change so the end of the message must
702 * be on a record boundary.
704 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
705 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
706 return MSG_PROCESS_ERROR;
709 if (!PACKET_get_1(pkt, &updatetype)
710 || PACKET_remaining(pkt) != 0) {
711 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
712 return MSG_PROCESS_ERROR;
716 * There are only two defined key update types. Fail if we get a value we
719 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
720 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
721 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
722 return MSG_PROCESS_ERROR;
726 * If we get a request for us to update our sending keys too then, we need
727 * to additionally send a KeyUpdate message. However that message should
728 * not also request an update (otherwise we get into an infinite loop).
730 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
731 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
733 if (!tls13_update_key(s, 0)) {
734 /* SSLfatal() already called */
735 return MSG_PROCESS_ERROR;
738 return MSG_PROCESS_FINISHED_READING;
742 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
745 int ssl3_take_mac(SSL_CONNECTION *s)
749 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
752 sender = ssl->method->ssl3_enc->server_finished_label;
753 slen = ssl->method->ssl3_enc->server_finished_label_len;
755 sender = ssl->method->ssl3_enc->client_finished_label;
756 slen = ssl->method->ssl3_enc->client_finished_label_len;
759 s->s3.tmp.peer_finish_md_len =
760 ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
761 s->s3.tmp.peer_finish_md);
763 if (s->s3.tmp.peer_finish_md_len == 0) {
764 /* SSLfatal() already called */
771 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
776 remain = PACKET_remaining(pkt);
778 * 'Change Cipher Spec' is just a single byte, which should already have
779 * been consumed by ssl_get_message() so there should be no bytes left,
780 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
782 if (SSL_CONNECTION_IS_DTLS(s)) {
783 if ((s->version == DTLS1_BAD_VER
784 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
785 || (s->version != DTLS1_BAD_VER
786 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
787 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
788 return MSG_PROCESS_ERROR;
792 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
793 return MSG_PROCESS_ERROR;
797 /* Check we have a cipher to change to */
798 if (s->s3.tmp.new_cipher == NULL) {
799 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
800 return MSG_PROCESS_ERROR;
803 s->s3.change_cipher_spec = 1;
804 if (!ssl3_do_change_cipher_spec(s)) {
805 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
806 return MSG_PROCESS_ERROR;
809 if (SSL_CONNECTION_IS_DTLS(s)) {
810 dtls1_increment_epoch(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(SSL_CONNECTION_GET_SSL(s)),
822 BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
826 return MSG_PROCESS_CONTINUE_READING;
829 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
832 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
833 int was_first = SSL_IS_FIRST_HANDSHAKE(s);
837 /* This is a real handshake so make sure we clean it up at the end */
840 * To get this far we must have read encrypted data from the client. We
841 * no longer tolerate unencrypted alerts. This is ignored if less than
844 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
845 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
846 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
847 s->statem.cleanuphand = 1;
848 if (SSL_CONNECTION_IS_TLS13(s)
849 && !tls13_save_handshake_digest_for_pha(s)) {
850 /* SSLfatal() already called */
851 return MSG_PROCESS_ERROR;
856 * In TLSv1.3 a Finished message signals a key change so the end of the
857 * message must be on a record boundary.
859 if (SSL_CONNECTION_IS_TLS13(s)
860 && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
861 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
862 return MSG_PROCESS_ERROR;
865 /* If this occurs, we have missed a message */
866 if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
867 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
868 return MSG_PROCESS_ERROR;
870 s->s3.change_cipher_spec = 0;
872 md_len = s->s3.tmp.peer_finish_md_len;
874 if (md_len != PACKET_remaining(pkt)) {
875 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
876 return MSG_PROCESS_ERROR;
879 ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
881 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
883 if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
889 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
890 return MSG_PROCESS_ERROR;
894 * Copy the finished so we can use it for renegotiation checks
896 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
897 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
898 return MSG_PROCESS_ERROR;
901 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
903 s->s3.previous_client_finished_len = md_len;
905 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
907 s->s3.previous_server_finished_len = md_len;
911 * In TLS1.3 we also have to change cipher state and do any final processing
912 * of the initial server flight (if we are a client)
914 if (SSL_CONNECTION_IS_TLS13(s)) {
916 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
917 !ssl->method->ssl3_enc->change_cipher_state(s,
918 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
919 /* SSLfatal() already called */
920 return MSG_PROCESS_ERROR;
923 /* TLS 1.3 gets the secret size from the handshake md */
925 if (!ssl->method->ssl3_enc->generate_master_secret(s,
926 s->master_secret, s->handshake_secret, 0,
928 /* SSLfatal() already called */
929 return MSG_PROCESS_ERROR;
931 if (!ssl->method->ssl3_enc->change_cipher_state(s,
932 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
933 /* SSLfatal() already called */
934 return MSG_PROCESS_ERROR;
936 if (!tls_process_initial_server_flight(s)) {
937 /* SSLfatal() already called */
938 return MSG_PROCESS_ERROR;
944 && !SSL_IS_FIRST_HANDSHAKE(s)
945 && s->rlayer.rrlmethod->set_first_handshake != NULL)
946 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
948 return MSG_PROCESS_FINISHED_READING;
951 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
953 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
954 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
955 return CON_FUNC_ERROR;
958 return CON_FUNC_SUCCESS;
961 /* Add a certificate to the WPACKET */
962 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
963 X509 *x, int chain, int for_comp)
966 unsigned char *outbytes;
967 int context = SSL_EXT_TLS1_3_CERTIFICATE;
970 context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
972 len = i2d_X509(x, NULL);
975 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
978 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
979 || i2d_X509(x, &outbytes) != len) {
981 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
985 if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
986 && !tls_construct_extensions(s, pkt, context, x, chain)) {
987 /* SSLfatal() already called */
994 /* Add certificate chain to provided WPACKET */
995 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
999 STACK_OF(X509) *extra_certs;
1000 STACK_OF(X509) *chain = NULL;
1001 X509_STORE *chain_store;
1002 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1004 if (cpk == NULL || cpk->x509 == NULL)
1010 * If we have a certificate specific chain use it, else use parent ctx.
1012 if (cpk->chain != NULL)
1013 extra_certs = cpk->chain;
1015 extra_certs = sctx->extra_certs;
1017 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1019 else if (s->cert->chain_store)
1020 chain_store = s->cert->chain_store;
1022 chain_store = sctx->cert_store;
1024 if (chain_store != NULL) {
1025 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1028 if (xs_ctx == NULL) {
1030 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1033 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1034 X509_STORE_CTX_free(xs_ctx);
1036 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1040 * It is valid for the chain not to be complete (because normally we
1041 * don't include the root cert in the chain). Therefore we deliberately
1042 * ignore the error return from this call. We're not actually verifying
1043 * the cert - we're just building as much of the chain as we can
1045 (void)X509_verify_cert(xs_ctx);
1046 /* Don't leave errors in the queue */
1048 chain = X509_STORE_CTX_get0_chain(xs_ctx);
1049 i = ssl_security_cert_chain(s, chain, NULL, 0);
1052 /* Dummy error calls so mkerr generates them */
1053 ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1054 ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1055 ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1057 X509_STORE_CTX_free(xs_ctx);
1059 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1062 chain_count = sk_X509_num(chain);
1063 for (i = 0; i < chain_count; i++) {
1064 x = sk_X509_value(chain, i);
1066 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1067 /* SSLfatal() already called */
1068 X509_STORE_CTX_free(xs_ctx);
1072 X509_STORE_CTX_free(xs_ctx);
1074 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1077 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1080 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1081 /* SSLfatal() already called */
1084 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1085 x = sk_X509_value(extra_certs, i);
1086 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1087 /* SSLfatal() already called */
1095 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1096 CERT_PKEY *cpk, int for_comp)
1098 if (!WPACKET_start_sub_packet_u24(pkt)) {
1100 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1104 if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1107 if (!WPACKET_close(pkt)) {
1109 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1117 * Tidy up after the end of a handshake. In the case of SCTP this may result
1118 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1121 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1122 int clearbufs, int stop)
1124 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1125 int cleanuphand = s->statem.cleanuphand;
1126 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1127 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1130 if (!SSL_CONNECTION_IS_DTLS(s)
1131 #ifndef OPENSSL_NO_SCTP
1133 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1134 * messages that require it. Therefore, DTLS procedures for retransmissions
1136 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1138 || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1142 * We don't do this in DTLS over UDP because we may still need the init_buf
1143 * in case there are any unexpected retransmits
1145 BUF_MEM_free(s->init_buf);
1149 if (!ssl_free_wbio_buffer(s)) {
1150 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1156 if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1157 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1158 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1161 * Only set if there was a Finished message and this isn't after a TLSv1.3
1162 * post handshake exchange
1165 /* skipped if we just sent a HelloRequest */
1168 s->statem.cleanuphand = 0;
1169 s->ext.ticket_expected = 0;
1171 ssl3_cleanup_key_block(s);
1175 * In TLSv1.3 we update the cache as part of constructing the
1178 if (!SSL_CONNECTION_IS_TLS13(s))
1179 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1181 /* N.B. s->ctx may not equal s->session_ctx */
1182 ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1183 s->handshake_func = ossl_statem_accept;
1185 if (SSL_CONNECTION_IS_TLS13(s)) {
1187 * We encourage applications to only use TLSv1.3 tickets once,
1188 * so we remove this one from the cache.
1190 if ((s->session_ctx->session_cache_mode
1191 & SSL_SESS_CACHE_CLIENT) != 0)
1192 SSL_CTX_remove_session(s->session_ctx, s->session);
1195 * In TLSv1.3 we update the cache as part of processing the
1198 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1201 ssl_tsan_counter(s->session_ctx,
1202 &s->session_ctx->stats.sess_hit);
1204 s->handshake_func = ossl_statem_connect;
1205 ssl_tsan_counter(s->session_ctx,
1206 &s->session_ctx->stats.sess_connect_good);
1209 if (SSL_CONNECTION_IS_DTLS(s)) {
1210 /* done with handshaking */
1211 s->d1->handshake_read_seq = 0;
1212 s->d1->handshake_write_seq = 0;
1213 s->d1->next_handshake_write_seq = 0;
1214 dtls1_clear_received_buffer(s);
1218 if (s->info_callback != NULL)
1219 cb = s->info_callback;
1220 else if (sctx->info_callback != NULL)
1221 cb = sctx->info_callback;
1223 /* The callback may expect us to not be in init at handshake done */
1224 ossl_statem_set_in_init(s, 0);
1228 || !SSL_CONNECTION_IS_TLS13(s)
1229 || SSL_IS_FIRST_HANDSHAKE(s))
1230 cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1234 /* If we've got more work to do we go back into init */
1235 ossl_statem_set_in_init(s, 1);
1236 return WORK_FINISHED_CONTINUE;
1239 return WORK_FINISHED_STOP;
1242 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1244 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1245 int skip_message, i, recvd_type;
1247 size_t l, readbytes;
1248 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1250 p = (unsigned char *)s->init_buf->data;
1253 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1254 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1256 SSL3_HM_HEADER_LENGTH - s->init_num,
1259 s->rwstate = SSL_READING;
1262 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1264 * A ChangeCipherSpec must be a single byte and may not occur
1265 * in the middle of a handshake message.
1267 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1268 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1269 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1272 if (s->statem.hand_state == TLS_ST_BEFORE
1273 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1275 * We are stateless and we received a CCS. Probably this is
1276 * from a client between the first and second ClientHellos.
1277 * We should ignore this, but return an error because we do
1278 * not return success until we see the second ClientHello
1279 * with a valid cookie.
1283 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1284 s->init_num = readbytes - 1;
1285 s->init_msg = s->init_buf->data;
1286 s->s3.tmp.message_size = readbytes;
1288 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1289 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1290 SSL_R_CCS_RECEIVED_EARLY);
1293 s->init_num += readbytes;
1298 if (s->statem.hand_state != TLS_ST_OK
1299 && p[0] == SSL3_MT_HELLO_REQUEST)
1301 * The server may always send 'Hello Request' messages --
1302 * we are doing a handshake anyway now, so ignore them if
1303 * their format is correct. Does not count for 'Finished'
1306 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1310 if (s->msg_callback)
1311 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1312 p, SSL3_HM_HEADER_LENGTH, ssl,
1313 s->msg_callback_arg);
1315 } while (skip_message);
1316 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1319 s->s3.tmp.message_type = *(p++);
1321 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1323 * Only happens with SSLv3+ in an SSLv2 backward compatible
1326 * Total message size is the remaining record bytes to read
1327 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1329 l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1330 s->s3.tmp.message_size = l;
1332 s->init_msg = s->init_buf->data;
1333 s->init_num = SSL3_HM_HEADER_LENGTH;
1336 /* BUF_MEM_grow takes an 'int' parameter */
1337 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1338 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1339 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1342 s->s3.tmp.message_size = l;
1344 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1351 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1353 size_t n, readbytes;
1356 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1358 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1359 /* We've already read everything in */
1360 *len = (unsigned long)s->init_num;
1365 n = s->s3.tmp.message_size - s->init_num;
1367 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1368 &p[s->init_num], n, 0, &readbytes);
1370 s->rwstate = SSL_READING;
1374 s->init_num += readbytes;
1379 * If receiving Finished, record MAC of prior handshake messages for
1380 * Finished verification.
1382 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1383 /* SSLfatal() already called */
1388 /* Feed this message into MAC computation. */
1389 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1390 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1392 /* SSLfatal() already called */
1396 if (s->msg_callback)
1397 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1398 (size_t)s->init_num, ssl, s->msg_callback_arg);
1401 * We defer feeding in the HRR until later. We'll do it as part of
1402 * processing the message
1403 * The TLsv1.3 handshake transcript stops at the ClientFinished
1406 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1407 /* KeyUpdate and NewSessionTicket do not need to be added */
1408 if (!SSL_CONNECTION_IS_TLS13(s)
1409 || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1410 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1411 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1412 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1413 || memcmp(hrrrandom,
1414 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1415 SSL3_RANDOM_SIZE) != 0) {
1416 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1417 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1418 /* SSLfatal() already called */
1424 if (s->msg_callback)
1425 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1426 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1427 s->msg_callback_arg);
1434 static const X509ERR2ALERT x509table[] = {
1435 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1436 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1437 {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1438 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1439 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1440 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1441 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1442 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1443 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1444 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1445 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1446 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1447 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1448 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1449 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1450 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1451 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1452 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1453 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1454 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1455 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1456 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1457 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1458 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1459 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1460 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1461 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1462 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1463 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1464 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1465 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1466 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1467 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1468 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1469 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1470 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1471 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1472 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1473 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1474 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1476 /* Last entry; return this if we don't find the value above. */
1477 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1480 int ssl_x509err2alert(int x509err)
1482 const X509ERR2ALERT *tp;
1484 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1485 if (tp->x509err == x509err)
1490 int ssl_allow_compression(SSL_CONNECTION *s)
1492 if (s->options & SSL_OP_NO_COMPRESSION)
1494 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1497 static int version_cmp(const SSL_CONNECTION *s, int a, int b)
1499 int dtls = SSL_CONNECTION_IS_DTLS(s);
1504 return a < b ? -1 : 1;
1505 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1510 const SSL_METHOD *(*cmeth) (void);
1511 const SSL_METHOD *(*smeth) (void);
1514 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1515 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1518 /* Must be in order high to low */
1519 static const version_info tls_version_table[] = {
1520 #ifndef OPENSSL_NO_TLS1_3
1521 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1523 {TLS1_3_VERSION, NULL, NULL},
1525 #ifndef OPENSSL_NO_TLS1_2
1526 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1528 {TLS1_2_VERSION, NULL, NULL},
1530 #ifndef OPENSSL_NO_TLS1_1
1531 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1533 {TLS1_1_VERSION, NULL, NULL},
1535 #ifndef OPENSSL_NO_TLS1
1536 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1538 {TLS1_VERSION, NULL, NULL},
1540 #ifndef OPENSSL_NO_SSL3
1541 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1543 {SSL3_VERSION, NULL, NULL},
1548 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1549 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1552 /* Must be in order high to low */
1553 static const version_info dtls_version_table[] = {
1554 #ifndef OPENSSL_NO_DTLS1_2
1555 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1557 {DTLS1_2_VERSION, NULL, NULL},
1559 #ifndef OPENSSL_NO_DTLS1
1560 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1561 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1563 {DTLS1_VERSION, NULL, NULL},
1564 {DTLS1_BAD_VER, NULL, NULL},
1570 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1572 * @s: The SSL handle for the candidate method
1573 * @method: the intended method.
1575 * Returns 0 on success, or an SSL error reason on failure.
1577 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1579 int version = method->version;
1581 if ((s->min_proto_version != 0 &&
1582 version_cmp(s, version, s->min_proto_version) < 0) ||
1583 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1584 return SSL_R_VERSION_TOO_LOW;
1586 if (s->max_proto_version != 0 &&
1587 version_cmp(s, version, s->max_proto_version) > 0)
1588 return SSL_R_VERSION_TOO_HIGH;
1590 if ((s->options & method->mask) != 0)
1591 return SSL_R_UNSUPPORTED_PROTOCOL;
1592 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1593 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1599 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1600 * certificate type, or has PSK or a certificate callback configured, or has
1601 * a servername callback configure. Otherwise returns 0.
1603 static int is_tls13_capable(const SSL_CONNECTION *s)
1607 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1609 if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1613 * A servername callback can change the available certs, so if a servername
1614 * cb is set then we just assume TLSv1.3 will be ok
1616 if (sctx->ext.servername_cb != NULL
1617 || s->session_ctx->ext.servername_cb != NULL)
1620 #ifndef OPENSSL_NO_PSK
1621 if (s->psk_server_callback != NULL)
1625 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1628 for (i = 0; i < SSL_PKEY_NUM; i++) {
1629 /* Skip over certs disallowed for TLSv1.3 */
1631 case SSL_PKEY_DSA_SIGN:
1632 case SSL_PKEY_GOST01:
1633 case SSL_PKEY_GOST12_256:
1634 case SSL_PKEY_GOST12_512:
1639 if (!ssl_has_cert(s, i))
1641 if (i != SSL_PKEY_ECC)
1644 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1645 * more restrictive so check that our sig algs are consistent with this
1646 * EC cert. See section 4.2.3 of RFC8446.
1648 curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1649 if (tls_check_sigalg_curve(s, curve))
1657 * ssl_version_supported - Check that the specified `version` is supported by
1660 * @s: The SSL handle for the candidate method
1661 * @version: Protocol version to test against
1663 * Returns 1 when supported, otherwise 0
1665 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1666 const SSL_METHOD **meth)
1668 const version_info *vent;
1669 const version_info *table;
1671 switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1673 /* Version should match method version for non-ANY method */
1674 return version_cmp(s, version, s->version) == 0;
1675 case TLS_ANY_VERSION:
1676 table = tls_version_table;
1678 case DTLS_ANY_VERSION:
1679 table = dtls_version_table;
1684 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1686 if (vent->cmeth != NULL
1687 && version_cmp(s, version, vent->version) == 0
1688 && ssl_method_error(s, vent->cmeth()) == 0
1690 || version != TLS1_3_VERSION
1691 || is_tls13_capable(s))) {
1693 *meth = vent->cmeth();
1701 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1702 * fallback indication from a client check whether we're using the highest
1703 * supported protocol version.
1705 * @s server SSL handle.
1707 * Returns 1 when using the highest enabled version, 0 otherwise.
1709 int ssl_check_version_downgrade(SSL_CONNECTION *s)
1711 const version_info *vent;
1712 const version_info *table;
1713 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1716 * Check that the current protocol is the highest enabled version
1717 * (according to ssl->defltmethod, as version negotiation may have changed
1720 if (s->version == ssl->defltmeth->version)
1724 * Apparently we're using a version-flexible SSL_METHOD (not at its
1725 * highest protocol version).
1727 if (ssl->defltmeth->version == TLS_method()->version)
1728 table = tls_version_table;
1729 else if (ssl->defltmeth->version == DTLS_method()->version)
1730 table = dtls_version_table;
1732 /* Unexpected state; fail closed. */
1736 for (vent = table; vent->version != 0; ++vent) {
1737 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1738 return s->version == vent->version;
1744 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1745 * protocols, provided the initial (D)TLS method is version-flexible. This
1746 * function sanity-checks the proposed value and makes sure the method is
1747 * version-flexible, then sets the limit if all is well.
1749 * @method_version: The version of the current SSL_METHOD.
1750 * @version: the intended limit.
1751 * @bound: pointer to limit to be updated.
1753 * Returns 1 on success, 0 on failure.
1755 int ssl_set_version_bound(int method_version, int version, int *bound)
1765 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1767 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1768 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1770 if (!valid_tls && !valid_dtls)
1774 * Restrict TLS methods to TLS protocol versions.
1775 * Restrict DTLS methods to DTLS protocol versions.
1776 * Note, DTLS version numbers are decreasing, use comparison macros.
1778 * Note that for both lower-bounds we use explicit versions, not
1779 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1780 * configurations. If the MIN (supported) version ever rises, the user's
1781 * "floor" remains valid even if no longer available. We don't expect the
1782 * MAX ceiling to ever get lower, so making that variable makes sense.
1784 * We ignore attempts to set bounds on version-inflexible methods,
1785 * returning success.
1787 switch (method_version) {
1791 case TLS_ANY_VERSION:
1796 case DTLS_ANY_VERSION:
1804 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
1806 if (vers == TLS1_2_VERSION
1807 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1808 *dgrd = DOWNGRADE_TO_1_2;
1809 } else if (!SSL_CONNECTION_IS_DTLS(s)
1810 && vers < TLS1_2_VERSION
1812 * We need to ensure that a server that disables TLSv1.2
1813 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1814 * complete handshakes with clients that support TLSv1.2 and
1815 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1816 * enabled and TLSv1.2 is not.
1818 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1819 *dgrd = DOWNGRADE_TO_1_1;
1821 *dgrd = DOWNGRADE_NONE;
1826 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1827 * client HELLO is received to select the final server protocol version and
1828 * the version specific method.
1830 * @s: server SSL handle.
1832 * Returns 0 on success or an SSL error reason number on failure.
1834 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
1838 * With version-flexible methods we have an initial state with:
1840 * s->method->version == (D)TLS_ANY_VERSION,
1841 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1843 * So we detect version-flexible methods via the method version, not the
1846 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1847 int server_version = ssl->method->version;
1848 int client_version = hello->legacy_version;
1849 const version_info *vent;
1850 const version_info *table;
1852 RAW_EXTENSION *suppversions;
1854 s->client_version = client_version;
1856 switch (server_version) {
1858 if (!SSL_CONNECTION_IS_TLS13(s)) {
1859 if (version_cmp(s, client_version, s->version) < 0)
1860 return SSL_R_WRONG_SSL_VERSION;
1861 *dgrd = DOWNGRADE_NONE;
1863 * If this SSL handle is not from a version flexible method we don't
1864 * (and never did) check min/max FIPS or Suite B constraints. Hope
1865 * that's OK. It is up to the caller to not choose fixed protocol
1866 * versions they don't want. If not, then easy to fix, just return
1867 * ssl_method_error(s, s->method)
1872 * Fall through if we are TLSv1.3 already (this means we must be after
1873 * a HelloRetryRequest
1876 case TLS_ANY_VERSION:
1877 table = tls_version_table;
1879 case DTLS_ANY_VERSION:
1880 table = dtls_version_table;
1884 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1886 /* If we did an HRR then supported versions is mandatory */
1887 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1888 return SSL_R_UNSUPPORTED_PROTOCOL;
1890 if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
1891 unsigned int candidate_vers = 0;
1892 unsigned int best_vers = 0;
1893 const SSL_METHOD *best_method = NULL;
1894 PACKET versionslist;
1896 suppversions->parsed = 1;
1898 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1899 /* Trailing or invalid data? */
1900 return SSL_R_LENGTH_MISMATCH;
1904 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1905 * The spec only requires servers to check that it isn't SSLv3:
1906 * "Any endpoint receiving a Hello message with
1907 * ClientHello.legacy_version or ServerHello.legacy_version set to
1908 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1909 * We are slightly stricter and require that it isn't SSLv3 or lower.
1910 * We tolerate TLSv1 and TLSv1.1.
1912 if (client_version <= SSL3_VERSION)
1913 return SSL_R_BAD_LEGACY_VERSION;
1915 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1916 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1918 if (ssl_version_supported(s, candidate_vers, &best_method))
1919 best_vers = candidate_vers;
1921 if (PACKET_remaining(&versionslist) != 0) {
1922 /* Trailing data? */
1923 return SSL_R_LENGTH_MISMATCH;
1926 if (best_vers > 0) {
1927 if (s->hello_retry_request != SSL_HRR_NONE) {
1929 * This is after a HelloRetryRequest so we better check that we
1930 * negotiated TLSv1.3
1932 if (best_vers != TLS1_3_VERSION)
1933 return SSL_R_UNSUPPORTED_PROTOCOL;
1936 check_for_downgrade(s, best_vers, dgrd);
1937 s->version = best_vers;
1938 ssl->method = best_method;
1939 if (!ssl_set_record_protocol_version(s, best_vers))
1940 return ERR_R_INTERNAL_ERROR;
1944 return SSL_R_UNSUPPORTED_PROTOCOL;
1948 * If the supported versions extension isn't present, then the highest
1949 * version we can negotiate is TLSv1.2
1951 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1952 client_version = TLS1_2_VERSION;
1955 * No supported versions extension, so we just use the version supplied in
1958 for (vent = table; vent->version != 0; ++vent) {
1959 const SSL_METHOD *method;
1961 if (vent->smeth == NULL ||
1962 version_cmp(s, client_version, vent->version) < 0)
1964 method = vent->smeth();
1965 if (ssl_method_error(s, method) == 0) {
1966 check_for_downgrade(s, vent->version, dgrd);
1967 s->version = vent->version;
1968 ssl->method = method;
1969 if (!ssl_set_record_protocol_version(s, s->version))
1970 return ERR_R_INTERNAL_ERROR;
1976 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1980 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1981 * server HELLO is received to select the final client protocol version and
1982 * the version specific method.
1984 * @s: client SSL handle.
1985 * @version: The proposed version from the server's HELLO.
1986 * @extensions: The extensions received
1988 * Returns 1 on success or 0 on error.
1990 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
1991 RAW_EXTENSION *extensions)
1993 const version_info *vent;
1994 const version_info *table;
1995 int ret, ver_min, ver_max, real_max, origv;
1996 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1999 s->version = version;
2001 /* This will overwrite s->version if the extension is present */
2002 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2003 SSL_EXT_TLS1_2_SERVER_HELLO
2004 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
2010 if (s->hello_retry_request != SSL_HRR_NONE
2011 && s->version != TLS1_3_VERSION) {
2013 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2017 switch (ssl->method->version) {
2019 if (s->version != ssl->method->version) {
2021 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2025 * If this SSL handle is not from a version flexible method we don't
2026 * (and never did) check min/max, FIPS or Suite B constraints. Hope
2027 * that's OK. It is up to the caller to not choose fixed protocol
2028 * versions they don't want. If not, then easy to fix, just return
2029 * ssl_method_error(s, s->method)
2031 if (!ssl_set_record_protocol_version(s, s->version)) {
2032 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2036 case TLS_ANY_VERSION:
2037 table = tls_version_table;
2039 case DTLS_ANY_VERSION:
2040 table = dtls_version_table;
2044 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2047 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2050 if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2051 : s->version < ver_min) {
2053 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2055 } else if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2056 : s->version > ver_max) {
2058 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2062 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2065 /* Check for downgrades */
2066 if (s->version == TLS1_2_VERSION && real_max > s->version) {
2067 if (memcmp(tls12downgrade,
2068 s->s3.server_random + SSL3_RANDOM_SIZE
2069 - sizeof(tls12downgrade),
2070 sizeof(tls12downgrade)) == 0) {
2072 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2073 SSL_R_INAPPROPRIATE_FALLBACK);
2076 } else if (!SSL_CONNECTION_IS_DTLS(s)
2077 && s->version < TLS1_2_VERSION
2078 && real_max > s->version) {
2079 if (memcmp(tls11downgrade,
2080 s->s3.server_random + SSL3_RANDOM_SIZE
2081 - sizeof(tls11downgrade),
2082 sizeof(tls11downgrade)) == 0) {
2084 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2085 SSL_R_INAPPROPRIATE_FALLBACK);
2090 for (vent = table; vent->version != 0; ++vent) {
2091 if (vent->cmeth == NULL || s->version != vent->version)
2094 ssl->method = vent->cmeth();
2095 if (!ssl_set_record_protocol_version(s, s->version)) {
2096 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2103 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2108 * ssl_get_min_max_version - get minimum and maximum protocol version
2109 * @s: The SSL connection
2110 * @min_version: The minimum supported version
2111 * @max_version: The maximum supported version
2112 * @real_max: The highest version below the lowest compile time version hole
2113 * where that hole lies above at least one run-time enabled
2116 * Work out what version we should be using for the initial ClientHello if the
2117 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2118 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2119 * constraints and any floor imposed by the security level here,
2120 * so we don't advertise the wrong protocol version to only reject the outcome later.
2122 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2123 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2124 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2126 * Returns 0 on success or an SSL error reason number on failure. On failure
2127 * min_version and max_version will also be set to 0.
2129 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2130 int *max_version, int *real_max)
2132 int version, tmp_real_max;
2134 const SSL_METHOD *single = NULL;
2135 const SSL_METHOD *method;
2136 const version_info *table;
2137 const version_info *vent;
2138 const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2140 switch (ssl->method->version) {
2143 * If this SSL handle is not from a version flexible method we don't
2144 * (and never did) check min/max FIPS or Suite B constraints. Hope
2145 * that's OK. It is up to the caller to not choose fixed protocol
2146 * versions they don't want. If not, then easy to fix, just return
2147 * ssl_method_error(s, s->method)
2149 *min_version = *max_version = s->version;
2151 * Providing a real_max only makes sense where we're using a version
2154 if (!ossl_assert(real_max == NULL))
2155 return ERR_R_INTERNAL_ERROR;
2157 case TLS_ANY_VERSION:
2158 table = tls_version_table;
2160 case DTLS_ANY_VERSION:
2161 table = dtls_version_table;
2166 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2167 * below X enabled. This is required in order to maintain the "version
2168 * capability" vector contiguous. Any versions with a NULL client method
2169 * (protocol version client is disabled at compile-time) is also a "hole".
2171 * Our initial state is hole == 1, version == 0. That is, versions above
2172 * the first version in the method table are disabled (a "hole" above
2173 * the valid protocol entries) and we don't have a selected version yet.
2175 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2176 * the selected version, and the method becomes a candidate "single"
2177 * method. We're no longer in a hole, so "hole" becomes 0.
2179 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2180 * as we support a contiguous range of at least two methods. If we hit
2181 * a disabled method, then hole becomes true again, but nothing else
2182 * changes yet, because all the remaining methods may be disabled too.
2183 * If we again hit an enabled method after the new hole, it becomes
2184 * selected, as we start from scratch.
2186 *min_version = version = 0;
2188 if (real_max != NULL)
2191 for (vent = table; vent->version != 0; ++vent) {
2193 * A table entry with a NULL client method is still a hole in the
2194 * "version capability" vector.
2196 if (vent->cmeth == NULL) {
2201 method = vent->cmeth();
2203 if (hole == 1 && tmp_real_max == 0)
2204 tmp_real_max = vent->version;
2206 if (ssl_method_error(s, method) != 0) {
2210 *min_version = method->version;
2212 if (real_max != NULL && tmp_real_max != 0)
2213 *real_max = tmp_real_max;
2214 version = (single = method)->version;
2215 *min_version = version;
2220 *max_version = version;
2222 /* Fail if everything is disabled */
2224 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2230 * ssl_set_client_hello_version - Work out what version we should be using for
2231 * the initial ClientHello.legacy_version field.
2233 * @s: client SSL handle.
2235 * Returns 0 on success or an SSL error reason number on failure.
2237 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2239 int ver_min, ver_max, ret;
2242 * In a renegotiation we always send the same client_version that we sent
2243 * last time, regardless of which version we eventually negotiated.
2245 if (!SSL_IS_FIRST_HANDSHAKE(s))
2248 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2253 s->version = ver_max;
2255 if (SSL_CONNECTION_IS_DTLS(s)) {
2256 if (ver_max == DTLS1_BAD_VER) {
2258 * Even though this is technically before version negotiation,
2259 * because we have asked for DTLS1_BAD_VER we will never negotiate
2260 * anything else, and this has impacts on the record layer for when
2261 * we read the ServerHello. So we need to tell the record layer
2262 * about this immediately.
2264 if (!ssl_set_record_protocol_version(s, ver_max))
2267 } else if (ver_max > TLS1_2_VERSION) {
2268 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2269 ver_max = TLS1_2_VERSION;
2272 s->client_version = ver_max;
2277 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2278 * and |checkallow| is 1 then additionally check if the group is allowed to be
2279 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2280 * 1) or 0 otherwise.
2282 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2283 size_t num_groups, int checkallow)
2287 if (groups == NULL || num_groups == 0)
2290 for (i = 0; i < num_groups; i++) {
2291 uint16_t group = groups[i];
2293 if (group_id == group
2295 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2303 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2304 int create_synthetic_message_hash(SSL_CONNECTION *s,
2305 const unsigned char *hashval,
2306 size_t hashlen, const unsigned char *hrr,
2309 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2310 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2312 memset(msghdr, 0, sizeof(msghdr));
2314 if (hashval == NULL) {
2315 hashval = hashvaltmp;
2317 /* Get the hash of the initial ClientHello */
2318 if (!ssl3_digest_cached_records(s, 0)
2319 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2321 /* SSLfatal() already called */
2326 /* Reinitialise the transcript hash */
2327 if (!ssl3_init_finished_mac(s)) {
2328 /* SSLfatal() already called */
2332 /* Inject the synthetic message_hash message */
2333 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2334 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2335 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2336 || !ssl3_finish_mac(s, hashval, hashlen)) {
2337 /* SSLfatal() already called */
2342 * Now re-inject the HRR and current message if appropriate (we just deleted
2343 * it when we reinitialised the transcript hash above). Only necessary after
2344 * receiving a ClientHello2 with a cookie.
2347 && (!ssl3_finish_mac(s, hrr, hrrlen)
2348 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2349 s->s3.tmp.message_size
2350 + SSL3_HM_HEADER_LENGTH))) {
2351 /* SSLfatal() already called */
2358 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2360 return X509_NAME_cmp(*a, *b);
2363 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2365 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2366 X509_NAME *xn = NULL;
2369 if (ca_sk == NULL) {
2370 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2373 /* get the CA RDNs */
2374 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2375 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2379 while (PACKET_remaining(&cadns)) {
2380 const unsigned char *namestart, *namebytes;
2381 unsigned int name_len;
2383 if (!PACKET_get_net_2(&cadns, &name_len)
2384 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2385 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2389 namestart = namebytes;
2390 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2391 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2394 if (namebytes != (namestart + name_len)) {
2395 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2399 if (!sk_X509_NAME_push(ca_sk, xn)) {
2400 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2406 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2407 s->s3.tmp.peer_ca_names = ca_sk;
2412 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2417 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2419 const STACK_OF(X509_NAME) *ca_sk = NULL;
2420 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2423 ca_sk = SSL_get_client_CA_list(ssl);
2424 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2429 ca_sk = SSL_get0_CA_list(ssl);
2434 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2437 /* Start sub-packet for client CA list */
2438 if (!WPACKET_start_sub_packet_u16(pkt)) {
2439 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2443 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2446 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2447 unsigned char *namebytes;
2448 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2452 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2453 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2455 || i2d_X509_NAME(name, &namebytes) != namelen) {
2456 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2462 if (!WPACKET_close(pkt)) {
2463 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2470 /* Create a buffer containing data to be signed for server key exchange */
2471 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2472 const void *param, size_t paramlen)
2474 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2475 unsigned char *tbs = OPENSSL_malloc(tbslen);
2478 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2481 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2482 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2484 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2491 * Saves the current handshake digest for Post-Handshake Auth,
2492 * Done after ClientFinished is processed, done exactly once
2494 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2496 if (s->pha_dgst == NULL) {
2497 if (!ssl3_digest_cached_records(s, 1))
2498 /* SSLfatal() already called */
2501 s->pha_dgst = EVP_MD_CTX_new();
2502 if (s->pha_dgst == NULL) {
2503 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2506 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2507 s->s3.handshake_dgst)) {
2508 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2509 EVP_MD_CTX_free(s->pha_dgst);
2518 * Restores the Post-Handshake Auth handshake digest
2519 * Done just before sending/processing the Cert Request
2521 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2523 if (s->pha_dgst == NULL) {
2524 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2527 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2529 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2535 #ifndef OPENSSL_NO_COMP_ALG
2536 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2541 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2543 COMP_METHOD *method = NULL;
2544 COMP_CTX *comp = NULL;
2545 size_t expected_length;
2551 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2554 if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2555 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2558 /* If we have a prefs list, make sure the algorithm is in it */
2559 if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2560 for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2561 if (sc->cert_comp_prefs[i] == comp_alg) {
2567 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2571 if (!ossl_comp_has_alg(comp_alg)) {
2572 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2576 case TLSEXT_comp_cert_zlib:
2577 method = COMP_zlib_oneshot();
2579 case TLSEXT_comp_cert_brotli:
2580 method = COMP_brotli_oneshot();
2582 case TLSEXT_comp_cert_zstd:
2583 method = COMP_zstd_oneshot();
2586 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2590 if ((comp = COMP_CTX_new(method)) == NULL
2591 || !PACKET_get_net_3_len(pkt, &expected_length)
2592 || !PACKET_get_net_3_len(pkt, &comp_length)
2593 || PACKET_remaining(pkt) != comp_length
2594 || !BUF_MEM_grow(buf, expected_length)
2595 || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2596 || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2597 (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2598 SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2601 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2603 COMP_CTX_free(comp);