2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12 * ECC cipher suite support in OpenSSL originally developed by
13 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
19 #include "../ssl_locl.h"
20 #include "statem_locl.h"
21 #include <openssl/buffer.h>
22 #include <openssl/objects.h>
23 #include <openssl/evp.h>
24 #include <openssl/x509.h>
27 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
28 * SSL3_RT_CHANGE_CIPHER_SPEC)
30 int ssl3_do_write(SSL *s, int type)
35 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
36 s->init_num, &written);
39 if (type == SSL3_RT_HANDSHAKE)
41 * should not be done for 'Hello Request's, but in that case we'll
42 * ignore the result anyway
44 if (!ssl3_finish_mac(s,
45 (unsigned char *)&s->init_buf->data[s->init_off],
49 if (written == s->init_num) {
51 s->msg_callback(1, s->version, type, s->init_buf->data,
52 (size_t)(s->init_off + s->init_num), s,
56 s->init_off += written;
57 s->init_num -= written;
61 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
65 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
66 || !WPACKET_get_length(pkt, &msglen)
69 s->init_num = (int)msglen;
75 int tls_setup_handshake(SSL *s)
77 if (!ssl3_init_finished_mac(s))
81 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
82 int i, ver_min, ver_max, ok = 0;
85 * Sanity check that the maximum version we accept has ciphers
86 * enabled. For clients we do this check during construction of the
89 if (ssl_get_min_max_version(s, &ver_min, &ver_max) != 0) {
90 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, ERR_R_INTERNAL_ERROR);
91 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
94 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
95 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
98 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
99 DTLS_VERSION_LE(ver_max, c->max_dtls))
101 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
108 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, SSL_R_NO_CIPHERS_AVAILABLE);
109 ERR_add_error_data(1, "No ciphers enabled for max supported "
111 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
114 if (SSL_IS_FIRST_HANDSHAKE(s)) {
115 s->ctx->stats.sess_accept++;
116 } else if (!s->s3->send_connection_binding &&
118 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
120 * Server attempting to renegotiate with client that doesn't
121 * support secure renegotiation.
123 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
124 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
125 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
128 s->ctx->stats.sess_accept_renegotiate++;
130 s->s3->tmp.cert_request = 0;
133 if (SSL_IS_FIRST_HANDSHAKE(s))
134 s->ctx->stats.sess_connect++;
136 s->ctx->stats.sess_connect_renegotiate++;
138 /* mark client_random uninitialized */
139 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
142 s->s3->tmp.cert_req = 0;
145 s->statem.use_timer = 1;
152 * Size of the to-be-signed TLS13 data, without the hash size itself:
153 * 64 bytes of value 32, 33 context bytes, 1 byte separator
155 #define TLS13_TBS_START_SIZE 64
156 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
158 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
159 void **hdata, size_t *hdatalen)
161 static const char *servercontext = "TLS 1.3, server CertificateVerify";
162 static const char *clientcontext = "TLS 1.3, client CertificateVerify";
164 if (SSL_IS_TLS13(s)) {
167 /* Set the first 64 bytes of to-be-signed data to octet 32 */
168 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
169 /* This copies the 33 bytes of context plus the 0 separator byte */
170 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
171 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
172 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
174 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
177 * If we're currently reading then we need to use the saved handshake
178 * hash value. We can't use the current handshake hash state because
179 * that includes the CertVerify itself.
181 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
182 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
183 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
184 s->cert_verify_hash_len);
185 hashlen = s->cert_verify_hash_len;
186 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
187 EVP_MAX_MD_SIZE, &hashlen)) {
192 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
196 retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
205 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
207 EVP_PKEY *pkey = NULL;
208 const EVP_MD *md = NULL;
209 EVP_MD_CTX *mctx = NULL;
210 EVP_PKEY_CTX *pctx = NULL;
211 size_t hdatalen = 0, siglen = 0;
213 unsigned char *sig = NULL;
214 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
215 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
217 if (lu == NULL || s->s3->tmp.cert == NULL) {
218 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
221 pkey = s->s3->tmp.cert->privatekey;
222 md = ssl_md(lu->hash_idx);
224 if (pkey == NULL || md == NULL) {
225 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
229 mctx = EVP_MD_CTX_new();
231 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
235 /* Get the data to be signed */
236 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
237 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
241 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
242 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
245 siglen = EVP_PKEY_size(pkey);
246 sig = OPENSSL_malloc(siglen);
248 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
252 if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
253 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
257 if (lu->sig == EVP_PKEY_RSA_PSS) {
258 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
259 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
260 RSA_PSS_SALTLEN_DIGEST) <= 0) {
261 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
264 } else if (s->version == SSL3_VERSION) {
265 if (!EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
266 (int)s->session->master_key_length,
267 s->session->master_key)) {
268 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
273 if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
274 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
278 #ifndef OPENSSL_NO_GOST
280 int pktype = lu->sig;
282 if (pktype == NID_id_GostR3410_2001
283 || pktype == NID_id_GostR3410_2012_256
284 || pktype == NID_id_GostR3410_2012_512)
285 BUF_reverse(sig, NULL, siglen);
289 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
290 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
294 /* Digest cached records and discard handshake buffer */
295 if (!ssl3_digest_cached_records(s, 0))
299 EVP_MD_CTX_free(mctx);
303 EVP_MD_CTX_free(mctx);
304 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
308 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
310 EVP_PKEY *pkey = NULL;
311 const unsigned char *data;
312 #ifndef OPENSSL_NO_GOST
313 unsigned char *gost_data = NULL;
315 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
319 const EVP_MD *md = NULL;
322 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
323 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
324 EVP_PKEY_CTX *pctx = NULL;
327 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
331 peer = s->session->peer;
332 pkey = X509_get0_pubkey(peer);
334 al = SSL_AD_INTERNAL_ERROR;
338 type = X509_certificate_type(peer, pkey);
340 if (!(type & EVP_PKT_SIGN)) {
341 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
342 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
343 al = SSL_AD_ILLEGAL_PARAMETER;
347 /* Check for broken implementations of GOST ciphersuites */
349 * If key is GOST and n is exactly 64, it is bare signature without
350 * length field (CryptoPro implementations at least till CSP 4.0)
352 #ifndef OPENSSL_NO_GOST
353 if (PACKET_remaining(pkt) == 64
354 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
359 if (SSL_USE_SIGALGS(s)) {
363 if (!PACKET_get_net_2(pkt, &sigalg)) {
364 al = SSL_AD_DECODE_ERROR;
367 rv = tls12_check_peer_sigalg(s, sigalg, pkey);
370 } else if (rv == 0) {
371 al = SSL_AD_DECODE_ERROR;
375 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
377 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
378 al = SSL_AD_INTERNAL_ERROR;
382 md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
384 if (!PACKET_get_net_2(pkt, &len)) {
385 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
386 al = SSL_AD_DECODE_ERROR;
390 j = EVP_PKEY_size(pkey);
391 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
392 || (PACKET_remaining(pkt) == 0)) {
393 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
394 al = SSL_AD_DECODE_ERROR;
397 if (!PACKET_get_bytes(pkt, &data, len)) {
398 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
399 al = SSL_AD_DECODE_ERROR;
403 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
404 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
409 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
411 if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0) {
412 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
415 #ifndef OPENSSL_NO_GOST
417 int pktype = EVP_PKEY_id(pkey);
418 if (pktype == NID_id_GostR3410_2001
419 || pktype == NID_id_GostR3410_2012_256
420 || pktype == NID_id_GostR3410_2012_512) {
421 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
422 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
425 BUF_reverse(gost_data, data, len);
431 if (SSL_USE_PSS(s)) {
432 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
433 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
434 RSA_PSS_SALTLEN_DIGEST) <= 0) {
435 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
438 } else if (s->version == SSL3_VERSION
439 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
440 (int)s->session->master_key_length,
441 s->session->master_key)) {
442 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
446 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
449 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
452 al = SSL_AD_DECRYPT_ERROR;
453 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
457 ret = MSG_PROCESS_CONTINUE_READING;
460 ssl3_send_alert(s, SSL3_AL_FATAL, al);
461 ossl_statem_set_error(s);
463 BIO_free(s->s3->handshake_buffer);
464 s->s3->handshake_buffer = NULL;
465 EVP_MD_CTX_free(mctx);
466 #ifndef OPENSSL_NO_GOST
467 OPENSSL_free(gost_data);
472 int tls_construct_finished(SSL *s, WPACKET *pkt)
474 size_t finish_md_len;
478 /* This is a real handshake so make sure we clean it up at the end */
480 s->statem.cleanuphand = 1;
483 * We only change the keys if we didn't already do this when we sent the
488 && s->s3->tmp.cert_req == 0
489 && (!s->method->ssl3_enc->change_cipher_state(s,
490 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
491 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
496 sender = s->method->ssl3_enc->server_finished_label;
497 slen = s->method->ssl3_enc->server_finished_label_len;
499 sender = s->method->ssl3_enc->client_finished_label;
500 slen = s->method->ssl3_enc->client_finished_label_len;
503 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
505 s->s3->tmp.finish_md);
506 if (finish_md_len == 0) {
507 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
511 s->s3->tmp.finish_md_len = finish_md_len;
513 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
514 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
519 * Log the master secret, if logging is enabled. We don't log it for
520 * TLSv1.3: there's a different key schedule for that.
522 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
523 s->session->master_key,
524 s->session->master_key_length))
528 * Copy the finished so we can use it for renegotiation checks
531 OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
532 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
534 s->s3->previous_client_finished_len = finish_md_len;
536 OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
537 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
539 s->s3->previous_server_finished_len = finish_md_len;
544 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
548 int tls_construct_key_update(SSL *s, WPACKET *pkt)
550 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
551 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
555 s->key_update = SSL_KEY_UPDATE_NONE;
559 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
563 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
566 unsigned int updatetype;
568 s->key_update_count++;
569 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
570 al = SSL_AD_ILLEGAL_PARAMETER;
571 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
576 * A KeyUpdate message signals a key change so the end of the message must
577 * be on a record boundary.
579 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
580 al = SSL_AD_UNEXPECTED_MESSAGE;
581 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
585 if (!PACKET_get_1(pkt, &updatetype)
586 || PACKET_remaining(pkt) != 0) {
587 al = SSL_AD_DECODE_ERROR;
588 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
592 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
593 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
594 al = SSL_AD_ILLEGAL_PARAMETER;
595 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
600 * If we get a request for us to update our sending keys too then, we need
601 * to additionally send a KeyUpdate message. However that message should
602 * not also request an update (otherwise we get into an infinite loop).
604 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
605 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
607 if (!tls13_update_key(s, 0)) {
608 al = SSL_AD_INTERNAL_ERROR;
609 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
613 return MSG_PROCESS_FINISHED_READING;
615 ssl3_send_alert(s, SSL3_AL_FATAL, al);
616 ossl_statem_set_error(s);
617 return MSG_PROCESS_ERROR;
620 #ifndef OPENSSL_NO_NEXTPROTONEG
622 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
625 static void ssl3_take_mac(SSL *s)
630 * If no new cipher setup return immediately: other functions will set
631 * the appropriate error.
633 if (s->s3->tmp.new_cipher == NULL)
636 sender = s->method->ssl3_enc->server_finished_label;
637 slen = s->method->ssl3_enc->server_finished_label_len;
639 sender = s->method->ssl3_enc->client_finished_label;
640 slen = s->method->ssl3_enc->client_finished_label_len;
643 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
646 s->s3->tmp.peer_finish_md);
650 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
655 remain = PACKET_remaining(pkt);
657 * 'Change Cipher Spec' is just a single byte, which should already have
658 * been consumed by ssl_get_message() so there should be no bytes left,
659 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
661 if (SSL_IS_DTLS(s)) {
662 if ((s->version == DTLS1_BAD_VER
663 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
664 || (s->version != DTLS1_BAD_VER
665 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
666 al = SSL_AD_ILLEGAL_PARAMETER;
667 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
668 SSL_R_BAD_CHANGE_CIPHER_SPEC);
673 al = SSL_AD_ILLEGAL_PARAMETER;
674 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
675 SSL_R_BAD_CHANGE_CIPHER_SPEC);
680 /* Check we have a cipher to change to */
681 if (s->s3->tmp.new_cipher == NULL) {
682 al = SSL_AD_UNEXPECTED_MESSAGE;
683 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
687 s->s3->change_cipher_spec = 1;
688 if (!ssl3_do_change_cipher_spec(s)) {
689 al = SSL_AD_INTERNAL_ERROR;
690 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
694 if (SSL_IS_DTLS(s)) {
695 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
697 if (s->version == DTLS1_BAD_VER)
698 s->d1->handshake_read_seq++;
700 #ifndef OPENSSL_NO_SCTP
702 * Remember that a CCS has been received, so that an old key of
703 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
706 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
710 return MSG_PROCESS_CONTINUE_READING;
712 ssl3_send_alert(s, SSL3_AL_FATAL, al);
713 ossl_statem_set_error(s);
714 return MSG_PROCESS_ERROR;
717 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
719 int al = SSL_AD_INTERNAL_ERROR;
723 /* This is a real handshake so make sure we clean it up at the end */
725 s->statem.cleanuphand = 1;
728 * In TLSv1.3 a Finished message signals a key change so the end of the
729 * message must be on a record boundary.
731 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
732 al = SSL_AD_UNEXPECTED_MESSAGE;
733 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
737 /* If this occurs, we have missed a message */
738 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
739 al = SSL_AD_UNEXPECTED_MESSAGE;
740 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
743 s->s3->change_cipher_spec = 0;
745 md_len = s->s3->tmp.peer_finish_md_len;
747 if (md_len != PACKET_remaining(pkt)) {
748 al = SSL_AD_DECODE_ERROR;
749 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
753 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
755 al = SSL_AD_DECRYPT_ERROR;
756 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
761 * Copy the finished so we can use it for renegotiation checks
764 OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
765 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
767 s->s3->previous_client_finished_len = md_len;
769 OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
770 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
772 s->s3->previous_server_finished_len = md_len;
776 * In TLS1.3 we also have to change cipher state and do any final processing
777 * of the initial server flight (if we are a client)
779 if (SSL_IS_TLS13(s)) {
781 if (!s->method->ssl3_enc->change_cipher_state(s,
782 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
783 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
787 if (!s->method->ssl3_enc->generate_master_secret(s,
788 s->master_secret, s->handshake_secret, 0,
789 &s->session->master_key_length)) {
790 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
793 if (!s->method->ssl3_enc->change_cipher_state(s,
794 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
795 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
798 if (!tls_process_initial_server_flight(s, &al))
803 return MSG_PROCESS_FINISHED_READING;
805 ssl3_send_alert(s, SSL3_AL_FATAL, al);
806 ossl_statem_set_error(s);
807 return MSG_PROCESS_ERROR;
810 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
812 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
813 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
814 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
821 /* Add a certificate to the WPACKET */
822 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
826 unsigned char *outbytes;
828 len = i2d_X509(x, NULL);
830 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
831 *al = SSL_AD_INTERNAL_ERROR;
834 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
835 || i2d_X509(x, &outbytes) != len) {
836 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
837 *al = SSL_AD_INTERNAL_ERROR;
842 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
849 /* Add certificate chain to provided WPACKET */
850 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
854 STACK_OF(X509) *extra_certs;
855 STACK_OF(X509) *chain = NULL;
856 X509_STORE *chain_store;
857 int tmpal = SSL_AD_INTERNAL_ERROR;
859 if (cpk == NULL || cpk->x509 == NULL)
865 * If we have a certificate specific chain use it, else use parent ctx.
867 if (cpk->chain != NULL)
868 extra_certs = cpk->chain;
870 extra_certs = s->ctx->extra_certs;
872 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
874 else if (s->cert->chain_store)
875 chain_store = s->cert->chain_store;
877 chain_store = s->ctx->cert_store;
879 if (chain_store != NULL) {
880 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
882 if (xs_ctx == NULL) {
883 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
886 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
887 X509_STORE_CTX_free(xs_ctx);
888 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
892 * It is valid for the chain not to be complete (because normally we
893 * don't include the root cert in the chain). Therefore we deliberately
894 * ignore the error return from this call. We're not actually verifying
895 * the cert - we're just building as much of the chain as we can
897 (void)X509_verify_cert(xs_ctx);
898 /* Don't leave errors in the queue */
900 chain = X509_STORE_CTX_get0_chain(xs_ctx);
901 i = ssl_security_cert_chain(s, chain, NULL, 0);
904 /* Dummy error calls so mkerr generates them */
905 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
906 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
907 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
909 X509_STORE_CTX_free(xs_ctx);
910 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
913 chain_count = sk_X509_num(chain);
914 for (i = 0; i < chain_count; i++) {
915 x = sk_X509_value(chain, i);
917 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
918 X509_STORE_CTX_free(xs_ctx);
922 X509_STORE_CTX_free(xs_ctx);
924 i = ssl_security_cert_chain(s, extra_certs, x, 0);
926 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
929 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
931 for (i = 0; i < sk_X509_num(extra_certs); i++) {
932 x = sk_X509_value(extra_certs, i);
933 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
944 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
947 int tmpal = SSL_AD_INTERNAL_ERROR;
949 if (!WPACKET_start_sub_packet_u24(pkt)
950 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
951 || !WPACKET_close(pkt)) {
952 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
960 * Tidy up after the end of a handshake. In the case of SCTP this may result
961 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
964 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
966 void (*cb) (const SSL *ssl, int type, int val) = NULL;
968 #ifndef OPENSSL_NO_SCTP
969 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
971 ret = dtls_wait_for_dry(s);
972 if (ret != WORK_FINISHED_CONTINUE)
978 if (!SSL_IS_DTLS(s)) {
980 * We don't do this in DTLS because we may still need the init_buf
981 * in case there are any unexpected retransmits
983 BUF_MEM_free(s->init_buf);
986 ssl_free_wbio_buffer(s);
990 if (s->statem.cleanuphand) {
991 /* skipped if we just sent a HelloRequest */
994 s->statem.cleanuphand = 0;
996 ssl3_cleanup_key_block(s);
999 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1001 s->ctx->stats.sess_accept_good++;
1002 s->handshake_func = ossl_statem_accept;
1004 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1006 s->ctx->stats.sess_hit++;
1008 s->handshake_func = ossl_statem_connect;
1009 s->ctx->stats.sess_connect_good++;
1012 if (s->info_callback != NULL)
1013 cb = s->info_callback;
1014 else if (s->ctx->info_callback != NULL)
1015 cb = s->ctx->info_callback;
1018 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1020 if (SSL_IS_DTLS(s)) {
1021 /* done with handshaking */
1022 s->d1->handshake_read_seq = 0;
1023 s->d1->handshake_write_seq = 0;
1024 s->d1->next_handshake_write_seq = 0;
1025 dtls1_clear_received_buffer(s);
1030 * If we've not cleared the buffers its because we've got more work to do,
1034 return WORK_FINISHED_CONTINUE;
1036 ossl_statem_set_in_init(s, 0);
1037 return WORK_FINISHED_STOP;
1040 int tls_get_message_header(SSL *s, int *mt)
1042 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1043 int skip_message, i, recvd_type, al;
1045 size_t l, readbytes;
1047 p = (unsigned char *)s->init_buf->data;
1050 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1051 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1053 SSL3_HM_HEADER_LENGTH - s->init_num,
1056 s->rwstate = SSL_READING;
1059 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1061 * A ChangeCipherSpec must be a single byte and may not occur
1062 * in the middle of a handshake message.
1064 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1065 al = SSL_AD_UNEXPECTED_MESSAGE;
1066 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1067 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1070 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1071 s->init_num = readbytes - 1;
1072 s->init_msg = s->init_buf->data;
1073 s->s3->tmp.message_size = readbytes;
1075 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1076 al = SSL_AD_UNEXPECTED_MESSAGE;
1077 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1080 s->init_num += readbytes;
1085 if (s->statem.hand_state != TLS_ST_OK
1086 && p[0] == SSL3_MT_HELLO_REQUEST)
1088 * The server may always send 'Hello Request' messages --
1089 * we are doing a handshake anyway now, so ignore them if
1090 * their format is correct. Does not count for 'Finished'
1093 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1097 if (s->msg_callback)
1098 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1099 p, SSL3_HM_HEADER_LENGTH, s,
1100 s->msg_callback_arg);
1102 } while (skip_message);
1103 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1106 s->s3->tmp.message_type = *(p++);
1108 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1110 * Only happens with SSLv3+ in an SSLv2 backward compatible
1113 * Total message size is the remaining record bytes to read
1114 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1116 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1117 + SSL3_HM_HEADER_LENGTH;
1118 s->s3->tmp.message_size = l;
1120 s->init_msg = s->init_buf->data;
1121 s->init_num = SSL3_HM_HEADER_LENGTH;
1124 /* BUF_MEM_grow takes an 'int' parameter */
1125 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1126 al = SSL_AD_ILLEGAL_PARAMETER;
1127 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1130 s->s3->tmp.message_size = l;
1132 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1138 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1142 int tls_get_message_body(SSL *s, size_t *len)
1144 size_t n, readbytes;
1148 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1149 /* We've already read everything in */
1150 *len = (unsigned long)s->init_num;
1155 n = s->s3->tmp.message_size - s->init_num;
1157 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1158 &p[s->init_num], n, 0, &readbytes);
1160 s->rwstate = SSL_READING;
1164 s->init_num += readbytes;
1168 #ifndef OPENSSL_NO_NEXTPROTONEG
1170 * If receiving Finished, record MAC of prior handshake messages for
1171 * Finished verification.
1173 if (*s->init_buf->data == SSL3_MT_FINISHED)
1177 /* Feed this message into MAC computation. */
1178 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1179 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1181 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1182 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1186 if (s->msg_callback)
1187 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1188 (size_t)s->init_num, s, s->msg_callback_arg);
1191 * We defer feeding in the HRR until later. We'll do it as part of
1192 * processing the message
1194 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1195 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1196 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1197 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1198 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1202 if (s->msg_callback)
1203 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1204 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1205 s->msg_callback_arg);
1212 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1214 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1217 switch (EVP_PKEY_id(pk)) {
1221 return SSL_PKEY_RSA;
1223 return SSL_PKEY_DSA_SIGN;
1224 #ifndef OPENSSL_NO_EC
1226 return SSL_PKEY_ECC;
1228 #ifndef OPENSSL_NO_GOST
1229 case NID_id_GostR3410_2001:
1230 return SSL_PKEY_GOST01;
1231 case NID_id_GostR3410_2012_256:
1232 return SSL_PKEY_GOST12_256;
1233 case NID_id_GostR3410_2012_512:
1234 return SSL_PKEY_GOST12_512;
1239 int ssl_verify_alarm_type(long type)
1244 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1245 case X509_V_ERR_UNABLE_TO_GET_CRL:
1246 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1247 al = SSL_AD_UNKNOWN_CA;
1249 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1250 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1251 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1252 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1253 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1254 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1255 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1256 case X509_V_ERR_CERT_NOT_YET_VALID:
1257 case X509_V_ERR_CRL_NOT_YET_VALID:
1258 case X509_V_ERR_CERT_UNTRUSTED:
1259 case X509_V_ERR_CERT_REJECTED:
1260 case X509_V_ERR_HOSTNAME_MISMATCH:
1261 case X509_V_ERR_EMAIL_MISMATCH:
1262 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1263 case X509_V_ERR_DANE_NO_MATCH:
1264 case X509_V_ERR_EE_KEY_TOO_SMALL:
1265 case X509_V_ERR_CA_KEY_TOO_SMALL:
1266 case X509_V_ERR_CA_MD_TOO_WEAK:
1267 al = SSL_AD_BAD_CERTIFICATE;
1269 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1270 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1271 al = SSL_AD_DECRYPT_ERROR;
1273 case X509_V_ERR_CERT_HAS_EXPIRED:
1274 case X509_V_ERR_CRL_HAS_EXPIRED:
1275 al = SSL_AD_CERTIFICATE_EXPIRED;
1277 case X509_V_ERR_CERT_REVOKED:
1278 al = SSL_AD_CERTIFICATE_REVOKED;
1280 case X509_V_ERR_UNSPECIFIED:
1281 case X509_V_ERR_OUT_OF_MEM:
1282 case X509_V_ERR_INVALID_CALL:
1283 case X509_V_ERR_STORE_LOOKUP:
1284 al = SSL_AD_INTERNAL_ERROR;
1286 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1287 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1288 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1289 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1290 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1291 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1292 case X509_V_ERR_INVALID_CA:
1293 al = SSL_AD_UNKNOWN_CA;
1295 case X509_V_ERR_APPLICATION_VERIFICATION:
1296 al = SSL_AD_HANDSHAKE_FAILURE;
1298 case X509_V_ERR_INVALID_PURPOSE:
1299 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1302 al = SSL_AD_CERTIFICATE_UNKNOWN;
1308 int ssl_allow_compression(SSL *s)
1310 if (s->options & SSL_OP_NO_COMPRESSION)
1312 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1315 static int version_cmp(const SSL *s, int a, int b)
1317 int dtls = SSL_IS_DTLS(s);
1322 return a < b ? -1 : 1;
1323 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1328 const SSL_METHOD *(*cmeth) (void);
1329 const SSL_METHOD *(*smeth) (void);
1332 #if TLS_MAX_VERSION != TLS1_3_VERSION
1333 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1336 /* Must be in order high to low */
1337 static const version_info tls_version_table[] = {
1338 #ifndef OPENSSL_NO_TLS1_3
1339 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1341 {TLS1_3_VERSION, NULL, NULL},
1343 #ifndef OPENSSL_NO_TLS1_2
1344 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1346 {TLS1_2_VERSION, NULL, NULL},
1348 #ifndef OPENSSL_NO_TLS1_1
1349 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1351 {TLS1_1_VERSION, NULL, NULL},
1353 #ifndef OPENSSL_NO_TLS1
1354 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1356 {TLS1_VERSION, NULL, NULL},
1358 #ifndef OPENSSL_NO_SSL3
1359 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1361 {SSL3_VERSION, NULL, NULL},
1366 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1367 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1370 /* Must be in order high to low */
1371 static const version_info dtls_version_table[] = {
1372 #ifndef OPENSSL_NO_DTLS1_2
1373 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1375 {DTLS1_2_VERSION, NULL, NULL},
1377 #ifndef OPENSSL_NO_DTLS1
1378 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1379 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1381 {DTLS1_VERSION, NULL, NULL},
1382 {DTLS1_BAD_VER, NULL, NULL},
1388 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1390 * @s: The SSL handle for the candidate method
1391 * @method: the intended method.
1393 * Returns 0 on success, or an SSL error reason on failure.
1395 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1397 int version = method->version;
1399 if ((s->min_proto_version != 0 &&
1400 version_cmp(s, version, s->min_proto_version) < 0) ||
1401 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1402 return SSL_R_VERSION_TOO_LOW;
1404 if (s->max_proto_version != 0 &&
1405 version_cmp(s, version, s->max_proto_version) > 0)
1406 return SSL_R_VERSION_TOO_HIGH;
1408 if ((s->options & method->mask) != 0)
1409 return SSL_R_UNSUPPORTED_PROTOCOL;
1410 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1411 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1417 * ssl_version_supported - Check that the specified `version` is supported by
1420 * @s: The SSL handle for the candidate method
1421 * @version: Protocol version to test against
1423 * Returns 1 when supported, otherwise 0
1425 int ssl_version_supported(const SSL *s, int version)
1427 const version_info *vent;
1428 const version_info *table;
1430 switch (s->method->version) {
1432 /* Version should match method version for non-ANY method */
1433 return version_cmp(s, version, s->version) == 0;
1434 case TLS_ANY_VERSION:
1435 table = tls_version_table;
1437 case DTLS_ANY_VERSION:
1438 table = dtls_version_table;
1443 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1445 if (vent->cmeth != NULL &&
1446 version_cmp(s, version, vent->version) == 0 &&
1447 ssl_method_error(s, vent->cmeth()) == 0) {
1455 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1456 * fallback indication from a client check whether we're using the highest
1457 * supported protocol version.
1459 * @s server SSL handle.
1461 * Returns 1 when using the highest enabled version, 0 otherwise.
1463 int ssl_check_version_downgrade(SSL *s)
1465 const version_info *vent;
1466 const version_info *table;
1469 * Check that the current protocol is the highest enabled version
1470 * (according to s->ctx->method, as version negotiation may have changed
1473 if (s->version == s->ctx->method->version)
1477 * Apparently we're using a version-flexible SSL_METHOD (not at its
1478 * highest protocol version).
1480 if (s->ctx->method->version == TLS_method()->version)
1481 table = tls_version_table;
1482 else if (s->ctx->method->version == DTLS_method()->version)
1483 table = dtls_version_table;
1485 /* Unexpected state; fail closed. */
1489 for (vent = table; vent->version != 0; ++vent) {
1490 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1491 return s->version == vent->version;
1497 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1498 * protocols, provided the initial (D)TLS method is version-flexible. This
1499 * function sanity-checks the proposed value and makes sure the method is
1500 * version-flexible, then sets the limit if all is well.
1502 * @method_version: The version of the current SSL_METHOD.
1503 * @version: the intended limit.
1504 * @bound: pointer to limit to be updated.
1506 * Returns 1 on success, 0 on failure.
1508 int ssl_set_version_bound(int method_version, int version, int *bound)
1516 * Restrict TLS methods to TLS protocol versions.
1517 * Restrict DTLS methods to DTLS protocol versions.
1518 * Note, DTLS version numbers are decreasing, use comparison macros.
1520 * Note that for both lower-bounds we use explicit versions, not
1521 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1522 * configurations. If the MIN (supported) version ever rises, the user's
1523 * "floor" remains valid even if no longer available. We don't expect the
1524 * MAX ceiling to ever get lower, so making that variable makes sense.
1526 switch (method_version) {
1529 * XXX For fixed version methods, should we always fail and not set any
1530 * bounds, always succeed and not set any bounds, or set the bounds and
1531 * arrange to fail later if they are not met? At present fixed-version
1532 * methods are not subject to controls that disable individual protocol
1537 case TLS_ANY_VERSION:
1538 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1542 case DTLS_ANY_VERSION:
1543 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1544 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1553 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1555 if (vers == TLS1_2_VERSION
1556 && ssl_version_supported(s, TLS1_3_VERSION)) {
1557 *dgrd = DOWNGRADE_TO_1_2;
1558 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1559 && (ssl_version_supported(s, TLS1_2_VERSION)
1560 || ssl_version_supported(s, TLS1_3_VERSION))) {
1561 *dgrd = DOWNGRADE_TO_1_1;
1563 *dgrd = DOWNGRADE_NONE;
1568 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1569 * client HELLO is received to select the final server protocol version and
1570 * the version specific method.
1572 * @s: server SSL handle.
1574 * Returns 0 on success or an SSL error reason number on failure.
1576 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1579 * With version-flexible methods we have an initial state with:
1581 * s->method->version == (D)TLS_ANY_VERSION,
1582 * s->version == (D)TLS_MAX_VERSION.
1584 * So we detect version-flexible methods via the method version, not the
1587 int server_version = s->method->version;
1588 int client_version = hello->legacy_version;
1589 const version_info *vent;
1590 const version_info *table;
1592 RAW_EXTENSION *suppversions;
1594 s->client_version = client_version;
1596 switch (server_version) {
1598 if (!SSL_IS_TLS13(s)) {
1599 if (version_cmp(s, client_version, s->version) < 0)
1600 return SSL_R_WRONG_SSL_VERSION;
1601 *dgrd = DOWNGRADE_NONE;
1603 * If this SSL handle is not from a version flexible method we don't
1604 * (and never did) check min/max FIPS or Suite B constraints. Hope
1605 * that's OK. It is up to the caller to not choose fixed protocol
1606 * versions they don't want. If not, then easy to fix, just return
1607 * ssl_method_error(s, s->method)
1612 * Fall through if we are TLSv1.3 already (this means we must be after
1613 * a HelloRetryRequest
1615 case TLS_ANY_VERSION:
1616 table = tls_version_table;
1618 case DTLS_ANY_VERSION:
1619 table = dtls_version_table;
1623 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1625 if (suppversions->present && !SSL_IS_DTLS(s)) {
1626 unsigned int candidate_vers = 0;
1627 unsigned int best_vers = 0;
1628 const SSL_METHOD *best_method = NULL;
1629 PACKET versionslist;
1631 suppversions->parsed = 1;
1633 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1634 /* Trailing or invalid data? */
1635 return SSL_R_LENGTH_MISMATCH;
1638 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1639 /* TODO(TLS1.3): Remove this before release */
1640 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1641 candidate_vers = TLS1_3_VERSION;
1643 * TODO(TLS1.3): There is some discussion on the TLS list about
1644 * whether to ignore versions <TLS1.2 in supported_versions. At the
1645 * moment we honour them if present. To be reviewed later
1647 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1650 vent->version != 0 && vent->version != (int)candidate_vers;
1653 if (vent->version != 0 && vent->smeth != NULL) {
1654 const SSL_METHOD *method;
1656 method = vent->smeth();
1657 if (ssl_method_error(s, method) == 0) {
1658 best_vers = candidate_vers;
1659 best_method = method;
1663 if (PACKET_remaining(&versionslist) != 0) {
1664 /* Trailing data? */
1665 return SSL_R_LENGTH_MISMATCH;
1668 if (best_vers > 0) {
1669 if (SSL_IS_TLS13(s)) {
1671 * We get here if this is after a HelloRetryRequest. In this
1672 * case we just check that we still negotiated TLSv1.3
1674 if (best_vers != TLS1_3_VERSION)
1675 return SSL_R_UNSUPPORTED_PROTOCOL;
1678 check_for_downgrade(s, best_vers, dgrd);
1679 s->version = best_vers;
1680 s->method = best_method;
1683 return SSL_R_UNSUPPORTED_PROTOCOL;
1687 * If the supported versions extension isn't present, then the highest
1688 * version we can negotiate is TLSv1.2
1690 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1691 client_version = TLS1_2_VERSION;
1694 * No supported versions extension, so we just use the version supplied in
1697 for (vent = table; vent->version != 0; ++vent) {
1698 const SSL_METHOD *method;
1700 if (vent->smeth == NULL ||
1701 version_cmp(s, client_version, vent->version) < 0)
1703 method = vent->smeth();
1704 if (ssl_method_error(s, method) == 0) {
1705 check_for_downgrade(s, vent->version, dgrd);
1706 s->version = vent->version;
1712 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1716 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1717 * server HELLO is received to select the final client protocol version and
1718 * the version specific method.
1720 * @s: client SSL handle.
1721 * @version: The proposed version from the server's HELLO.
1722 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1723 * @al: Where to store any alert value that may be generated
1725 * Returns 0 on success or an SSL error reason number on failure.
1727 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1729 const version_info *vent;
1730 const version_info *table;
1733 /* TODO(TLS1.3): Remove this before release */
1734 if (version == TLS1_3_VERSION_DRAFT)
1735 version = TLS1_3_VERSION;
1737 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1738 *al = SSL_AD_PROTOCOL_VERSION;
1739 return SSL_R_WRONG_SSL_VERSION;
1742 switch (s->method->version) {
1744 if (version != s->version) {
1745 *al = SSL_AD_PROTOCOL_VERSION;
1746 return SSL_R_WRONG_SSL_VERSION;
1749 * If this SSL handle is not from a version flexible method we don't
1750 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1751 * that's OK. It is up to the caller to not choose fixed protocol
1752 * versions they don't want. If not, then easy to fix, just return
1753 * ssl_method_error(s, s->method)
1756 case TLS_ANY_VERSION:
1757 table = tls_version_table;
1759 case DTLS_ANY_VERSION:
1760 table = dtls_version_table;
1764 for (vent = table; vent->version != 0; ++vent) {
1765 const SSL_METHOD *method;
1768 if (vent->cmeth == NULL)
1771 if (highver != 0 && version != vent->version)
1774 method = vent->cmeth();
1775 err = ssl_method_error(s, method);
1777 if (version == vent->version) {
1778 *al = SSL_AD_PROTOCOL_VERSION;
1785 highver = vent->version;
1787 if (version != vent->version)
1790 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1791 /* Check for downgrades */
1793 if (version == TLS1_2_VERSION && highver > version) {
1794 if (memcmp(tls12downgrade,
1795 s->s3->server_random + SSL3_RANDOM_SIZE
1796 - sizeof(tls12downgrade),
1797 sizeof(tls12downgrade)) == 0) {
1798 *al = SSL_AD_ILLEGAL_PARAMETER;
1799 return SSL_R_INAPPROPRIATE_FALLBACK;
1801 } else if (!SSL_IS_DTLS(s)
1802 && version < TLS1_2_VERSION
1803 && highver > version) {
1804 if (memcmp(tls11downgrade,
1805 s->s3->server_random + SSL3_RANDOM_SIZE
1806 - sizeof(tls11downgrade),
1807 sizeof(tls11downgrade)) == 0) {
1808 *al = SSL_AD_ILLEGAL_PARAMETER;
1809 return SSL_R_INAPPROPRIATE_FALLBACK;
1816 s->version = version;
1820 *al = SSL_AD_PROTOCOL_VERSION;
1821 return SSL_R_UNSUPPORTED_PROTOCOL;
1825 * ssl_get_min_max_version - get minimum and maximum protocol version
1826 * @s: The SSL connection
1827 * @min_version: The minimum supported version
1828 * @max_version: The maximum supported version
1830 * Work out what version we should be using for the initial ClientHello if the
1831 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1832 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1833 * constraints and any floor imposed by the security level here,
1834 * so we don't advertise the wrong protocol version to only reject the outcome later.
1836 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
1837 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1838 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1840 * Returns 0 on success or an SSL error reason number on failure. On failure
1841 * min_version and max_version will also be set to 0.
1843 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1847 const SSL_METHOD *single = NULL;
1848 const SSL_METHOD *method;
1849 const version_info *table;
1850 const version_info *vent;
1852 switch (s->method->version) {
1855 * If this SSL handle is not from a version flexible method we don't
1856 * (and never did) check min/max FIPS or Suite B constraints. Hope
1857 * that's OK. It is up to the caller to not choose fixed protocol
1858 * versions they don't want. If not, then easy to fix, just return
1859 * ssl_method_error(s, s->method)
1861 *min_version = *max_version = s->version;
1863 case TLS_ANY_VERSION:
1864 table = tls_version_table;
1866 case DTLS_ANY_VERSION:
1867 table = dtls_version_table;
1872 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1873 * below X enabled. This is required in order to maintain the "version
1874 * capability" vector contiguous. Any versions with a NULL client method
1875 * (protocol version client is disabled at compile-time) is also a "hole".
1877 * Our initial state is hole == 1, version == 0. That is, versions above
1878 * the first version in the method table are disabled (a "hole" above
1879 * the valid protocol entries) and we don't have a selected version yet.
1881 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1882 * the selected version, and the method becomes a candidate "single"
1883 * method. We're no longer in a hole, so "hole" becomes 0.
1885 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1886 * as we support a contiguous range of at least two methods. If we hit
1887 * a disabled method, then hole becomes true again, but nothing else
1888 * changes yet, because all the remaining methods may be disabled too.
1889 * If we again hit an enabled method after the new hole, it becomes
1890 * selected, as we start from scratch.
1892 *min_version = version = 0;
1894 for (vent = table; vent->version != 0; ++vent) {
1896 * A table entry with a NULL client method is still a hole in the
1897 * "version capability" vector.
1899 if (vent->cmeth == NULL) {
1903 method = vent->cmeth();
1904 if (ssl_method_error(s, method) != 0) {
1908 *min_version = method->version;
1910 version = (single = method)->version;
1911 *min_version = version;
1916 *max_version = version;
1918 /* Fail if everything is disabled */
1920 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1926 * ssl_set_client_hello_version - Work out what version we should be using for
1927 * the initial ClientHello.legacy_version field.
1929 * @s: client SSL handle.
1931 * Returns 0 on success or an SSL error reason number on failure.
1933 int ssl_set_client_hello_version(SSL *s)
1935 int ver_min, ver_max, ret;
1937 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
1942 s->version = ver_max;
1944 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1945 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1946 ver_max = TLS1_2_VERSION;
1948 s->client_version = ver_max;
1953 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1954 * and |checkallow| is 1 then additionally check if the group is allowed to be
1955 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1956 * 1) or 0 otherwise.
1958 #ifndef OPENSSL_NO_EC
1959 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1960 size_t num_groups, int checkallow)
1964 if (groups == NULL || num_groups == 0)
1967 for (i = 0; i < num_groups; i++, groups += 2) {
1968 if (group_id == GET_GROUP_ID(groups, 0)
1970 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
1979 /* Replace ClientHello1 in the transcript hash with a synthetic message */
1980 int create_synthetic_message_hash(SSL *s)
1982 unsigned char hashval[EVP_MAX_MD_SIZE];
1984 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
1986 memset(msghdr, 0, sizeof(msghdr));
1988 /* Get the hash of the initial ClientHello */
1989 if (!ssl3_digest_cached_records(s, 0)
1990 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
1991 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
1995 /* Reinitialise the transcript hash */
1996 if (!ssl3_init_finished_mac(s))
1999 /* Inject the synthetic message_hash message */
2000 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2001 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
2002 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2003 || !ssl3_finish_mac(s, hashval, hashlen)) {
2004 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2011 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2013 return X509_NAME_cmp(*a, *b);
2016 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2018 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2019 X509_NAME *xn = NULL;
2022 if (ca_sk == NULL) {
2023 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2026 /* get the CA RDNs */
2027 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2028 *al = SSL_AD_DECODE_ERROR;
2029 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2033 while (PACKET_remaining(&cadns)) {
2034 const unsigned char *namestart, *namebytes;
2035 unsigned int name_len;
2037 if (!PACKET_get_net_2(&cadns, &name_len)
2038 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2039 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2043 namestart = namebytes;
2044 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2045 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2048 if (namebytes != (namestart + name_len)) {
2049 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2053 if (!sk_X509_NAME_push(ca_sk, xn)) {
2054 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2055 *al = SSL_AD_INTERNAL_ERROR;
2061 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2062 s->s3->tmp.peer_ca_names = ca_sk;
2067 *al = SSL_AD_DECODE_ERROR;
2069 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2074 int construct_ca_names(SSL *s, WPACKET *pkt)
2076 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2078 /* Start sub-packet for client CA list */
2079 if (!WPACKET_start_sub_packet_u16(pkt))
2082 if (ca_sk != NULL) {
2085 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2086 unsigned char *namebytes;
2087 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2091 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2092 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2094 || i2d_X509_NAME(name, &namebytes) != namelen) {
2100 if (!WPACKET_close(pkt))