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))
80 /* Reset any extension flags */
81 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
84 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
85 int i, ver_min, ver_max, ok = 0;
88 * Sanity check that the maximum version we accept has ciphers
89 * enabled. For clients we do this check during construction of the
92 if (ssl_get_min_max_version(s, &ver_min, &ver_max) != 0) {
93 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, ERR_R_INTERNAL_ERROR);
94 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
97 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
98 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
100 if (SSL_IS_DTLS(s)) {
101 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
102 DTLS_VERSION_LE(ver_max, c->max_dtls))
104 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
111 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, SSL_R_NO_CIPHERS_AVAILABLE);
112 ERR_add_error_data(1, "No ciphers enabled for max supported "
114 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
117 if (SSL_IS_FIRST_HANDSHAKE(s)) {
118 s->ctx->stats.sess_accept++;
119 } else if (!s->s3->send_connection_binding &&
121 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
123 * Server attempting to renegotiate with client that doesn't
124 * support secure renegotiation.
126 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
127 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
128 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
131 s->ctx->stats.sess_accept_renegotiate++;
133 s->s3->tmp.cert_request = 0;
136 if (SSL_IS_FIRST_HANDSHAKE(s))
137 s->ctx->stats.sess_connect++;
139 s->ctx->stats.sess_connect_renegotiate++;
141 /* mark client_random uninitialized */
142 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
145 s->s3->tmp.cert_req = 0;
148 s->statem.use_timer = 1;
155 * Size of the to-be-signed TLS13 data, without the hash size itself:
156 * 64 bytes of value 32, 33 context bytes, 1 byte separator
158 #define TLS13_TBS_START_SIZE 64
159 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
161 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
162 void **hdata, size_t *hdatalen)
164 static const char *servercontext = "TLS 1.3, server CertificateVerify";
165 static const char *clientcontext = "TLS 1.3, client CertificateVerify";
167 if (SSL_IS_TLS13(s)) {
170 /* Set the first 64 bytes of to-be-signed data to octet 32 */
171 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
172 /* This copies the 33 bytes of context plus the 0 separator byte */
173 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
174 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
175 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
177 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
180 * If we're currently reading then we need to use the saved handshake
181 * hash value. We can't use the current handshake hash state because
182 * that includes the CertVerify itself.
184 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
185 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
186 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
187 s->cert_verify_hash_len);
188 hashlen = s->cert_verify_hash_len;
189 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
190 EVP_MAX_MD_SIZE, &hashlen)) {
195 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
199 retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
208 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
210 EVP_PKEY *pkey = NULL;
211 const EVP_MD *md = NULL;
212 EVP_MD_CTX *mctx = NULL;
213 EVP_PKEY_CTX *pctx = NULL;
214 size_t hdatalen = 0, siglen = 0;
216 unsigned char *sig = NULL;
217 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
218 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
220 if (lu == NULL || s->s3->tmp.cert == NULL) {
221 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
224 pkey = s->s3->tmp.cert->privatekey;
225 md = ssl_md(lu->hash_idx);
227 if (pkey == NULL || md == NULL) {
228 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
232 mctx = EVP_MD_CTX_new();
234 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
238 /* Get the data to be signed */
239 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
240 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
244 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
245 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
248 siglen = EVP_PKEY_size(pkey);
249 sig = OPENSSL_malloc(siglen);
251 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
255 if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
256 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
260 if (lu->sig == EVP_PKEY_RSA_PSS) {
261 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
262 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
263 RSA_PSS_SALTLEN_DIGEST) <= 0) {
264 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
267 } else if (s->version == SSL3_VERSION) {
268 if (!EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
269 (int)s->session->master_key_length,
270 s->session->master_key)) {
271 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
276 if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
277 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
281 #ifndef OPENSSL_NO_GOST
283 int pktype = lu->sig;
285 if (pktype == NID_id_GostR3410_2001
286 || pktype == NID_id_GostR3410_2012_256
287 || pktype == NID_id_GostR3410_2012_512)
288 BUF_reverse(sig, NULL, siglen);
292 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
293 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
297 /* Digest cached records and discard handshake buffer */
298 if (!ssl3_digest_cached_records(s, 0))
302 EVP_MD_CTX_free(mctx);
306 EVP_MD_CTX_free(mctx);
307 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
311 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
313 EVP_PKEY *pkey = NULL;
314 const unsigned char *data;
315 #ifndef OPENSSL_NO_GOST
316 unsigned char *gost_data = NULL;
318 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
322 const EVP_MD *md = NULL;
325 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
326 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
327 EVP_PKEY_CTX *pctx = NULL;
330 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
334 peer = s->session->peer;
335 pkey = X509_get0_pubkey(peer);
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 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
416 #ifndef OPENSSL_NO_GOST
418 int pktype = EVP_PKEY_id(pkey);
419 if (pktype == NID_id_GostR3410_2001
420 || pktype == NID_id_GostR3410_2012_256
421 || pktype == NID_id_GostR3410_2012_512) {
422 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
423 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
426 BUF_reverse(gost_data, data, len);
432 if (SSL_USE_PSS(s)) {
433 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
434 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
435 RSA_PSS_SALTLEN_DIGEST) <= 0) {
436 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
439 } else if (s->version == SSL3_VERSION
440 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
441 (int)s->session->master_key_length,
442 s->session->master_key)) {
443 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
447 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
450 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
453 al = SSL_AD_DECRYPT_ERROR;
454 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
458 ret = MSG_PROCESS_CONTINUE_READING;
461 ssl3_send_alert(s, SSL3_AL_FATAL, al);
462 ossl_statem_set_error(s);
464 BIO_free(s->s3->handshake_buffer);
465 s->s3->handshake_buffer = NULL;
466 EVP_MD_CTX_free(mctx);
467 #ifndef OPENSSL_NO_GOST
468 OPENSSL_free(gost_data);
473 int tls_construct_finished(SSL *s, WPACKET *pkt)
475 size_t finish_md_len;
479 /* This is a real handshake so make sure we clean it up at the end */
481 s->statem.cleanuphand = 1;
484 * We only change the keys if we didn't already do this when we sent the
489 && s->s3->tmp.cert_req == 0
490 && (!s->method->ssl3_enc->change_cipher_state(s,
491 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
492 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
497 sender = s->method->ssl3_enc->server_finished_label;
498 slen = s->method->ssl3_enc->server_finished_label_len;
500 sender = s->method->ssl3_enc->client_finished_label;
501 slen = s->method->ssl3_enc->client_finished_label_len;
504 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
506 s->s3->tmp.finish_md);
507 if (finish_md_len == 0) {
508 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
512 s->s3->tmp.finish_md_len = finish_md_len;
514 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
515 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
520 * Log the master secret, if logging is enabled. We don't log it for
521 * TLSv1.3: there's a different key schedule for that.
523 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
524 s->session->master_key,
525 s->session->master_key_length)) {
526 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
531 * Copy the finished so we can use it for renegotiation checks
533 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
534 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
538 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
540 s->s3->previous_client_finished_len = finish_md_len;
542 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
544 s->s3->previous_server_finished_len = finish_md_len;
549 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
553 int tls_construct_key_update(SSL *s, WPACKET *pkt)
555 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
556 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
560 s->key_update = SSL_KEY_UPDATE_NONE;
564 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
568 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
571 unsigned int updatetype;
573 s->key_update_count++;
574 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
575 al = SSL_AD_ILLEGAL_PARAMETER;
576 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
581 * A KeyUpdate message signals a key change so the end of the message must
582 * be on a record boundary.
584 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
585 al = SSL_AD_UNEXPECTED_MESSAGE;
586 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
590 if (!PACKET_get_1(pkt, &updatetype)
591 || PACKET_remaining(pkt) != 0) {
592 al = SSL_AD_DECODE_ERROR;
593 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
598 * There are only two defined key update types. Fail if we get a value we
601 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
602 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
603 al = SSL_AD_ILLEGAL_PARAMETER;
604 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
609 * If we get a request for us to update our sending keys too then, we need
610 * to additionally send a KeyUpdate message. However that message should
611 * not also request an update (otherwise we get into an infinite loop).
613 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
614 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
616 if (!tls13_update_key(s, 0)) {
617 al = SSL_AD_INTERNAL_ERROR;
618 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
622 return MSG_PROCESS_FINISHED_READING;
624 ssl3_send_alert(s, SSL3_AL_FATAL, al);
625 ossl_statem_set_error(s);
626 return MSG_PROCESS_ERROR;
629 #ifndef OPENSSL_NO_NEXTPROTONEG
631 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
634 static void ssl3_take_mac(SSL *s)
639 * If no new cipher setup return immediately: other functions will set
640 * the appropriate error.
642 if (s->s3->tmp.new_cipher == NULL)
645 sender = s->method->ssl3_enc->server_finished_label;
646 slen = s->method->ssl3_enc->server_finished_label_len;
648 sender = s->method->ssl3_enc->client_finished_label;
649 slen = s->method->ssl3_enc->client_finished_label_len;
652 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
655 s->s3->tmp.peer_finish_md);
659 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
664 remain = PACKET_remaining(pkt);
666 * 'Change Cipher Spec' is just a single byte, which should already have
667 * been consumed by ssl_get_message() so there should be no bytes left,
668 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
670 if (SSL_IS_DTLS(s)) {
671 if ((s->version == DTLS1_BAD_VER
672 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
673 || (s->version != DTLS1_BAD_VER
674 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
675 al = SSL_AD_DECODE_ERROR;
676 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
677 SSL_R_BAD_CHANGE_CIPHER_SPEC);
682 al = SSL_AD_DECODE_ERROR;
683 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
684 SSL_R_BAD_CHANGE_CIPHER_SPEC);
689 /* Check we have a cipher to change to */
690 if (s->s3->tmp.new_cipher == NULL) {
691 al = SSL_AD_UNEXPECTED_MESSAGE;
692 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
696 s->s3->change_cipher_spec = 1;
697 if (!ssl3_do_change_cipher_spec(s)) {
698 al = SSL_AD_INTERNAL_ERROR;
699 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
703 if (SSL_IS_DTLS(s)) {
704 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
706 if (s->version == DTLS1_BAD_VER)
707 s->d1->handshake_read_seq++;
709 #ifndef OPENSSL_NO_SCTP
711 * Remember that a CCS has been received, so that an old key of
712 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
715 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
719 return MSG_PROCESS_CONTINUE_READING;
721 ssl3_send_alert(s, SSL3_AL_FATAL, al);
722 ossl_statem_set_error(s);
723 return MSG_PROCESS_ERROR;
726 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
728 int al = SSL_AD_INTERNAL_ERROR;
732 /* This is a real handshake so make sure we clean it up at the end */
734 s->statem.cleanuphand = 1;
737 * In TLSv1.3 a Finished message signals a key change so the end of the
738 * message must be on a record boundary.
740 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
741 al = SSL_AD_UNEXPECTED_MESSAGE;
742 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
746 /* If this occurs, we have missed a message */
747 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
748 al = SSL_AD_UNEXPECTED_MESSAGE;
749 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
752 s->s3->change_cipher_spec = 0;
754 md_len = s->s3->tmp.peer_finish_md_len;
756 if (md_len != PACKET_remaining(pkt)) {
757 al = SSL_AD_DECODE_ERROR;
758 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
762 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
764 al = SSL_AD_DECRYPT_ERROR;
765 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
770 * Copy the finished so we can use it for renegotiation checks
772 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
773 al = SSL_AD_INTERNAL_ERROR;
774 SSLerr(SSL_F_TLS_PROCESS_FINISHED, ERR_R_INTERNAL_ERROR);
778 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
780 s->s3->previous_client_finished_len = md_len;
782 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
784 s->s3->previous_server_finished_len = md_len;
788 * In TLS1.3 we also have to change cipher state and do any final processing
789 * of the initial server flight (if we are a client)
791 if (SSL_IS_TLS13(s)) {
793 if (!s->method->ssl3_enc->change_cipher_state(s,
794 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
795 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
799 if (!s->method->ssl3_enc->generate_master_secret(s,
800 s->master_secret, s->handshake_secret, 0,
801 &s->session->master_key_length)) {
802 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
805 if (!s->method->ssl3_enc->change_cipher_state(s,
806 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
807 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
810 if (!tls_process_initial_server_flight(s, &al))
815 return MSG_PROCESS_FINISHED_READING;
817 ssl3_send_alert(s, SSL3_AL_FATAL, al);
818 ossl_statem_set_error(s);
819 return MSG_PROCESS_ERROR;
822 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
824 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
825 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
826 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
833 /* Add a certificate to the WPACKET */
834 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
838 unsigned char *outbytes;
840 len = i2d_X509(x, NULL);
842 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
843 *al = SSL_AD_INTERNAL_ERROR;
846 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
847 || i2d_X509(x, &outbytes) != len) {
848 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
849 *al = SSL_AD_INTERNAL_ERROR;
854 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
861 /* Add certificate chain to provided WPACKET */
862 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
866 STACK_OF(X509) *extra_certs;
867 STACK_OF(X509) *chain = NULL;
868 X509_STORE *chain_store;
869 int tmpal = SSL_AD_INTERNAL_ERROR;
871 if (cpk == NULL || cpk->x509 == NULL)
877 * If we have a certificate specific chain use it, else use parent ctx.
879 if (cpk->chain != NULL)
880 extra_certs = cpk->chain;
882 extra_certs = s->ctx->extra_certs;
884 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
886 else if (s->cert->chain_store)
887 chain_store = s->cert->chain_store;
889 chain_store = s->ctx->cert_store;
891 if (chain_store != NULL) {
892 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
894 if (xs_ctx == NULL) {
895 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
898 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
899 X509_STORE_CTX_free(xs_ctx);
900 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
904 * It is valid for the chain not to be complete (because normally we
905 * don't include the root cert in the chain). Therefore we deliberately
906 * ignore the error return from this call. We're not actually verifying
907 * the cert - we're just building as much of the chain as we can
909 (void)X509_verify_cert(xs_ctx);
910 /* Don't leave errors in the queue */
912 chain = X509_STORE_CTX_get0_chain(xs_ctx);
913 i = ssl_security_cert_chain(s, chain, NULL, 0);
916 /* Dummy error calls so mkerr generates them */
917 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
918 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
919 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
921 X509_STORE_CTX_free(xs_ctx);
922 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
925 chain_count = sk_X509_num(chain);
926 for (i = 0; i < chain_count; i++) {
927 x = sk_X509_value(chain, i);
929 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
930 X509_STORE_CTX_free(xs_ctx);
934 X509_STORE_CTX_free(xs_ctx);
936 i = ssl_security_cert_chain(s, extra_certs, x, 0);
938 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
941 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
943 for (i = 0; i < sk_X509_num(extra_certs); i++) {
944 x = sk_X509_value(extra_certs, i);
945 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
956 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
959 int tmpal = SSL_AD_INTERNAL_ERROR;
961 if (!WPACKET_start_sub_packet_u24(pkt)
962 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
963 || !WPACKET_close(pkt)) {
964 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
972 * Tidy up after the end of a handshake. In the case of SCTP this may result
973 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
976 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
978 void (*cb) (const SSL *ssl, int type, int val) = NULL;
980 #ifndef OPENSSL_NO_SCTP
981 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
983 ret = dtls_wait_for_dry(s);
984 if (ret != WORK_FINISHED_CONTINUE)
990 if (!SSL_IS_DTLS(s)) {
992 * We don't do this in DTLS because we may still need the init_buf
993 * in case there are any unexpected retransmits
995 BUF_MEM_free(s->init_buf);
998 if (!ssl_free_wbio_buffer(s))
1003 if (s->statem.cleanuphand) {
1004 /* skipped if we just sent a HelloRequest */
1007 s->statem.cleanuphand = 0;
1009 ssl3_cleanup_key_block(s);
1012 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1014 s->ctx->stats.sess_accept_good++;
1015 s->handshake_func = ossl_statem_accept;
1017 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1019 s->ctx->stats.sess_hit++;
1021 s->handshake_func = ossl_statem_connect;
1022 s->ctx->stats.sess_connect_good++;
1025 if (s->info_callback != NULL)
1026 cb = s->info_callback;
1027 else if (s->ctx->info_callback != NULL)
1028 cb = s->ctx->info_callback;
1031 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1033 if (SSL_IS_DTLS(s)) {
1034 /* done with handshaking */
1035 s->d1->handshake_read_seq = 0;
1036 s->d1->handshake_write_seq = 0;
1037 s->d1->next_handshake_write_seq = 0;
1038 dtls1_clear_received_buffer(s);
1043 * If we've not cleared the buffers its because we've got more work to do,
1047 return WORK_FINISHED_CONTINUE;
1049 ossl_statem_set_in_init(s, 0);
1050 return WORK_FINISHED_STOP;
1053 int tls_get_message_header(SSL *s, int *mt)
1055 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1056 int skip_message, i, recvd_type, al;
1058 size_t l, readbytes;
1060 p = (unsigned char *)s->init_buf->data;
1063 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1064 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1066 SSL3_HM_HEADER_LENGTH - s->init_num,
1069 s->rwstate = SSL_READING;
1072 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1074 * A ChangeCipherSpec must be a single byte and may not occur
1075 * in the middle of a handshake message.
1077 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1078 al = SSL_AD_UNEXPECTED_MESSAGE;
1079 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1080 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1083 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1084 s->init_num = readbytes - 1;
1085 s->init_msg = s->init_buf->data;
1086 s->s3->tmp.message_size = readbytes;
1088 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1089 al = SSL_AD_UNEXPECTED_MESSAGE;
1090 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1093 s->init_num += readbytes;
1098 if (s->statem.hand_state != TLS_ST_OK
1099 && p[0] == SSL3_MT_HELLO_REQUEST)
1101 * The server may always send 'Hello Request' messages --
1102 * we are doing a handshake anyway now, so ignore them if
1103 * their format is correct. Does not count for 'Finished'
1106 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1110 if (s->msg_callback)
1111 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1112 p, SSL3_HM_HEADER_LENGTH, s,
1113 s->msg_callback_arg);
1115 } while (skip_message);
1116 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1119 s->s3->tmp.message_type = *(p++);
1121 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1123 * Only happens with SSLv3+ in an SSLv2 backward compatible
1126 * Total message size is the remaining record bytes to read
1127 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1129 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1130 + SSL3_HM_HEADER_LENGTH;
1131 s->s3->tmp.message_size = l;
1133 s->init_msg = s->init_buf->data;
1134 s->init_num = SSL3_HM_HEADER_LENGTH;
1137 /* BUF_MEM_grow takes an 'int' parameter */
1138 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1139 al = SSL_AD_ILLEGAL_PARAMETER;
1140 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1143 s->s3->tmp.message_size = l;
1145 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1151 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1155 int tls_get_message_body(SSL *s, size_t *len)
1157 size_t n, readbytes;
1161 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1162 /* We've already read everything in */
1163 *len = (unsigned long)s->init_num;
1168 n = s->s3->tmp.message_size - s->init_num;
1170 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1171 &p[s->init_num], n, 0, &readbytes);
1173 s->rwstate = SSL_READING;
1177 s->init_num += readbytes;
1181 #ifndef OPENSSL_NO_NEXTPROTONEG
1183 * If receiving Finished, record MAC of prior handshake messages for
1184 * Finished verification.
1186 if (*s->init_buf->data == SSL3_MT_FINISHED)
1190 /* Feed this message into MAC computation. */
1191 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1192 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1194 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1195 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1199 if (s->msg_callback)
1200 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1201 (size_t)s->init_num, s, s->msg_callback_arg);
1204 * We defer feeding in the HRR until later. We'll do it as part of
1205 * processing the message
1207 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1208 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1209 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1210 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1211 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1215 if (s->msg_callback)
1216 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1217 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1218 s->msg_callback_arg);
1225 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1227 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1230 switch (EVP_PKEY_id(pk)) {
1234 return SSL_PKEY_RSA;
1236 return SSL_PKEY_DSA_SIGN;
1237 #ifndef OPENSSL_NO_EC
1239 return SSL_PKEY_ECC;
1241 #ifndef OPENSSL_NO_GOST
1242 case NID_id_GostR3410_2001:
1243 return SSL_PKEY_GOST01;
1244 case NID_id_GostR3410_2012_256:
1245 return SSL_PKEY_GOST12_256;
1246 case NID_id_GostR3410_2012_512:
1247 return SSL_PKEY_GOST12_512;
1252 int ssl_verify_alarm_type(long type)
1257 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1258 case X509_V_ERR_UNABLE_TO_GET_CRL:
1259 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1260 al = SSL_AD_UNKNOWN_CA;
1262 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1263 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1264 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1265 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1266 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1267 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1268 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1269 case X509_V_ERR_CERT_NOT_YET_VALID:
1270 case X509_V_ERR_CRL_NOT_YET_VALID:
1271 case X509_V_ERR_CERT_UNTRUSTED:
1272 case X509_V_ERR_CERT_REJECTED:
1273 case X509_V_ERR_HOSTNAME_MISMATCH:
1274 case X509_V_ERR_EMAIL_MISMATCH:
1275 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1276 case X509_V_ERR_DANE_NO_MATCH:
1277 case X509_V_ERR_EE_KEY_TOO_SMALL:
1278 case X509_V_ERR_CA_KEY_TOO_SMALL:
1279 case X509_V_ERR_CA_MD_TOO_WEAK:
1280 al = SSL_AD_BAD_CERTIFICATE;
1282 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1283 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1284 al = SSL_AD_DECRYPT_ERROR;
1286 case X509_V_ERR_CERT_HAS_EXPIRED:
1287 case X509_V_ERR_CRL_HAS_EXPIRED:
1288 al = SSL_AD_CERTIFICATE_EXPIRED;
1290 case X509_V_ERR_CERT_REVOKED:
1291 al = SSL_AD_CERTIFICATE_REVOKED;
1293 case X509_V_ERR_UNSPECIFIED:
1294 case X509_V_ERR_OUT_OF_MEM:
1295 case X509_V_ERR_INVALID_CALL:
1296 case X509_V_ERR_STORE_LOOKUP:
1297 al = SSL_AD_INTERNAL_ERROR;
1299 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1300 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1301 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1302 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1303 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1304 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1305 case X509_V_ERR_INVALID_CA:
1306 al = SSL_AD_UNKNOWN_CA;
1308 case X509_V_ERR_APPLICATION_VERIFICATION:
1309 al = SSL_AD_HANDSHAKE_FAILURE;
1311 case X509_V_ERR_INVALID_PURPOSE:
1312 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1315 al = SSL_AD_CERTIFICATE_UNKNOWN;
1321 int ssl_allow_compression(SSL *s)
1323 if (s->options & SSL_OP_NO_COMPRESSION)
1325 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1328 static int version_cmp(const SSL *s, int a, int b)
1330 int dtls = SSL_IS_DTLS(s);
1335 return a < b ? -1 : 1;
1336 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1341 const SSL_METHOD *(*cmeth) (void);
1342 const SSL_METHOD *(*smeth) (void);
1345 #if TLS_MAX_VERSION != TLS1_3_VERSION
1346 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1349 /* Must be in order high to low */
1350 static const version_info tls_version_table[] = {
1351 #ifndef OPENSSL_NO_TLS1_3
1352 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1354 {TLS1_3_VERSION, NULL, NULL},
1356 #ifndef OPENSSL_NO_TLS1_2
1357 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1359 {TLS1_2_VERSION, NULL, NULL},
1361 #ifndef OPENSSL_NO_TLS1_1
1362 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1364 {TLS1_1_VERSION, NULL, NULL},
1366 #ifndef OPENSSL_NO_TLS1
1367 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1369 {TLS1_VERSION, NULL, NULL},
1371 #ifndef OPENSSL_NO_SSL3
1372 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1374 {SSL3_VERSION, NULL, NULL},
1379 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1380 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1383 /* Must be in order high to low */
1384 static const version_info dtls_version_table[] = {
1385 #ifndef OPENSSL_NO_DTLS1_2
1386 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1388 {DTLS1_2_VERSION, NULL, NULL},
1390 #ifndef OPENSSL_NO_DTLS1
1391 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1392 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1394 {DTLS1_VERSION, NULL, NULL},
1395 {DTLS1_BAD_VER, NULL, NULL},
1401 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1403 * @s: The SSL handle for the candidate method
1404 * @method: the intended method.
1406 * Returns 0 on success, or an SSL error reason on failure.
1408 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1410 int version = method->version;
1412 if ((s->min_proto_version != 0 &&
1413 version_cmp(s, version, s->min_proto_version) < 0) ||
1414 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1415 return SSL_R_VERSION_TOO_LOW;
1417 if (s->max_proto_version != 0 &&
1418 version_cmp(s, version, s->max_proto_version) > 0)
1419 return SSL_R_VERSION_TOO_HIGH;
1421 if ((s->options & method->mask) != 0)
1422 return SSL_R_UNSUPPORTED_PROTOCOL;
1423 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1424 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1430 * ssl_version_supported - Check that the specified `version` is supported by
1433 * @s: The SSL handle for the candidate method
1434 * @version: Protocol version to test against
1436 * Returns 1 when supported, otherwise 0
1438 int ssl_version_supported(const SSL *s, int version)
1440 const version_info *vent;
1441 const version_info *table;
1443 switch (s->method->version) {
1445 /* Version should match method version for non-ANY method */
1446 return version_cmp(s, version, s->version) == 0;
1447 case TLS_ANY_VERSION:
1448 table = tls_version_table;
1450 case DTLS_ANY_VERSION:
1451 table = dtls_version_table;
1456 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1458 if (vent->cmeth != NULL &&
1459 version_cmp(s, version, vent->version) == 0 &&
1460 ssl_method_error(s, vent->cmeth()) == 0) {
1468 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1469 * fallback indication from a client check whether we're using the highest
1470 * supported protocol version.
1472 * @s server SSL handle.
1474 * Returns 1 when using the highest enabled version, 0 otherwise.
1476 int ssl_check_version_downgrade(SSL *s)
1478 const version_info *vent;
1479 const version_info *table;
1482 * Check that the current protocol is the highest enabled version
1483 * (according to s->ctx->method, as version negotiation may have changed
1486 if (s->version == s->ctx->method->version)
1490 * Apparently we're using a version-flexible SSL_METHOD (not at its
1491 * highest protocol version).
1493 if (s->ctx->method->version == TLS_method()->version)
1494 table = tls_version_table;
1495 else if (s->ctx->method->version == DTLS_method()->version)
1496 table = dtls_version_table;
1498 /* Unexpected state; fail closed. */
1502 for (vent = table; vent->version != 0; ++vent) {
1503 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1504 return s->version == vent->version;
1510 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1511 * protocols, provided the initial (D)TLS method is version-flexible. This
1512 * function sanity-checks the proposed value and makes sure the method is
1513 * version-flexible, then sets the limit if all is well.
1515 * @method_version: The version of the current SSL_METHOD.
1516 * @version: the intended limit.
1517 * @bound: pointer to limit to be updated.
1519 * Returns 1 on success, 0 on failure.
1521 int ssl_set_version_bound(int method_version, int version, int *bound)
1529 * Restrict TLS methods to TLS protocol versions.
1530 * Restrict DTLS methods to DTLS protocol versions.
1531 * Note, DTLS version numbers are decreasing, use comparison macros.
1533 * Note that for both lower-bounds we use explicit versions, not
1534 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1535 * configurations. If the MIN (supported) version ever rises, the user's
1536 * "floor" remains valid even if no longer available. We don't expect the
1537 * MAX ceiling to ever get lower, so making that variable makes sense.
1539 switch (method_version) {
1542 * XXX For fixed version methods, should we always fail and not set any
1543 * bounds, always succeed and not set any bounds, or set the bounds and
1544 * arrange to fail later if they are not met? At present fixed-version
1545 * methods are not subject to controls that disable individual protocol
1550 case TLS_ANY_VERSION:
1551 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1555 case DTLS_ANY_VERSION:
1556 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1557 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1566 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1568 if (vers == TLS1_2_VERSION
1569 && ssl_version_supported(s, TLS1_3_VERSION)) {
1570 *dgrd = DOWNGRADE_TO_1_2;
1571 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1572 && (ssl_version_supported(s, TLS1_2_VERSION)
1573 || ssl_version_supported(s, TLS1_3_VERSION))) {
1574 *dgrd = DOWNGRADE_TO_1_1;
1576 *dgrd = DOWNGRADE_NONE;
1581 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1582 * client HELLO is received to select the final server protocol version and
1583 * the version specific method.
1585 * @s: server SSL handle.
1587 * Returns 0 on success or an SSL error reason number on failure.
1589 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1592 * With version-flexible methods we have an initial state with:
1594 * s->method->version == (D)TLS_ANY_VERSION,
1595 * s->version == (D)TLS_MAX_VERSION.
1597 * So we detect version-flexible methods via the method version, not the
1600 int server_version = s->method->version;
1601 int client_version = hello->legacy_version;
1602 const version_info *vent;
1603 const version_info *table;
1605 RAW_EXTENSION *suppversions;
1607 s->client_version = client_version;
1609 switch (server_version) {
1611 if (!SSL_IS_TLS13(s)) {
1612 if (version_cmp(s, client_version, s->version) < 0)
1613 return SSL_R_WRONG_SSL_VERSION;
1614 *dgrd = DOWNGRADE_NONE;
1616 * If this SSL handle is not from a version flexible method we don't
1617 * (and never did) check min/max FIPS or Suite B constraints. Hope
1618 * that's OK. It is up to the caller to not choose fixed protocol
1619 * versions they don't want. If not, then easy to fix, just return
1620 * ssl_method_error(s, s->method)
1625 * Fall through if we are TLSv1.3 already (this means we must be after
1626 * a HelloRetryRequest
1629 case TLS_ANY_VERSION:
1630 table = tls_version_table;
1632 case DTLS_ANY_VERSION:
1633 table = dtls_version_table;
1637 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1639 if (suppversions->present && !SSL_IS_DTLS(s)) {
1640 unsigned int candidate_vers = 0;
1641 unsigned int best_vers = 0;
1642 const SSL_METHOD *best_method = NULL;
1643 PACKET versionslist;
1645 suppversions->parsed = 1;
1647 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1648 /* Trailing or invalid data? */
1649 return SSL_R_LENGTH_MISMATCH;
1652 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1653 /* TODO(TLS1.3): Remove this before release */
1654 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1655 candidate_vers = TLS1_3_VERSION;
1657 * TODO(TLS1.3): There is some discussion on the TLS list about
1658 * whether to ignore versions <TLS1.2 in supported_versions. At the
1659 * moment we honour them if present. To be reviewed later
1661 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1664 vent->version != 0 && vent->version != (int)candidate_vers;
1667 if (vent->version != 0 && vent->smeth != NULL) {
1668 const SSL_METHOD *method;
1670 method = vent->smeth();
1671 if (ssl_method_error(s, method) == 0) {
1672 best_vers = candidate_vers;
1673 best_method = method;
1677 if (PACKET_remaining(&versionslist) != 0) {
1678 /* Trailing data? */
1679 return SSL_R_LENGTH_MISMATCH;
1682 if (best_vers > 0) {
1683 if (SSL_IS_TLS13(s)) {
1685 * We get here if this is after a HelloRetryRequest. In this
1686 * case we just check that we still negotiated TLSv1.3
1688 if (best_vers != TLS1_3_VERSION)
1689 return SSL_R_UNSUPPORTED_PROTOCOL;
1692 check_for_downgrade(s, best_vers, dgrd);
1693 s->version = best_vers;
1694 s->method = best_method;
1697 return SSL_R_UNSUPPORTED_PROTOCOL;
1701 * If the supported versions extension isn't present, then the highest
1702 * version we can negotiate is TLSv1.2
1704 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1705 client_version = TLS1_2_VERSION;
1708 * No supported versions extension, so we just use the version supplied in
1711 for (vent = table; vent->version != 0; ++vent) {
1712 const SSL_METHOD *method;
1714 if (vent->smeth == NULL ||
1715 version_cmp(s, client_version, vent->version) < 0)
1717 method = vent->smeth();
1718 if (ssl_method_error(s, method) == 0) {
1719 check_for_downgrade(s, vent->version, dgrd);
1720 s->version = vent->version;
1726 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1730 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1731 * server HELLO is received to select the final client protocol version and
1732 * the version specific method.
1734 * @s: client SSL handle.
1735 * @version: The proposed version from the server's HELLO.
1736 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1737 * @al: Where to store any alert value that may be generated
1739 * Returns 0 on success or an SSL error reason number on failure.
1741 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1743 const version_info *vent;
1744 const version_info *table;
1747 /* TODO(TLS1.3): Remove this before release */
1748 if (version == TLS1_3_VERSION_DRAFT)
1749 version = TLS1_3_VERSION;
1751 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1752 *al = SSL_AD_PROTOCOL_VERSION;
1753 return SSL_R_WRONG_SSL_VERSION;
1756 switch (s->method->version) {
1758 if (version != s->version) {
1759 *al = SSL_AD_PROTOCOL_VERSION;
1760 return SSL_R_WRONG_SSL_VERSION;
1763 * If this SSL handle is not from a version flexible method we don't
1764 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1765 * that's OK. It is up to the caller to not choose fixed protocol
1766 * versions they don't want. If not, then easy to fix, just return
1767 * ssl_method_error(s, s->method)
1770 case TLS_ANY_VERSION:
1771 table = tls_version_table;
1773 case DTLS_ANY_VERSION:
1774 table = dtls_version_table;
1778 for (vent = table; vent->version != 0; ++vent) {
1779 const SSL_METHOD *method;
1782 if (vent->cmeth == NULL)
1785 if (highver != 0 && version != vent->version)
1788 method = vent->cmeth();
1789 err = ssl_method_error(s, method);
1791 if (version == vent->version) {
1792 *al = SSL_AD_PROTOCOL_VERSION;
1799 highver = vent->version;
1801 if (version != vent->version)
1804 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1805 /* Check for downgrades */
1807 if (version == TLS1_2_VERSION && highver > version) {
1808 if (memcmp(tls12downgrade,
1809 s->s3->server_random + SSL3_RANDOM_SIZE
1810 - sizeof(tls12downgrade),
1811 sizeof(tls12downgrade)) == 0) {
1812 *al = SSL_AD_ILLEGAL_PARAMETER;
1813 return SSL_R_INAPPROPRIATE_FALLBACK;
1815 } else if (!SSL_IS_DTLS(s)
1816 && version < TLS1_2_VERSION
1817 && highver > version) {
1818 if (memcmp(tls11downgrade,
1819 s->s3->server_random + SSL3_RANDOM_SIZE
1820 - sizeof(tls11downgrade),
1821 sizeof(tls11downgrade)) == 0) {
1822 *al = SSL_AD_ILLEGAL_PARAMETER;
1823 return SSL_R_INAPPROPRIATE_FALLBACK;
1830 s->version = version;
1834 *al = SSL_AD_PROTOCOL_VERSION;
1835 return SSL_R_UNSUPPORTED_PROTOCOL;
1839 * ssl_get_min_max_version - get minimum and maximum protocol version
1840 * @s: The SSL connection
1841 * @min_version: The minimum supported version
1842 * @max_version: The maximum supported version
1844 * Work out what version we should be using for the initial ClientHello if the
1845 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1846 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1847 * constraints and any floor imposed by the security level here,
1848 * so we don't advertise the wrong protocol version to only reject the outcome later.
1850 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
1851 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1852 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1854 * Returns 0 on success or an SSL error reason number on failure. On failure
1855 * min_version and max_version will also be set to 0.
1857 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1861 const SSL_METHOD *single = NULL;
1862 const SSL_METHOD *method;
1863 const version_info *table;
1864 const version_info *vent;
1866 switch (s->method->version) {
1869 * If this SSL handle is not from a version flexible method we don't
1870 * (and never did) check min/max FIPS or Suite B constraints. Hope
1871 * that's OK. It is up to the caller to not choose fixed protocol
1872 * versions they don't want. If not, then easy to fix, just return
1873 * ssl_method_error(s, s->method)
1875 *min_version = *max_version = s->version;
1877 case TLS_ANY_VERSION:
1878 table = tls_version_table;
1880 case DTLS_ANY_VERSION:
1881 table = dtls_version_table;
1886 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1887 * below X enabled. This is required in order to maintain the "version
1888 * capability" vector contiguous. Any versions with a NULL client method
1889 * (protocol version client is disabled at compile-time) is also a "hole".
1891 * Our initial state is hole == 1, version == 0. That is, versions above
1892 * the first version in the method table are disabled (a "hole" above
1893 * the valid protocol entries) and we don't have a selected version yet.
1895 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1896 * the selected version, and the method becomes a candidate "single"
1897 * method. We're no longer in a hole, so "hole" becomes 0.
1899 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1900 * as we support a contiguous range of at least two methods. If we hit
1901 * a disabled method, then hole becomes true again, but nothing else
1902 * changes yet, because all the remaining methods may be disabled too.
1903 * If we again hit an enabled method after the new hole, it becomes
1904 * selected, as we start from scratch.
1906 *min_version = version = 0;
1908 for (vent = table; vent->version != 0; ++vent) {
1910 * A table entry with a NULL client method is still a hole in the
1911 * "version capability" vector.
1913 if (vent->cmeth == NULL) {
1917 method = vent->cmeth();
1918 if (ssl_method_error(s, method) != 0) {
1922 *min_version = method->version;
1924 version = (single = method)->version;
1925 *min_version = version;
1930 *max_version = version;
1932 /* Fail if everything is disabled */
1934 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1940 * ssl_set_client_hello_version - Work out what version we should be using for
1941 * the initial ClientHello.legacy_version field.
1943 * @s: client SSL handle.
1945 * Returns 0 on success or an SSL error reason number on failure.
1947 int ssl_set_client_hello_version(SSL *s)
1949 int ver_min, ver_max, ret;
1951 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
1956 s->version = ver_max;
1958 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1959 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1960 ver_max = TLS1_2_VERSION;
1962 s->client_version = ver_max;
1967 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1968 * and |checkallow| is 1 then additionally check if the group is allowed to be
1969 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1970 * 1) or 0 otherwise.
1972 #ifndef OPENSSL_NO_EC
1973 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1974 size_t num_groups, int checkallow)
1978 if (groups == NULL || num_groups == 0)
1981 for (i = 0; i < num_groups; i++, groups += 2) {
1982 if (group_id == GET_GROUP_ID(groups, 0)
1984 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
1993 /* Replace ClientHello1 in the transcript hash with a synthetic message */
1994 int create_synthetic_message_hash(SSL *s)
1996 unsigned char hashval[EVP_MAX_MD_SIZE];
1998 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2000 memset(msghdr, 0, sizeof(msghdr));
2002 /* Get the hash of the initial ClientHello */
2003 if (!ssl3_digest_cached_records(s, 0)
2004 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
2005 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2009 /* Reinitialise the transcript hash */
2010 if (!ssl3_init_finished_mac(s))
2013 /* Inject the synthetic message_hash message */
2014 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2015 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
2016 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2017 || !ssl3_finish_mac(s, hashval, hashlen)) {
2018 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2025 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2027 return X509_NAME_cmp(*a, *b);
2030 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2032 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2033 X509_NAME *xn = NULL;
2036 if (ca_sk == NULL) {
2037 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2040 /* get the CA RDNs */
2041 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2042 *al = SSL_AD_DECODE_ERROR;
2043 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2047 while (PACKET_remaining(&cadns)) {
2048 const unsigned char *namestart, *namebytes;
2049 unsigned int name_len;
2051 if (!PACKET_get_net_2(&cadns, &name_len)
2052 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2053 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2057 namestart = namebytes;
2058 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2059 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2062 if (namebytes != (namestart + name_len)) {
2063 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2067 if (!sk_X509_NAME_push(ca_sk, xn)) {
2068 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2069 *al = SSL_AD_INTERNAL_ERROR;
2075 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2076 s->s3->tmp.peer_ca_names = ca_sk;
2081 *al = SSL_AD_DECODE_ERROR;
2083 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2088 int construct_ca_names(SSL *s, WPACKET *pkt)
2090 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2092 /* Start sub-packet for client CA list */
2093 if (!WPACKET_start_sub_packet_u16(pkt))
2096 if (ca_sk != NULL) {
2099 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2100 unsigned char *namebytes;
2101 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2105 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2106 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2108 || i2d_X509_NAME(name, &namebytes) != namelen) {
2114 if (!WPACKET_close(pkt))