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->options & SSL_OP_NO_RENEGOTIATION)) {
120 /* Renegotiation is disabled */
121 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
123 } else if (!s->s3->send_connection_binding &&
125 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
127 * Server attempting to renegotiate with client that doesn't
128 * support secure renegotiation.
130 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
131 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
132 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
135 s->ctx->stats.sess_accept_renegotiate++;
137 s->s3->tmp.cert_request = 0;
140 if (SSL_IS_FIRST_HANDSHAKE(s))
141 s->ctx->stats.sess_connect++;
143 s->ctx->stats.sess_connect_renegotiate++;
145 /* mark client_random uninitialized */
146 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
149 s->s3->tmp.cert_req = 0;
152 s->statem.use_timer = 1;
159 * Size of the to-be-signed TLS13 data, without the hash size itself:
160 * 64 bytes of value 32, 33 context bytes, 1 byte separator
162 #define TLS13_TBS_START_SIZE 64
163 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
165 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
166 void **hdata, size_t *hdatalen)
168 static const char *servercontext = "TLS 1.3, server CertificateVerify";
169 static const char *clientcontext = "TLS 1.3, client CertificateVerify";
171 if (SSL_IS_TLS13(s)) {
174 /* Set the first 64 bytes of to-be-signed data to octet 32 */
175 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
176 /* This copies the 33 bytes of context plus the 0 separator byte */
177 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
178 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
179 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
181 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
184 * If we're currently reading then we need to use the saved handshake
185 * hash value. We can't use the current handshake hash state because
186 * that includes the CertVerify itself.
188 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
189 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
190 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
191 s->cert_verify_hash_len);
192 hashlen = s->cert_verify_hash_len;
193 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
194 EVP_MAX_MD_SIZE, &hashlen)) {
199 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
203 retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
212 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
214 EVP_PKEY *pkey = NULL;
215 const EVP_MD *md = NULL;
216 EVP_MD_CTX *mctx = NULL;
217 EVP_PKEY_CTX *pctx = NULL;
218 size_t hdatalen = 0, siglen = 0;
220 unsigned char *sig = NULL;
221 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
222 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
224 if (lu == NULL || s->s3->tmp.cert == NULL) {
225 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
228 pkey = s->s3->tmp.cert->privatekey;
229 md = ssl_md(lu->hash_idx);
231 if (pkey == NULL || md == NULL) {
232 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
236 mctx = EVP_MD_CTX_new();
238 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
242 /* Get the data to be signed */
243 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
244 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
248 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
249 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
252 siglen = EVP_PKEY_size(pkey);
253 sig = OPENSSL_malloc(siglen);
255 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
259 if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
260 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
264 if (lu->sig == EVP_PKEY_RSA_PSS) {
265 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
266 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
267 RSA_PSS_SALTLEN_DIGEST) <= 0) {
268 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
272 if (s->version == SSL3_VERSION) {
273 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
274 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
275 (int)s->session->master_key_length,
276 s->session->master_key)
277 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
279 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
282 } else if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
283 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
287 #ifndef OPENSSL_NO_GOST
289 int pktype = lu->sig;
291 if (pktype == NID_id_GostR3410_2001
292 || pktype == NID_id_GostR3410_2012_256
293 || pktype == NID_id_GostR3410_2012_512)
294 BUF_reverse(sig, NULL, siglen);
298 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
299 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
303 /* Digest cached records and discard handshake buffer */
304 if (!ssl3_digest_cached_records(s, 0))
308 EVP_MD_CTX_free(mctx);
312 EVP_MD_CTX_free(mctx);
313 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
317 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
319 EVP_PKEY *pkey = NULL;
320 const unsigned char *data;
321 #ifndef OPENSSL_NO_GOST
322 unsigned char *gost_data = NULL;
324 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
328 const EVP_MD *md = NULL;
331 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
332 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
333 EVP_PKEY_CTX *pctx = NULL;
336 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
340 peer = s->session->peer;
341 pkey = X509_get0_pubkey(peer);
345 type = X509_certificate_type(peer, pkey);
347 if (!(type & EVP_PKT_SIGN)) {
348 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
349 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
350 al = SSL_AD_ILLEGAL_PARAMETER;
354 /* Check for broken implementations of GOST ciphersuites */
356 * If key is GOST and n is exactly 64, it is bare signature without
357 * length field (CryptoPro implementations at least till CSP 4.0)
359 #ifndef OPENSSL_NO_GOST
360 if (PACKET_remaining(pkt) == 64
361 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
366 if (SSL_USE_SIGALGS(s)) {
370 if (!PACKET_get_net_2(pkt, &sigalg)) {
371 al = SSL_AD_DECODE_ERROR;
374 rv = tls12_check_peer_sigalg(s, sigalg, pkey);
377 } else if (rv == 0) {
378 al = SSL_AD_DECODE_ERROR;
382 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
384 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
385 al = SSL_AD_INTERNAL_ERROR;
389 md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
391 if (!PACKET_get_net_2(pkt, &len)) {
392 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
393 al = SSL_AD_DECODE_ERROR;
397 j = EVP_PKEY_size(pkey);
398 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
399 || (PACKET_remaining(pkt) == 0)) {
400 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
401 al = SSL_AD_DECODE_ERROR;
404 if (!PACKET_get_bytes(pkt, &data, len)) {
405 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
406 al = SSL_AD_DECODE_ERROR;
410 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
411 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
416 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
418 if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0) {
419 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
422 #ifndef OPENSSL_NO_GOST
424 int pktype = EVP_PKEY_id(pkey);
425 if (pktype == NID_id_GostR3410_2001
426 || pktype == NID_id_GostR3410_2012_256
427 || pktype == NID_id_GostR3410_2012_512) {
428 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
429 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
432 BUF_reverse(gost_data, data, len);
438 if (SSL_USE_PSS(s)) {
439 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
440 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
441 RSA_PSS_SALTLEN_DIGEST) <= 0) {
442 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
446 if (s->version == SSL3_VERSION) {
447 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
448 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
449 (int)s->session->master_key_length,
450 s->session->master_key)) {
451 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
454 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
455 al = SSL_AD_DECRYPT_ERROR;
456 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
460 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
462 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
465 al = SSL_AD_DECRYPT_ERROR;
466 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
471 ret = MSG_PROCESS_CONTINUE_READING;
474 ssl3_send_alert(s, SSL3_AL_FATAL, al);
475 ossl_statem_set_error(s);
477 BIO_free(s->s3->handshake_buffer);
478 s->s3->handshake_buffer = NULL;
479 EVP_MD_CTX_free(mctx);
480 #ifndef OPENSSL_NO_GOST
481 OPENSSL_free(gost_data);
486 int tls_construct_finished(SSL *s, WPACKET *pkt)
488 size_t finish_md_len;
492 /* This is a real handshake so make sure we clean it up at the end */
494 s->statem.cleanuphand = 1;
497 * We only change the keys if we didn't already do this when we sent the
502 && s->s3->tmp.cert_req == 0
503 && (!s->method->ssl3_enc->change_cipher_state(s,
504 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
505 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
510 sender = s->method->ssl3_enc->server_finished_label;
511 slen = s->method->ssl3_enc->server_finished_label_len;
513 sender = s->method->ssl3_enc->client_finished_label;
514 slen = s->method->ssl3_enc->client_finished_label_len;
517 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
519 s->s3->tmp.finish_md);
520 if (finish_md_len == 0) {
521 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
525 s->s3->tmp.finish_md_len = finish_md_len;
527 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
528 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
533 * Log the master secret, if logging is enabled. We don't log it for
534 * TLSv1.3: there's a different key schedule for that.
536 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
537 s->session->master_key,
538 s->session->master_key_length)) {
539 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
544 * Copy the finished so we can use it for renegotiation checks
546 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
547 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
551 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
553 s->s3->previous_client_finished_len = finish_md_len;
555 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
557 s->s3->previous_server_finished_len = finish_md_len;
562 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
566 int tls_construct_key_update(SSL *s, WPACKET *pkt)
568 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
569 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
573 s->key_update = SSL_KEY_UPDATE_NONE;
577 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
581 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
584 unsigned int updatetype;
586 s->key_update_count++;
587 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
588 al = SSL_AD_ILLEGAL_PARAMETER;
589 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
594 * A KeyUpdate message signals a key change so the end of the message must
595 * be on a record boundary.
597 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
598 al = SSL_AD_UNEXPECTED_MESSAGE;
599 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
603 if (!PACKET_get_1(pkt, &updatetype)
604 || PACKET_remaining(pkt) != 0) {
605 al = SSL_AD_DECODE_ERROR;
606 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
611 * There are only two defined key update types. Fail if we get a value we
614 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
615 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
616 al = SSL_AD_ILLEGAL_PARAMETER;
617 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
622 * If we get a request for us to update our sending keys too then, we need
623 * to additionally send a KeyUpdate message. However that message should
624 * not also request an update (otherwise we get into an infinite loop).
626 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
627 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
629 if (!tls13_update_key(s, 0)) {
630 al = SSL_AD_INTERNAL_ERROR;
631 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
635 return MSG_PROCESS_FINISHED_READING;
637 ssl3_send_alert(s, SSL3_AL_FATAL, al);
638 ossl_statem_set_error(s);
639 return MSG_PROCESS_ERROR;
642 #ifndef OPENSSL_NO_NEXTPROTONEG
644 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
647 static void ssl3_take_mac(SSL *s)
652 * If no new cipher setup return immediately: other functions will set
653 * the appropriate error.
655 if (s->s3->tmp.new_cipher == NULL)
658 sender = s->method->ssl3_enc->server_finished_label;
659 slen = s->method->ssl3_enc->server_finished_label_len;
661 sender = s->method->ssl3_enc->client_finished_label;
662 slen = s->method->ssl3_enc->client_finished_label_len;
665 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
668 s->s3->tmp.peer_finish_md);
672 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
677 remain = PACKET_remaining(pkt);
679 * 'Change Cipher Spec' is just a single byte, which should already have
680 * been consumed by ssl_get_message() so there should be no bytes left,
681 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
683 if (SSL_IS_DTLS(s)) {
684 if ((s->version == DTLS1_BAD_VER
685 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
686 || (s->version != DTLS1_BAD_VER
687 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
688 al = SSL_AD_DECODE_ERROR;
689 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
690 SSL_R_BAD_CHANGE_CIPHER_SPEC);
695 al = SSL_AD_DECODE_ERROR;
696 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
697 SSL_R_BAD_CHANGE_CIPHER_SPEC);
702 /* Check we have a cipher to change to */
703 if (s->s3->tmp.new_cipher == NULL) {
704 al = SSL_AD_UNEXPECTED_MESSAGE;
705 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
709 s->s3->change_cipher_spec = 1;
710 if (!ssl3_do_change_cipher_spec(s)) {
711 al = SSL_AD_INTERNAL_ERROR;
712 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
716 if (SSL_IS_DTLS(s)) {
717 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
719 if (s->version == DTLS1_BAD_VER)
720 s->d1->handshake_read_seq++;
722 #ifndef OPENSSL_NO_SCTP
724 * Remember that a CCS has been received, so that an old key of
725 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
728 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
732 return MSG_PROCESS_CONTINUE_READING;
734 ssl3_send_alert(s, SSL3_AL_FATAL, al);
735 ossl_statem_set_error(s);
736 return MSG_PROCESS_ERROR;
739 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
741 int al = SSL_AD_INTERNAL_ERROR;
745 /* This is a real handshake so make sure we clean it up at the end */
747 s->statem.cleanuphand = 1;
750 * In TLSv1.3 a Finished message signals a key change so the end of the
751 * message must be on a record boundary.
753 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
754 al = SSL_AD_UNEXPECTED_MESSAGE;
755 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
759 /* If this occurs, we have missed a message */
760 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
761 al = SSL_AD_UNEXPECTED_MESSAGE;
762 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
765 s->s3->change_cipher_spec = 0;
767 md_len = s->s3->tmp.peer_finish_md_len;
769 if (md_len != PACKET_remaining(pkt)) {
770 al = SSL_AD_DECODE_ERROR;
771 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
775 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
777 al = SSL_AD_DECRYPT_ERROR;
778 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
783 * Copy the finished so we can use it for renegotiation checks
785 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
786 al = SSL_AD_INTERNAL_ERROR;
787 SSLerr(SSL_F_TLS_PROCESS_FINISHED, ERR_R_INTERNAL_ERROR);
791 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
793 s->s3->previous_client_finished_len = md_len;
795 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
797 s->s3->previous_server_finished_len = md_len;
801 * In TLS1.3 we also have to change cipher state and do any final processing
802 * of the initial server flight (if we are a client)
804 if (SSL_IS_TLS13(s)) {
806 if (!s->method->ssl3_enc->change_cipher_state(s,
807 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
808 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
812 if (!s->method->ssl3_enc->generate_master_secret(s,
813 s->master_secret, s->handshake_secret, 0,
814 &s->session->master_key_length)) {
815 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
818 if (!s->method->ssl3_enc->change_cipher_state(s,
819 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
820 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
823 if (!tls_process_initial_server_flight(s, &al))
828 return MSG_PROCESS_FINISHED_READING;
830 ssl3_send_alert(s, SSL3_AL_FATAL, al);
831 ossl_statem_set_error(s);
832 return MSG_PROCESS_ERROR;
835 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
837 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
838 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
839 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
846 /* Add a certificate to the WPACKET */
847 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
851 unsigned char *outbytes;
853 len = i2d_X509(x, NULL);
855 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
856 *al = SSL_AD_INTERNAL_ERROR;
859 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
860 || i2d_X509(x, &outbytes) != len) {
861 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
862 *al = SSL_AD_INTERNAL_ERROR;
867 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
874 /* Add certificate chain to provided WPACKET */
875 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
879 STACK_OF(X509) *extra_certs;
880 STACK_OF(X509) *chain = NULL;
881 X509_STORE *chain_store;
882 int tmpal = SSL_AD_INTERNAL_ERROR;
884 if (cpk == NULL || cpk->x509 == NULL)
890 * If we have a certificate specific chain use it, else use parent ctx.
892 if (cpk->chain != NULL)
893 extra_certs = cpk->chain;
895 extra_certs = s->ctx->extra_certs;
897 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
899 else if (s->cert->chain_store)
900 chain_store = s->cert->chain_store;
902 chain_store = s->ctx->cert_store;
904 if (chain_store != NULL) {
905 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
907 if (xs_ctx == NULL) {
908 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
911 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
912 X509_STORE_CTX_free(xs_ctx);
913 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
917 * It is valid for the chain not to be complete (because normally we
918 * don't include the root cert in the chain). Therefore we deliberately
919 * ignore the error return from this call. We're not actually verifying
920 * the cert - we're just building as much of the chain as we can
922 (void)X509_verify_cert(xs_ctx);
923 /* Don't leave errors in the queue */
925 chain = X509_STORE_CTX_get0_chain(xs_ctx);
926 i = ssl_security_cert_chain(s, chain, NULL, 0);
929 /* Dummy error calls so mkerr generates them */
930 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
931 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
932 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
934 X509_STORE_CTX_free(xs_ctx);
935 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
938 chain_count = sk_X509_num(chain);
939 for (i = 0; i < chain_count; i++) {
940 x = sk_X509_value(chain, i);
942 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
943 X509_STORE_CTX_free(xs_ctx);
947 X509_STORE_CTX_free(xs_ctx);
949 i = ssl_security_cert_chain(s, extra_certs, x, 0);
951 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
954 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
956 for (i = 0; i < sk_X509_num(extra_certs); i++) {
957 x = sk_X509_value(extra_certs, i);
958 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
969 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
972 int tmpal = SSL_AD_INTERNAL_ERROR;
974 if (!WPACKET_start_sub_packet_u24(pkt)
975 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
976 || !WPACKET_close(pkt)) {
977 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
985 * Tidy up after the end of a handshake. In the case of SCTP this may result
986 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
989 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
991 void (*cb) (const SSL *ssl, int type, int val) = NULL;
993 #ifndef OPENSSL_NO_SCTP
994 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
996 ret = dtls_wait_for_dry(s);
997 if (ret != WORK_FINISHED_CONTINUE)
1003 if (!SSL_IS_DTLS(s)) {
1005 * We don't do this in DTLS because we may still need the init_buf
1006 * in case there are any unexpected retransmits
1008 BUF_MEM_free(s->init_buf);
1011 if (!ssl_free_wbio_buffer(s))
1016 if (s->statem.cleanuphand) {
1017 /* skipped if we just sent a HelloRequest */
1020 s->statem.cleanuphand = 0;
1022 ssl3_cleanup_key_block(s);
1025 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1027 s->ctx->stats.sess_accept_good++;
1028 s->handshake_func = ossl_statem_accept;
1030 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1032 s->ctx->stats.sess_hit++;
1034 s->handshake_func = ossl_statem_connect;
1035 s->ctx->stats.sess_connect_good++;
1038 if (s->info_callback != NULL)
1039 cb = s->info_callback;
1040 else if (s->ctx->info_callback != NULL)
1041 cb = s->ctx->info_callback;
1044 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1046 if (SSL_IS_DTLS(s)) {
1047 /* done with handshaking */
1048 s->d1->handshake_read_seq = 0;
1049 s->d1->handshake_write_seq = 0;
1050 s->d1->next_handshake_write_seq = 0;
1051 dtls1_clear_received_buffer(s);
1056 * If we've not cleared the buffers its because we've got more work to do,
1060 return WORK_FINISHED_CONTINUE;
1062 ossl_statem_set_in_init(s, 0);
1063 return WORK_FINISHED_STOP;
1066 int tls_get_message_header(SSL *s, int *mt)
1068 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1069 int skip_message, i, recvd_type, al;
1071 size_t l, readbytes;
1073 p = (unsigned char *)s->init_buf->data;
1076 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1077 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1079 SSL3_HM_HEADER_LENGTH - s->init_num,
1082 s->rwstate = SSL_READING;
1085 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1087 * A ChangeCipherSpec must be a single byte and may not occur
1088 * in the middle of a handshake message.
1090 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1091 al = SSL_AD_UNEXPECTED_MESSAGE;
1092 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1093 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1096 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1097 s->init_num = readbytes - 1;
1098 s->init_msg = s->init_buf->data;
1099 s->s3->tmp.message_size = readbytes;
1101 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1102 al = SSL_AD_UNEXPECTED_MESSAGE;
1103 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1106 s->init_num += readbytes;
1111 if (s->statem.hand_state != TLS_ST_OK
1112 && p[0] == SSL3_MT_HELLO_REQUEST)
1114 * The server may always send 'Hello Request' messages --
1115 * we are doing a handshake anyway now, so ignore them if
1116 * their format is correct. Does not count for 'Finished'
1119 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1123 if (s->msg_callback)
1124 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1125 p, SSL3_HM_HEADER_LENGTH, s,
1126 s->msg_callback_arg);
1128 } while (skip_message);
1129 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1132 s->s3->tmp.message_type = *(p++);
1134 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1136 * Only happens with SSLv3+ in an SSLv2 backward compatible
1139 * Total message size is the remaining record bytes to read
1140 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1142 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1143 + SSL3_HM_HEADER_LENGTH;
1144 s->s3->tmp.message_size = l;
1146 s->init_msg = s->init_buf->data;
1147 s->init_num = SSL3_HM_HEADER_LENGTH;
1150 /* BUF_MEM_grow takes an 'int' parameter */
1151 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1152 al = SSL_AD_ILLEGAL_PARAMETER;
1153 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1156 s->s3->tmp.message_size = l;
1158 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1164 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1168 int tls_get_message_body(SSL *s, size_t *len)
1170 size_t n, readbytes;
1174 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1175 /* We've already read everything in */
1176 *len = (unsigned long)s->init_num;
1181 n = s->s3->tmp.message_size - s->init_num;
1183 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1184 &p[s->init_num], n, 0, &readbytes);
1186 s->rwstate = SSL_READING;
1190 s->init_num += readbytes;
1194 #ifndef OPENSSL_NO_NEXTPROTONEG
1196 * If receiving Finished, record MAC of prior handshake messages for
1197 * Finished verification.
1199 if (*s->init_buf->data == SSL3_MT_FINISHED)
1203 /* Feed this message into MAC computation. */
1204 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1205 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1207 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1208 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1212 if (s->msg_callback)
1213 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1214 (size_t)s->init_num, s, s->msg_callback_arg);
1217 * We defer feeding in the HRR until later. We'll do it as part of
1218 * processing the message
1220 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1221 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1222 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1223 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1224 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1228 if (s->msg_callback)
1229 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1230 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1231 s->msg_callback_arg);
1238 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1240 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1243 switch (EVP_PKEY_id(pk)) {
1247 return SSL_PKEY_RSA;
1249 return SSL_PKEY_DSA_SIGN;
1250 #ifndef OPENSSL_NO_EC
1252 return SSL_PKEY_ECC;
1254 #ifndef OPENSSL_NO_GOST
1255 case NID_id_GostR3410_2001:
1256 return SSL_PKEY_GOST01;
1257 case NID_id_GostR3410_2012_256:
1258 return SSL_PKEY_GOST12_256;
1259 case NID_id_GostR3410_2012_512:
1260 return SSL_PKEY_GOST12_512;
1265 int ssl_verify_alarm_type(long type)
1270 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1271 case X509_V_ERR_UNABLE_TO_GET_CRL:
1272 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1273 al = SSL_AD_UNKNOWN_CA;
1275 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1276 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1277 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1278 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1279 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1280 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1281 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1282 case X509_V_ERR_CERT_NOT_YET_VALID:
1283 case X509_V_ERR_CRL_NOT_YET_VALID:
1284 case X509_V_ERR_CERT_UNTRUSTED:
1285 case X509_V_ERR_CERT_REJECTED:
1286 case X509_V_ERR_HOSTNAME_MISMATCH:
1287 case X509_V_ERR_EMAIL_MISMATCH:
1288 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1289 case X509_V_ERR_DANE_NO_MATCH:
1290 case X509_V_ERR_EE_KEY_TOO_SMALL:
1291 case X509_V_ERR_CA_KEY_TOO_SMALL:
1292 case X509_V_ERR_CA_MD_TOO_WEAK:
1293 al = SSL_AD_BAD_CERTIFICATE;
1295 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1296 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1297 al = SSL_AD_DECRYPT_ERROR;
1299 case X509_V_ERR_CERT_HAS_EXPIRED:
1300 case X509_V_ERR_CRL_HAS_EXPIRED:
1301 al = SSL_AD_CERTIFICATE_EXPIRED;
1303 case X509_V_ERR_CERT_REVOKED:
1304 al = SSL_AD_CERTIFICATE_REVOKED;
1306 case X509_V_ERR_UNSPECIFIED:
1307 case X509_V_ERR_OUT_OF_MEM:
1308 case X509_V_ERR_INVALID_CALL:
1309 case X509_V_ERR_STORE_LOOKUP:
1310 al = SSL_AD_INTERNAL_ERROR;
1312 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1313 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1314 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1315 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1316 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1317 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1318 case X509_V_ERR_INVALID_CA:
1319 al = SSL_AD_UNKNOWN_CA;
1321 case X509_V_ERR_APPLICATION_VERIFICATION:
1322 al = SSL_AD_HANDSHAKE_FAILURE;
1324 case X509_V_ERR_INVALID_PURPOSE:
1325 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1328 al = SSL_AD_CERTIFICATE_UNKNOWN;
1334 int ssl_allow_compression(SSL *s)
1336 if (s->options & SSL_OP_NO_COMPRESSION)
1338 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1341 static int version_cmp(const SSL *s, int a, int b)
1343 int dtls = SSL_IS_DTLS(s);
1348 return a < b ? -1 : 1;
1349 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1354 const SSL_METHOD *(*cmeth) (void);
1355 const SSL_METHOD *(*smeth) (void);
1358 #if TLS_MAX_VERSION != TLS1_3_VERSION
1359 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1362 /* Must be in order high to low */
1363 static const version_info tls_version_table[] = {
1364 #ifndef OPENSSL_NO_TLS1_3
1365 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1367 {TLS1_3_VERSION, NULL, NULL},
1369 #ifndef OPENSSL_NO_TLS1_2
1370 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1372 {TLS1_2_VERSION, NULL, NULL},
1374 #ifndef OPENSSL_NO_TLS1_1
1375 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1377 {TLS1_1_VERSION, NULL, NULL},
1379 #ifndef OPENSSL_NO_TLS1
1380 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1382 {TLS1_VERSION, NULL, NULL},
1384 #ifndef OPENSSL_NO_SSL3
1385 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1387 {SSL3_VERSION, NULL, NULL},
1392 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1393 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1396 /* Must be in order high to low */
1397 static const version_info dtls_version_table[] = {
1398 #ifndef OPENSSL_NO_DTLS1_2
1399 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1401 {DTLS1_2_VERSION, NULL, NULL},
1403 #ifndef OPENSSL_NO_DTLS1
1404 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1405 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1407 {DTLS1_VERSION, NULL, NULL},
1408 {DTLS1_BAD_VER, NULL, NULL},
1414 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1416 * @s: The SSL handle for the candidate method
1417 * @method: the intended method.
1419 * Returns 0 on success, or an SSL error reason on failure.
1421 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1423 int version = method->version;
1425 if ((s->min_proto_version != 0 &&
1426 version_cmp(s, version, s->min_proto_version) < 0) ||
1427 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1428 return SSL_R_VERSION_TOO_LOW;
1430 if (s->max_proto_version != 0 &&
1431 version_cmp(s, version, s->max_proto_version) > 0)
1432 return SSL_R_VERSION_TOO_HIGH;
1434 if ((s->options & method->mask) != 0)
1435 return SSL_R_UNSUPPORTED_PROTOCOL;
1436 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1437 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1443 * ssl_version_supported - Check that the specified `version` is supported by
1446 * @s: The SSL handle for the candidate method
1447 * @version: Protocol version to test against
1449 * Returns 1 when supported, otherwise 0
1451 int ssl_version_supported(const SSL *s, int version)
1453 const version_info *vent;
1454 const version_info *table;
1456 switch (s->method->version) {
1458 /* Version should match method version for non-ANY method */
1459 return version_cmp(s, version, s->version) == 0;
1460 case TLS_ANY_VERSION:
1461 table = tls_version_table;
1463 case DTLS_ANY_VERSION:
1464 table = dtls_version_table;
1469 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1471 if (vent->cmeth != NULL &&
1472 version_cmp(s, version, vent->version) == 0 &&
1473 ssl_method_error(s, vent->cmeth()) == 0) {
1481 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1482 * fallback indication from a client check whether we're using the highest
1483 * supported protocol version.
1485 * @s server SSL handle.
1487 * Returns 1 when using the highest enabled version, 0 otherwise.
1489 int ssl_check_version_downgrade(SSL *s)
1491 const version_info *vent;
1492 const version_info *table;
1495 * Check that the current protocol is the highest enabled version
1496 * (according to s->ctx->method, as version negotiation may have changed
1499 if (s->version == s->ctx->method->version)
1503 * Apparently we're using a version-flexible SSL_METHOD (not at its
1504 * highest protocol version).
1506 if (s->ctx->method->version == TLS_method()->version)
1507 table = tls_version_table;
1508 else if (s->ctx->method->version == DTLS_method()->version)
1509 table = dtls_version_table;
1511 /* Unexpected state; fail closed. */
1515 for (vent = table; vent->version != 0; ++vent) {
1516 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1517 return s->version == vent->version;
1523 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1524 * protocols, provided the initial (D)TLS method is version-flexible. This
1525 * function sanity-checks the proposed value and makes sure the method is
1526 * version-flexible, then sets the limit if all is well.
1528 * @method_version: The version of the current SSL_METHOD.
1529 * @version: the intended limit.
1530 * @bound: pointer to limit to be updated.
1532 * Returns 1 on success, 0 on failure.
1534 int ssl_set_version_bound(int method_version, int version, int *bound)
1542 * Restrict TLS methods to TLS protocol versions.
1543 * Restrict DTLS methods to DTLS protocol versions.
1544 * Note, DTLS version numbers are decreasing, use comparison macros.
1546 * Note that for both lower-bounds we use explicit versions, not
1547 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1548 * configurations. If the MIN (supported) version ever rises, the user's
1549 * "floor" remains valid even if no longer available. We don't expect the
1550 * MAX ceiling to ever get lower, so making that variable makes sense.
1552 switch (method_version) {
1555 * XXX For fixed version methods, should we always fail and not set any
1556 * bounds, always succeed and not set any bounds, or set the bounds and
1557 * arrange to fail later if they are not met? At present fixed-version
1558 * methods are not subject to controls that disable individual protocol
1563 case TLS_ANY_VERSION:
1564 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1568 case DTLS_ANY_VERSION:
1569 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1570 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1579 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1581 if (vers == TLS1_2_VERSION
1582 && ssl_version_supported(s, TLS1_3_VERSION)) {
1583 *dgrd = DOWNGRADE_TO_1_2;
1584 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1585 && (ssl_version_supported(s, TLS1_2_VERSION)
1586 || ssl_version_supported(s, TLS1_3_VERSION))) {
1587 *dgrd = DOWNGRADE_TO_1_1;
1589 *dgrd = DOWNGRADE_NONE;
1594 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1595 * client HELLO is received to select the final server protocol version and
1596 * the version specific method.
1598 * @s: server SSL handle.
1600 * Returns 0 on success or an SSL error reason number on failure.
1602 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1605 * With version-flexible methods we have an initial state with:
1607 * s->method->version == (D)TLS_ANY_VERSION,
1608 * s->version == (D)TLS_MAX_VERSION.
1610 * So we detect version-flexible methods via the method version, not the
1613 int server_version = s->method->version;
1614 int client_version = hello->legacy_version;
1615 const version_info *vent;
1616 const version_info *table;
1618 RAW_EXTENSION *suppversions;
1620 s->client_version = client_version;
1622 switch (server_version) {
1624 if (!SSL_IS_TLS13(s)) {
1625 if (version_cmp(s, client_version, s->version) < 0)
1626 return SSL_R_WRONG_SSL_VERSION;
1627 *dgrd = DOWNGRADE_NONE;
1629 * If this SSL handle is not from a version flexible method we don't
1630 * (and never did) check min/max FIPS or Suite B constraints. Hope
1631 * that's OK. It is up to the caller to not choose fixed protocol
1632 * versions they don't want. If not, then easy to fix, just return
1633 * ssl_method_error(s, s->method)
1638 * Fall through if we are TLSv1.3 already (this means we must be after
1639 * a HelloRetryRequest
1642 case TLS_ANY_VERSION:
1643 table = tls_version_table;
1645 case DTLS_ANY_VERSION:
1646 table = dtls_version_table;
1650 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1652 if (suppversions->present && !SSL_IS_DTLS(s)) {
1653 unsigned int candidate_vers = 0;
1654 unsigned int best_vers = 0;
1655 const SSL_METHOD *best_method = NULL;
1656 PACKET versionslist;
1658 suppversions->parsed = 1;
1660 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1661 /* Trailing or invalid data? */
1662 return SSL_R_LENGTH_MISMATCH;
1665 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1666 /* TODO(TLS1.3): Remove this before release */
1667 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1668 candidate_vers = TLS1_3_VERSION;
1670 * TODO(TLS1.3): There is some discussion on the TLS list about
1671 * whether to ignore versions <TLS1.2 in supported_versions. At the
1672 * moment we honour them if present. To be reviewed later
1674 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1677 vent->version != 0 && vent->version != (int)candidate_vers;
1680 if (vent->version != 0 && vent->smeth != NULL) {
1681 const SSL_METHOD *method;
1683 method = vent->smeth();
1684 if (ssl_method_error(s, method) == 0) {
1685 best_vers = candidate_vers;
1686 best_method = method;
1690 if (PACKET_remaining(&versionslist) != 0) {
1691 /* Trailing data? */
1692 return SSL_R_LENGTH_MISMATCH;
1695 if (best_vers > 0) {
1696 if (SSL_IS_TLS13(s)) {
1698 * We get here if this is after a HelloRetryRequest. In this
1699 * case we just check that we still negotiated TLSv1.3
1701 if (best_vers != TLS1_3_VERSION)
1702 return SSL_R_UNSUPPORTED_PROTOCOL;
1705 check_for_downgrade(s, best_vers, dgrd);
1706 s->version = best_vers;
1707 s->method = best_method;
1710 return SSL_R_UNSUPPORTED_PROTOCOL;
1714 * If the supported versions extension isn't present, then the highest
1715 * version we can negotiate is TLSv1.2
1717 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1718 client_version = TLS1_2_VERSION;
1721 * No supported versions extension, so we just use the version supplied in
1724 for (vent = table; vent->version != 0; ++vent) {
1725 const SSL_METHOD *method;
1727 if (vent->smeth == NULL ||
1728 version_cmp(s, client_version, vent->version) < 0)
1730 method = vent->smeth();
1731 if (ssl_method_error(s, method) == 0) {
1732 check_for_downgrade(s, vent->version, dgrd);
1733 s->version = vent->version;
1739 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1743 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1744 * server HELLO is received to select the final client protocol version and
1745 * the version specific method.
1747 * @s: client SSL handle.
1748 * @version: The proposed version from the server's HELLO.
1749 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1750 * @al: Where to store any alert value that may be generated
1752 * Returns 0 on success or an SSL error reason number on failure.
1754 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1756 const version_info *vent;
1757 const version_info *table;
1760 /* TODO(TLS1.3): Remove this before release */
1761 if (version == TLS1_3_VERSION_DRAFT)
1762 version = TLS1_3_VERSION;
1764 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1765 *al = SSL_AD_PROTOCOL_VERSION;
1766 return SSL_R_WRONG_SSL_VERSION;
1769 switch (s->method->version) {
1771 if (version != s->version) {
1772 *al = SSL_AD_PROTOCOL_VERSION;
1773 return SSL_R_WRONG_SSL_VERSION;
1776 * If this SSL handle is not from a version flexible method we don't
1777 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1778 * that's OK. It is up to the caller to not choose fixed protocol
1779 * versions they don't want. If not, then easy to fix, just return
1780 * ssl_method_error(s, s->method)
1783 case TLS_ANY_VERSION:
1784 table = tls_version_table;
1786 case DTLS_ANY_VERSION:
1787 table = dtls_version_table;
1791 for (vent = table; vent->version != 0; ++vent) {
1792 const SSL_METHOD *method;
1795 if (vent->cmeth == NULL)
1798 if (highver != 0 && version != vent->version)
1801 method = vent->cmeth();
1802 err = ssl_method_error(s, method);
1804 if (version == vent->version) {
1805 *al = SSL_AD_PROTOCOL_VERSION;
1812 highver = vent->version;
1814 if (version != vent->version)
1817 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1818 /* Check for downgrades */
1820 if (version == TLS1_2_VERSION && highver > version) {
1821 if (memcmp(tls12downgrade,
1822 s->s3->server_random + SSL3_RANDOM_SIZE
1823 - sizeof(tls12downgrade),
1824 sizeof(tls12downgrade)) == 0) {
1825 *al = SSL_AD_ILLEGAL_PARAMETER;
1826 return SSL_R_INAPPROPRIATE_FALLBACK;
1828 } else if (!SSL_IS_DTLS(s)
1829 && version < TLS1_2_VERSION
1830 && highver > version) {
1831 if (memcmp(tls11downgrade,
1832 s->s3->server_random + SSL3_RANDOM_SIZE
1833 - sizeof(tls11downgrade),
1834 sizeof(tls11downgrade)) == 0) {
1835 *al = SSL_AD_ILLEGAL_PARAMETER;
1836 return SSL_R_INAPPROPRIATE_FALLBACK;
1843 s->version = version;
1847 *al = SSL_AD_PROTOCOL_VERSION;
1848 return SSL_R_UNSUPPORTED_PROTOCOL;
1852 * ssl_get_min_max_version - get minimum and maximum protocol version
1853 * @s: The SSL connection
1854 * @min_version: The minimum supported version
1855 * @max_version: The maximum supported version
1857 * Work out what version we should be using for the initial ClientHello if the
1858 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1859 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1860 * constraints and any floor imposed by the security level here,
1861 * so we don't advertise the wrong protocol version to only reject the outcome later.
1863 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
1864 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1865 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1867 * Returns 0 on success or an SSL error reason number on failure. On failure
1868 * min_version and max_version will also be set to 0.
1870 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1874 const SSL_METHOD *single = NULL;
1875 const SSL_METHOD *method;
1876 const version_info *table;
1877 const version_info *vent;
1879 switch (s->method->version) {
1882 * If this SSL handle is not from a version flexible method we don't
1883 * (and never did) check min/max FIPS or Suite B constraints. Hope
1884 * that's OK. It is up to the caller to not choose fixed protocol
1885 * versions they don't want. If not, then easy to fix, just return
1886 * ssl_method_error(s, s->method)
1888 *min_version = *max_version = s->version;
1890 case TLS_ANY_VERSION:
1891 table = tls_version_table;
1893 case DTLS_ANY_VERSION:
1894 table = dtls_version_table;
1899 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1900 * below X enabled. This is required in order to maintain the "version
1901 * capability" vector contiguous. Any versions with a NULL client method
1902 * (protocol version client is disabled at compile-time) is also a "hole".
1904 * Our initial state is hole == 1, version == 0. That is, versions above
1905 * the first version in the method table are disabled (a "hole" above
1906 * the valid protocol entries) and we don't have a selected version yet.
1908 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1909 * the selected version, and the method becomes a candidate "single"
1910 * method. We're no longer in a hole, so "hole" becomes 0.
1912 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1913 * as we support a contiguous range of at least two methods. If we hit
1914 * a disabled method, then hole becomes true again, but nothing else
1915 * changes yet, because all the remaining methods may be disabled too.
1916 * If we again hit an enabled method after the new hole, it becomes
1917 * selected, as we start from scratch.
1919 *min_version = version = 0;
1921 for (vent = table; vent->version != 0; ++vent) {
1923 * A table entry with a NULL client method is still a hole in the
1924 * "version capability" vector.
1926 if (vent->cmeth == NULL) {
1930 method = vent->cmeth();
1931 if (ssl_method_error(s, method) != 0) {
1935 *min_version = method->version;
1937 version = (single = method)->version;
1938 *min_version = version;
1943 *max_version = version;
1945 /* Fail if everything is disabled */
1947 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1953 * ssl_set_client_hello_version - Work out what version we should be using for
1954 * the initial ClientHello.legacy_version field.
1956 * @s: client SSL handle.
1958 * Returns 0 on success or an SSL error reason number on failure.
1960 int ssl_set_client_hello_version(SSL *s)
1962 int ver_min, ver_max, ret;
1964 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
1969 s->version = ver_max;
1971 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1972 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1973 ver_max = TLS1_2_VERSION;
1975 s->client_version = ver_max;
1980 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1981 * and |checkallow| is 1 then additionally check if the group is allowed to be
1982 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1983 * 1) or 0 otherwise.
1985 #ifndef OPENSSL_NO_EC
1986 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1987 size_t num_groups, int checkallow)
1991 if (groups == NULL || num_groups == 0)
1994 for (i = 0; i < num_groups; i++, groups += 2) {
1995 if (group_id == GET_GROUP_ID(groups, 0)
1997 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
2006 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2007 int create_synthetic_message_hash(SSL *s)
2009 unsigned char hashval[EVP_MAX_MD_SIZE];
2011 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2013 memset(msghdr, 0, sizeof(msghdr));
2015 /* Get the hash of the initial ClientHello */
2016 if (!ssl3_digest_cached_records(s, 0)
2017 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
2018 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2022 /* Reinitialise the transcript hash */
2023 if (!ssl3_init_finished_mac(s))
2026 /* Inject the synthetic message_hash message */
2027 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2028 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
2029 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2030 || !ssl3_finish_mac(s, hashval, hashlen)) {
2031 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2038 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2040 return X509_NAME_cmp(*a, *b);
2043 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2045 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2046 X509_NAME *xn = NULL;
2049 if (ca_sk == NULL) {
2050 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2053 /* get the CA RDNs */
2054 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2055 *al = SSL_AD_DECODE_ERROR;
2056 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2060 while (PACKET_remaining(&cadns)) {
2061 const unsigned char *namestart, *namebytes;
2062 unsigned int name_len;
2064 if (!PACKET_get_net_2(&cadns, &name_len)
2065 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2066 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2070 namestart = namebytes;
2071 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2072 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2075 if (namebytes != (namestart + name_len)) {
2076 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2080 if (!sk_X509_NAME_push(ca_sk, xn)) {
2081 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2082 *al = SSL_AD_INTERNAL_ERROR;
2088 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2089 s->s3->tmp.peer_ca_names = ca_sk;
2094 *al = SSL_AD_DECODE_ERROR;
2096 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2101 int construct_ca_names(SSL *s, WPACKET *pkt)
2103 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2105 /* Start sub-packet for client CA list */
2106 if (!WPACKET_start_sub_packet_u16(pkt))
2109 if (ca_sk != NULL) {
2112 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2113 unsigned char *namebytes;
2114 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2118 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2119 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2121 || i2d_X509_NAME(name, &namebytes) != namelen) {
2127 if (!WPACKET_close(pkt))