2 * Copyright 1995-2018 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/x509.h>
21 #include <openssl/trace.h>
24 * Map error codes to TLS/SSL alart types.
26 typedef struct x509err2alert_st {
31 /* Fixed value used in the ServerHello random field to identify an HRR */
32 const unsigned char hrrrandom[] = {
33 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
34 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
35 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
39 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
40 * SSL3_RT_CHANGE_CIPHER_SPEC)
42 int ssl3_do_write(SSL *s, int type)
47 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
48 s->init_num, &written);
51 if (type == SSL3_RT_HANDSHAKE)
53 * should not be done for 'Hello Request's, but in that case we'll
54 * ignore the result anyway
55 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
57 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
58 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
59 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
60 if (!ssl3_finish_mac(s,
61 (unsigned char *)&s->init_buf->data[s->init_off],
64 if (written == s->init_num) {
66 s->msg_callback(1, s->version, type, s->init_buf->data,
67 (size_t)(s->init_off + s->init_num), s,
71 s->init_off += written;
72 s->init_num -= written;
76 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
80 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
81 || !WPACKET_get_length(pkt, &msglen)
84 s->init_num = (int)msglen;
90 int tls_setup_handshake(SSL *s)
92 if (!ssl3_init_finished_mac(s)) {
93 /* SSLfatal() already called */
97 /* Reset any extension flags */
98 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
101 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
102 int i, ver_min, ver_max, ok = 0;
105 * Sanity check that the maximum version we accept has ciphers
106 * enabled. For clients we do this check during construction of the
109 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
110 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_SETUP_HANDSHAKE,
111 ERR_R_INTERNAL_ERROR);
114 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
115 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
117 if (SSL_IS_DTLS(s)) {
118 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
119 DTLS_VERSION_LE(ver_max, c->max_dtls))
121 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
128 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
129 SSL_R_NO_CIPHERS_AVAILABLE);
130 ERR_add_error_data(1, "No ciphers enabled for max supported "
134 if (SSL_IS_FIRST_HANDSHAKE(s)) {
135 /* N.B. s->session_ctx == s->ctx here */
136 tsan_counter(&s->session_ctx->stats.sess_accept);
138 /* N.B. s->ctx may not equal s->session_ctx */
139 tsan_counter(&s->ctx->stats.sess_accept_renegotiate);
141 s->s3.tmp.cert_request = 0;
144 if (SSL_IS_FIRST_HANDSHAKE(s))
145 tsan_counter(&s->session_ctx->stats.sess_connect);
147 tsan_counter(&s->session_ctx->stats.sess_connect_renegotiate);
149 /* mark client_random uninitialized */
150 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
153 s->s3.tmp.cert_req = 0;
156 s->statem.use_timer = 1;
163 * Size of the to-be-signed TLS13 data, without the hash size itself:
164 * 64 bytes of value 32, 33 context bytes, 1 byte separator
166 #define TLS13_TBS_START_SIZE 64
167 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
169 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
170 void **hdata, size_t *hdatalen)
172 #ifdef CHARSET_EBCDIC
173 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
174 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
175 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
176 0x69, 0x66, 0x79, 0x00 };
177 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
178 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
179 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
180 0x69, 0x66, 0x79, 0x00 };
182 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
183 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
185 if (SSL_IS_TLS13(s)) {
188 /* Set the first 64 bytes of to-be-signed data to octet 32 */
189 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
190 /* This copies the 33 bytes of context plus the 0 separator byte */
191 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
192 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
193 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
195 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
198 * If we're currently reading then we need to use the saved handshake
199 * hash value. We can't use the current handshake hash state because
200 * that includes the CertVerify itself.
202 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
203 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
204 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
205 s->cert_verify_hash_len);
206 hashlen = s->cert_verify_hash_len;
207 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
208 EVP_MAX_MD_SIZE, &hashlen)) {
209 /* SSLfatal() already called */
214 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
219 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
221 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
222 ERR_R_INTERNAL_ERROR);
231 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
233 EVP_PKEY *pkey = NULL;
234 const EVP_MD *md = NULL;
235 EVP_MD_CTX *mctx = NULL;
236 EVP_PKEY_CTX *pctx = NULL;
237 size_t hdatalen = 0, siglen = 0;
239 unsigned char *sig = NULL;
240 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
241 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
243 if (lu == NULL || s->s3.tmp.cert == NULL) {
244 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
245 ERR_R_INTERNAL_ERROR);
248 pkey = s->s3.tmp.cert->privatekey;
250 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
251 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
252 ERR_R_INTERNAL_ERROR);
256 mctx = EVP_MD_CTX_new();
258 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
259 ERR_R_MALLOC_FAILURE);
263 /* Get the data to be signed */
264 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
265 /* SSLfatal() already called */
269 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
270 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
271 ERR_R_INTERNAL_ERROR);
275 if (EVP_DigestSignInit_ex(mctx, &pctx,
276 md == NULL ? NULL : EVP_MD_name(md),
277 s->ctx->propq, pkey, s->ctx->libctx) <= 0) {
278 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
283 if (lu->sig == EVP_PKEY_RSA_PSS) {
284 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
285 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
286 RSA_PSS_SALTLEN_DIGEST) <= 0) {
287 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
292 if (s->version == SSL3_VERSION) {
294 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
295 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
297 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
299 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
300 * with a call to ssl3_digest_master_key_set_params()
302 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
303 (int)s->session->master_key_length,
304 s->session->master_key) <= 0
305 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
307 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
311 sig = OPENSSL_malloc(siglen);
313 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
314 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
320 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
321 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
323 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
324 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
328 sig = OPENSSL_malloc(siglen);
330 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
331 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
337 #ifndef OPENSSL_NO_GOST
339 int pktype = lu->sig;
341 if (pktype == NID_id_GostR3410_2001
342 || pktype == NID_id_GostR3410_2012_256
343 || pktype == NID_id_GostR3410_2012_512)
344 BUF_reverse(sig, NULL, siglen);
348 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
349 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
350 ERR_R_INTERNAL_ERROR);
354 /* Digest cached records and discard handshake buffer */
355 if (!ssl3_digest_cached_records(s, 0)) {
356 /* SSLfatal() already called */
361 EVP_MD_CTX_free(mctx);
365 EVP_MD_CTX_free(mctx);
369 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
371 EVP_PKEY *pkey = NULL;
372 const unsigned char *data;
373 #ifndef OPENSSL_NO_GOST
374 unsigned char *gost_data = NULL;
376 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
380 const EVP_MD *md = NULL;
383 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
384 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
385 EVP_PKEY_CTX *pctx = NULL;
388 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
389 ERR_R_MALLOC_FAILURE);
393 peer = s->session->peer;
394 pkey = X509_get0_pubkey(peer);
396 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
397 ERR_R_INTERNAL_ERROR);
401 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
402 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
403 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
407 if (SSL_USE_SIGALGS(s)) {
410 if (!PACKET_get_net_2(pkt, &sigalg)) {
411 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
415 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
416 /* SSLfatal() already called */
419 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
420 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
421 ERR_R_INTERNAL_ERROR);
425 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
426 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
427 ERR_R_INTERNAL_ERROR);
431 if (SSL_USE_SIGALGS(s))
432 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
433 md == NULL ? "n/a" : EVP_MD_name(md));
435 /* Check for broken implementations of GOST ciphersuites */
437 * If key is GOST and len is exactly 64 or 128, it is signature without
438 * length field (CryptoPro implementations at least till TLS 1.2)
440 #ifndef OPENSSL_NO_GOST
441 if (!SSL_USE_SIGALGS(s)
442 && ((PACKET_remaining(pkt) == 64
443 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
444 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
445 || (PACKET_remaining(pkt) == 128
446 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
447 len = PACKET_remaining(pkt);
450 if (!PACKET_get_net_2(pkt, &len)) {
451 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
452 SSL_R_LENGTH_MISMATCH);
456 if (!PACKET_get_bytes(pkt, &data, len)) {
457 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
458 SSL_R_LENGTH_MISMATCH);
462 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
463 /* SSLfatal() already called */
467 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
468 md == NULL ? "n/a" : EVP_MD_name(md));
470 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
471 md == NULL ? NULL : EVP_MD_name(md),
472 s->ctx->propq, pkey, s->ctx->libctx) <= 0) {
473 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
477 #ifndef OPENSSL_NO_GOST
479 int pktype = EVP_PKEY_id(pkey);
480 if (pktype == NID_id_GostR3410_2001
481 || pktype == NID_id_GostR3410_2012_256
482 || pktype == NID_id_GostR3410_2012_512) {
483 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
484 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
485 SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
488 BUF_reverse(gost_data, data, len);
494 if (SSL_USE_PSS(s)) {
495 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
496 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
497 RSA_PSS_SALTLEN_DIGEST) <= 0) {
498 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
503 if (s->version == SSL3_VERSION) {
505 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
506 * with a call to ssl3_digest_master_key_set_params()
508 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
509 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
510 (int)s->session->master_key_length,
511 s->session->master_key) <= 0) {
512 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
516 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
517 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
518 SSL_R_BAD_SIGNATURE);
522 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
524 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
525 SSL_R_BAD_SIGNATURE);
531 * In TLSv1.3 on the client side we make sure we prepare the client
532 * certificate after the CertVerify instead of when we get the
533 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
534 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
535 * want to make sure that SSL_get_peer_certificate() will return the actual
536 * server certificate from the client_cert_cb callback.
538 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
539 ret = MSG_PROCESS_CONTINUE_PROCESSING;
541 ret = MSG_PROCESS_CONTINUE_READING;
543 BIO_free(s->s3.handshake_buffer);
544 s->s3.handshake_buffer = NULL;
545 EVP_MD_CTX_free(mctx);
546 #ifndef OPENSSL_NO_GOST
547 OPENSSL_free(gost_data);
552 int tls_construct_finished(SSL *s, WPACKET *pkt)
554 size_t finish_md_len;
558 /* This is a real handshake so make sure we clean it up at the end */
559 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
560 s->statem.cleanuphand = 1;
563 * We only change the keys if we didn't already do this when we sent the
568 && s->s3.tmp.cert_req == 0
569 && (!s->method->ssl3_enc->change_cipher_state(s,
570 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
571 /* SSLfatal() already called */
576 sender = s->method->ssl3_enc->server_finished_label;
577 slen = s->method->ssl3_enc->server_finished_label_len;
579 sender = s->method->ssl3_enc->client_finished_label;
580 slen = s->method->ssl3_enc->client_finished_label_len;
583 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
585 s->s3.tmp.finish_md);
586 if (finish_md_len == 0) {
587 /* SSLfatal() already called */
591 s->s3.tmp.finish_md_len = finish_md_len;
593 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
594 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
595 ERR_R_INTERNAL_ERROR);
600 * Log the master secret, if logging is enabled. We don't log it for
601 * TLSv1.3: there's a different key schedule for that.
603 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
604 s->session->master_key,
605 s->session->master_key_length)) {
606 /* SSLfatal() already called */
611 * Copy the finished so we can use it for renegotiation checks
613 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
614 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
615 ERR_R_INTERNAL_ERROR);
619 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
621 s->s3.previous_client_finished_len = finish_md_len;
623 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
625 s->s3.previous_server_finished_len = finish_md_len;
631 int tls_construct_key_update(SSL *s, WPACKET *pkt)
633 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
634 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
635 ERR_R_INTERNAL_ERROR);
639 s->key_update = SSL_KEY_UPDATE_NONE;
643 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
645 unsigned int updatetype;
648 * A KeyUpdate message signals a key change so the end of the message must
649 * be on a record boundary.
651 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
652 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
653 SSL_R_NOT_ON_RECORD_BOUNDARY);
654 return MSG_PROCESS_ERROR;
657 if (!PACKET_get_1(pkt, &updatetype)
658 || PACKET_remaining(pkt) != 0) {
659 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
660 SSL_R_BAD_KEY_UPDATE);
661 return MSG_PROCESS_ERROR;
665 * There are only two defined key update types. Fail if we get a value we
668 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
669 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
670 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
671 SSL_R_BAD_KEY_UPDATE);
672 return MSG_PROCESS_ERROR;
676 * If we get a request for us to update our sending keys too then, we need
677 * to additionally send a KeyUpdate message. However that message should
678 * not also request an update (otherwise we get into an infinite loop).
680 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
681 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
683 if (!tls13_update_key(s, 0)) {
684 /* SSLfatal() already called */
685 return MSG_PROCESS_ERROR;
688 return MSG_PROCESS_FINISHED_READING;
692 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
695 int ssl3_take_mac(SSL *s)
701 sender = s->method->ssl3_enc->server_finished_label;
702 slen = s->method->ssl3_enc->server_finished_label_len;
704 sender = s->method->ssl3_enc->client_finished_label;
705 slen = s->method->ssl3_enc->client_finished_label_len;
708 s->s3.tmp.peer_finish_md_len =
709 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
710 s->s3.tmp.peer_finish_md);
712 if (s->s3.tmp.peer_finish_md_len == 0) {
713 /* SSLfatal() already called */
720 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
724 remain = PACKET_remaining(pkt);
726 * 'Change Cipher Spec' is just a single byte, which should already have
727 * been consumed by ssl_get_message() so there should be no bytes left,
728 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
730 if (SSL_IS_DTLS(s)) {
731 if ((s->version == DTLS1_BAD_VER
732 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
733 || (s->version != DTLS1_BAD_VER
734 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
735 SSLfatal(s, SSL_AD_DECODE_ERROR,
736 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
737 SSL_R_BAD_CHANGE_CIPHER_SPEC);
738 return MSG_PROCESS_ERROR;
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 /* Check we have a cipher to change to */
750 if (s->s3.tmp.new_cipher == NULL) {
751 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
752 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
753 return MSG_PROCESS_ERROR;
756 s->s3.change_cipher_spec = 1;
757 if (!ssl3_do_change_cipher_spec(s)) {
758 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
759 ERR_R_INTERNAL_ERROR);
760 return MSG_PROCESS_ERROR;
763 if (SSL_IS_DTLS(s)) {
764 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
766 if (s->version == DTLS1_BAD_VER)
767 s->d1->handshake_read_seq++;
769 #ifndef OPENSSL_NO_SCTP
771 * Remember that a CCS has been received, so that an old key of
772 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
775 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
779 return MSG_PROCESS_CONTINUE_READING;
782 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
787 /* This is a real handshake so make sure we clean it up at the end */
790 * To get this far we must have read encrypted data from the client. We
791 * no longer tolerate unencrypted alerts. This value is ignored if less
794 s->statem.enc_read_state = ENC_READ_STATE_VALID;
795 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
796 s->statem.cleanuphand = 1;
797 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
798 /* SSLfatal() already called */
799 return MSG_PROCESS_ERROR;
804 * In TLSv1.3 a Finished message signals a key change so the end of the
805 * message must be on a record boundary.
807 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
808 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
809 SSL_R_NOT_ON_RECORD_BOUNDARY);
810 return MSG_PROCESS_ERROR;
813 /* If this occurs, we have missed a message */
814 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
815 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
816 SSL_R_GOT_A_FIN_BEFORE_A_CCS);
817 return MSG_PROCESS_ERROR;
819 s->s3.change_cipher_spec = 0;
821 md_len = s->s3.tmp.peer_finish_md_len;
823 if (md_len != PACKET_remaining(pkt)) {
824 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
825 SSL_R_BAD_DIGEST_LENGTH);
826 return MSG_PROCESS_ERROR;
829 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
831 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
832 SSL_R_DIGEST_CHECK_FAILED);
833 return MSG_PROCESS_ERROR;
837 * Copy the finished so we can use it for renegotiation checks
839 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
840 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
841 ERR_R_INTERNAL_ERROR);
842 return MSG_PROCESS_ERROR;
845 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
847 s->s3.previous_client_finished_len = md_len;
849 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
851 s->s3.previous_server_finished_len = md_len;
855 * In TLS1.3 we also have to change cipher state and do any final processing
856 * of the initial server flight (if we are a client)
858 if (SSL_IS_TLS13(s)) {
860 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
861 !s->method->ssl3_enc->change_cipher_state(s,
862 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
863 /* SSLfatal() already called */
864 return MSG_PROCESS_ERROR;
867 /* TLS 1.3 gets the secret size from the handshake md */
869 if (!s->method->ssl3_enc->generate_master_secret(s,
870 s->master_secret, s->handshake_secret, 0,
872 /* SSLfatal() already called */
873 return MSG_PROCESS_ERROR;
875 if (!s->method->ssl3_enc->change_cipher_state(s,
876 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
877 /* SSLfatal() already called */
878 return MSG_PROCESS_ERROR;
880 if (!tls_process_initial_server_flight(s)) {
881 /* SSLfatal() already called */
882 return MSG_PROCESS_ERROR;
887 return MSG_PROCESS_FINISHED_READING;
890 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
892 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
893 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
894 SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
901 /* Add a certificate to the WPACKET */
902 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
905 unsigned char *outbytes;
907 len = i2d_X509(x, NULL);
909 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
913 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
914 || i2d_X509(x, &outbytes) != len) {
915 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
916 ERR_R_INTERNAL_ERROR);
921 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
923 /* SSLfatal() already called */
930 /* Add certificate chain to provided WPACKET */
931 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
935 STACK_OF(X509) *extra_certs;
936 STACK_OF(X509) *chain = NULL;
937 X509_STORE *chain_store;
939 if (cpk == NULL || cpk->x509 == NULL)
945 * If we have a certificate specific chain use it, else use parent ctx.
947 if (cpk->chain != NULL)
948 extra_certs = cpk->chain;
950 extra_certs = s->ctx->extra_certs;
952 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
954 else if (s->cert->chain_store)
955 chain_store = s->cert->chain_store;
957 chain_store = s->ctx->cert_store;
959 if (chain_store != NULL) {
960 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
962 if (xs_ctx == NULL) {
963 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
964 ERR_R_MALLOC_FAILURE);
967 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
968 X509_STORE_CTX_free(xs_ctx);
969 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
974 * It is valid for the chain not to be complete (because normally we
975 * don't include the root cert in the chain). Therefore we deliberately
976 * ignore the error return from this call. We're not actually verifying
977 * the cert - we're just building as much of the chain as we can
979 (void)X509_verify_cert(xs_ctx);
980 /* Don't leave errors in the queue */
982 chain = X509_STORE_CTX_get0_chain(xs_ctx);
983 i = ssl_security_cert_chain(s, chain, NULL, 0);
986 /* Dummy error calls so mkerr generates them */
987 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
988 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
989 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
991 X509_STORE_CTX_free(xs_ctx);
992 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
995 chain_count = sk_X509_num(chain);
996 for (i = 0; i < chain_count; i++) {
997 x = sk_X509_value(chain, i);
999 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1000 /* SSLfatal() already called */
1001 X509_STORE_CTX_free(xs_ctx);
1005 X509_STORE_CTX_free(xs_ctx);
1007 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1009 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1012 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1013 /* SSLfatal() already called */
1016 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1017 x = sk_X509_value(extra_certs, i);
1018 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1019 /* SSLfatal() already called */
1027 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1029 if (!WPACKET_start_sub_packet_u24(pkt)) {
1030 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1031 ERR_R_INTERNAL_ERROR);
1035 if (!ssl_add_cert_chain(s, pkt, cpk))
1038 if (!WPACKET_close(pkt)) {
1039 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1040 ERR_R_INTERNAL_ERROR);
1048 * Tidy up after the end of a handshake. In the case of SCTP this may result
1049 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1052 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1054 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1055 int cleanuphand = s->statem.cleanuphand;
1059 #ifndef OPENSSL_NO_SCTP
1061 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1062 * messages that require it. Therefore, DTLS procedures for retransmissions
1064 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1066 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1070 * We don't do this in DTLS over UDP because we may still need the init_buf
1071 * in case there are any unexpected retransmits
1073 BUF_MEM_free(s->init_buf);
1077 if (!ssl_free_wbio_buffer(s)) {
1078 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_FINISH_HANDSHAKE,
1079 ERR_R_INTERNAL_ERROR);
1085 if (SSL_IS_TLS13(s) && !s->server
1086 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1087 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1090 * Only set if there was a Finished message and this isn't after a TLSv1.3
1091 * post handshake exchange
1094 /* skipped if we just sent a HelloRequest */
1097 s->statem.cleanuphand = 0;
1098 s->ext.ticket_expected = 0;
1100 ssl3_cleanup_key_block(s);
1104 * In TLSv1.3 we update the cache as part of constructing the
1107 if (!SSL_IS_TLS13(s))
1108 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1110 /* N.B. s->ctx may not equal s->session_ctx */
1111 tsan_counter(&s->ctx->stats.sess_accept_good);
1112 s->handshake_func = ossl_statem_accept;
1114 if (SSL_IS_TLS13(s)) {
1116 * We encourage applications to only use TLSv1.3 tickets once,
1117 * so we remove this one from the cache.
1119 if ((s->session_ctx->session_cache_mode
1120 & SSL_SESS_CACHE_CLIENT) != 0)
1121 SSL_CTX_remove_session(s->session_ctx, s->session);
1124 * In TLSv1.3 we update the cache as part of processing the
1127 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1130 tsan_counter(&s->session_ctx->stats.sess_hit);
1132 s->handshake_func = ossl_statem_connect;
1133 tsan_counter(&s->session_ctx->stats.sess_connect_good);
1136 if (SSL_IS_DTLS(s)) {
1137 /* done with handshaking */
1138 s->d1->handshake_read_seq = 0;
1139 s->d1->handshake_write_seq = 0;
1140 s->d1->next_handshake_write_seq = 0;
1141 dtls1_clear_received_buffer(s);
1145 if (s->info_callback != NULL)
1146 cb = s->info_callback;
1147 else if (s->ctx->info_callback != NULL)
1148 cb = s->ctx->info_callback;
1150 /* The callback may expect us to not be in init at handshake done */
1151 ossl_statem_set_in_init(s, 0);
1156 || SSL_IS_FIRST_HANDSHAKE(s))
1157 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1161 /* If we've got more work to do we go back into init */
1162 ossl_statem_set_in_init(s, 1);
1163 return WORK_FINISHED_CONTINUE;
1166 return WORK_FINISHED_STOP;
1169 int tls_get_message_header(SSL *s, int *mt)
1171 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1172 int skip_message, i, recvd_type;
1174 size_t l, readbytes;
1176 p = (unsigned char *)s->init_buf->data;
1179 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1180 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1182 SSL3_HM_HEADER_LENGTH - s->init_num,
1185 s->rwstate = SSL_READING;
1188 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1190 * A ChangeCipherSpec must be a single byte and may not occur
1191 * in the middle of a handshake message.
1193 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1194 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1195 SSL_F_TLS_GET_MESSAGE_HEADER,
1196 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1199 if (s->statem.hand_state == TLS_ST_BEFORE
1200 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1202 * We are stateless and we received a CCS. Probably this is
1203 * from a client between the first and second ClientHellos.
1204 * We should ignore this, but return an error because we do
1205 * not return success until we see the second ClientHello
1206 * with a valid cookie.
1210 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1211 s->init_num = readbytes - 1;
1212 s->init_msg = s->init_buf->data;
1213 s->s3.tmp.message_size = readbytes;
1215 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1216 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1217 SSL_F_TLS_GET_MESSAGE_HEADER,
1218 SSL_R_CCS_RECEIVED_EARLY);
1221 s->init_num += readbytes;
1226 if (s->statem.hand_state != TLS_ST_OK
1227 && p[0] == SSL3_MT_HELLO_REQUEST)
1229 * The server may always send 'Hello Request' messages --
1230 * we are doing a handshake anyway now, so ignore them if
1231 * their format is correct. Does not count for 'Finished'
1234 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1238 if (s->msg_callback)
1239 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1240 p, SSL3_HM_HEADER_LENGTH, s,
1241 s->msg_callback_arg);
1243 } while (skip_message);
1244 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1247 s->s3.tmp.message_type = *(p++);
1249 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1251 * Only happens with SSLv3+ in an SSLv2 backward compatible
1254 * Total message size is the remaining record bytes to read
1255 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1257 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1258 + SSL3_HM_HEADER_LENGTH;
1259 s->s3.tmp.message_size = l;
1261 s->init_msg = s->init_buf->data;
1262 s->init_num = SSL3_HM_HEADER_LENGTH;
1265 /* BUF_MEM_grow takes an 'int' parameter */
1266 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1267 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1268 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1271 s->s3.tmp.message_size = l;
1273 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1280 int tls_get_message_body(SSL *s, size_t *len)
1282 size_t n, readbytes;
1286 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1287 /* We've already read everything in */
1288 *len = (unsigned long)s->init_num;
1293 n = s->s3.tmp.message_size - s->init_num;
1295 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1296 &p[s->init_num], n, 0, &readbytes);
1298 s->rwstate = SSL_READING;
1302 s->init_num += readbytes;
1307 * If receiving Finished, record MAC of prior handshake messages for
1308 * Finished verification.
1310 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1311 /* SSLfatal() already called */
1316 /* Feed this message into MAC computation. */
1317 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1318 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1320 /* SSLfatal() already called */
1324 if (s->msg_callback)
1325 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1326 (size_t)s->init_num, s, s->msg_callback_arg);
1329 * We defer feeding in the HRR until later. We'll do it as part of
1330 * processing the message
1331 * The TLsv1.3 handshake transcript stops at the ClientFinished
1334 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1335 /* KeyUpdate and NewSessionTicket do not need to be added */
1336 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1337 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1338 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1339 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1340 || memcmp(hrrrandom,
1341 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1342 SSL3_RANDOM_SIZE) != 0) {
1343 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1344 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1345 /* SSLfatal() already called */
1351 if (s->msg_callback)
1352 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1353 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1354 s->msg_callback_arg);
1361 static const X509ERR2ALERT x509table[] = {
1362 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1363 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1364 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1365 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1366 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1367 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1368 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1369 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1370 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1371 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1372 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1373 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1374 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1375 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1376 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1377 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1378 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1379 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1380 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1381 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1382 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1383 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1384 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1385 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1386 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1387 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1388 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1389 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1390 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1391 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1392 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1393 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1394 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1395 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1396 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1397 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1398 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1399 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1400 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1402 /* Last entry; return this if we don't find the value above. */
1403 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1406 int ssl_x509err2alert(int x509err)
1408 const X509ERR2ALERT *tp;
1410 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1411 if (tp->x509err == x509err)
1416 int ssl_allow_compression(SSL *s)
1418 if (s->options & SSL_OP_NO_COMPRESSION)
1420 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1423 static int version_cmp(const SSL *s, int a, int b)
1425 int dtls = SSL_IS_DTLS(s);
1430 return a < b ? -1 : 1;
1431 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1436 const SSL_METHOD *(*cmeth) (void);
1437 const SSL_METHOD *(*smeth) (void);
1440 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1441 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1444 /* Must be in order high to low */
1445 static const version_info tls_version_table[] = {
1446 #ifndef OPENSSL_NO_TLS1_3
1447 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1449 {TLS1_3_VERSION, NULL, NULL},
1451 #ifndef OPENSSL_NO_TLS1_2
1452 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1454 {TLS1_2_VERSION, NULL, NULL},
1456 #ifndef OPENSSL_NO_TLS1_1
1457 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1459 {TLS1_1_VERSION, NULL, NULL},
1461 #ifndef OPENSSL_NO_TLS1
1462 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1464 {TLS1_VERSION, NULL, NULL},
1466 #ifndef OPENSSL_NO_SSL3
1467 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1469 {SSL3_VERSION, NULL, NULL},
1474 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1475 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1478 /* Must be in order high to low */
1479 static const version_info dtls_version_table[] = {
1480 #ifndef OPENSSL_NO_DTLS1_2
1481 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1483 {DTLS1_2_VERSION, NULL, NULL},
1485 #ifndef OPENSSL_NO_DTLS1
1486 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1487 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1489 {DTLS1_VERSION, NULL, NULL},
1490 {DTLS1_BAD_VER, NULL, NULL},
1496 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1498 * @s: The SSL handle for the candidate method
1499 * @method: the intended method.
1501 * Returns 0 on success, or an SSL error reason on failure.
1503 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1505 int version = method->version;
1507 if ((s->min_proto_version != 0 &&
1508 version_cmp(s, version, s->min_proto_version) < 0) ||
1509 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1510 return SSL_R_VERSION_TOO_LOW;
1512 if (s->max_proto_version != 0 &&
1513 version_cmp(s, version, s->max_proto_version) > 0)
1514 return SSL_R_VERSION_TOO_HIGH;
1516 if ((s->options & method->mask) != 0)
1517 return SSL_R_UNSUPPORTED_PROTOCOL;
1518 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1519 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1525 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1526 * certificate type, or has PSK or a certificate callback configured. Otherwise
1529 static int is_tls13_capable(const SSL *s)
1532 #ifndef OPENSSL_NO_EC
1537 #ifndef OPENSSL_NO_PSK
1538 if (s->psk_server_callback != NULL)
1542 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1545 for (i = 0; i < SSL_PKEY_NUM; i++) {
1546 /* Skip over certs disallowed for TLSv1.3 */
1548 case SSL_PKEY_DSA_SIGN:
1549 case SSL_PKEY_GOST01:
1550 case SSL_PKEY_GOST12_256:
1551 case SSL_PKEY_GOST12_512:
1556 if (!ssl_has_cert(s, i))
1558 #ifndef OPENSSL_NO_EC
1559 if (i != SSL_PKEY_ECC)
1562 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1563 * more restrictive so check that our sig algs are consistent with this
1564 * EC cert. See section 4.2.3 of RFC8446.
1566 eckey = EVP_PKEY_get0_EC_KEY(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1569 curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(eckey));
1570 if (tls_check_sigalg_curve(s, curve))
1581 * ssl_version_supported - Check that the specified `version` is supported by
1584 * @s: The SSL handle for the candidate method
1585 * @version: Protocol version to test against
1587 * Returns 1 when supported, otherwise 0
1589 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1591 const version_info *vent;
1592 const version_info *table;
1594 switch (s->method->version) {
1596 /* Version should match method version for non-ANY method */
1597 return version_cmp(s, version, s->version) == 0;
1598 case TLS_ANY_VERSION:
1599 table = tls_version_table;
1601 case DTLS_ANY_VERSION:
1602 table = dtls_version_table;
1607 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1609 if (vent->cmeth != NULL
1610 && version_cmp(s, version, vent->version) == 0
1611 && ssl_method_error(s, vent->cmeth()) == 0
1613 || version != TLS1_3_VERSION
1614 || is_tls13_capable(s))) {
1616 *meth = vent->cmeth();
1624 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1625 * fallback indication from a client check whether we're using the highest
1626 * supported protocol version.
1628 * @s server SSL handle.
1630 * Returns 1 when using the highest enabled version, 0 otherwise.
1632 int ssl_check_version_downgrade(SSL *s)
1634 const version_info *vent;
1635 const version_info *table;
1638 * Check that the current protocol is the highest enabled version
1639 * (according to s->ctx->method, as version negotiation may have changed
1642 if (s->version == s->ctx->method->version)
1646 * Apparently we're using a version-flexible SSL_METHOD (not at its
1647 * highest protocol version).
1649 if (s->ctx->method->version == TLS_method()->version)
1650 table = tls_version_table;
1651 else if (s->ctx->method->version == DTLS_method()->version)
1652 table = dtls_version_table;
1654 /* Unexpected state; fail closed. */
1658 for (vent = table; vent->version != 0; ++vent) {
1659 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1660 return s->version == vent->version;
1666 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1667 * protocols, provided the initial (D)TLS method is version-flexible. This
1668 * function sanity-checks the proposed value and makes sure the method is
1669 * version-flexible, then sets the limit if all is well.
1671 * @method_version: The version of the current SSL_METHOD.
1672 * @version: the intended limit.
1673 * @bound: pointer to limit to be updated.
1675 * Returns 1 on success, 0 on failure.
1677 int ssl_set_version_bound(int method_version, int version, int *bound)
1685 * Restrict TLS methods to TLS protocol versions.
1686 * Restrict DTLS methods to DTLS protocol versions.
1687 * Note, DTLS version numbers are decreasing, use comparison macros.
1689 * Note that for both lower-bounds we use explicit versions, not
1690 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1691 * configurations. If the MIN (supported) version ever rises, the user's
1692 * "floor" remains valid even if no longer available. We don't expect the
1693 * MAX ceiling to ever get lower, so making that variable makes sense.
1695 switch (method_version) {
1698 * XXX For fixed version methods, should we always fail and not set any
1699 * bounds, always succeed and not set any bounds, or set the bounds and
1700 * arrange to fail later if they are not met? At present fixed-version
1701 * methods are not subject to controls that disable individual protocol
1706 case TLS_ANY_VERSION:
1707 if (version < SSL3_VERSION || version > TLS_MAX_VERSION_INTERNAL)
1711 case DTLS_ANY_VERSION:
1712 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION_INTERNAL) ||
1713 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1722 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1724 if (vers == TLS1_2_VERSION
1725 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1726 *dgrd = DOWNGRADE_TO_1_2;
1727 } else if (!SSL_IS_DTLS(s)
1728 && vers < TLS1_2_VERSION
1730 * We need to ensure that a server that disables TLSv1.2
1731 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1732 * complete handshakes with clients that support TLSv1.2 and
1733 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1734 * enabled and TLSv1.2 is not.
1736 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1737 *dgrd = DOWNGRADE_TO_1_1;
1739 *dgrd = DOWNGRADE_NONE;
1744 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1745 * client HELLO is received to select the final server protocol version and
1746 * the version specific method.
1748 * @s: server SSL handle.
1750 * Returns 0 on success or an SSL error reason number on failure.
1752 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1755 * With version-flexible methods we have an initial state with:
1757 * s->method->version == (D)TLS_ANY_VERSION,
1758 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1760 * So we detect version-flexible methods via the method version, not the
1763 int server_version = s->method->version;
1764 int client_version = hello->legacy_version;
1765 const version_info *vent;
1766 const version_info *table;
1768 RAW_EXTENSION *suppversions;
1770 s->client_version = client_version;
1772 switch (server_version) {
1774 if (!SSL_IS_TLS13(s)) {
1775 if (version_cmp(s, client_version, s->version) < 0)
1776 return SSL_R_WRONG_SSL_VERSION;
1777 *dgrd = DOWNGRADE_NONE;
1779 * If this SSL handle is not from a version flexible method we don't
1780 * (and never did) check min/max FIPS or Suite B constraints. Hope
1781 * that's OK. It is up to the caller to not choose fixed protocol
1782 * versions they don't want. If not, then easy to fix, just return
1783 * ssl_method_error(s, s->method)
1788 * Fall through if we are TLSv1.3 already (this means we must be after
1789 * a HelloRetryRequest
1792 case TLS_ANY_VERSION:
1793 table = tls_version_table;
1795 case DTLS_ANY_VERSION:
1796 table = dtls_version_table;
1800 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1802 /* If we did an HRR then supported versions is mandatory */
1803 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1804 return SSL_R_UNSUPPORTED_PROTOCOL;
1806 if (suppversions->present && !SSL_IS_DTLS(s)) {
1807 unsigned int candidate_vers = 0;
1808 unsigned int best_vers = 0;
1809 const SSL_METHOD *best_method = NULL;
1810 PACKET versionslist;
1812 suppversions->parsed = 1;
1814 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1815 /* Trailing or invalid data? */
1816 return SSL_R_LENGTH_MISMATCH;
1820 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1821 * The spec only requires servers to check that it isn't SSLv3:
1822 * "Any endpoint receiving a Hello message with
1823 * ClientHello.legacy_version or ServerHello.legacy_version set to
1824 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1825 * We are slightly stricter and require that it isn't SSLv3 or lower.
1826 * We tolerate TLSv1 and TLSv1.1.
1828 if (client_version <= SSL3_VERSION)
1829 return SSL_R_BAD_LEGACY_VERSION;
1831 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1832 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1834 if (ssl_version_supported(s, candidate_vers, &best_method))
1835 best_vers = candidate_vers;
1837 if (PACKET_remaining(&versionslist) != 0) {
1838 /* Trailing data? */
1839 return SSL_R_LENGTH_MISMATCH;
1842 if (best_vers > 0) {
1843 if (s->hello_retry_request != SSL_HRR_NONE) {
1845 * This is after a HelloRetryRequest so we better check that we
1846 * negotiated TLSv1.3
1848 if (best_vers != TLS1_3_VERSION)
1849 return SSL_R_UNSUPPORTED_PROTOCOL;
1852 check_for_downgrade(s, best_vers, dgrd);
1853 s->version = best_vers;
1854 s->method = best_method;
1857 return SSL_R_UNSUPPORTED_PROTOCOL;
1861 * If the supported versions extension isn't present, then the highest
1862 * version we can negotiate is TLSv1.2
1864 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1865 client_version = TLS1_2_VERSION;
1868 * No supported versions extension, so we just use the version supplied in
1871 for (vent = table; vent->version != 0; ++vent) {
1872 const SSL_METHOD *method;
1874 if (vent->smeth == NULL ||
1875 version_cmp(s, client_version, vent->version) < 0)
1877 method = vent->smeth();
1878 if (ssl_method_error(s, method) == 0) {
1879 check_for_downgrade(s, vent->version, dgrd);
1880 s->version = vent->version;
1886 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1890 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1891 * server HELLO is received to select the final client protocol version and
1892 * the version specific method.
1894 * @s: client SSL handle.
1895 * @version: The proposed version from the server's HELLO.
1896 * @extensions: The extensions received
1898 * Returns 1 on success or 0 on error.
1900 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1902 const version_info *vent;
1903 const version_info *table;
1904 int ret, ver_min, ver_max, real_max, origv;
1907 s->version = version;
1909 /* This will overwrite s->version if the extension is present */
1910 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1911 SSL_EXT_TLS1_2_SERVER_HELLO
1912 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1918 if (s->hello_retry_request != SSL_HRR_NONE
1919 && s->version != TLS1_3_VERSION) {
1921 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1922 SSL_R_WRONG_SSL_VERSION);
1926 switch (s->method->version) {
1928 if (s->version != s->method->version) {
1930 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1931 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1932 SSL_R_WRONG_SSL_VERSION);
1936 * If this SSL handle is not from a version flexible method we don't
1937 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1938 * that's OK. It is up to the caller to not choose fixed protocol
1939 * versions they don't want. If not, then easy to fix, just return
1940 * ssl_method_error(s, s->method)
1943 case TLS_ANY_VERSION:
1944 table = tls_version_table;
1946 case DTLS_ANY_VERSION:
1947 table = dtls_version_table;
1951 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1954 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1955 SSL_F_SSL_CHOOSE_CLIENT_VERSION, ret);
1958 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1959 : s->version < ver_min) {
1961 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1962 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1964 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1965 : s->version > ver_max) {
1967 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1968 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1972 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1975 /* Check for downgrades */
1976 if (s->version == TLS1_2_VERSION && real_max > s->version) {
1977 if (memcmp(tls12downgrade,
1978 s->s3.server_random + SSL3_RANDOM_SIZE
1979 - sizeof(tls12downgrade),
1980 sizeof(tls12downgrade)) == 0) {
1982 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1983 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1984 SSL_R_INAPPROPRIATE_FALLBACK);
1987 } else if (!SSL_IS_DTLS(s)
1988 && s->version < TLS1_2_VERSION
1989 && real_max > s->version) {
1990 if (memcmp(tls11downgrade,
1991 s->s3.server_random + SSL3_RANDOM_SIZE
1992 - sizeof(tls11downgrade),
1993 sizeof(tls11downgrade)) == 0) {
1995 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1996 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1997 SSL_R_INAPPROPRIATE_FALLBACK);
2002 for (vent = table; vent->version != 0; ++vent) {
2003 if (vent->cmeth == NULL || s->version != vent->version)
2006 s->method = vent->cmeth();
2011 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2012 SSL_R_UNSUPPORTED_PROTOCOL);
2017 * ssl_get_min_max_version - get minimum and maximum protocol version
2018 * @s: The SSL connection
2019 * @min_version: The minimum supported version
2020 * @max_version: The maximum supported version
2021 * @real_max: The highest version below the lowest compile time version hole
2022 * where that hole lies above at least one run-time enabled
2025 * Work out what version we should be using for the initial ClientHello if the
2026 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2027 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2028 * constraints and any floor imposed by the security level here,
2029 * so we don't advertise the wrong protocol version to only reject the outcome later.
2031 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2032 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2033 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2035 * Returns 0 on success or an SSL error reason number on failure. On failure
2036 * min_version and max_version will also be set to 0.
2038 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2041 int version, tmp_real_max;
2043 const SSL_METHOD *single = NULL;
2044 const SSL_METHOD *method;
2045 const version_info *table;
2046 const version_info *vent;
2048 switch (s->method->version) {
2051 * If this SSL handle is not from a version flexible method we don't
2052 * (and never did) check min/max FIPS or Suite B constraints. Hope
2053 * that's OK. It is up to the caller to not choose fixed protocol
2054 * versions they don't want. If not, then easy to fix, just return
2055 * ssl_method_error(s, s->method)
2057 *min_version = *max_version = s->version;
2059 * Providing a real_max only makes sense where we're using a version
2062 if (!ossl_assert(real_max == NULL))
2063 return ERR_R_INTERNAL_ERROR;
2065 case TLS_ANY_VERSION:
2066 table = tls_version_table;
2068 case DTLS_ANY_VERSION:
2069 table = dtls_version_table;
2074 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2075 * below X enabled. This is required in order to maintain the "version
2076 * capability" vector contiguous. Any versions with a NULL client method
2077 * (protocol version client is disabled at compile-time) is also a "hole".
2079 * Our initial state is hole == 1, version == 0. That is, versions above
2080 * the first version in the method table are disabled (a "hole" above
2081 * the valid protocol entries) and we don't have a selected version yet.
2083 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2084 * the selected version, and the method becomes a candidate "single"
2085 * method. We're no longer in a hole, so "hole" becomes 0.
2087 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2088 * as we support a contiguous range of at least two methods. If we hit
2089 * a disabled method, then hole becomes true again, but nothing else
2090 * changes yet, because all the remaining methods may be disabled too.
2091 * If we again hit an enabled method after the new hole, it becomes
2092 * selected, as we start from scratch.
2094 *min_version = version = 0;
2096 if (real_max != NULL)
2099 for (vent = table; vent->version != 0; ++vent) {
2101 * A table entry with a NULL client method is still a hole in the
2102 * "version capability" vector.
2104 if (vent->cmeth == NULL) {
2109 method = vent->cmeth();
2111 if (hole == 1 && tmp_real_max == 0)
2112 tmp_real_max = vent->version;
2114 if (ssl_method_error(s, method) != 0) {
2118 *min_version = method->version;
2120 if (real_max != NULL && tmp_real_max != 0)
2121 *real_max = tmp_real_max;
2122 version = (single = method)->version;
2123 *min_version = version;
2128 *max_version = version;
2130 /* Fail if everything is disabled */
2132 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2138 * ssl_set_client_hello_version - Work out what version we should be using for
2139 * the initial ClientHello.legacy_version field.
2141 * @s: client SSL handle.
2143 * Returns 0 on success or an SSL error reason number on failure.
2145 int ssl_set_client_hello_version(SSL *s)
2147 int ver_min, ver_max, ret;
2150 * In a renegotiation we always send the same client_version that we sent
2151 * last time, regardless of which version we eventually negotiated.
2153 if (!SSL_IS_FIRST_HANDSHAKE(s))
2156 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2161 s->version = ver_max;
2163 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2164 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2165 ver_max = TLS1_2_VERSION;
2167 s->client_version = ver_max;
2172 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2173 * and |checkallow| is 1 then additionally check if the group is allowed to be
2174 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2175 * 1) or 0 otherwise.
2177 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2178 size_t num_groups, int checkallow)
2182 if (groups == NULL || num_groups == 0)
2185 for (i = 0; i < num_groups; i++) {
2186 uint16_t group = groups[i];
2188 if (group_id == group
2190 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2198 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2199 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2200 size_t hashlen, const unsigned char *hrr,
2203 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2204 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2206 memset(msghdr, 0, sizeof(msghdr));
2208 if (hashval == NULL) {
2209 hashval = hashvaltmp;
2211 /* Get the hash of the initial ClientHello */
2212 if (!ssl3_digest_cached_records(s, 0)
2213 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2215 /* SSLfatal() already called */
2220 /* Reinitialise the transcript hash */
2221 if (!ssl3_init_finished_mac(s)) {
2222 /* SSLfatal() already called */
2226 /* Inject the synthetic message_hash message */
2227 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2228 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2229 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2230 || !ssl3_finish_mac(s, hashval, hashlen)) {
2231 /* SSLfatal() already called */
2236 * Now re-inject the HRR and current message if appropriate (we just deleted
2237 * it when we reinitialised the transcript hash above). Only necessary after
2238 * receiving a ClientHello2 with a cookie.
2241 && (!ssl3_finish_mac(s, hrr, hrrlen)
2242 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2243 s->s3.tmp.message_size
2244 + SSL3_HM_HEADER_LENGTH))) {
2245 /* SSLfatal() already called */
2252 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2254 return X509_NAME_cmp(*a, *b);
2257 int parse_ca_names(SSL *s, PACKET *pkt)
2259 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2260 X509_NAME *xn = NULL;
2263 if (ca_sk == NULL) {
2264 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2265 ERR_R_MALLOC_FAILURE);
2268 /* get the CA RDNs */
2269 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2270 SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2271 SSL_R_LENGTH_MISMATCH);
2275 while (PACKET_remaining(&cadns)) {
2276 const unsigned char *namestart, *namebytes;
2277 unsigned int name_len;
2279 if (!PACKET_get_net_2(&cadns, &name_len)
2280 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2281 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2282 SSL_R_LENGTH_MISMATCH);
2286 namestart = namebytes;
2287 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2288 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2292 if (namebytes != (namestart + name_len)) {
2293 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2294 SSL_R_CA_DN_LENGTH_MISMATCH);
2298 if (!sk_X509_NAME_push(ca_sk, xn)) {
2299 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2300 ERR_R_MALLOC_FAILURE);
2306 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2307 s->s3.tmp.peer_ca_names = ca_sk;
2312 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2317 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2319 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2322 ca_sk = SSL_get_client_CA_list(s);
2323 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2328 ca_sk = SSL_get0_CA_list(s);
2333 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2335 /* Start sub-packet for client CA list */
2336 if (!WPACKET_start_sub_packet_u16(pkt)) {
2337 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2338 ERR_R_INTERNAL_ERROR);
2342 if (ca_sk != NULL) {
2345 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2346 unsigned char *namebytes;
2347 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2351 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2352 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2354 || i2d_X509_NAME(name, &namebytes) != namelen) {
2355 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2356 ERR_R_INTERNAL_ERROR);
2362 if (!WPACKET_close(pkt)) {
2363 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2364 ERR_R_INTERNAL_ERROR);
2371 /* Create a buffer containing data to be signed for server key exchange */
2372 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2373 const void *param, size_t paramlen)
2375 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2376 unsigned char *tbs = OPENSSL_malloc(tbslen);
2379 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2380 ERR_R_MALLOC_FAILURE);
2383 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2384 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2386 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2393 * Saves the current handshake digest for Post-Handshake Auth,
2394 * Done after ClientFinished is processed, done exactly once
2396 int tls13_save_handshake_digest_for_pha(SSL *s)
2398 if (s->pha_dgst == NULL) {
2399 if (!ssl3_digest_cached_records(s, 1))
2400 /* SSLfatal() already called */
2403 s->pha_dgst = EVP_MD_CTX_new();
2404 if (s->pha_dgst == NULL) {
2405 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2406 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2407 ERR_R_INTERNAL_ERROR);
2410 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2411 s->s3.handshake_dgst)) {
2412 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2413 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2414 ERR_R_INTERNAL_ERROR);
2422 * Restores the Post-Handshake Auth handshake digest
2423 * Done just before sending/processing the Cert Request
2425 int tls13_restore_handshake_digest_for_pha(SSL *s)
2427 if (s->pha_dgst == NULL) {
2428 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2429 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2430 ERR_R_INTERNAL_ERROR);
2433 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2435 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2436 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2437 ERR_R_INTERNAL_ERROR);