2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include "internal/evp.h"
18 #include <openssl/buffer.h>
19 #include <openssl/objects.h>
20 #include <openssl/evp.h>
21 #include <openssl/x509.h>
22 #include <openssl/trace.h>
25 * Map error codes to TLS/SSL alart types.
27 typedef struct x509err2alert_st {
32 /* Fixed value used in the ServerHello random field to identify an HRR */
33 const unsigned char hrrrandom[] = {
34 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
35 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
36 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
40 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
41 * SSL3_RT_CHANGE_CIPHER_SPEC)
43 int ssl3_do_write(SSL *s, int type)
48 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
49 s->init_num, &written);
52 if (type == SSL3_RT_HANDSHAKE)
54 * should not be done for 'Hello Request's, but in that case we'll
55 * ignore the result anyway
56 * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
58 if (!SSL_IS_TLS13(s) || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
59 && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
60 && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
61 if (!ssl3_finish_mac(s,
62 (unsigned char *)&s->init_buf->data[s->init_off],
65 if (written == s->init_num) {
67 s->msg_callback(1, s->version, type, s->init_buf->data,
68 (size_t)(s->init_off + s->init_num), s,
72 s->init_off += written;
73 s->init_num -= written;
77 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
81 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
82 || !WPACKET_get_length(pkt, &msglen)
85 s->init_num = (int)msglen;
91 int tls_setup_handshake(SSL *s)
93 if (!ssl3_init_finished_mac(s)) {
94 /* SSLfatal() already called */
98 /* Reset any extension flags */
99 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
102 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
103 int i, ver_min, ver_max, ok = 0;
106 * Sanity check that the maximum version we accept has ciphers
107 * enabled. For clients we do this check during construction of the
110 if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
111 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_SETUP_HANDSHAKE,
112 ERR_R_INTERNAL_ERROR);
115 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
116 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
118 if (SSL_IS_DTLS(s)) {
119 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
120 DTLS_VERSION_LE(ver_max, c->max_dtls))
122 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
129 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_SETUP_HANDSHAKE,
130 SSL_R_NO_CIPHERS_AVAILABLE);
131 ERR_add_error_data(1, "No ciphers enabled for max supported "
135 if (SSL_IS_FIRST_HANDSHAKE(s)) {
136 /* N.B. s->session_ctx == s->ctx here */
137 tsan_counter(&s->session_ctx->stats.sess_accept);
139 /* N.B. s->ctx may not equal s->session_ctx */
140 tsan_counter(&s->ctx->stats.sess_accept_renegotiate);
142 s->s3.tmp.cert_request = 0;
145 if (SSL_IS_FIRST_HANDSHAKE(s))
146 tsan_counter(&s->session_ctx->stats.sess_connect);
148 tsan_counter(&s->session_ctx->stats.sess_connect_renegotiate);
150 /* mark client_random uninitialized */
151 memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
154 s->s3.tmp.cert_req = 0;
157 s->statem.use_timer = 1;
164 * Size of the to-be-signed TLS13 data, without the hash size itself:
165 * 64 bytes of value 32, 33 context bytes, 1 byte separator
167 #define TLS13_TBS_START_SIZE 64
168 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
170 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
171 void **hdata, size_t *hdatalen)
173 #ifdef CHARSET_EBCDIC
174 static const char servercontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
175 0x33, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65,
176 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
177 0x69, 0x66, 0x79, 0x00 };
178 static const char clientcontext[] = { 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e,
179 0x33, 0x2c, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x65,
180 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x56, 0x65, 0x72,
181 0x69, 0x66, 0x79, 0x00 };
183 static const char servercontext[] = "TLS 1.3, server CertificateVerify";
184 static const char clientcontext[] = "TLS 1.3, client CertificateVerify";
186 if (SSL_IS_TLS13(s)) {
189 /* Set the first 64 bytes of to-be-signed data to octet 32 */
190 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
191 /* This copies the 33 bytes of context plus the 0 separator byte */
192 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
193 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
194 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
196 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
199 * If we're currently reading then we need to use the saved handshake
200 * hash value. We can't use the current handshake hash state because
201 * that includes the CertVerify itself.
203 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
204 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
205 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
206 s->cert_verify_hash_len);
207 hashlen = s->cert_verify_hash_len;
208 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
209 EVP_MAX_MD_SIZE, &hashlen)) {
210 /* SSLfatal() already called */
215 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
220 retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
222 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
223 ERR_R_INTERNAL_ERROR);
232 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
234 EVP_PKEY *pkey = NULL;
235 const EVP_MD *md = NULL;
236 EVP_MD_CTX *mctx = NULL;
237 EVP_PKEY_CTX *pctx = NULL;
238 size_t hdatalen = 0, siglen = 0;
240 unsigned char *sig = NULL;
241 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
242 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
244 if (lu == NULL || s->s3.tmp.cert == NULL) {
245 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
246 ERR_R_INTERNAL_ERROR);
249 pkey = s->s3.tmp.cert->privatekey;
251 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
252 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
253 ERR_R_INTERNAL_ERROR);
257 mctx = EVP_MD_CTX_new();
259 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
260 ERR_R_MALLOC_FAILURE);
264 /* Get the data to be signed */
265 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
266 /* SSLfatal() already called */
270 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
271 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
272 ERR_R_INTERNAL_ERROR);
276 if (EVP_DigestSignInit_ex(mctx, &pctx,
277 md == NULL ? NULL : EVP_MD_name(md),
278 s->ctx->propq, pkey, s->ctx->libctx) <= 0) {
279 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
284 if (lu->sig == EVP_PKEY_RSA_PSS) {
285 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
286 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
287 RSA_PSS_SALTLEN_DIGEST) <= 0) {
288 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
293 if (s->version == SSL3_VERSION) {
295 * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
296 * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
298 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
300 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
301 * with a call to ssl3_digest_master_key_set_params()
303 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
304 (int)s->session->master_key_length,
305 s->session->master_key) <= 0
306 || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
308 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
312 sig = OPENSSL_malloc(siglen);
314 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
315 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
321 * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
322 * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
324 if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
325 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
329 sig = OPENSSL_malloc(siglen);
331 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
332 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
338 #ifndef OPENSSL_NO_GOST
340 int pktype = lu->sig;
342 if (pktype == NID_id_GostR3410_2001
343 || pktype == NID_id_GostR3410_2012_256
344 || pktype == NID_id_GostR3410_2012_512)
345 BUF_reverse(sig, NULL, siglen);
349 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
350 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
351 ERR_R_INTERNAL_ERROR);
355 /* Digest cached records and discard handshake buffer */
356 if (!ssl3_digest_cached_records(s, 0)) {
357 /* SSLfatal() already called */
362 EVP_MD_CTX_free(mctx);
366 EVP_MD_CTX_free(mctx);
370 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
372 EVP_PKEY *pkey = NULL;
373 const unsigned char *data;
374 #ifndef OPENSSL_NO_GOST
375 unsigned char *gost_data = NULL;
377 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
381 const EVP_MD *md = NULL;
384 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
385 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
386 EVP_PKEY_CTX *pctx = NULL;
389 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
390 ERR_R_MALLOC_FAILURE);
394 peer = s->session->peer;
395 pkey = X509_get0_pubkey(peer);
397 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
398 ERR_R_INTERNAL_ERROR);
402 if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
403 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
404 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
408 if (SSL_USE_SIGALGS(s)) {
411 if (!PACKET_get_net_2(pkt, &sigalg)) {
412 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
416 if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
417 /* SSLfatal() already called */
420 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
421 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
422 ERR_R_INTERNAL_ERROR);
426 if (!tls1_lookup_md(s->ctx, s->s3.tmp.peer_sigalg, &md)) {
427 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
428 ERR_R_INTERNAL_ERROR);
432 if (SSL_USE_SIGALGS(s))
433 OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
434 md == NULL ? "n/a" : EVP_MD_name(md));
436 /* Check for broken implementations of GOST ciphersuites */
438 * If key is GOST and len is exactly 64 or 128, it is signature without
439 * length field (CryptoPro implementations at least till TLS 1.2)
441 #ifndef OPENSSL_NO_GOST
442 if (!SSL_USE_SIGALGS(s)
443 && ((PACKET_remaining(pkt) == 64
444 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
445 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
446 || (PACKET_remaining(pkt) == 128
447 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
448 len = PACKET_remaining(pkt);
451 if (!PACKET_get_net_2(pkt, &len)) {
452 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
453 SSL_R_LENGTH_MISMATCH);
457 if (!PACKET_get_bytes(pkt, &data, len)) {
458 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
459 SSL_R_LENGTH_MISMATCH);
463 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
464 /* SSLfatal() already called */
468 OSSL_TRACE1(TLS, "Using client verify alg %s\n",
469 md == NULL ? "n/a" : EVP_MD_name(md));
471 if (EVP_DigestVerifyInit_ex(mctx, &pctx,
472 md == NULL ? NULL : EVP_MD_name(md),
473 s->ctx->propq, pkey, s->ctx->libctx) <= 0) {
474 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
478 #ifndef OPENSSL_NO_GOST
480 int pktype = EVP_PKEY_id(pkey);
481 if (pktype == NID_id_GostR3410_2001
482 || pktype == NID_id_GostR3410_2012_256
483 || pktype == NID_id_GostR3410_2012_512) {
484 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
485 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
486 SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
489 BUF_reverse(gost_data, data, len);
495 if (SSL_USE_PSS(s)) {
496 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
497 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
498 RSA_PSS_SALTLEN_DIGEST) <= 0) {
499 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
504 if (s->version == SSL3_VERSION) {
506 * TODO(3.0) Replace this when EVP_MD_CTX_ctrl() is deprecated
507 * with a call to ssl3_digest_master_key_set_params()
509 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
510 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
511 (int)s->session->master_key_length,
512 s->session->master_key) <= 0) {
513 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
517 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
518 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
519 SSL_R_BAD_SIGNATURE);
523 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
525 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
526 SSL_R_BAD_SIGNATURE);
532 * In TLSv1.3 on the client side we make sure we prepare the client
533 * certificate after the CertVerify instead of when we get the
534 * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
535 * comes *before* the Certificate message. In TLSv1.2 it comes after. We
536 * want to make sure that SSL_get_peer_certificate() will return the actual
537 * server certificate from the client_cert_cb callback.
539 if (!s->server && SSL_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
540 ret = MSG_PROCESS_CONTINUE_PROCESSING;
542 ret = MSG_PROCESS_CONTINUE_READING;
544 BIO_free(s->s3.handshake_buffer);
545 s->s3.handshake_buffer = NULL;
546 EVP_MD_CTX_free(mctx);
547 #ifndef OPENSSL_NO_GOST
548 OPENSSL_free(gost_data);
553 int tls_construct_finished(SSL *s, WPACKET *pkt)
555 size_t finish_md_len;
559 /* This is a real handshake so make sure we clean it up at the end */
560 if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
561 s->statem.cleanuphand = 1;
564 * We only change the keys if we didn't already do this when we sent the
569 && s->s3.tmp.cert_req == 0
570 && (!s->method->ssl3_enc->change_cipher_state(s,
571 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
572 /* SSLfatal() already called */
577 sender = s->method->ssl3_enc->server_finished_label;
578 slen = s->method->ssl3_enc->server_finished_label_len;
580 sender = s->method->ssl3_enc->client_finished_label;
581 slen = s->method->ssl3_enc->client_finished_label_len;
584 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
586 s->s3.tmp.finish_md);
587 if (finish_md_len == 0) {
588 /* SSLfatal() already called */
592 s->s3.tmp.finish_md_len = finish_md_len;
594 if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
595 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
596 ERR_R_INTERNAL_ERROR);
601 * Log the master secret, if logging is enabled. We don't log it for
602 * TLSv1.3: there's a different key schedule for that.
604 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
605 s->session->master_key,
606 s->session->master_key_length)) {
607 /* SSLfatal() already called */
612 * Copy the finished so we can use it for renegotiation checks
614 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
615 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
616 ERR_R_INTERNAL_ERROR);
620 memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
622 s->s3.previous_client_finished_len = finish_md_len;
624 memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
626 s->s3.previous_server_finished_len = finish_md_len;
632 int tls_construct_key_update(SSL *s, WPACKET *pkt)
634 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
635 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
636 ERR_R_INTERNAL_ERROR);
640 s->key_update = SSL_KEY_UPDATE_NONE;
644 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
646 unsigned int updatetype;
649 * A KeyUpdate message signals a key change so the end of the message must
650 * be on a record boundary.
652 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
653 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
654 SSL_R_NOT_ON_RECORD_BOUNDARY);
655 return MSG_PROCESS_ERROR;
658 if (!PACKET_get_1(pkt, &updatetype)
659 || PACKET_remaining(pkt) != 0) {
660 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
661 SSL_R_BAD_KEY_UPDATE);
662 return MSG_PROCESS_ERROR;
666 * There are only two defined key update types. Fail if we get a value we
669 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
670 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
671 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
672 SSL_R_BAD_KEY_UPDATE);
673 return MSG_PROCESS_ERROR;
677 * If we get a request for us to update our sending keys too then, we need
678 * to additionally send a KeyUpdate message. However that message should
679 * not also request an update (otherwise we get into an infinite loop).
681 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
682 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
684 if (!tls13_update_key(s, 0)) {
685 /* SSLfatal() already called */
686 return MSG_PROCESS_ERROR;
689 return MSG_PROCESS_FINISHED_READING;
693 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
696 int ssl3_take_mac(SSL *s)
702 sender = s->method->ssl3_enc->server_finished_label;
703 slen = s->method->ssl3_enc->server_finished_label_len;
705 sender = s->method->ssl3_enc->client_finished_label;
706 slen = s->method->ssl3_enc->client_finished_label_len;
709 s->s3.tmp.peer_finish_md_len =
710 s->method->ssl3_enc->final_finish_mac(s, sender, slen,
711 s->s3.tmp.peer_finish_md);
713 if (s->s3.tmp.peer_finish_md_len == 0) {
714 /* SSLfatal() already called */
721 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
725 remain = PACKET_remaining(pkt);
727 * 'Change Cipher Spec' is just a single byte, which should already have
728 * been consumed by ssl_get_message() so there should be no bytes left,
729 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
731 if (SSL_IS_DTLS(s)) {
732 if ((s->version == DTLS1_BAD_VER
733 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
734 || (s->version != DTLS1_BAD_VER
735 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
736 SSLfatal(s, SSL_AD_DECODE_ERROR,
737 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
738 SSL_R_BAD_CHANGE_CIPHER_SPEC);
739 return MSG_PROCESS_ERROR;
743 SSLfatal(s, SSL_AD_DECODE_ERROR,
744 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
745 SSL_R_BAD_CHANGE_CIPHER_SPEC);
746 return MSG_PROCESS_ERROR;
750 /* Check we have a cipher to change to */
751 if (s->s3.tmp.new_cipher == NULL) {
752 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
753 SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
754 return MSG_PROCESS_ERROR;
757 s->s3.change_cipher_spec = 1;
758 if (!ssl3_do_change_cipher_spec(s)) {
759 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
760 ERR_R_INTERNAL_ERROR);
761 return MSG_PROCESS_ERROR;
764 if (SSL_IS_DTLS(s)) {
765 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
767 if (s->version == DTLS1_BAD_VER)
768 s->d1->handshake_read_seq++;
770 #ifndef OPENSSL_NO_SCTP
772 * Remember that a CCS has been received, so that an old key of
773 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
776 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
780 return MSG_PROCESS_CONTINUE_READING;
783 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
788 /* This is a real handshake so make sure we clean it up at the end */
791 * To get this far we must have read encrypted data from the client. We
792 * no longer tolerate unencrypted alerts. This value is ignored if less
795 s->statem.enc_read_state = ENC_READ_STATE_VALID;
796 if (s->post_handshake_auth != SSL_PHA_REQUESTED)
797 s->statem.cleanuphand = 1;
798 if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
799 /* SSLfatal() already called */
800 return MSG_PROCESS_ERROR;
805 * In TLSv1.3 a Finished message signals a key change so the end of the
806 * message must be on a record boundary.
808 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
809 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
810 SSL_R_NOT_ON_RECORD_BOUNDARY);
811 return MSG_PROCESS_ERROR;
814 /* If this occurs, we have missed a message */
815 if (!SSL_IS_TLS13(s) && !s->s3.change_cipher_spec) {
816 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
817 SSL_R_GOT_A_FIN_BEFORE_A_CCS);
818 return MSG_PROCESS_ERROR;
820 s->s3.change_cipher_spec = 0;
822 md_len = s->s3.tmp.peer_finish_md_len;
824 if (md_len != PACKET_remaining(pkt)) {
825 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
826 SSL_R_BAD_DIGEST_LENGTH);
827 return MSG_PROCESS_ERROR;
830 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
832 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
833 SSL_R_DIGEST_CHECK_FAILED);
834 return MSG_PROCESS_ERROR;
838 * Copy the finished so we can use it for renegotiation checks
840 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
841 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
842 ERR_R_INTERNAL_ERROR);
843 return MSG_PROCESS_ERROR;
846 memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
848 s->s3.previous_client_finished_len = md_len;
850 memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
852 s->s3.previous_server_finished_len = md_len;
856 * In TLS1.3 we also have to change cipher state and do any final processing
857 * of the initial server flight (if we are a client)
859 if (SSL_IS_TLS13(s)) {
861 if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
862 !s->method->ssl3_enc->change_cipher_state(s,
863 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
864 /* SSLfatal() already called */
865 return MSG_PROCESS_ERROR;
868 /* TLS 1.3 gets the secret size from the handshake md */
870 if (!s->method->ssl3_enc->generate_master_secret(s,
871 s->master_secret, s->handshake_secret, 0,
873 /* SSLfatal() already called */
874 return MSG_PROCESS_ERROR;
876 if (!s->method->ssl3_enc->change_cipher_state(s,
877 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
878 /* SSLfatal() already called */
879 return MSG_PROCESS_ERROR;
881 if (!tls_process_initial_server_flight(s)) {
882 /* SSLfatal() already called */
883 return MSG_PROCESS_ERROR;
888 return MSG_PROCESS_FINISHED_READING;
891 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
893 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
894 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
895 SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
902 /* Add a certificate to the WPACKET */
903 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
906 unsigned char *outbytes;
908 len = i2d_X509(x, NULL);
910 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
914 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
915 || i2d_X509(x, &outbytes) != len) {
916 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
917 ERR_R_INTERNAL_ERROR);
922 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
924 /* SSLfatal() already called */
931 /* Add certificate chain to provided WPACKET */
932 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
936 STACK_OF(X509) *extra_certs;
937 STACK_OF(X509) *chain = NULL;
938 X509_STORE *chain_store;
940 if (cpk == NULL || cpk->x509 == NULL)
946 * If we have a certificate specific chain use it, else use parent ctx.
948 if (cpk->chain != NULL)
949 extra_certs = cpk->chain;
951 extra_certs = s->ctx->extra_certs;
953 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
955 else if (s->cert->chain_store)
956 chain_store = s->cert->chain_store;
958 chain_store = s->ctx->cert_store;
960 if (chain_store != NULL) {
961 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_with_libctx(s->ctx->libctx,
964 if (xs_ctx == NULL) {
965 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
966 ERR_R_MALLOC_FAILURE);
969 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
970 X509_STORE_CTX_free(xs_ctx);
971 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
976 * It is valid for the chain not to be complete (because normally we
977 * don't include the root cert in the chain). Therefore we deliberately
978 * ignore the error return from this call. We're not actually verifying
979 * the cert - we're just building as much of the chain as we can
981 (void)X509_verify_cert(xs_ctx);
982 /* Don't leave errors in the queue */
984 chain = X509_STORE_CTX_get0_chain(xs_ctx);
985 i = ssl_security_cert_chain(s, chain, NULL, 0);
988 /* Dummy error calls so mkerr generates them */
989 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
990 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
991 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
993 X509_STORE_CTX_free(xs_ctx);
994 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
997 chain_count = sk_X509_num(chain);
998 for (i = 0; i < chain_count; i++) {
999 x = sk_X509_value(chain, i);
1001 if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
1002 /* SSLfatal() already called */
1003 X509_STORE_CTX_free(xs_ctx);
1007 X509_STORE_CTX_free(xs_ctx);
1009 i = ssl_security_cert_chain(s, extra_certs, x, 0);
1011 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
1014 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
1015 /* SSLfatal() already called */
1018 for (i = 0; i < sk_X509_num(extra_certs); i++) {
1019 x = sk_X509_value(extra_certs, i);
1020 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
1021 /* SSLfatal() already called */
1029 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
1031 if (!WPACKET_start_sub_packet_u24(pkt)) {
1032 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1033 ERR_R_INTERNAL_ERROR);
1037 if (!ssl_add_cert_chain(s, pkt, cpk))
1040 if (!WPACKET_close(pkt)) {
1041 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
1042 ERR_R_INTERNAL_ERROR);
1050 * Tidy up after the end of a handshake. In the case of SCTP this may result
1051 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1054 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1056 void (*cb) (const SSL *ssl, int type, int val) = NULL;
1057 int cleanuphand = s->statem.cleanuphand;
1061 #ifndef OPENSSL_NO_SCTP
1063 * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1064 * messages that require it. Therefore, DTLS procedures for retransmissions
1066 * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1068 || BIO_dgram_is_sctp(SSL_get_wbio(s))
1072 * We don't do this in DTLS over UDP because we may still need the init_buf
1073 * in case there are any unexpected retransmits
1075 BUF_MEM_free(s->init_buf);
1079 if (!ssl_free_wbio_buffer(s)) {
1080 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_FINISH_HANDSHAKE,
1081 ERR_R_INTERNAL_ERROR);
1087 if (SSL_IS_TLS13(s) && !s->server
1088 && s->post_handshake_auth == SSL_PHA_REQUESTED)
1089 s->post_handshake_auth = SSL_PHA_EXT_SENT;
1092 * Only set if there was a Finished message and this isn't after a TLSv1.3
1093 * post handshake exchange
1096 /* skipped if we just sent a HelloRequest */
1099 s->statem.cleanuphand = 0;
1100 s->ext.ticket_expected = 0;
1102 ssl3_cleanup_key_block(s);
1106 * In TLSv1.3 we update the cache as part of constructing the
1109 if (!SSL_IS_TLS13(s))
1110 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1112 /* N.B. s->ctx may not equal s->session_ctx */
1113 tsan_counter(&s->ctx->stats.sess_accept_good);
1114 s->handshake_func = ossl_statem_accept;
1116 if (SSL_IS_TLS13(s)) {
1118 * We encourage applications to only use TLSv1.3 tickets once,
1119 * so we remove this one from the cache.
1121 if ((s->session_ctx->session_cache_mode
1122 & SSL_SESS_CACHE_CLIENT) != 0)
1123 SSL_CTX_remove_session(s->session_ctx, s->session);
1126 * In TLSv1.3 we update the cache as part of processing the
1129 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1132 tsan_counter(&s->session_ctx->stats.sess_hit);
1134 s->handshake_func = ossl_statem_connect;
1135 tsan_counter(&s->session_ctx->stats.sess_connect_good);
1138 if (SSL_IS_DTLS(s)) {
1139 /* done with handshaking */
1140 s->d1->handshake_read_seq = 0;
1141 s->d1->handshake_write_seq = 0;
1142 s->d1->next_handshake_write_seq = 0;
1143 dtls1_clear_received_buffer(s);
1147 if (s->info_callback != NULL)
1148 cb = s->info_callback;
1149 else if (s->ctx->info_callback != NULL)
1150 cb = s->ctx->info_callback;
1152 /* The callback may expect us to not be in init at handshake done */
1153 ossl_statem_set_in_init(s, 0);
1158 || SSL_IS_FIRST_HANDSHAKE(s))
1159 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1163 /* If we've got more work to do we go back into init */
1164 ossl_statem_set_in_init(s, 1);
1165 return WORK_FINISHED_CONTINUE;
1168 return WORK_FINISHED_STOP;
1171 int tls_get_message_header(SSL *s, int *mt)
1173 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1174 int skip_message, i, recvd_type;
1176 size_t l, readbytes;
1178 p = (unsigned char *)s->init_buf->data;
1181 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1182 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1184 SSL3_HM_HEADER_LENGTH - s->init_num,
1187 s->rwstate = SSL_READING;
1190 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1192 * A ChangeCipherSpec must be a single byte and may not occur
1193 * in the middle of a handshake message.
1195 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1196 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1197 SSL_F_TLS_GET_MESSAGE_HEADER,
1198 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1201 if (s->statem.hand_state == TLS_ST_BEFORE
1202 && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1204 * We are stateless and we received a CCS. Probably this is
1205 * from a client between the first and second ClientHellos.
1206 * We should ignore this, but return an error because we do
1207 * not return success until we see the second ClientHello
1208 * with a valid cookie.
1212 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1213 s->init_num = readbytes - 1;
1214 s->init_msg = s->init_buf->data;
1215 s->s3.tmp.message_size = readbytes;
1217 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1218 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1219 SSL_F_TLS_GET_MESSAGE_HEADER,
1220 SSL_R_CCS_RECEIVED_EARLY);
1223 s->init_num += readbytes;
1228 if (s->statem.hand_state != TLS_ST_OK
1229 && p[0] == SSL3_MT_HELLO_REQUEST)
1231 * The server may always send 'Hello Request' messages --
1232 * we are doing a handshake anyway now, so ignore them if
1233 * their format is correct. Does not count for 'Finished'
1236 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1240 if (s->msg_callback)
1241 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1242 p, SSL3_HM_HEADER_LENGTH, s,
1243 s->msg_callback_arg);
1245 } while (skip_message);
1246 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1249 s->s3.tmp.message_type = *(p++);
1251 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1253 * Only happens with SSLv3+ in an SSLv2 backward compatible
1256 * Total message size is the remaining record bytes to read
1257 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1259 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1260 + SSL3_HM_HEADER_LENGTH;
1261 s->s3.tmp.message_size = l;
1263 s->init_msg = s->init_buf->data;
1264 s->init_num = SSL3_HM_HEADER_LENGTH;
1267 /* BUF_MEM_grow takes an 'int' parameter */
1268 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1269 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1270 SSL_R_EXCESSIVE_MESSAGE_SIZE);
1273 s->s3.tmp.message_size = l;
1275 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1282 int tls_get_message_body(SSL *s, size_t *len)
1284 size_t n, readbytes;
1288 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1289 /* We've already read everything in */
1290 *len = (unsigned long)s->init_num;
1295 n = s->s3.tmp.message_size - s->init_num;
1297 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1298 &p[s->init_num], n, 0, &readbytes);
1300 s->rwstate = SSL_READING;
1304 s->init_num += readbytes;
1309 * If receiving Finished, record MAC of prior handshake messages for
1310 * Finished verification.
1312 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1313 /* SSLfatal() already called */
1318 /* Feed this message into MAC computation. */
1319 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1320 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1322 /* SSLfatal() already called */
1326 if (s->msg_callback)
1327 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1328 (size_t)s->init_num, s, s->msg_callback_arg);
1331 * We defer feeding in the HRR until later. We'll do it as part of
1332 * processing the message
1333 * The TLsv1.3 handshake transcript stops at the ClientFinished
1336 #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1337 /* KeyUpdate and NewSessionTicket do not need to be added */
1338 if (!SSL_IS_TLS13(s) || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1339 && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1340 if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1341 || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1342 || memcmp(hrrrandom,
1343 s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1344 SSL3_RANDOM_SIZE) != 0) {
1345 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1346 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1347 /* SSLfatal() already called */
1353 if (s->msg_callback)
1354 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1355 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1356 s->msg_callback_arg);
1363 static const X509ERR2ALERT x509table[] = {
1364 {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1365 {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1366 {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1367 {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1368 {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1369 {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1370 {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1371 {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1372 {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1373 {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1374 {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1375 {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1376 {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1377 {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1378 {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1379 {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1380 {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1381 {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1382 {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1383 {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1384 {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1385 {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1386 {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1387 {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1388 {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1389 {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1390 {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1391 {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1392 {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1393 {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1394 {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1395 {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1396 {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1397 {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1398 {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1399 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1400 {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1401 {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1402 {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1404 /* Last entry; return this if we don't find the value above. */
1405 {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1408 int ssl_x509err2alert(int x509err)
1410 const X509ERR2ALERT *tp;
1412 for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1413 if (tp->x509err == x509err)
1418 int ssl_allow_compression(SSL *s)
1420 if (s->options & SSL_OP_NO_COMPRESSION)
1422 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1425 static int version_cmp(const SSL *s, int a, int b)
1427 int dtls = SSL_IS_DTLS(s);
1432 return a < b ? -1 : 1;
1433 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1438 const SSL_METHOD *(*cmeth) (void);
1439 const SSL_METHOD *(*smeth) (void);
1442 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1443 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1446 /* Must be in order high to low */
1447 static const version_info tls_version_table[] = {
1448 #ifndef OPENSSL_NO_TLS1_3
1449 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1451 {TLS1_3_VERSION, NULL, NULL},
1453 #ifndef OPENSSL_NO_TLS1_2
1454 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1456 {TLS1_2_VERSION, NULL, NULL},
1458 #ifndef OPENSSL_NO_TLS1_1
1459 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1461 {TLS1_1_VERSION, NULL, NULL},
1463 #ifndef OPENSSL_NO_TLS1
1464 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1466 {TLS1_VERSION, NULL, NULL},
1468 #ifndef OPENSSL_NO_SSL3
1469 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1471 {SSL3_VERSION, NULL, NULL},
1476 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1477 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1480 /* Must be in order high to low */
1481 static const version_info dtls_version_table[] = {
1482 #ifndef OPENSSL_NO_DTLS1_2
1483 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1485 {DTLS1_2_VERSION, NULL, NULL},
1487 #ifndef OPENSSL_NO_DTLS1
1488 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1489 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1491 {DTLS1_VERSION, NULL, NULL},
1492 {DTLS1_BAD_VER, NULL, NULL},
1498 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1500 * @s: The SSL handle for the candidate method
1501 * @method: the intended method.
1503 * Returns 0 on success, or an SSL error reason on failure.
1505 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1507 int version = method->version;
1509 if ((s->min_proto_version != 0 &&
1510 version_cmp(s, version, s->min_proto_version) < 0) ||
1511 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1512 return SSL_R_VERSION_TOO_LOW;
1514 if (s->max_proto_version != 0 &&
1515 version_cmp(s, version, s->max_proto_version) > 0)
1516 return SSL_R_VERSION_TOO_HIGH;
1518 if ((s->options & method->mask) != 0)
1519 return SSL_R_UNSUPPORTED_PROTOCOL;
1520 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1521 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1527 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1528 * certificate type, or has PSK or a certificate callback configured. Otherwise
1531 static int is_tls13_capable(const SSL *s)
1534 #ifndef OPENSSL_NO_EC
1538 #ifndef OPENSSL_NO_PSK
1539 if (s->psk_server_callback != NULL)
1543 if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1546 for (i = 0; i < SSL_PKEY_NUM; i++) {
1547 /* Skip over certs disallowed for TLSv1.3 */
1549 case SSL_PKEY_DSA_SIGN:
1550 case SSL_PKEY_GOST01:
1551 case SSL_PKEY_GOST12_256:
1552 case SSL_PKEY_GOST12_512:
1557 if (!ssl_has_cert(s, i))
1559 #ifndef OPENSSL_NO_EC
1560 if (i != SSL_PKEY_ECC)
1563 * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1564 * more restrictive so check that our sig algs are consistent with this
1565 * EC cert. See section 4.2.3 of RFC8446.
1567 curve = evp_pkey_get_EC_KEY_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
1569 if (tls_check_sigalg_curve(s, curve))
1580 * ssl_version_supported - Check that the specified `version` is supported by
1583 * @s: The SSL handle for the candidate method
1584 * @version: Protocol version to test against
1586 * Returns 1 when supported, otherwise 0
1588 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1590 const version_info *vent;
1591 const version_info *table;
1593 switch (s->method->version) {
1595 /* Version should match method version for non-ANY method */
1596 return version_cmp(s, version, s->version) == 0;
1597 case TLS_ANY_VERSION:
1598 table = tls_version_table;
1600 case DTLS_ANY_VERSION:
1601 table = dtls_version_table;
1606 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1608 if (vent->cmeth != NULL
1609 && version_cmp(s, version, vent->version) == 0
1610 && ssl_method_error(s, vent->cmeth()) == 0
1612 || version != TLS1_3_VERSION
1613 || is_tls13_capable(s))) {
1615 *meth = vent->cmeth();
1623 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1624 * fallback indication from a client check whether we're using the highest
1625 * supported protocol version.
1627 * @s server SSL handle.
1629 * Returns 1 when using the highest enabled version, 0 otherwise.
1631 int ssl_check_version_downgrade(SSL *s)
1633 const version_info *vent;
1634 const version_info *table;
1637 * Check that the current protocol is the highest enabled version
1638 * (according to s->ctx->method, as version negotiation may have changed
1641 if (s->version == s->ctx->method->version)
1645 * Apparently we're using a version-flexible SSL_METHOD (not at its
1646 * highest protocol version).
1648 if (s->ctx->method->version == TLS_method()->version)
1649 table = tls_version_table;
1650 else if (s->ctx->method->version == DTLS_method()->version)
1651 table = dtls_version_table;
1653 /* Unexpected state; fail closed. */
1657 for (vent = table; vent->version != 0; ++vent) {
1658 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1659 return s->version == vent->version;
1665 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1666 * protocols, provided the initial (D)TLS method is version-flexible. This
1667 * function sanity-checks the proposed value and makes sure the method is
1668 * version-flexible, then sets the limit if all is well.
1670 * @method_version: The version of the current SSL_METHOD.
1671 * @version: the intended limit.
1672 * @bound: pointer to limit to be updated.
1674 * Returns 1 on success, 0 on failure.
1676 int ssl_set_version_bound(int method_version, int version, int *bound)
1684 * Restrict TLS methods to TLS protocol versions.
1685 * Restrict DTLS methods to DTLS protocol versions.
1686 * Note, DTLS version numbers are decreasing, use comparison macros.
1688 * Note that for both lower-bounds we use explicit versions, not
1689 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1690 * configurations. If the MIN (supported) version ever rises, the user's
1691 * "floor" remains valid even if no longer available. We don't expect the
1692 * MAX ceiling to ever get lower, so making that variable makes sense.
1694 switch (method_version) {
1697 * XXX For fixed version methods, should we always fail and not set any
1698 * bounds, always succeed and not set any bounds, or set the bounds and
1699 * arrange to fail later if they are not met? At present fixed-version
1700 * methods are not subject to controls that disable individual protocol
1705 case TLS_ANY_VERSION:
1706 if (version < SSL3_VERSION || version > TLS_MAX_VERSION_INTERNAL)
1710 case DTLS_ANY_VERSION:
1711 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION_INTERNAL) ||
1712 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1721 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1723 if (vers == TLS1_2_VERSION
1724 && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1725 *dgrd = DOWNGRADE_TO_1_2;
1726 } else if (!SSL_IS_DTLS(s)
1727 && vers < TLS1_2_VERSION
1729 * We need to ensure that a server that disables TLSv1.2
1730 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1731 * complete handshakes with clients that support TLSv1.2 and
1732 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1733 * enabled and TLSv1.2 is not.
1735 && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1736 *dgrd = DOWNGRADE_TO_1_1;
1738 *dgrd = DOWNGRADE_NONE;
1743 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1744 * client HELLO is received to select the final server protocol version and
1745 * the version specific method.
1747 * @s: server SSL handle.
1749 * Returns 0 on success or an SSL error reason number on failure.
1751 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1754 * With version-flexible methods we have an initial state with:
1756 * s->method->version == (D)TLS_ANY_VERSION,
1757 * s->version == (D)TLS_MAX_VERSION_INTERNAL.
1759 * So we detect version-flexible methods via the method version, not the
1762 int server_version = s->method->version;
1763 int client_version = hello->legacy_version;
1764 const version_info *vent;
1765 const version_info *table;
1767 RAW_EXTENSION *suppversions;
1769 s->client_version = client_version;
1771 switch (server_version) {
1773 if (!SSL_IS_TLS13(s)) {
1774 if (version_cmp(s, client_version, s->version) < 0)
1775 return SSL_R_WRONG_SSL_VERSION;
1776 *dgrd = DOWNGRADE_NONE;
1778 * If this SSL handle is not from a version flexible method we don't
1779 * (and never did) check min/max FIPS or Suite B constraints. Hope
1780 * that's OK. It is up to the caller to not choose fixed protocol
1781 * versions they don't want. If not, then easy to fix, just return
1782 * ssl_method_error(s, s->method)
1787 * Fall through if we are TLSv1.3 already (this means we must be after
1788 * a HelloRetryRequest
1791 case TLS_ANY_VERSION:
1792 table = tls_version_table;
1794 case DTLS_ANY_VERSION:
1795 table = dtls_version_table;
1799 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1801 /* If we did an HRR then supported versions is mandatory */
1802 if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1803 return SSL_R_UNSUPPORTED_PROTOCOL;
1805 if (suppversions->present && !SSL_IS_DTLS(s)) {
1806 unsigned int candidate_vers = 0;
1807 unsigned int best_vers = 0;
1808 const SSL_METHOD *best_method = NULL;
1809 PACKET versionslist;
1811 suppversions->parsed = 1;
1813 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1814 /* Trailing or invalid data? */
1815 return SSL_R_LENGTH_MISMATCH;
1819 * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1820 * The spec only requires servers to check that it isn't SSLv3:
1821 * "Any endpoint receiving a Hello message with
1822 * ClientHello.legacy_version or ServerHello.legacy_version set to
1823 * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1824 * We are slightly stricter and require that it isn't SSLv3 or lower.
1825 * We tolerate TLSv1 and TLSv1.1.
1827 if (client_version <= SSL3_VERSION)
1828 return SSL_R_BAD_LEGACY_VERSION;
1830 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1831 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1833 if (ssl_version_supported(s, candidate_vers, &best_method))
1834 best_vers = candidate_vers;
1836 if (PACKET_remaining(&versionslist) != 0) {
1837 /* Trailing data? */
1838 return SSL_R_LENGTH_MISMATCH;
1841 if (best_vers > 0) {
1842 if (s->hello_retry_request != SSL_HRR_NONE) {
1844 * This is after a HelloRetryRequest so we better check that we
1845 * negotiated TLSv1.3
1847 if (best_vers != TLS1_3_VERSION)
1848 return SSL_R_UNSUPPORTED_PROTOCOL;
1851 check_for_downgrade(s, best_vers, dgrd);
1852 s->version = best_vers;
1853 s->method = best_method;
1856 return SSL_R_UNSUPPORTED_PROTOCOL;
1860 * If the supported versions extension isn't present, then the highest
1861 * version we can negotiate is TLSv1.2
1863 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1864 client_version = TLS1_2_VERSION;
1867 * No supported versions extension, so we just use the version supplied in
1870 for (vent = table; vent->version != 0; ++vent) {
1871 const SSL_METHOD *method;
1873 if (vent->smeth == NULL ||
1874 version_cmp(s, client_version, vent->version) < 0)
1876 method = vent->smeth();
1877 if (ssl_method_error(s, method) == 0) {
1878 check_for_downgrade(s, vent->version, dgrd);
1879 s->version = vent->version;
1885 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1889 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1890 * server HELLO is received to select the final client protocol version and
1891 * the version specific method.
1893 * @s: client SSL handle.
1894 * @version: The proposed version from the server's HELLO.
1895 * @extensions: The extensions received
1897 * Returns 1 on success or 0 on error.
1899 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1901 const version_info *vent;
1902 const version_info *table;
1903 int ret, ver_min, ver_max, real_max, origv;
1906 s->version = version;
1908 /* This will overwrite s->version if the extension is present */
1909 if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1910 SSL_EXT_TLS1_2_SERVER_HELLO
1911 | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1917 if (s->hello_retry_request != SSL_HRR_NONE
1918 && s->version != TLS1_3_VERSION) {
1920 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1921 SSL_R_WRONG_SSL_VERSION);
1925 switch (s->method->version) {
1927 if (s->version != s->method->version) {
1929 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1930 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1931 SSL_R_WRONG_SSL_VERSION);
1935 * If this SSL handle is not from a version flexible method we don't
1936 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1937 * that's OK. It is up to the caller to not choose fixed protocol
1938 * versions they don't want. If not, then easy to fix, just return
1939 * ssl_method_error(s, s->method)
1942 case TLS_ANY_VERSION:
1943 table = tls_version_table;
1945 case DTLS_ANY_VERSION:
1946 table = dtls_version_table;
1950 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
1953 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1954 SSL_F_SSL_CHOOSE_CLIENT_VERSION, ret);
1957 if (SSL_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
1958 : s->version < ver_min) {
1960 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1961 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1963 } else if (SSL_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
1964 : s->version > ver_max) {
1966 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1967 SSL_F_SSL_CHOOSE_CLIENT_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
1971 if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
1974 /* Check for downgrades */
1975 if (s->version == TLS1_2_VERSION && real_max > s->version) {
1976 if (memcmp(tls12downgrade,
1977 s->s3.server_random + SSL3_RANDOM_SIZE
1978 - sizeof(tls12downgrade),
1979 sizeof(tls12downgrade)) == 0) {
1981 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1982 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1983 SSL_R_INAPPROPRIATE_FALLBACK);
1986 } else if (!SSL_IS_DTLS(s)
1987 && s->version < TLS1_2_VERSION
1988 && real_max > s->version) {
1989 if (memcmp(tls11downgrade,
1990 s->s3.server_random + SSL3_RANDOM_SIZE
1991 - sizeof(tls11downgrade),
1992 sizeof(tls11downgrade)) == 0) {
1994 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1995 SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1996 SSL_R_INAPPROPRIATE_FALLBACK);
2001 for (vent = table; vent->version != 0; ++vent) {
2002 if (vent->cmeth == NULL || s->version != vent->version)
2005 s->method = vent->cmeth();
2010 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
2011 SSL_R_UNSUPPORTED_PROTOCOL);
2016 * ssl_get_min_max_version - get minimum and maximum protocol version
2017 * @s: The SSL connection
2018 * @min_version: The minimum supported version
2019 * @max_version: The maximum supported version
2020 * @real_max: The highest version below the lowest compile time version hole
2021 * where that hole lies above at least one run-time enabled
2024 * Work out what version we should be using for the initial ClientHello if the
2025 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
2026 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2027 * constraints and any floor imposed by the security level here,
2028 * so we don't advertise the wrong protocol version to only reject the outcome later.
2030 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
2031 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
2032 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2034 * Returns 0 on success or an SSL error reason number on failure. On failure
2035 * min_version and max_version will also be set to 0.
2037 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version,
2040 int version, tmp_real_max;
2042 const SSL_METHOD *single = NULL;
2043 const SSL_METHOD *method;
2044 const version_info *table;
2045 const version_info *vent;
2047 switch (s->method->version) {
2050 * If this SSL handle is not from a version flexible method we don't
2051 * (and never did) check min/max FIPS or Suite B constraints. Hope
2052 * that's OK. It is up to the caller to not choose fixed protocol
2053 * versions they don't want. If not, then easy to fix, just return
2054 * ssl_method_error(s, s->method)
2056 *min_version = *max_version = s->version;
2058 * Providing a real_max only makes sense where we're using a version
2061 if (!ossl_assert(real_max == NULL))
2062 return ERR_R_INTERNAL_ERROR;
2064 case TLS_ANY_VERSION:
2065 table = tls_version_table;
2067 case DTLS_ANY_VERSION:
2068 table = dtls_version_table;
2073 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2074 * below X enabled. This is required in order to maintain the "version
2075 * capability" vector contiguous. Any versions with a NULL client method
2076 * (protocol version client is disabled at compile-time) is also a "hole".
2078 * Our initial state is hole == 1, version == 0. That is, versions above
2079 * the first version in the method table are disabled (a "hole" above
2080 * the valid protocol entries) and we don't have a selected version yet.
2082 * Whenever "hole == 1", and we hit an enabled method, its version becomes
2083 * the selected version, and the method becomes a candidate "single"
2084 * method. We're no longer in a hole, so "hole" becomes 0.
2086 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2087 * as we support a contiguous range of at least two methods. If we hit
2088 * a disabled method, then hole becomes true again, but nothing else
2089 * changes yet, because all the remaining methods may be disabled too.
2090 * If we again hit an enabled method after the new hole, it becomes
2091 * selected, as we start from scratch.
2093 *min_version = version = 0;
2095 if (real_max != NULL)
2098 for (vent = table; vent->version != 0; ++vent) {
2100 * A table entry with a NULL client method is still a hole in the
2101 * "version capability" vector.
2103 if (vent->cmeth == NULL) {
2108 method = vent->cmeth();
2110 if (hole == 1 && tmp_real_max == 0)
2111 tmp_real_max = vent->version;
2113 if (ssl_method_error(s, method) != 0) {
2117 *min_version = method->version;
2119 if (real_max != NULL && tmp_real_max != 0)
2120 *real_max = tmp_real_max;
2121 version = (single = method)->version;
2122 *min_version = version;
2127 *max_version = version;
2129 /* Fail if everything is disabled */
2131 return SSL_R_NO_PROTOCOLS_AVAILABLE;
2137 * ssl_set_client_hello_version - Work out what version we should be using for
2138 * the initial ClientHello.legacy_version field.
2140 * @s: client SSL handle.
2142 * Returns 0 on success or an SSL error reason number on failure.
2144 int ssl_set_client_hello_version(SSL *s)
2146 int ver_min, ver_max, ret;
2149 * In a renegotiation we always send the same client_version that we sent
2150 * last time, regardless of which version we eventually negotiated.
2152 if (!SSL_IS_FIRST_HANDSHAKE(s))
2155 ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2160 s->version = ver_max;
2162 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2163 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2164 ver_max = TLS1_2_VERSION;
2166 s->client_version = ver_max;
2171 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2172 * and |checkallow| is 1 then additionally check if the group is allowed to be
2173 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2174 * 1) or 0 otherwise.
2176 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2177 size_t num_groups, int checkallow)
2181 if (groups == NULL || num_groups == 0)
2184 for (i = 0; i < num_groups; i++) {
2185 uint16_t group = groups[i];
2187 if (group_id == group
2189 || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2197 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2198 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2199 size_t hashlen, const unsigned char *hrr,
2202 unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2203 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2205 memset(msghdr, 0, sizeof(msghdr));
2207 if (hashval == NULL) {
2208 hashval = hashvaltmp;
2210 /* Get the hash of the initial ClientHello */
2211 if (!ssl3_digest_cached_records(s, 0)
2212 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2214 /* SSLfatal() already called */
2219 /* Reinitialise the transcript hash */
2220 if (!ssl3_init_finished_mac(s)) {
2221 /* SSLfatal() already called */
2225 /* Inject the synthetic message_hash message */
2226 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2227 msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2228 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2229 || !ssl3_finish_mac(s, hashval, hashlen)) {
2230 /* SSLfatal() already called */
2235 * Now re-inject the HRR and current message if appropriate (we just deleted
2236 * it when we reinitialised the transcript hash above). Only necessary after
2237 * receiving a ClientHello2 with a cookie.
2240 && (!ssl3_finish_mac(s, hrr, hrrlen)
2241 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2242 s->s3.tmp.message_size
2243 + SSL3_HM_HEADER_LENGTH))) {
2244 /* SSLfatal() already called */
2251 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2253 return X509_NAME_cmp(*a, *b);
2256 int parse_ca_names(SSL *s, PACKET *pkt)
2258 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2259 X509_NAME *xn = NULL;
2262 if (ca_sk == NULL) {
2263 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2264 ERR_R_MALLOC_FAILURE);
2267 /* get the CA RDNs */
2268 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2269 SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2270 SSL_R_LENGTH_MISMATCH);
2274 while (PACKET_remaining(&cadns)) {
2275 const unsigned char *namestart, *namebytes;
2276 unsigned int name_len;
2278 if (!PACKET_get_net_2(&cadns, &name_len)
2279 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2280 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2281 SSL_R_LENGTH_MISMATCH);
2285 namestart = namebytes;
2286 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2287 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2291 if (namebytes != (namestart + name_len)) {
2292 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2293 SSL_R_CA_DN_LENGTH_MISMATCH);
2297 if (!sk_X509_NAME_push(ca_sk, xn)) {
2298 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2299 ERR_R_MALLOC_FAILURE);
2305 sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2306 s->s3.tmp.peer_ca_names = ca_sk;
2311 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2316 const STACK_OF(X509_NAME) *get_ca_names(SSL *s)
2318 const STACK_OF(X509_NAME) *ca_sk = NULL;;
2321 ca_sk = SSL_get_client_CA_list(s);
2322 if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2327 ca_sk = SSL_get0_CA_list(s);
2332 int construct_ca_names(SSL *s, const STACK_OF(X509_NAME) *ca_sk, WPACKET *pkt)
2334 /* Start sub-packet for client CA list */
2335 if (!WPACKET_start_sub_packet_u16(pkt)) {
2336 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2337 ERR_R_INTERNAL_ERROR);
2341 if (ca_sk != NULL) {
2344 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2345 unsigned char *namebytes;
2346 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2350 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2351 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2353 || i2d_X509_NAME(name, &namebytes) != namelen) {
2354 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2355 ERR_R_INTERNAL_ERROR);
2361 if (!WPACKET_close(pkt)) {
2362 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2363 ERR_R_INTERNAL_ERROR);
2370 /* Create a buffer containing data to be signed for server key exchange */
2371 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2372 const void *param, size_t paramlen)
2374 size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2375 unsigned char *tbs = OPENSSL_malloc(tbslen);
2378 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2379 ERR_R_MALLOC_FAILURE);
2382 memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2383 memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2385 memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2392 * Saves the current handshake digest for Post-Handshake Auth,
2393 * Done after ClientFinished is processed, done exactly once
2395 int tls13_save_handshake_digest_for_pha(SSL *s)
2397 if (s->pha_dgst == NULL) {
2398 if (!ssl3_digest_cached_records(s, 1))
2399 /* SSLfatal() already called */
2402 s->pha_dgst = EVP_MD_CTX_new();
2403 if (s->pha_dgst == NULL) {
2404 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2405 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2406 ERR_R_INTERNAL_ERROR);
2409 if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2410 s->s3.handshake_dgst)) {
2411 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2412 SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2413 ERR_R_INTERNAL_ERROR);
2421 * Restores the Post-Handshake Auth handshake digest
2422 * Done just before sending/processing the Cert Request
2424 int tls13_restore_handshake_digest_for_pha(SSL *s)
2426 if (s->pha_dgst == NULL) {
2427 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2428 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2429 ERR_R_INTERNAL_ERROR);
2432 if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2434 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2435 SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2436 ERR_R_INTERNAL_ERROR);