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)
26 DEFINE_STACK_OF_CONST(SSL_CIPHER)
29 * Map error codes to TLS/SSL alart types.
31 typedef struct x509err2alert_st {
36 /* Fixed value used in the ServerHello random field to identify an HRR */
37 const unsigned char hrrrandom[] = {
38 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
39 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
40 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
44 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
45 * SSL3_RT_CHANGE_CIPHER_SPEC)
47 int ssl3_do_write(SSL *s, int type)
52 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
53 s->init_num, &written);
56 if (type == SSL3_RT_HANDSHAKE)
58 * should not be done for 'Hello Request's, but in that case we'll
59 * ignore the result anyway
60 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
62 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
63 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
64 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
65 if (!ssl3_finish_mac(s,
66 (unsigned char *)&s->init_buf->data[s->init_off],
69 if (written == s->init_num) {
71 s->msg_callback(1, s->version, type, s->init_buf->data,
72 (size_t)(s->init_off + s->init_num), s,
76 s->init_off += written;
77 s->init_num -= written;
81 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
85 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
86 || !WPACKET_get_length(pkt, &msglen)
89 s->init_num = (int)msglen;
95 int tls_setup_handshake(SSL *s)
97 if (!ssl3_init_finished_mac(s)) {
98 /* SSLfatal() already called */
102 /* Reset any extension flags */
103 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
106 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
107 int i, ver_min, ver_max, ok = 0;
110 * Sanity check that the maximum version we accept has ciphers
111 * enabled. For clients we do this check during construction of the
114 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
115 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_SETUP_HANDSHAKE,
116 ERR_R_INTERNAL_ERROR);
119 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
120 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
122 if (SSL_IS_DTLS(s)) {
123 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
124 DTLS_VERSION_LE(ver_max, c->max_dtls))
126 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
133 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
134 SSL_R_NO_CIPHERS_AVAILABLE);
135 ERR_add_error_data(1, "No ciphers enabled for max supported "
139 if (SSL_IS_FIRST_HANDSHAKE(s)) {
140 /* N.B. s->session_ctx == s->ctx here */
141 tsan_counter(&s->session_ctx->stats.sess_accept);
143 /* N.B. s->ctx may not equal s->session_ctx */
144 tsan_counter(&s->ctx->stats.sess_accept_renegotiate);
146 s->s3.tmp.cert_request = 0;
149 if (SSL_IS_FIRST_HANDSHAKE(s))
150 tsan_counter(&s->session_ctx->stats.sess_connect);
152 tsan_counter(&s->session_ctx->stats.sess_connect_renegotiate);
154 /* mark client_random uninitialized */
155 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
158 s->s3.tmp.cert_req = 0;
161 s->statem.use_timer = 1;
168 * Size of the to-be-signed TLS13 data, without the hash size itself:
169 * 64 bytes of value 32, 33 context bytes, 1 byte separator
171 #define TLS13_TBS_START_SIZE 64
172 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
174 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
175 void **hdata, size_t *hdatalen)
177 #ifdef CHARSET_EBCDIC
178 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
179 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
180 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
181 0x69, 0x66, 0x79, 0x00 };
182 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
183 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
184 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
185 0x69, 0x66, 0x79, 0x00 };
187 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
188 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
190 if (SSL_IS_TLS13(s)) {
193 /* Set the first 64 bytes of to-be-signed data to octet 32 */
194 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
195 /* This copies the 33 bytes of context plus the 0 separator byte */
196 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
197 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
198 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
200 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
203 * If we're currently reading then we need to use the saved handshake
204 * hash value. We can't use the current handshake hash state because
205 * that includes the CertVerify itself.
207 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
208 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
209 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
210 s->cert_verify_hash_len);
211 hashlen = s->cert_verify_hash_len;
212 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
213 EVP_MAX_MD_SIZE, &hashlen)) {
214 /* SSLfatal() already called */
219 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
224 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
226 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
227 ERR_R_INTERNAL_ERROR);
236 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
238 EVP_PKEY *pkey = NULL;
239 const EVP_MD *md = NULL;
240 EVP_MD_CTX *mctx = NULL;
241 EVP_PKEY_CTX *pctx = NULL;
242 size_t hdatalen = 0, siglen = 0;
244 unsigned char *sig = NULL;
245 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
246 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
248 if (lu == NULL || s->s3.tmp.cert == NULL) {
249 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
250 ERR_R_INTERNAL_ERROR);
253 pkey = s->s3.tmp.cert->privatekey;
255 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
256 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
257 ERR_R_INTERNAL_ERROR);
261 mctx = EVP_MD_CTX_new();
263 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
264 ERR_R_MALLOC_FAILURE);
268 /* Get the data to be signed */
269 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
270 /* SSLfatal() already called */
274 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
275 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
276 ERR_R_INTERNAL_ERROR);
280 if (EVP_DigestSignInit_with_libctx(mctx, &pctx,
281 md == NULL ? NULL : EVP_MD_name(md),
282 s->ctx->libctx, s->ctx->propq,
284 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
289 if (lu->sig == EVP_PKEY_RSA_PSS) {
290 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
291 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
292 RSA_PSS_SALTLEN_DIGEST) <= 0) {
293 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
298 if (s->version == SSL3_VERSION) {
300 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
301 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
303 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
305 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
306 * with a call to ssl3_digest_master_key_set_params()
308 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
309 (int)s->session->master_key_length,
310 s->session->master_key) <= 0
311 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
313 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
317 sig = OPENSSL_malloc(siglen);
319 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
320 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
326 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
327 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
329 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
330 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
334 sig = OPENSSL_malloc(siglen);
336 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
337 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
343 #ifndef OPENSSL_NO_GOST
345 int pktype = lu->sig;
347 if (pktype == NID_id_GostR3410_2001
348 || pktype == NID_id_GostR3410_2012_256
349 || pktype == NID_id_GostR3410_2012_512)
350 BUF_reverse(sig, NULL, siglen);
354 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
355 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
356 ERR_R_INTERNAL_ERROR);
360 /* Digest cached records and discard handshake buffer */
361 if (!ssl3_digest_cached_records(s, 0)) {
362 /* SSLfatal() already called */
367 EVP_MD_CTX_free(mctx);
371 EVP_MD_CTX_free(mctx);
375 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
377 EVP_PKEY *pkey = NULL;
378 const unsigned char *data;
379 #ifndef OPENSSL_NO_GOST
380 unsigned char *gost_data = NULL;
382 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
386 const EVP_MD *md = NULL;
389 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
390 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
391 EVP_PKEY_CTX *pctx = NULL;
394 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
395 ERR_R_MALLOC_FAILURE);
399 peer = s->session->peer;
400 pkey = X509_get0_pubkey(peer);
402 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
403 ERR_R_INTERNAL_ERROR);
407 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
408 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
409 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
413 if (SSL_USE_SIGALGS(s)) {
416 if (!PACKET_get_net_2(pkt, &sigalg)) {
417 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
421 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
422 /* SSLfatal() already called */
425 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
426 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
427 ERR_R_INTERNAL_ERROR);
431 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
432 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
433 ERR_R_INTERNAL_ERROR);
437 if (SSL_USE_SIGALGS(s))
438 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
439 md == NULL ? "n/a" : EVP_MD_name(md));
441 /* Check for broken implementations of GOST ciphersuites */
443 * If key is GOST and len is exactly 64 or 128, it is signature without
444 * length field (CryptoPro implementations at least till TLS 1.2)
446 #ifndef OPENSSL_NO_GOST
447 if (!SSL_USE_SIGALGS(s)
448 && ((PACKET_remaining(pkt) == 64
449 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
450 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
451 || (PACKET_remaining(pkt) == 128
452 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
453 len = PACKET_remaining(pkt);
456 if (!PACKET_get_net_2(pkt, &len)) {
457 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
458 SSL_R_LENGTH_MISMATCH);
462 if (!PACKET_get_bytes(pkt, &data, len)) {
463 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
464 SSL_R_LENGTH_MISMATCH);
468 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
469 /* SSLfatal() already called */
473 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
474 md == NULL ? "n/a" : EVP_MD_name(md));
476 if (EVP_DigestVerifyInit_with_libctx(mctx, &pctx,
477 md == NULL ? NULL : EVP_MD_name(md),
478 s->ctx->libctx, s->ctx->propq,
480 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
484 #ifndef OPENSSL_NO_GOST
486 int pktype = EVP_PKEY_id(pkey);
487 if (pktype == NID_id_GostR3410_2001
488 || pktype == NID_id_GostR3410_2012_256
489 || pktype == NID_id_GostR3410_2012_512) {
490 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
491 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
492 SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
495 BUF_reverse(gost_data, data, len);
501 if (SSL_USE_PSS(s)) {
502 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
503 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
504 RSA_PSS_SALTLEN_DIGEST) <= 0) {
505 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
510 if (s->version == SSL3_VERSION) {
512 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
513 * with a call to ssl3_digest_master_key_set_params()
515 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
516 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
517 (int)s->session->master_key_length,
518 s->session->master_key) <= 0) {
519 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
523 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
524 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
525 SSL_R_BAD_SIGNATURE);
529 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
531 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
532 SSL_R_BAD_SIGNATURE);
538 * In TLSv1.3 on the client side we make sure we prepare the client
539 * certificate after the CertVerify instead of when we get the
540 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
541 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
542 * want to make sure that SSL_get1_peer_certificate() will return the actual
543 * server certificate from the client_cert_cb callback.
545 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
546 ret = MSG_PROCESS_CONTINUE_PROCESSING;
548 ret = MSG_PROCESS_CONTINUE_READING;
550 BIO_free(s->s3.handshake_buffer);
551 s->s3.handshake_buffer = NULL;
552 EVP_MD_CTX_free(mctx);
553 #ifndef OPENSSL_NO_GOST
554 OPENSSL_free(gost_data);
559 int tls_construct_finished(SSL *s, WPACKET *pkt)
561 size_t finish_md_len;
565 /* This is a real handshake so make sure we clean it up at the end */
566 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
567 s->statem.cleanuphand = 1;
570 * We only change the keys if we didn't already do this when we sent the
575 && s->s3.tmp.cert_req == 0
576 && (!s->method->ssl3_enc->change_cipher_state(s,
577 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
578 /* SSLfatal() already called */
583 sender = s->method->ssl3_enc->server_finished_label;
584 slen = s->method->ssl3_enc->server_finished_label_len;
586 sender = s->method->ssl3_enc->client_finished_label;
587 slen = s->method->ssl3_enc->client_finished_label_len;
590 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
592 s->s3.tmp.finish_md);
593 if (finish_md_len == 0) {
594 /* SSLfatal() already called */
598 s->s3.tmp.finish_md_len = finish_md_len;
600 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
601 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
602 ERR_R_INTERNAL_ERROR);
607 * Log the master secret, if logging is enabled. We don't log it for
608 * TLSv1.3: there's a different key schedule for that.
610 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
611 s->session->master_key,
612 s->session->master_key_length)) {
613 /* SSLfatal() already called */
618 * Copy the finished so we can use it for renegotiation checks
620 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
621 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
622 ERR_R_INTERNAL_ERROR);
626 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
628 s->s3.previous_client_finished_len = finish_md_len;
630 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
632 s->s3.previous_server_finished_len = finish_md_len;
638 int tls_construct_key_update(SSL *s, WPACKET *pkt)
640 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
641 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
642 ERR_R_INTERNAL_ERROR);
646 s->key_update = SSL_KEY_UPDATE_NONE;
650 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
652 unsigned int updatetype;
655 * A KeyUpdate message signals a key change so the end of the message must
656 * be on a record boundary.
658 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
659 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
660 SSL_R_NOT_ON_RECORD_BOUNDARY);
661 return MSG_PROCESS_ERROR;
664 if (!PACKET_get_1(pkt, &updatetype)
665 || PACKET_remaining(pkt) != 0) {
666 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
667 SSL_R_BAD_KEY_UPDATE);
668 return MSG_PROCESS_ERROR;
672 * There are only two defined key update types. Fail if we get a value we
675 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
676 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
677 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
678 SSL_R_BAD_KEY_UPDATE);
679 return MSG_PROCESS_ERROR;
683 * If we get a request for us to update our sending keys too then, we need
684 * to additionally send a KeyUpdate message. However that message should
685 * not also request an update (otherwise we get into an infinite loop).
687 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
688 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
690 if (!tls13_update_key(s, 0)) {
691 /* SSLfatal() already called */
692 return MSG_PROCESS_ERROR;
695 return MSG_PROCESS_FINISHED_READING;
699 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
702 int ssl3_take_mac(SSL *s)
708 sender = s->method->ssl3_enc->server_finished_label;
709 slen = s->method->ssl3_enc->server_finished_label_len;
711 sender = s->method->ssl3_enc->client_finished_label;
712 slen = s->method->ssl3_enc->client_finished_label_len;
715 s->s3.tmp.peer_finish_md_len =
716 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
717 s->s3.tmp.peer_finish_md);
719 if (s->s3.tmp.peer_finish_md_len == 0) {
720 /* SSLfatal() already called */
727 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
731 remain = PACKET_remaining(pkt);
733 * 'Change Cipher Spec' is just a single byte, which should already have
734 * been consumed by ssl_get_message() so there should be no bytes left,
735 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
737 if (SSL_IS_DTLS(s)) {
738 if ((s->version == DTLS1_BAD_VER
739 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
740 || (s->version != DTLS1_BAD_VER
741 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
742 SSLfatal(s, SSL_AD_DECODE_ERROR,
743 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
744 SSL_R_BAD_CHANGE_CIPHER_SPEC);
745 return MSG_PROCESS_ERROR;
749 SSLfatal(s, SSL_AD_DECODE_ERROR,
750 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
751 SSL_R_BAD_CHANGE_CIPHER_SPEC);
752 return MSG_PROCESS_ERROR;
756 /* Check we have a cipher to change to */
757 if (s->s3.tmp.new_cipher == NULL) {
758 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
759 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
760 return MSG_PROCESS_ERROR;
763 s->s3.change_cipher_spec = 1;
764 if (!ssl3_do_change_cipher_spec(s)) {
765 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
766 ERR_R_INTERNAL_ERROR);
767 return MSG_PROCESS_ERROR;
770 if (SSL_IS_DTLS(s)) {
771 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
773 if (s->version == DTLS1_BAD_VER)
774 s->d1->handshake_read_seq++;
776 #ifndef OPENSSL_NO_SCTP
778 * Remember that a CCS has been received, so that an old key of
779 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
782 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
786 return MSG_PROCESS_CONTINUE_READING;
789 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
794 /* This is a real handshake so make sure we clean it up at the end */
797 * To get this far we must have read encrypted data from the client. We
798 * no longer tolerate unencrypted alerts. This value is ignored if less
801 s->statem.enc_read_state = ENC_READ_STATE_VALID;
802 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
803 s->statem.cleanuphand = 1;
804 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
805 /* SSLfatal() already called */
806 return MSG_PROCESS_ERROR;
811 * In TLSv1.3 a Finished message signals a key change so the end of the
812 * message must be on a record boundary.
814 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
815 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
816 SSL_R_NOT_ON_RECORD_BOUNDARY);
817 return MSG_PROCESS_ERROR;
820 /* If this occurs, we have missed a message */
821 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
822 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
823 SSL_R_GOT_A_FIN_BEFORE_A_CCS);
824 return MSG_PROCESS_ERROR;
826 s->s3.change_cipher_spec = 0;
828 md_len = s->s3.tmp.peer_finish_md_len;
830 if (md_len != PACKET_remaining(pkt)) {
831 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
832 SSL_R_BAD_DIGEST_LENGTH);
833 return MSG_PROCESS_ERROR;
836 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
838 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
839 SSL_R_DIGEST_CHECK_FAILED);
840 return MSG_PROCESS_ERROR;
844 * Copy the finished so we can use it for renegotiation checks
846 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
847 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
848 ERR_R_INTERNAL_ERROR);
849 return MSG_PROCESS_ERROR;
852 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
854 s->s3.previous_client_finished_len = md_len;
856 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
858 s->s3.previous_server_finished_len = md_len;
862 * In TLS1.3 we also have to change cipher state and do any final processing
863 * of the initial server flight (if we are a client)
865 if (SSL_IS_TLS13(s)) {
867 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
868 !s->method->ssl3_enc->change_cipher_state(s,
869 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
870 /* SSLfatal() already called */
871 return MSG_PROCESS_ERROR;
874 /* TLS 1.3 gets the secret size from the handshake md */
876 if (!s->method->ssl3_enc->generate_master_secret(s,
877 s->master_secret, s->handshake_secret, 0,
879 /* SSLfatal() already called */
880 return MSG_PROCESS_ERROR;
882 if (!s->method->ssl3_enc->change_cipher_state(s,
883 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
884 /* SSLfatal() already called */
885 return MSG_PROCESS_ERROR;
887 if (!tls_process_initial_server_flight(s)) {
888 /* SSLfatal() already called */
889 return MSG_PROCESS_ERROR;
894 return MSG_PROCESS_FINISHED_READING;
897 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
899 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
900 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
901 SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
908 /* Add a certificate to the WPACKET */
909 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
912 unsigned char *outbytes;
914 len = i2d_X509(x, NULL);
916 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
920 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
921 || i2d_X509(x, &outbytes) != len) {
922 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
923 ERR_R_INTERNAL_ERROR);
928 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
930 /* SSLfatal() already called */
937 /* Add certificate chain to provided WPACKET */
938 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
942 STACK_OF(X509) *extra_certs;
943 STACK_OF(X509) *chain = NULL;
944 X509_STORE *chain_store;
946 if (cpk == NULL || cpk->x509 == NULL)
952 * If we have a certificate specific chain use it, else use parent ctx.
954 if (cpk->chain != NULL)
955 extra_certs = cpk->chain;
957 extra_certs = s->ctx->extra_certs;
959 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
961 else if (s->cert->chain_store)
962 chain_store = s->cert->chain_store;
964 chain_store = s->ctx->cert_store;
966 if (chain_store != NULL) {
967 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_with_libctx(s->ctx->libctx,
970 if (xs_ctx == NULL) {
971 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
972 ERR_R_MALLOC_FAILURE);
975 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
976 X509_STORE_CTX_free(xs_ctx);
977 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
982 * It is valid for the chain not to be complete (because normally we
983 * don't include the root cert in the chain). Therefore we deliberately
984 * ignore the error return from this call. We're not actually verifying
985 * the cert - we're just building as much of the chain as we can
987 (void)X509_verify_cert(xs_ctx);
988 /* Don't leave errors in the queue */
990 chain = X509_STORE_CTX_get0_chain(xs_ctx);
991 i = ssl_security_cert_chain(s, chain, NULL, 0);
994 /* Dummy error calls so mkerr generates them */
995 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
996 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
997 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
999 X509_STORE_CTX_free(xs_ctx);
1000 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1003 chain_count = sk_X509_num(chain);
1004 for (i = 0; i < chain_count; i++) {
1005 x = sk_X509_value(chain, i);
1007 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1008 /* SSLfatal() already called */
1009 X509_STORE_CTX_free(xs_ctx);
1013 X509_STORE_CTX_free(xs_ctx);
1015 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1017 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1020 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1021 /* SSLfatal() already called */
1024 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1025 x = sk_X509_value(extra_certs, i);
1026 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1027 /* SSLfatal() already called */
1035 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1037 if (!WPACKET_start_sub_packet_u24(pkt)) {
1038 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1039 ERR_R_INTERNAL_ERROR);
1043 if (!ssl_add_cert_chain(s, pkt, cpk))
1046 if (!WPACKET_close(pkt)) {
1047 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1048 ERR_R_INTERNAL_ERROR);
1056 * Tidy up after the end of a handshake. In the case of SCTP this may result
1057 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1060 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1062 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1063 int cleanuphand = s->statem.cleanuphand;
1067 #ifndef OPENSSL_NO_SCTP
1069 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1070 * messages that require it. Therefore, DTLS procedures for retransmissions
1072 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1074 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1078 * We don't do this in DTLS over UDP because we may still need the init_buf
1079 * in case there are any unexpected retransmits
1081 BUF_MEM_free(s->init_buf);
1085 if (!ssl_free_wbio_buffer(s)) {
1086 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_FINISH_HANDSHAKE,
1087 ERR_R_INTERNAL_ERROR);
1093 if (SSL_IS_TLS13(s) && !s->server
1094 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1095 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1098 * Only set if there was a Finished message and this isn't after a TLSv1.3
1099 * post handshake exchange
1102 /* skipped if we just sent a HelloRequest */
1105 s->statem.cleanuphand = 0;
1106 s->ext.ticket_expected = 0;
1108 ssl3_cleanup_key_block(s);
1112 * In TLSv1.3 we update the cache as part of constructing the
1115 if (!SSL_IS_TLS13(s))
1116 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1118 /* N.B. s->ctx may not equal s->session_ctx */
1119 tsan_counter(&s->ctx->stats.sess_accept_good);
1120 s->handshake_func = ossl_statem_accept;
1122 if (SSL_IS_TLS13(s)) {
1124 * We encourage applications to only use TLSv1.3 tickets once,
1125 * so we remove this one from the cache.
1127 if ((s->session_ctx->session_cache_mode
1128 & SSL_SESS_CACHE_CLIENT) != 0)
1129 SSL_CTX_remove_session(s->session_ctx, s->session);
1132 * In TLSv1.3 we update the cache as part of processing the
1135 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1138 tsan_counter(&s->session_ctx->stats.sess_hit);
1140 s->handshake_func = ossl_statem_connect;
1141 tsan_counter(&s->session_ctx->stats.sess_connect_good);
1144 if (SSL_IS_DTLS(s)) {
1145 /* done with handshaking */
1146 s->d1->handshake_read_seq = 0;
1147 s->d1->handshake_write_seq = 0;
1148 s->d1->next_handshake_write_seq = 0;
1149 dtls1_clear_received_buffer(s);
1153 if (s->info_callback != NULL)
1154 cb = s->info_callback;
1155 else if (s->ctx->info_callback != NULL)
1156 cb = s->ctx->info_callback;
1158 /* The callback may expect us to not be in init at handshake done */
1159 ossl_statem_set_in_init(s, 0);
1164 || SSL_IS_FIRST_HANDSHAKE(s))
1165 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1169 /* If we've got more work to do we go back into init */
1170 ossl_statem_set_in_init(s, 1);
1171 return WORK_FINISHED_CONTINUE;
1174 return WORK_FINISHED_STOP;
1177 int tls_get_message_header(SSL *s, int *mt)
1179 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1180 int skip_message, i, recvd_type;
1182 size_t l, readbytes;
1184 p = (unsigned char *)s->init_buf->data;
1187 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1188 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1190 SSL3_HM_HEADER_LENGTH - s->init_num,
1193 s->rwstate = SSL_READING;
1196 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1198 * A ChangeCipherSpec must be a single byte and may not occur
1199 * in the middle of a handshake message.
1201 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1202 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1203 SSL_F_TLS_GET_MESSAGE_HEADER,
1204 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1207 if (s->statem.hand_state == TLS_ST_BEFORE
1208 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1210 * We are stateless and we received a CCS. Probably this is
1211 * from a client between the first and second ClientHellos.
1212 * We should ignore this, but return an error because we do
1213 * not return success until we see the second ClientHello
1214 * with a valid cookie.
1218 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1219 s->init_num = readbytes - 1;
1220 s->init_msg = s->init_buf->data;
1221 s->s3.tmp.message_size = readbytes;
1223 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1224 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1225 SSL_F_TLS_GET_MESSAGE_HEADER,
1226 SSL_R_CCS_RECEIVED_EARLY);
1229 s->init_num += readbytes;
1234 if (s->statem.hand_state != TLS_ST_OK
1235 && p[0] == SSL3_MT_HELLO_REQUEST)
1237 * The server may always send 'Hello Request' messages --
1238 * we are doing a handshake anyway now, so ignore them if
1239 * their format is correct. Does not count for 'Finished'
1242 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1246 if (s->msg_callback)
1247 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1248 p, SSL3_HM_HEADER_LENGTH, s,
1249 s->msg_callback_arg);
1251 } while (skip_message);
1252 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1255 s->s3.tmp.message_type = *(p++);
1257 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1259 * Only happens with SSLv3+ in an SSLv2 backward compatible
1262 * Total message size is the remaining record bytes to read
1263 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1265 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1266 + SSL3_HM_HEADER_LENGTH;
1267 s->s3.tmp.message_size = l;
1269 s->init_msg = s->init_buf->data;
1270 s->init_num = SSL3_HM_HEADER_LENGTH;
1273 /* BUF_MEM_grow takes an 'int' parameter */
1274 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1275 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1276 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1279 s->s3.tmp.message_size = l;
1281 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1288 int tls_get_message_body(SSL *s, size_t *len)
1290 size_t n, readbytes;
1294 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1295 /* We've already read everything in */
1296 *len = (unsigned long)s->init_num;
1301 n = s->s3.tmp.message_size - s->init_num;
1303 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1304 &p[s->init_num], n, 0, &readbytes);
1306 s->rwstate = SSL_READING;
1310 s->init_num += readbytes;
1315 * If receiving Finished, record MAC of prior handshake messages for
1316 * Finished verification.
1318 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1319 /* SSLfatal() already called */
1324 /* Feed this message into MAC computation. */
1325 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1326 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1328 /* SSLfatal() already called */
1332 if (s->msg_callback)
1333 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1334 (size_t)s->init_num, s, s->msg_callback_arg);
1337 * We defer feeding in the HRR until later. We'll do it as part of
1338 * processing the message
1339 * The TLsv1.3 handshake transcript stops at the ClientFinished
1342 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1343 /* KeyUpdate and NewSessionTicket do not need to be added */
1344 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1345 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1346 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1347 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1348 || memcmp(hrrrandom,
1349 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1350 SSL3_RANDOM_SIZE) != 0) {
1351 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1352 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1353 /* SSLfatal() already called */
1359 if (s->msg_callback)
1360 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1361 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1362 s->msg_callback_arg);
1369 static const X509ERR2ALERT x509table[] = {
1370 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1371 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1372 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1373 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1374 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1375 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1376 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1377 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1378 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1379 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1380 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1381 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1382 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1383 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1384 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1385 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1386 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1387 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1388 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1389 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1390 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1391 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1392 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1393 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1394 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1395 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1396 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1397 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1398 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1399 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1400 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1401 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1402 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1403 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1404 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1405 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1406 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1407 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1408 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1410 /* Last entry; return this if we don't find the value above. */
1411 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1414 int ssl_x509err2alert(int x509err)
1416 const X509ERR2ALERT *tp;
1418 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1419 if (tp->x509err == x509err)
1424 int ssl_allow_compression(SSL *s)
1426 if (s->options & SSL_OP_NO_COMPRESSION)
1428 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1431 static int version_cmp(const SSL *s, int a, int b)
1433 int dtls = SSL_IS_DTLS(s);
1438 return a < b ? -1 : 1;
1439 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1444 const SSL_METHOD *(*cmeth) (void);
1445 const SSL_METHOD *(*smeth) (void);
1448 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1449 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1452 /* Must be in order high to low */
1453 static const version_info tls_version_table[] = {
1454 #ifndef OPENSSL_NO_TLS1_3
1455 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1457 {TLS1_3_VERSION, NULL, NULL},
1459 #ifndef OPENSSL_NO_TLS1_2
1460 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1462 {TLS1_2_VERSION, NULL, NULL},
1464 #ifndef OPENSSL_NO_TLS1_1
1465 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1467 {TLS1_1_VERSION, NULL, NULL},
1469 #ifndef OPENSSL_NO_TLS1
1470 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1472 {TLS1_VERSION, NULL, NULL},
1474 #ifndef OPENSSL_NO_SSL3
1475 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1477 {SSL3_VERSION, NULL, NULL},
1482 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1483 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1486 /* Must be in order high to low */
1487 static const version_info dtls_version_table[] = {
1488 #ifndef OPENSSL_NO_DTLS1_2
1489 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1491 {DTLS1_2_VERSION, NULL, NULL},
1493 #ifndef OPENSSL_NO_DTLS1
1494 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1495 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1497 {DTLS1_VERSION, NULL, NULL},
1498 {DTLS1_BAD_VER, NULL, NULL},
1504 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1506 * @s: The SSL handle for the candidate method
1507 * @method: the intended method.
1509 * Returns 0 on success, or an SSL error reason on failure.
1511 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1513 int version = method->version;
1515 if ((s->min_proto_version != 0 &&
1516 version_cmp(s, version, s->min_proto_version) < 0) ||
1517 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1518 return SSL_R_VERSION_TOO_LOW;
1520 if (s->max_proto_version != 0 &&
1521 version_cmp(s, version, s->max_proto_version) > 0)
1522 return SSL_R_VERSION_TOO_HIGH;
1524 if ((s->options & method->mask) != 0)
1525 return SSL_R_UNSUPPORTED_PROTOCOL;
1526 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1527 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1533 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1534 * certificate type, or has PSK or a certificate callback configured. Otherwise
1537 static int is_tls13_capable(const SSL *s)
1540 #ifndef OPENSSL_NO_EC
1544 #ifndef OPENSSL_NO_PSK
1545 if (s->psk_server_callback != NULL)
1549 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1552 for (i = 0; i < SSL_PKEY_NUM; i++) {
1553 /* Skip over certs disallowed for TLSv1.3 */
1555 case SSL_PKEY_DSA_SIGN:
1556 case SSL_PKEY_GOST01:
1557 case SSL_PKEY_GOST12_256:
1558 case SSL_PKEY_GOST12_512:
1563 if (!ssl_has_cert(s, i))
1565 #ifndef OPENSSL_NO_EC
1566 if (i != SSL_PKEY_ECC)
1569 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1570 * more restrictive so check that our sig algs are consistent with this
1571 * EC cert. See section 4.2.3 of RFC8446.
1573 curve = evp_pkey_get_EC_KEY_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
1575 if (tls_check_sigalg_curve(s, curve))
1586 * ssl_version_supported - Check that the specified `version` is supported by
1589 * @s: The SSL handle for the candidate method
1590 * @version: Protocol version to test against
1592 * Returns 1 when supported, otherwise 0
1594 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1596 const version_info *vent;
1597 const version_info *table;
1599 switch (s->method->version) {
1601 /* Version should match method version for non-ANY method */
1602 return version_cmp(s, version, s->version) == 0;
1603 case TLS_ANY_VERSION:
1604 table = tls_version_table;
1606 case DTLS_ANY_VERSION:
1607 table = dtls_version_table;
1612 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1614 if (vent->cmeth != NULL
1615 && version_cmp(s, version, vent->version) == 0
1616 && ssl_method_error(s, vent->cmeth()) == 0
1618 || version != TLS1_3_VERSION
1619 || is_tls13_capable(s))) {
1621 *meth = vent->cmeth();
1629 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1630 * fallback indication from a client check whether we're using the highest
1631 * supported protocol version.
1633 * @s server SSL handle.
1635 * Returns 1 when using the highest enabled version, 0 otherwise.
1637 int ssl_check_version_downgrade(SSL *s)
1639 const version_info *vent;
1640 const version_info *table;
1643 * Check that the current protocol is the highest enabled version
1644 * (according to s->ctx->method, as version negotiation may have changed
1647 if (s->version == s->ctx->method->version)
1651 * Apparently we're using a version-flexible SSL_METHOD (not at its
1652 * highest protocol version).
1654 if (s->ctx->method->version == TLS_method()->version)
1655 table = tls_version_table;
1656 else if (s->ctx->method->version == DTLS_method()->version)
1657 table = dtls_version_table;
1659 /* Unexpected state; fail closed. */
1663 for (vent = table; vent->version != 0; ++vent) {
1664 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1665 return s->version == vent->version;
1671 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1672 * protocols, provided the initial (D)TLS method is version-flexible. This
1673 * function sanity-checks the proposed value and makes sure the method is
1674 * version-flexible, then sets the limit if all is well.
1676 * @method_version: The version of the current SSL_METHOD.
1677 * @version: the intended limit.
1678 * @bound: pointer to limit to be updated.
1680 * Returns 1 on success, 0 on failure.
1682 int ssl_set_version_bound(int method_version, int version, int *bound)
1692 valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1694 DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1695 DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1697 if (!valid_tls && !valid_dtls)
1701 * Restrict TLS methods to TLS protocol versions.
1702 * Restrict DTLS methods to DTLS protocol versions.
1703 * Note, DTLS version numbers are decreasing, use comparison macros.
1705 * Note that for both lower-bounds we use explicit versions, not
1706 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1707 * configurations. If the MIN (supported) version ever rises, the user's
1708 * "floor" remains valid even if no longer available. We don't expect the
1709 * MAX ceiling to ever get lower, so making that variable makes sense.
1711 * We ignore attempts to set bounds on version-inflexible methods,
1712 * returning success.
1714 switch (method_version) {
1718 case TLS_ANY_VERSION:
1723 case DTLS_ANY_VERSION:
1731 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1733 if (vers == TLS1_2_VERSION
1734 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1735 *dgrd = DOWNGRADE_TO_1_2;
1736 } else if (!SSL_IS_DTLS(s)
1737 && vers < TLS1_2_VERSION
1739 * We need to ensure that a server that disables TLSv1.2
1740 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1741 * complete handshakes with clients that support TLSv1.2 and
1742 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1743 * enabled and TLSv1.2 is not.
1745 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1746 *dgrd = DOWNGRADE_TO_1_1;
1748 *dgrd = DOWNGRADE_NONE;
1753 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1754 * client HELLO is received to select the final server protocol version and
1755 * the version specific method.
1757 * @s: server SSL handle.
1759 * Returns 0 on success or an SSL error reason number on failure.
1761 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1764 * With version-flexible methods we have an initial state with:
1766 * s->method->version == (D)TLS_ANY_VERSION,
1767 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1769 * So we detect version-flexible methods via the method version, not the
1772 int server_version = s->method->version;
1773 int client_version = hello->legacy_version;
1774 const version_info *vent;
1775 const version_info *table;
1777 RAW_EXTENSION *suppversions;
1779 s->client_version = client_version;
1781 switch (server_version) {
1783 if (!SSL_IS_TLS13(s)) {
1784 if (version_cmp(s, client_version, s->version) < 0)
1785 return SSL_R_WRONG_SSL_VERSION;
1786 *dgrd = DOWNGRADE_NONE;
1788 * If this SSL handle is not from a version flexible method we don't
1789 * (and never did) check min/max FIPS or Suite B constraints. Hope
1790 * that's OK. It is up to the caller to not choose fixed protocol
1791 * versions they don't want. If not, then easy to fix, just return
1792 * ssl_method_error(s, s->method)
1797 * Fall through if we are TLSv1.3 already (this means we must be after
1798 * a HelloRetryRequest
1801 case TLS_ANY_VERSION:
1802 table = tls_version_table;
1804 case DTLS_ANY_VERSION:
1805 table = dtls_version_table;
1809 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1811 /* If we did an HRR then supported versions is mandatory */
1812 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1813 return SSL_R_UNSUPPORTED_PROTOCOL;
1815 if (suppversions->present && !SSL_IS_DTLS(s)) {
1816 unsigned int candidate_vers = 0;
1817 unsigned int best_vers = 0;
1818 const SSL_METHOD *best_method = NULL;
1819 PACKET versionslist;
1821 suppversions->parsed = 1;
1823 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1824 /* Trailing or invalid data? */
1825 return SSL_R_LENGTH_MISMATCH;
1829 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1830 * The spec only requires servers to check that it isn't SSLv3:
1831 * "Any endpoint receiving a Hello message with
1832 * ClientHello.legacy_version or ServerHello.legacy_version set to
1833 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1834 * We are slightly stricter and require that it isn't SSLv3 or lower.
1835 * We tolerate TLSv1 and TLSv1.1.
1837 if (client_version <= SSL3_VERSION)
1838 return SSL_R_BAD_LEGACY_VERSION;
1840 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1841 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1843 if (ssl_version_supported(s, candidate_vers, &best_method))
1844 best_vers = candidate_vers;
1846 if (PACKET_remaining(&versionslist) != 0) {
1847 /* Trailing data? */
1848 return SSL_R_LENGTH_MISMATCH;
1851 if (best_vers > 0) {
1852 if (s->hello_retry_request != SSL_HRR_NONE) {
1854 * This is after a HelloRetryRequest so we better check that we
1855 * negotiated TLSv1.3
1857 if (best_vers != TLS1_3_VERSION)
1858 return SSL_R_UNSUPPORTED_PROTOCOL;
1861 check_for_downgrade(s, best_vers, dgrd);
1862 s->version = best_vers;
1863 s->method = best_method;
1866 return SSL_R_UNSUPPORTED_PROTOCOL;
1870 * If the supported versions extension isn't present, then the highest
1871 * version we can negotiate is TLSv1.2
1873 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1874 client_version = TLS1_2_VERSION;
1877 * No supported versions extension, so we just use the version supplied in
1880 for (vent = table; vent->version != 0; ++vent) {
1881 const SSL_METHOD *method;
1883 if (vent->smeth == NULL ||
1884 version_cmp(s, client_version, vent->version) < 0)
1886 method = vent->smeth();
1887 if (ssl_method_error(s, method) == 0) {
1888 check_for_downgrade(s, vent->version, dgrd);
1889 s->version = vent->version;
1895 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1899 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1900 * server HELLO is received to select the final client protocol version and
1901 * the version specific method.
1903 * @s: client SSL handle.
1904 * @version: The proposed version from the server's HELLO.
1905 * @extensions: The extensions received
1907 * Returns 1 on success or 0 on error.
1909 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1911 const version_info *vent;
1912 const version_info *table;
1913 int ret, ver_min, ver_max, real_max, origv;
1916 s->version = version;
1918 /* This will overwrite s->version if the extension is present */
1919 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1920 SSL_EXT_TLS1_2_SERVER_HELLO
1921 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1927 if (s->hello_retry_request != SSL_HRR_NONE
1928 && s->version != TLS1_3_VERSION) {
1930 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1931 SSL_R_WRONG_SSL_VERSION);
1935 switch (s->method->version) {
1937 if (s->version != s->method->version) {
1939 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1940 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1941 SSL_R_WRONG_SSL_VERSION);
1945 * If this SSL handle is not from a version flexible method we don't
1946 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1947 * that's OK. It is up to the caller to not choose fixed protocol
1948 * versions they don't want. If not, then easy to fix, just return
1949 * ssl_method_error(s, s->method)
1952 case TLS_ANY_VERSION:
1953 table = tls_version_table;
1955 case DTLS_ANY_VERSION:
1956 table = dtls_version_table;
1960 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1963 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1964 SSL_F_SSL_CHOOSE_CLIENT_VERSION, ret);
1967 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1968 : s->version < ver_min) {
1970 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1971 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1973 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1974 : s->version > ver_max) {
1976 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1977 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1981 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1984 /* Check for downgrades */
1985 if (s->version == TLS1_2_VERSION && real_max > s->version) {
1986 if (memcmp(tls12downgrade,
1987 s->s3.server_random + SSL3_RANDOM_SIZE
1988 - sizeof(tls12downgrade),
1989 sizeof(tls12downgrade)) == 0) {
1991 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1992 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1993 SSL_R_INAPPROPRIATE_FALLBACK);
1996 } else if (!SSL_IS_DTLS(s)
1997 && s->version < TLS1_2_VERSION
1998 && real_max > s->version) {
1999 if (memcmp(tls11downgrade,
2000 s->s3.server_random + SSL3_RANDOM_SIZE
2001 - sizeof(tls11downgrade),
2002 sizeof(tls11downgrade)) == 0) {
2004 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2005 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2006 SSL_R_INAPPROPRIATE_FALLBACK);
2011 for (vent = table; vent->version != 0; ++vent) {
2012 if (vent->cmeth == NULL || s->version != vent->version)
2015 s->method = vent->cmeth();
2020 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2021 SSL_R_UNSUPPORTED_PROTOCOL);
2026 * ssl_get_min_max_version - get minimum and maximum protocol version
2027 * @s: The SSL connection
2028 * @min_version: The minimum supported version
2029 * @max_version: The maximum supported version
2030 * @real_max: The highest version below the lowest compile time version hole
2031 * where that hole lies above at least one run-time enabled
2034 * Work out what version we should be using for the initial ClientHello if the
2035 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2036 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2037 * constraints and any floor imposed by the security level here,
2038 * so we don't advertise the wrong protocol version to only reject the outcome later.
2040 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2041 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2042 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2044 * Returns 0 on success or an SSL error reason number on failure. On failure
2045 * min_version and max_version will also be set to 0.
2047 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2050 int version, tmp_real_max;
2052 const SSL_METHOD *single = NULL;
2053 const SSL_METHOD *method;
2054 const version_info *table;
2055 const version_info *vent;
2057 switch (s->method->version) {
2060 * If this SSL handle is not from a version flexible method we don't
2061 * (and never did) check min/max FIPS or Suite B constraints. Hope
2062 * that's OK. It is up to the caller to not choose fixed protocol
2063 * versions they don't want. If not, then easy to fix, just return
2064 * ssl_method_error(s, s->method)
2066 *min_version = *max_version = s->version;
2068 * Providing a real_max only makes sense where we're using a version
2071 if (!ossl_assert(real_max == NULL))
2072 return ERR_R_INTERNAL_ERROR;
2074 case TLS_ANY_VERSION:
2075 table = tls_version_table;
2077 case DTLS_ANY_VERSION:
2078 table = dtls_version_table;
2083 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2084 * below X enabled. This is required in order to maintain the "version
2085 * capability" vector contiguous. Any versions with a NULL client method
2086 * (protocol version client is disabled at compile-time) is also a "hole".
2088 * Our initial state is hole == 1, version == 0. That is, versions above
2089 * the first version in the method table are disabled (a "hole" above
2090 * the valid protocol entries) and we don't have a selected version yet.
2092 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2093 * the selected version, and the method becomes a candidate "single"
2094 * method. We're no longer in a hole, so "hole" becomes 0.
2096 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2097 * as we support a contiguous range of at least two methods. If we hit
2098 * a disabled method, then hole becomes true again, but nothing else
2099 * changes yet, because all the remaining methods may be disabled too.
2100 * If we again hit an enabled method after the new hole, it becomes
2101 * selected, as we start from scratch.
2103 *min_version = version = 0;
2105 if (real_max != NULL)
2108 for (vent = table; vent->version != 0; ++vent) {
2110 * A table entry with a NULL client method is still a hole in the
2111 * "version capability" vector.
2113 if (vent->cmeth == NULL) {
2118 method = vent->cmeth();
2120 if (hole == 1 && tmp_real_max == 0)
2121 tmp_real_max = vent->version;
2123 if (ssl_method_error(s, method) != 0) {
2127 *min_version = method->version;
2129 if (real_max != NULL && tmp_real_max != 0)
2130 *real_max = tmp_real_max;
2131 version = (single = method)->version;
2132 *min_version = version;
2137 *max_version = version;
2139 /* Fail if everything is disabled */
2141 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2147 * ssl_set_client_hello_version - Work out what version we should be using for
2148 * the initial ClientHello.legacy_version field.
2150 * @s: client SSL handle.
2152 * Returns 0 on success or an SSL error reason number on failure.
2154 int ssl_set_client_hello_version(SSL *s)
2156 int ver_min, ver_max, ret;
2159 * In a renegotiation we always send the same client_version that we sent
2160 * last time, regardless of which version we eventually negotiated.
2162 if (!SSL_IS_FIRST_HANDSHAKE(s))
2165 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2170 s->version = ver_max;
2172 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2173 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2174 ver_max = TLS1_2_VERSION;
2176 s->client_version = ver_max;
2181 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2182 * and |checkallow| is 1 then additionally check if the group is allowed to be
2183 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2184 * 1) or 0 otherwise.
2186 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2187 size_t num_groups, int checkallow)
2191 if (groups == NULL || num_groups == 0)
2194 for (i = 0; i < num_groups; i++) {
2195 uint16_t group = groups[i];
2197 if (group_id == group
2199 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2207 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2208 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2209 size_t hashlen, const unsigned char *hrr,
2212 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2213 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2215 memset(msghdr, 0, sizeof(msghdr));
2217 if (hashval == NULL) {
2218 hashval = hashvaltmp;
2220 /* Get the hash of the initial ClientHello */
2221 if (!ssl3_digest_cached_records(s, 0)
2222 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2224 /* SSLfatal() already called */
2229 /* Reinitialise the transcript hash */
2230 if (!ssl3_init_finished_mac(s)) {
2231 /* SSLfatal() already called */
2235 /* Inject the synthetic message_hash message */
2236 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2237 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2238 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2239 || !ssl3_finish_mac(s, hashval, hashlen)) {
2240 /* SSLfatal() already called */
2245 * Now re-inject the HRR and current message if appropriate (we just deleted
2246 * it when we reinitialised the transcript hash above). Only necessary after
2247 * receiving a ClientHello2 with a cookie.
2250 && (!ssl3_finish_mac(s, hrr, hrrlen)
2251 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2252 s->s3.tmp.message_size
2253 + SSL3_HM_HEADER_LENGTH))) {
2254 /* SSLfatal() already called */
2261 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2263 return X509_NAME_cmp(*a, *b);
2266 int parse_ca_names(SSL *s, PACKET *pkt)
2268 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2269 X509_NAME *xn = NULL;
2272 if (ca_sk == NULL) {
2273 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2274 ERR_R_MALLOC_FAILURE);
2277 /* get the CA RDNs */
2278 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2279 SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2280 SSL_R_LENGTH_MISMATCH);
2284 while (PACKET_remaining(&cadns)) {
2285 const unsigned char *namestart, *namebytes;
2286 unsigned int name_len;
2288 if (!PACKET_get_net_2(&cadns, &name_len)
2289 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2290 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2291 SSL_R_LENGTH_MISMATCH);
2295 namestart = namebytes;
2296 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2297 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2301 if (namebytes != (namestart + name_len)) {
2302 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2303 SSL_R_CA_DN_LENGTH_MISMATCH);
2307 if (!sk_X509_NAME_push(ca_sk, xn)) {
2308 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2309 ERR_R_MALLOC_FAILURE);
2315 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2316 s->s3.tmp.peer_ca_names = ca_sk;
2321 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2326 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2328 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2331 ca_sk = SSL_get_client_CA_list(s);
2332 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2337 ca_sk = SSL_get0_CA_list(s);
2342 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2344 /* Start sub-packet for client CA list */
2345 if (!WPACKET_start_sub_packet_u16(pkt)) {
2346 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2347 ERR_R_INTERNAL_ERROR);
2351 if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2354 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2355 unsigned char *namebytes;
2356 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2360 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2361 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2363 || i2d_X509_NAME(name, &namebytes) != namelen) {
2364 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2365 ERR_R_INTERNAL_ERROR);
2371 if (!WPACKET_close(pkt)) {
2372 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2373 ERR_R_INTERNAL_ERROR);
2380 /* Create a buffer containing data to be signed for server key exchange */
2381 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2382 const void *param, size_t paramlen)
2384 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2385 unsigned char *tbs = OPENSSL_malloc(tbslen);
2388 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2389 ERR_R_MALLOC_FAILURE);
2392 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2393 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2395 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2402 * Saves the current handshake digest for Post-Handshake Auth,
2403 * Done after ClientFinished is processed, done exactly once
2405 int tls13_save_handshake_digest_for_pha(SSL *s)
2407 if (s->pha_dgst == NULL) {
2408 if (!ssl3_digest_cached_records(s, 1))
2409 /* SSLfatal() already called */
2412 s->pha_dgst = EVP_MD_CTX_new();
2413 if (s->pha_dgst == NULL) {
2414 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2415 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2416 ERR_R_INTERNAL_ERROR);
2419 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2420 s->s3.handshake_dgst)) {
2421 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2422 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2423 ERR_R_INTERNAL_ERROR);
2431 * Restores the Post-Handshake Auth handshake digest
2432 * Done just before sending/processing the Cert Request
2434 int tls13_restore_handshake_digest_for_pha(SSL *s)
2436 if (s->pha_dgst == NULL) {
2437 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2438 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2439 ERR_R_INTERNAL_ERROR);
2442 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2444 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2445 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2446 ERR_R_INTERNAL_ERROR);