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 || EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0) {
254 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
258 if (lu->sig == EVP_PKEY_RSA_PSS) {
259 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
260 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
261 RSA_PSS_SALTLEN_DIGEST) <= 0) {
262 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
265 } else if (s->version == SSL3_VERSION) {
266 if (!EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
267 (int)s->session->master_key_length,
268 s->session->master_key)) {
269 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
274 if (EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
275 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
279 #ifndef OPENSSL_NO_GOST
281 int pktype = lu->sig;
283 if (pktype == NID_id_GostR3410_2001
284 || pktype == NID_id_GostR3410_2012_256
285 || pktype == NID_id_GostR3410_2012_512)
286 BUF_reverse(sig, NULL, siglen);
290 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
291 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
295 /* Digest cached records and discard handshake buffer */
296 if (!ssl3_digest_cached_records(s, 0))
300 EVP_MD_CTX_free(mctx);
304 EVP_MD_CTX_free(mctx);
305 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
309 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
311 EVP_PKEY *pkey = NULL;
312 const unsigned char *data;
313 #ifndef OPENSSL_NO_GOST
314 unsigned char *gost_data = NULL;
316 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
320 const EVP_MD *md = NULL;
323 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
324 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
325 EVP_PKEY_CTX *pctx = NULL;
328 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
332 peer = s->session->peer;
333 pkey = X509_get0_pubkey(peer);
335 al = SSL_AD_INTERNAL_ERROR;
339 type = X509_certificate_type(peer, pkey);
341 if (!(type & EVP_PKT_SIGN)) {
342 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
343 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
344 al = SSL_AD_ILLEGAL_PARAMETER;
348 /* Check for broken implementations of GOST ciphersuites */
350 * If key is GOST and n is exactly 64, it is bare signature without
351 * length field (CryptoPro implementations at least till CSP 4.0)
353 #ifndef OPENSSL_NO_GOST
354 if (PACKET_remaining(pkt) == 64
355 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
360 if (SSL_USE_SIGALGS(s)) {
364 if (!PACKET_get_net_2(pkt, &sigalg)) {
365 al = SSL_AD_DECODE_ERROR;
368 rv = tls12_check_peer_sigalg(s, sigalg, pkey);
371 } else if (rv == 0) {
372 al = SSL_AD_DECODE_ERROR;
376 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
378 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
379 al = SSL_AD_INTERNAL_ERROR;
383 md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
385 if (!PACKET_get_net_2(pkt, &len)) {
386 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
387 al = SSL_AD_DECODE_ERROR;
391 j = EVP_PKEY_size(pkey);
392 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
393 || (PACKET_remaining(pkt) == 0)) {
394 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
395 al = SSL_AD_DECODE_ERROR;
398 if (!PACKET_get_bytes(pkt, &data, len)) {
399 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
400 al = SSL_AD_DECODE_ERROR;
404 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
405 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
410 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
412 if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0
413 || EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0) {
414 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
417 #ifndef OPENSSL_NO_GOST
419 int pktype = EVP_PKEY_id(pkey);
420 if (pktype == NID_id_GostR3410_2001
421 || pktype == NID_id_GostR3410_2012_256
422 || pktype == NID_id_GostR3410_2012_512) {
423 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
424 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
427 BUF_reverse(gost_data, data, len);
433 if (SSL_USE_PSS(s)) {
434 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
435 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
436 RSA_PSS_SALTLEN_DIGEST) <= 0) {
437 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
440 } else if (s->version == SSL3_VERSION
441 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
442 (int)s->session->master_key_length,
443 s->session->master_key)) {
444 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
448 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
449 al = SSL_AD_DECRYPT_ERROR;
450 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
454 ret = MSG_PROCESS_CONTINUE_READING;
457 ssl3_send_alert(s, SSL3_AL_FATAL, al);
458 ossl_statem_set_error(s);
460 BIO_free(s->s3->handshake_buffer);
461 s->s3->handshake_buffer = NULL;
462 EVP_MD_CTX_free(mctx);
463 #ifndef OPENSSL_NO_GOST
464 OPENSSL_free(gost_data);
469 int tls_construct_finished(SSL *s, WPACKET *pkt)
471 size_t finish_md_len;
475 /* This is a real handshake so make sure we clean it up at the end */
477 s->statem.cleanuphand = 1;
480 * We only change the keys if we didn't already do this when we sent the
485 && s->s3->tmp.cert_req == 0
486 && (!s->method->ssl3_enc->change_cipher_state(s,
487 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
488 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
493 sender = s->method->ssl3_enc->server_finished_label;
494 slen = s->method->ssl3_enc->server_finished_label_len;
496 sender = s->method->ssl3_enc->client_finished_label;
497 slen = s->method->ssl3_enc->client_finished_label_len;
500 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
502 s->s3->tmp.finish_md);
503 if (finish_md_len == 0) {
504 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
508 s->s3->tmp.finish_md_len = finish_md_len;
510 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
511 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
516 * Log the master secret, if logging is enabled. We don't log it for
517 * TLSv1.3: there's a different key schedule for that.
519 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
520 s->session->master_key,
521 s->session->master_key_length))
525 * Copy the finished so we can use it for renegotiation checks
528 OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
529 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
531 s->s3->previous_client_finished_len = finish_md_len;
533 OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
534 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
536 s->s3->previous_server_finished_len = finish_md_len;
541 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
545 int tls_construct_key_update(SSL *s, WPACKET *pkt)
547 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
548 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
552 s->key_update = SSL_KEY_UPDATE_NONE;
556 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
560 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
563 unsigned int updatetype;
565 s->key_update_count++;
566 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
567 al = SSL_AD_ILLEGAL_PARAMETER;
568 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
573 * A KeyUpdate message signals a key change so the end of the message must
574 * be on a record boundary.
576 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
577 al = SSL_AD_UNEXPECTED_MESSAGE;
578 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
582 if (!PACKET_get_1(pkt, &updatetype)
583 || PACKET_remaining(pkt) != 0
584 || (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
585 && updatetype != SSL_KEY_UPDATE_REQUESTED)) {
586 al = SSL_AD_DECODE_ERROR;
587 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
592 * If we get a request for us to update our sending keys too then, we need
593 * to additionally send a KeyUpdate message. However that message should
594 * not also request an update (otherwise we get into an infinite loop).
596 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
597 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
599 if (!tls13_update_key(s, 0)) {
600 al = SSL_AD_INTERNAL_ERROR;
601 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
605 return MSG_PROCESS_FINISHED_READING;
607 ssl3_send_alert(s, SSL3_AL_FATAL, al);
608 ossl_statem_set_error(s);
609 return MSG_PROCESS_ERROR;
612 #ifndef OPENSSL_NO_NEXTPROTONEG
614 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
617 static void ssl3_take_mac(SSL *s)
622 * If no new cipher setup return immediately: other functions will set
623 * the appropriate error.
625 if (s->s3->tmp.new_cipher == NULL)
628 sender = s->method->ssl3_enc->server_finished_label;
629 slen = s->method->ssl3_enc->server_finished_label_len;
631 sender = s->method->ssl3_enc->client_finished_label;
632 slen = s->method->ssl3_enc->client_finished_label_len;
635 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
638 s->s3->tmp.peer_finish_md);
642 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
647 remain = PACKET_remaining(pkt);
649 * 'Change Cipher Spec' is just a single byte, which should already have
650 * been consumed by ssl_get_message() so there should be no bytes left,
651 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
653 if (SSL_IS_DTLS(s)) {
654 if ((s->version == DTLS1_BAD_VER
655 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
656 || (s->version != DTLS1_BAD_VER
657 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
658 al = SSL_AD_ILLEGAL_PARAMETER;
659 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
660 SSL_R_BAD_CHANGE_CIPHER_SPEC);
665 al = SSL_AD_ILLEGAL_PARAMETER;
666 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
667 SSL_R_BAD_CHANGE_CIPHER_SPEC);
672 /* Check we have a cipher to change to */
673 if (s->s3->tmp.new_cipher == NULL) {
674 al = SSL_AD_UNEXPECTED_MESSAGE;
675 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
679 s->s3->change_cipher_spec = 1;
680 if (!ssl3_do_change_cipher_spec(s)) {
681 al = SSL_AD_INTERNAL_ERROR;
682 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
686 if (SSL_IS_DTLS(s)) {
687 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
689 if (s->version == DTLS1_BAD_VER)
690 s->d1->handshake_read_seq++;
692 #ifndef OPENSSL_NO_SCTP
694 * Remember that a CCS has been received, so that an old key of
695 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
698 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
702 return MSG_PROCESS_CONTINUE_READING;
704 ssl3_send_alert(s, SSL3_AL_FATAL, al);
705 ossl_statem_set_error(s);
706 return MSG_PROCESS_ERROR;
709 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
711 int al = SSL_AD_INTERNAL_ERROR;
715 /* This is a real handshake so make sure we clean it up at the end */
717 s->statem.cleanuphand = 1;
720 * In TLSv1.3 a Finished message signals a key change so the end of the
721 * message must be on a record boundary.
723 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
724 al = SSL_AD_UNEXPECTED_MESSAGE;
725 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
729 /* If this occurs, we have missed a message */
730 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
731 al = SSL_AD_UNEXPECTED_MESSAGE;
732 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
735 s->s3->change_cipher_spec = 0;
737 md_len = s->s3->tmp.peer_finish_md_len;
739 if (md_len != PACKET_remaining(pkt)) {
740 al = SSL_AD_DECODE_ERROR;
741 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
745 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
747 al = SSL_AD_DECRYPT_ERROR;
748 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
753 * Copy the finished so we can use it for renegotiation checks
756 OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
757 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
759 s->s3->previous_client_finished_len = md_len;
761 OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
762 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
764 s->s3->previous_server_finished_len = md_len;
768 * In TLS1.3 we also have to change cipher state and do any final processing
769 * of the initial server flight (if we are a client)
771 if (SSL_IS_TLS13(s)) {
773 if (!s->method->ssl3_enc->change_cipher_state(s,
774 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
775 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
779 if (!s->method->ssl3_enc->generate_master_secret(s,
780 s->master_secret, s->handshake_secret, 0,
781 &s->session->master_key_length)) {
782 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
785 if (!s->method->ssl3_enc->change_cipher_state(s,
786 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
787 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
790 if (!tls_process_initial_server_flight(s, &al))
795 return MSG_PROCESS_FINISHED_READING;
797 ssl3_send_alert(s, SSL3_AL_FATAL, al);
798 ossl_statem_set_error(s);
799 return MSG_PROCESS_ERROR;
802 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
804 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
805 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
806 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
813 /* Add a certificate to the WPACKET */
814 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
818 unsigned char *outbytes;
820 len = i2d_X509(x, NULL);
822 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
823 *al = SSL_AD_INTERNAL_ERROR;
826 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
827 || i2d_X509(x, &outbytes) != len) {
828 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
829 *al = SSL_AD_INTERNAL_ERROR;
834 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
841 /* Add certificate chain to provided WPACKET */
842 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
846 STACK_OF(X509) *extra_certs;
847 STACK_OF(X509) *chain = NULL;
848 X509_STORE *chain_store;
849 int tmpal = SSL_AD_INTERNAL_ERROR;
851 if (cpk == NULL || cpk->x509 == NULL)
857 * If we have a certificate specific chain use it, else use parent ctx.
859 if (cpk->chain != NULL)
860 extra_certs = cpk->chain;
862 extra_certs = s->ctx->extra_certs;
864 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
866 else if (s->cert->chain_store)
867 chain_store = s->cert->chain_store;
869 chain_store = s->ctx->cert_store;
871 if (chain_store != NULL) {
872 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
874 if (xs_ctx == NULL) {
875 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
878 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
879 X509_STORE_CTX_free(xs_ctx);
880 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
884 * It is valid for the chain not to be complete (because normally we
885 * don't include the root cert in the chain). Therefore we deliberately
886 * ignore the error return from this call. We're not actually verifying
887 * the cert - we're just building as much of the chain as we can
889 (void)X509_verify_cert(xs_ctx);
890 /* Don't leave errors in the queue */
892 chain = X509_STORE_CTX_get0_chain(xs_ctx);
893 i = ssl_security_cert_chain(s, chain, NULL, 0);
896 /* Dummy error calls so mkerr generates them */
897 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
898 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
899 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
901 X509_STORE_CTX_free(xs_ctx);
902 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
905 chain_count = sk_X509_num(chain);
906 for (i = 0; i < chain_count; i++) {
907 x = sk_X509_value(chain, i);
909 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
910 X509_STORE_CTX_free(xs_ctx);
914 X509_STORE_CTX_free(xs_ctx);
916 i = ssl_security_cert_chain(s, extra_certs, x, 0);
918 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
921 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
923 for (i = 0; i < sk_X509_num(extra_certs); i++) {
924 x = sk_X509_value(extra_certs, i);
925 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
936 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
939 int tmpal = SSL_AD_INTERNAL_ERROR;
941 if (!WPACKET_start_sub_packet_u24(pkt)
942 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
943 || !WPACKET_close(pkt)) {
944 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
952 * Tidy up after the end of a handshake. In the case of SCTP this may result
953 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
956 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
958 void (*cb) (const SSL *ssl, int type, int val) = NULL;
960 #ifndef OPENSSL_NO_SCTP
961 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
963 ret = dtls_wait_for_dry(s);
964 if (ret != WORK_FINISHED_CONTINUE)
970 if (!SSL_IS_DTLS(s)) {
972 * We don't do this in DTLS because we may still need the init_buf
973 * in case there are any unexpected retransmits
975 BUF_MEM_free(s->init_buf);
978 ssl_free_wbio_buffer(s);
982 if (s->statem.cleanuphand) {
983 /* skipped if we just sent a HelloRequest */
986 s->statem.cleanuphand = 0;
988 ssl3_cleanup_key_block(s);
991 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
993 s->ctx->stats.sess_accept_good++;
994 s->handshake_func = ossl_statem_accept;
996 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
998 s->ctx->stats.sess_hit++;
1000 s->handshake_func = ossl_statem_connect;
1001 s->ctx->stats.sess_connect_good++;
1004 if (s->info_callback != NULL)
1005 cb = s->info_callback;
1006 else if (s->ctx->info_callback != NULL)
1007 cb = s->ctx->info_callback;
1010 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1012 if (SSL_IS_DTLS(s)) {
1013 /* done with handshaking */
1014 s->d1->handshake_read_seq = 0;
1015 s->d1->handshake_write_seq = 0;
1016 s->d1->next_handshake_write_seq = 0;
1017 dtls1_clear_received_buffer(s);
1022 * If we've not cleared the buffers its because we've got more work to do,
1026 return WORK_FINISHED_CONTINUE;
1028 ossl_statem_set_in_init(s, 0);
1029 return WORK_FINISHED_STOP;
1032 int tls_get_message_header(SSL *s, int *mt)
1034 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1035 int skip_message, i, recvd_type, al;
1037 size_t l, readbytes;
1039 p = (unsigned char *)s->init_buf->data;
1042 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1043 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1045 SSL3_HM_HEADER_LENGTH - s->init_num,
1048 s->rwstate = SSL_READING;
1051 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1053 * A ChangeCipherSpec must be a single byte and may not occur
1054 * in the middle of a handshake message.
1056 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1057 al = SSL_AD_UNEXPECTED_MESSAGE;
1058 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1059 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1062 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1063 s->init_num = readbytes - 1;
1064 s->init_msg = s->init_buf->data;
1065 s->s3->tmp.message_size = readbytes;
1067 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1068 al = SSL_AD_UNEXPECTED_MESSAGE;
1069 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1072 s->init_num += readbytes;
1077 if (s->statem.hand_state != TLS_ST_OK
1078 && p[0] == SSL3_MT_HELLO_REQUEST)
1080 * The server may always send 'Hello Request' messages --
1081 * we are doing a handshake anyway now, so ignore them if
1082 * their format is correct. Does not count for 'Finished'
1085 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1089 if (s->msg_callback)
1090 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1091 p, SSL3_HM_HEADER_LENGTH, s,
1092 s->msg_callback_arg);
1094 } while (skip_message);
1095 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1098 s->s3->tmp.message_type = *(p++);
1100 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1102 * Only happens with SSLv3+ in an SSLv2 backward compatible
1105 * Total message size is the remaining record bytes to read
1106 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1108 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1109 + SSL3_HM_HEADER_LENGTH;
1110 s->s3->tmp.message_size = l;
1112 s->init_msg = s->init_buf->data;
1113 s->init_num = SSL3_HM_HEADER_LENGTH;
1116 /* BUF_MEM_grow takes an 'int' parameter */
1117 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1118 al = SSL_AD_ILLEGAL_PARAMETER;
1119 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1122 s->s3->tmp.message_size = l;
1124 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1130 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1134 int tls_get_message_body(SSL *s, size_t *len)
1136 size_t n, readbytes;
1140 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1141 /* We've already read everything in */
1142 *len = (unsigned long)s->init_num;
1147 n = s->s3->tmp.message_size - s->init_num;
1149 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1150 &p[s->init_num], n, 0, &readbytes);
1152 s->rwstate = SSL_READING;
1156 s->init_num += readbytes;
1160 #ifndef OPENSSL_NO_NEXTPROTONEG
1162 * If receiving Finished, record MAC of prior handshake messages for
1163 * Finished verification.
1165 if (*s->init_buf->data == SSL3_MT_FINISHED)
1169 /* Feed this message into MAC computation. */
1170 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1171 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1173 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1174 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1178 if (s->msg_callback)
1179 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1180 (size_t)s->init_num, s, s->msg_callback_arg);
1183 * We defer feeding in the HRR until later. We'll do it as part of
1184 * processing the message
1186 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1187 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1188 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1189 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1190 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1194 if (s->msg_callback)
1195 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1196 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1197 s->msg_callback_arg);
1204 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1206 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1209 switch (EVP_PKEY_id(pk)) {
1213 return SSL_PKEY_RSA;
1215 return SSL_PKEY_DSA_SIGN;
1216 #ifndef OPENSSL_NO_EC
1218 return SSL_PKEY_ECC;
1220 #ifndef OPENSSL_NO_GOST
1221 case NID_id_GostR3410_2001:
1222 return SSL_PKEY_GOST01;
1223 case NID_id_GostR3410_2012_256:
1224 return SSL_PKEY_GOST12_256;
1225 case NID_id_GostR3410_2012_512:
1226 return SSL_PKEY_GOST12_512;
1231 int ssl_verify_alarm_type(long type)
1236 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1237 case X509_V_ERR_UNABLE_TO_GET_CRL:
1238 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1239 al = SSL_AD_UNKNOWN_CA;
1241 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1242 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1243 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1244 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1245 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1246 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1247 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1248 case X509_V_ERR_CERT_NOT_YET_VALID:
1249 case X509_V_ERR_CRL_NOT_YET_VALID:
1250 case X509_V_ERR_CERT_UNTRUSTED:
1251 case X509_V_ERR_CERT_REJECTED:
1252 case X509_V_ERR_HOSTNAME_MISMATCH:
1253 case X509_V_ERR_EMAIL_MISMATCH:
1254 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1255 case X509_V_ERR_DANE_NO_MATCH:
1256 case X509_V_ERR_EE_KEY_TOO_SMALL:
1257 case X509_V_ERR_CA_KEY_TOO_SMALL:
1258 case X509_V_ERR_CA_MD_TOO_WEAK:
1259 al = SSL_AD_BAD_CERTIFICATE;
1261 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1262 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1263 al = SSL_AD_DECRYPT_ERROR;
1265 case X509_V_ERR_CERT_HAS_EXPIRED:
1266 case X509_V_ERR_CRL_HAS_EXPIRED:
1267 al = SSL_AD_CERTIFICATE_EXPIRED;
1269 case X509_V_ERR_CERT_REVOKED:
1270 al = SSL_AD_CERTIFICATE_REVOKED;
1272 case X509_V_ERR_UNSPECIFIED:
1273 case X509_V_ERR_OUT_OF_MEM:
1274 case X509_V_ERR_INVALID_CALL:
1275 case X509_V_ERR_STORE_LOOKUP:
1276 al = SSL_AD_INTERNAL_ERROR;
1278 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1279 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1280 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1281 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1282 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1283 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1284 case X509_V_ERR_INVALID_CA:
1285 al = SSL_AD_UNKNOWN_CA;
1287 case X509_V_ERR_APPLICATION_VERIFICATION:
1288 al = SSL_AD_HANDSHAKE_FAILURE;
1290 case X509_V_ERR_INVALID_PURPOSE:
1291 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1294 al = SSL_AD_CERTIFICATE_UNKNOWN;
1300 int ssl_allow_compression(SSL *s)
1302 if (s->options & SSL_OP_NO_COMPRESSION)
1304 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1307 static int version_cmp(const SSL *s, int a, int b)
1309 int dtls = SSL_IS_DTLS(s);
1314 return a < b ? -1 : 1;
1315 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1320 const SSL_METHOD *(*cmeth) (void);
1321 const SSL_METHOD *(*smeth) (void);
1324 #if TLS_MAX_VERSION != TLS1_3_VERSION
1325 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1328 /* Must be in order high to low */
1329 static const version_info tls_version_table[] = {
1330 #ifndef OPENSSL_NO_TLS1_3
1331 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1333 {TLS1_3_VERSION, NULL, NULL},
1335 #ifndef OPENSSL_NO_TLS1_2
1336 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1338 {TLS1_2_VERSION, NULL, NULL},
1340 #ifndef OPENSSL_NO_TLS1_1
1341 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1343 {TLS1_1_VERSION, NULL, NULL},
1345 #ifndef OPENSSL_NO_TLS1
1346 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1348 {TLS1_VERSION, NULL, NULL},
1350 #ifndef OPENSSL_NO_SSL3
1351 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1353 {SSL3_VERSION, NULL, NULL},
1358 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1359 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1362 /* Must be in order high to low */
1363 static const version_info dtls_version_table[] = {
1364 #ifndef OPENSSL_NO_DTLS1_2
1365 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1367 {DTLS1_2_VERSION, NULL, NULL},
1369 #ifndef OPENSSL_NO_DTLS1
1370 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1371 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1373 {DTLS1_VERSION, NULL, NULL},
1374 {DTLS1_BAD_VER, NULL, NULL},
1380 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1382 * @s: The SSL handle for the candidate method
1383 * @method: the intended method.
1385 * Returns 0 on success, or an SSL error reason on failure.
1387 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1389 int version = method->version;
1391 if ((s->min_proto_version != 0 &&
1392 version_cmp(s, version, s->min_proto_version) < 0) ||
1393 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1394 return SSL_R_VERSION_TOO_LOW;
1396 if (s->max_proto_version != 0 &&
1397 version_cmp(s, version, s->max_proto_version) > 0)
1398 return SSL_R_VERSION_TOO_HIGH;
1400 if ((s->options & method->mask) != 0)
1401 return SSL_R_UNSUPPORTED_PROTOCOL;
1402 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1403 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1409 * ssl_version_supported - Check that the specified `version` is supported by
1412 * @s: The SSL handle for the candidate method
1413 * @version: Protocol version to test against
1415 * Returns 1 when supported, otherwise 0
1417 int ssl_version_supported(const SSL *s, int version)
1419 const version_info *vent;
1420 const version_info *table;
1422 switch (s->method->version) {
1424 /* Version should match method version for non-ANY method */
1425 return version_cmp(s, version, s->version) == 0;
1426 case TLS_ANY_VERSION:
1427 table = tls_version_table;
1429 case DTLS_ANY_VERSION:
1430 table = dtls_version_table;
1435 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1437 if (vent->cmeth != NULL &&
1438 version_cmp(s, version, vent->version) == 0 &&
1439 ssl_method_error(s, vent->cmeth()) == 0) {
1447 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1448 * fallback indication from a client check whether we're using the highest
1449 * supported protocol version.
1451 * @s server SSL handle.
1453 * Returns 1 when using the highest enabled version, 0 otherwise.
1455 int ssl_check_version_downgrade(SSL *s)
1457 const version_info *vent;
1458 const version_info *table;
1461 * Check that the current protocol is the highest enabled version
1462 * (according to s->ctx->method, as version negotiation may have changed
1465 if (s->version == s->ctx->method->version)
1469 * Apparently we're using a version-flexible SSL_METHOD (not at its
1470 * highest protocol version).
1472 if (s->ctx->method->version == TLS_method()->version)
1473 table = tls_version_table;
1474 else if (s->ctx->method->version == DTLS_method()->version)
1475 table = dtls_version_table;
1477 /* Unexpected state; fail closed. */
1481 for (vent = table; vent->version != 0; ++vent) {
1482 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1483 return s->version == vent->version;
1489 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1490 * protocols, provided the initial (D)TLS method is version-flexible. This
1491 * function sanity-checks the proposed value and makes sure the method is
1492 * version-flexible, then sets the limit if all is well.
1494 * @method_version: The version of the current SSL_METHOD.
1495 * @version: the intended limit.
1496 * @bound: pointer to limit to be updated.
1498 * Returns 1 on success, 0 on failure.
1500 int ssl_set_version_bound(int method_version, int version, int *bound)
1508 * Restrict TLS methods to TLS protocol versions.
1509 * Restrict DTLS methods to DTLS protocol versions.
1510 * Note, DTLS version numbers are decreasing, use comparison macros.
1512 * Note that for both lower-bounds we use explicit versions, not
1513 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1514 * configurations. If the MIN (supported) version ever rises, the user's
1515 * "floor" remains valid even if no longer available. We don't expect the
1516 * MAX ceiling to ever get lower, so making that variable makes sense.
1518 switch (method_version) {
1521 * XXX For fixed version methods, should we always fail and not set any
1522 * bounds, always succeed and not set any bounds, or set the bounds and
1523 * arrange to fail later if they are not met? At present fixed-version
1524 * methods are not subject to controls that disable individual protocol
1529 case TLS_ANY_VERSION:
1530 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1534 case DTLS_ANY_VERSION:
1535 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1536 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1545 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1547 if (vers == TLS1_2_VERSION
1548 && ssl_version_supported(s, TLS1_3_VERSION)) {
1549 *dgrd = DOWNGRADE_TO_1_2;
1550 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1551 && (ssl_version_supported(s, TLS1_2_VERSION)
1552 || ssl_version_supported(s, TLS1_3_VERSION))) {
1553 *dgrd = DOWNGRADE_TO_1_1;
1555 *dgrd = DOWNGRADE_NONE;
1560 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1561 * client HELLO is received to select the final server protocol version and
1562 * the version specific method.
1564 * @s: server SSL handle.
1566 * Returns 0 on success or an SSL error reason number on failure.
1568 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1571 * With version-flexible methods we have an initial state with:
1573 * s->method->version == (D)TLS_ANY_VERSION,
1574 * s->version == (D)TLS_MAX_VERSION.
1576 * So we detect version-flexible methods via the method version, not the
1579 int server_version = s->method->version;
1580 int client_version = hello->legacy_version;
1581 const version_info *vent;
1582 const version_info *table;
1584 RAW_EXTENSION *suppversions;
1586 s->client_version = client_version;
1588 switch (server_version) {
1590 if (!SSL_IS_TLS13(s)) {
1591 if (version_cmp(s, client_version, s->version) < 0)
1592 return SSL_R_WRONG_SSL_VERSION;
1593 *dgrd = DOWNGRADE_NONE;
1595 * If this SSL handle is not from a version flexible method we don't
1596 * (and never did) check min/max FIPS or Suite B constraints. Hope
1597 * that's OK. It is up to the caller to not choose fixed protocol
1598 * versions they don't want. If not, then easy to fix, just return
1599 * ssl_method_error(s, s->method)
1604 * Fall through if we are TLSv1.3 already (this means we must be after
1605 * a HelloRetryRequest
1607 case TLS_ANY_VERSION:
1608 table = tls_version_table;
1610 case DTLS_ANY_VERSION:
1611 table = dtls_version_table;
1615 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1617 if (suppversions->present && !SSL_IS_DTLS(s)) {
1618 unsigned int candidate_vers = 0;
1619 unsigned int best_vers = 0;
1620 const SSL_METHOD *best_method = NULL;
1621 PACKET versionslist;
1623 suppversions->parsed = 1;
1625 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1626 /* Trailing or invalid data? */
1627 return SSL_R_LENGTH_MISMATCH;
1630 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1631 /* TODO(TLS1.3): Remove this before release */
1632 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1633 candidate_vers = TLS1_3_VERSION;
1635 * TODO(TLS1.3): There is some discussion on the TLS list about
1636 * whether to ignore versions <TLS1.2 in supported_versions. At the
1637 * moment we honour them if present. To be reviewed later
1639 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1642 vent->version != 0 && vent->version != (int)candidate_vers;
1645 if (vent->version != 0 && vent->smeth != NULL) {
1646 const SSL_METHOD *method;
1648 method = vent->smeth();
1649 if (ssl_method_error(s, method) == 0) {
1650 best_vers = candidate_vers;
1651 best_method = method;
1655 if (PACKET_remaining(&versionslist) != 0) {
1656 /* Trailing data? */
1657 return SSL_R_LENGTH_MISMATCH;
1660 if (best_vers > 0) {
1661 if (SSL_IS_TLS13(s)) {
1663 * We get here if this is after a HelloRetryRequest. In this
1664 * case we just check that we still negotiated TLSv1.3
1666 if (best_vers != TLS1_3_VERSION)
1667 return SSL_R_UNSUPPORTED_PROTOCOL;
1670 check_for_downgrade(s, best_vers, dgrd);
1671 s->version = best_vers;
1672 s->method = best_method;
1675 return SSL_R_UNSUPPORTED_PROTOCOL;
1679 * If the supported versions extension isn't present, then the highest
1680 * version we can negotiate is TLSv1.2
1682 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1683 client_version = TLS1_2_VERSION;
1686 * No supported versions extension, so we just use the version supplied in
1689 for (vent = table; vent->version != 0; ++vent) {
1690 const SSL_METHOD *method;
1692 if (vent->smeth == NULL ||
1693 version_cmp(s, client_version, vent->version) < 0)
1695 method = vent->smeth();
1696 if (ssl_method_error(s, method) == 0) {
1697 check_for_downgrade(s, vent->version, dgrd);
1698 s->version = vent->version;
1704 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1708 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1709 * server HELLO is received to select the final client protocol version and
1710 * the version specific method.
1712 * @s: client SSL handle.
1713 * @version: The proposed version from the server's HELLO.
1714 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1715 * @al: Where to store any alert value that may be generated
1717 * Returns 0 on success or an SSL error reason number on failure.
1719 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1721 const version_info *vent;
1722 const version_info *table;
1725 /* TODO(TLS1.3): Remove this before release */
1726 if (version == TLS1_3_VERSION_DRAFT)
1727 version = TLS1_3_VERSION;
1729 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1730 *al = SSL_AD_PROTOCOL_VERSION;
1731 return SSL_R_WRONG_SSL_VERSION;
1734 switch (s->method->version) {
1736 if (version != s->version) {
1737 *al = SSL_AD_PROTOCOL_VERSION;
1738 return SSL_R_WRONG_SSL_VERSION;
1741 * If this SSL handle is not from a version flexible method we don't
1742 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1743 * that's OK. It is up to the caller to not choose fixed protocol
1744 * versions they don't want. If not, then easy to fix, just return
1745 * ssl_method_error(s, s->method)
1748 case TLS_ANY_VERSION:
1749 table = tls_version_table;
1751 case DTLS_ANY_VERSION:
1752 table = dtls_version_table;
1756 for (vent = table; vent->version != 0; ++vent) {
1757 const SSL_METHOD *method;
1760 if (vent->cmeth == NULL)
1763 if (highver != 0 && version != vent->version)
1766 method = vent->cmeth();
1767 err = ssl_method_error(s, method);
1769 if (version == vent->version) {
1770 *al = SSL_AD_PROTOCOL_VERSION;
1777 highver = vent->version;
1779 if (version != vent->version)
1782 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1783 /* Check for downgrades */
1785 if (version == TLS1_2_VERSION && highver > version) {
1786 if (memcmp(tls12downgrade,
1787 s->s3->server_random + SSL3_RANDOM_SIZE
1788 - sizeof(tls12downgrade),
1789 sizeof(tls12downgrade)) == 0) {
1790 *al = SSL_AD_ILLEGAL_PARAMETER;
1791 return SSL_R_INAPPROPRIATE_FALLBACK;
1793 } else if (!SSL_IS_DTLS(s)
1794 && version < TLS1_2_VERSION
1795 && highver > version) {
1796 if (memcmp(tls11downgrade,
1797 s->s3->server_random + SSL3_RANDOM_SIZE
1798 - sizeof(tls11downgrade),
1799 sizeof(tls11downgrade)) == 0) {
1800 *al = SSL_AD_ILLEGAL_PARAMETER;
1801 return SSL_R_INAPPROPRIATE_FALLBACK;
1808 s->version = version;
1812 *al = SSL_AD_PROTOCOL_VERSION;
1813 return SSL_R_UNSUPPORTED_PROTOCOL;
1817 * ssl_get_min_max_version - get minimum and maximum protocol version
1818 * @s: The SSL connection
1819 * @min_version: The minimum supported version
1820 * @max_version: The maximum supported version
1822 * Work out what version we should be using for the initial ClientHello if the
1823 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1824 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1825 * constraints and any floor imposed by the security level here,
1826 * so we don't advertise the wrong protocol version to only reject the outcome later.
1828 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
1829 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1830 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1832 * Returns 0 on success or an SSL error reason number on failure. On failure
1833 * min_version and max_version will also be set to 0.
1835 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1839 const SSL_METHOD *single = NULL;
1840 const SSL_METHOD *method;
1841 const version_info *table;
1842 const version_info *vent;
1844 switch (s->method->version) {
1847 * If this SSL handle is not from a version flexible method we don't
1848 * (and never did) check min/max FIPS or Suite B constraints. Hope
1849 * that's OK. It is up to the caller to not choose fixed protocol
1850 * versions they don't want. If not, then easy to fix, just return
1851 * ssl_method_error(s, s->method)
1853 *min_version = *max_version = s->version;
1855 case TLS_ANY_VERSION:
1856 table = tls_version_table;
1858 case DTLS_ANY_VERSION:
1859 table = dtls_version_table;
1864 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1865 * below X enabled. This is required in order to maintain the "version
1866 * capability" vector contiguous. Any versions with a NULL client method
1867 * (protocol version client is disabled at compile-time) is also a "hole".
1869 * Our initial state is hole == 1, version == 0. That is, versions above
1870 * the first version in the method table are disabled (a "hole" above
1871 * the valid protocol entries) and we don't have a selected version yet.
1873 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1874 * the selected version, and the method becomes a candidate "single"
1875 * method. We're no longer in a hole, so "hole" becomes 0.
1877 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1878 * as we support a contiguous range of at least two methods. If we hit
1879 * a disabled method, then hole becomes true again, but nothing else
1880 * changes yet, because all the remaining methods may be disabled too.
1881 * If we again hit an enabled method after the new hole, it becomes
1882 * selected, as we start from scratch.
1884 *min_version = version = 0;
1886 for (vent = table; vent->version != 0; ++vent) {
1888 * A table entry with a NULL client method is still a hole in the
1889 * "version capability" vector.
1891 if (vent->cmeth == NULL) {
1895 method = vent->cmeth();
1896 if (ssl_method_error(s, method) != 0) {
1900 *min_version = method->version;
1902 version = (single = method)->version;
1903 *min_version = version;
1908 *max_version = version;
1910 /* Fail if everything is disabled */
1912 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1918 * ssl_set_client_hello_version - Work out what version we should be using for
1919 * the initial ClientHello.legacy_version field.
1921 * @s: client SSL handle.
1923 * Returns 0 on success or an SSL error reason number on failure.
1925 int ssl_set_client_hello_version(SSL *s)
1927 int ver_min, ver_max, ret;
1929 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
1934 s->version = ver_max;
1936 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1937 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1938 ver_max = TLS1_2_VERSION;
1940 s->client_version = ver_max;
1945 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1946 * and |checkallow| is 1 then additionally check if the group is allowed to be
1947 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1948 * 1) or 0 otherwise.
1950 #ifndef OPENSSL_NO_EC
1951 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1952 size_t num_groups, int checkallow)
1956 if (groups == NULL || num_groups == 0)
1959 for (i = 0; i < num_groups; i++, groups += 2) {
1960 unsigned int share_id = (groups[0] << 8) | (groups[1]);
1962 if (group_id == share_id
1964 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
1973 /* Replace ClientHello1 in the transcript hash with a synthetic message */
1974 int create_synthetic_message_hash(SSL *s)
1976 unsigned char hashval[EVP_MAX_MD_SIZE];
1978 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
1980 memset(msghdr, 0, sizeof(msghdr));
1982 /* Get the hash of the initial ClientHello */
1983 if (!ssl3_digest_cached_records(s, 0)
1984 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
1985 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
1989 /* Reinitialise the transcript hash */
1990 if (!ssl3_init_finished_mac(s))
1993 /* Inject the synthetic message_hash message */
1994 msghdr[0] = SSL3_MT_MESSAGE_HASH;
1995 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
1996 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
1997 || !ssl3_finish_mac(s, hashval, hashlen)) {
1998 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2005 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2007 return X509_NAME_cmp(*a, *b);
2010 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2012 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2013 X509_NAME *xn = NULL;
2016 if (ca_sk == NULL) {
2017 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2020 /* get the CA RDNs */
2021 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2022 *al = SSL_AD_DECODE_ERROR;
2023 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2027 while (PACKET_remaining(&cadns)) {
2028 const unsigned char *namestart, *namebytes;
2029 unsigned int name_len;
2031 if (!PACKET_get_net_2(&cadns, &name_len)
2032 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2033 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2037 namestart = namebytes;
2038 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2039 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2042 if (namebytes != (namestart + name_len)) {
2043 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2047 if (!sk_X509_NAME_push(ca_sk, xn)) {
2048 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2049 *al = SSL_AD_INTERNAL_ERROR;
2055 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2056 s->s3->tmp.peer_ca_names = ca_sk;
2061 *al = SSL_AD_DECODE_ERROR;
2063 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2068 int construct_ca_names(SSL *s, WPACKET *pkt)
2070 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2072 /* Start sub-packet for client CA list */
2073 if (!WPACKET_start_sub_packet_u16(pkt))
2076 if (ca_sk != NULL) {
2079 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2080 unsigned char *namebytes;
2081 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2085 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2086 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2088 || i2d_X509_NAME(name, &namebytes) != namelen) {
2094 if (!WPACKET_close(pkt))