2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
14 #include "../ssl_locl.h"
15 #include "statem_locl.h"
16 #include <openssl/buffer.h>
17 #include <openssl/objects.h>
18 #include <openssl/evp.h>
19 #include <openssl/x509.h>
22 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
23 * SSL3_RT_CHANGE_CIPHER_SPEC)
25 int ssl3_do_write(SSL *s, int type)
30 ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
31 s->init_num, &written);
34 if (type == SSL3_RT_HANDSHAKE)
36 * should not be done for 'Hello Request's, but in that case we'll
37 * ignore the result anyway
39 if (!ssl3_finish_mac(s,
40 (unsigned char *)&s->init_buf->data[s->init_off],
44 if (written == s->init_num) {
46 s->msg_callback(1, s->version, type, s->init_buf->data,
47 (size_t)(s->init_off + s->init_num), s,
51 s->init_off += written;
52 s->init_num -= written;
56 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
60 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
61 || !WPACKET_get_length(pkt, &msglen)
64 s->init_num = (int)msglen;
70 int tls_setup_handshake(SSL *s)
72 if (!ssl3_init_finished_mac(s))
75 /* Reset any extension flags */
76 memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
79 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(s);
80 int i, ver_min, ver_max, ok = 0;
83 * Sanity check that the maximum version we accept has ciphers
84 * enabled. For clients we do this check during construction of the
87 if (ssl_get_min_max_version(s, &ver_min, &ver_max) != 0) {
88 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, ERR_R_INTERNAL_ERROR);
89 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
92 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
93 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
96 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
97 DTLS_VERSION_LE(ver_max, c->max_dtls))
99 } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
106 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE, SSL_R_NO_CIPHERS_AVAILABLE);
107 ERR_add_error_data(1, "No ciphers enabled for max supported "
109 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
112 if (SSL_IS_FIRST_HANDSHAKE(s)) {
113 s->ctx->stats.sess_accept++;
114 } else if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
115 /* Renegotiation is disabled */
116 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
118 } else if (!s->s3->send_connection_binding &&
120 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
122 * Server attempting to renegotiate with client that doesn't
123 * support secure renegotiation.
125 SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
126 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
127 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
130 s->ctx->stats.sess_accept_renegotiate++;
132 s->s3->tmp.cert_request = 0;
135 if (SSL_IS_FIRST_HANDSHAKE(s))
136 s->ctx->stats.sess_connect++;
138 s->ctx->stats.sess_connect_renegotiate++;
140 /* mark client_random uninitialized */
141 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
144 s->s3->tmp.cert_req = 0;
147 s->statem.use_timer = 1;
154 * Size of the to-be-signed TLS13 data, without the hash size itself:
155 * 64 bytes of value 32, 33 context bytes, 1 byte separator
157 #define TLS13_TBS_START_SIZE 64
158 #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
160 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
161 void **hdata, size_t *hdatalen)
163 static const char *servercontext = "TLS 1.3, server CertificateVerify";
164 static const char *clientcontext = "TLS 1.3, client CertificateVerify";
166 if (SSL_IS_TLS13(s)) {
169 /* Set the first 64 bytes of to-be-signed data to octet 32 */
170 memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
171 /* This copies the 33 bytes of context plus the 0 separator byte */
172 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
173 || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
174 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
176 strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
179 * If we're currently reading then we need to use the saved handshake
180 * hash value. We can't use the current handshake hash state because
181 * that includes the CertVerify itself.
183 if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
184 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
185 memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
186 s->cert_verify_hash_len);
187 hashlen = s->cert_verify_hash_len;
188 } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
189 EVP_MAX_MD_SIZE, &hashlen)) {
194 *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
198 retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
207 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
209 EVP_PKEY *pkey = NULL;
210 const EVP_MD *md = NULL;
211 EVP_MD_CTX *mctx = NULL;
212 EVP_PKEY_CTX *pctx = NULL;
213 size_t hdatalen = 0, siglen = 0;
215 unsigned char *sig = NULL;
216 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
217 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
219 if (lu == NULL || s->s3->tmp.cert == NULL) {
220 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
223 pkey = s->s3->tmp.cert->privatekey;
224 md = ssl_md(lu->hash_idx);
226 if (pkey == NULL || md == NULL) {
227 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
231 mctx = EVP_MD_CTX_new();
233 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
237 /* Get the data to be signed */
238 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
239 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
243 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
244 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
247 siglen = EVP_PKEY_size(pkey);
248 sig = OPENSSL_malloc(siglen);
250 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
254 if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
255 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
259 if (lu->sig == EVP_PKEY_RSA_PSS) {
260 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
261 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
262 RSA_PSS_SALTLEN_DIGEST) <= 0) {
263 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
267 if (s->version == SSL3_VERSION) {
268 if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
269 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
270 (int)s->session->master_key_length,
271 s->session->master_key)
272 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
274 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
277 } else if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
278 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
282 #ifndef OPENSSL_NO_GOST
284 int pktype = lu->sig;
286 if (pktype == NID_id_GostR3410_2001
287 || pktype == NID_id_GostR3410_2012_256
288 || pktype == NID_id_GostR3410_2012_512)
289 BUF_reverse(sig, NULL, siglen);
293 if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
294 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
298 /* Digest cached records and discard handshake buffer */
299 if (!ssl3_digest_cached_records(s, 0))
303 EVP_MD_CTX_free(mctx);
307 EVP_MD_CTX_free(mctx);
308 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
312 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
314 EVP_PKEY *pkey = NULL;
315 const unsigned char *data;
316 #ifndef OPENSSL_NO_GOST
317 unsigned char *gost_data = NULL;
319 int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
323 const EVP_MD *md = NULL;
326 unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
327 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
328 EVP_PKEY_CTX *pctx = NULL;
331 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
335 peer = s->session->peer;
336 pkey = X509_get0_pubkey(peer);
340 type = X509_certificate_type(peer, pkey);
342 if (!(type & EVP_PKT_SIGN)) {
343 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
344 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
345 al = SSL_AD_ILLEGAL_PARAMETER;
349 if (SSL_USE_SIGALGS(s)) {
353 if (!PACKET_get_net_2(pkt, &sigalg)) {
354 al = SSL_AD_DECODE_ERROR;
357 rv = tls12_check_peer_sigalg(s, sigalg, pkey);
360 } else if (rv == 0) {
361 al = SSL_AD_DECODE_ERROR;
365 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
367 } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
368 al = SSL_AD_INTERNAL_ERROR;
372 md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
374 /* Check for broken implementations of GOST ciphersuites */
376 * If key is GOST and len is exactly 64 or 128, it is signature without
377 * length field (CryptoPro implementations at least till TLS 1.2)
379 #ifndef OPENSSL_NO_GOST
380 if (!SSL_USE_SIGALGS(s)
381 && ((PACKET_remaining(pkt) == 64
382 && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
383 || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
384 || (PACKET_remaining(pkt) == 128
385 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
386 len = PACKET_remaining(pkt);
389 if (!PACKET_get_net_2(pkt, &len)) {
390 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
391 al = SSL_AD_DECODE_ERROR;
395 j = EVP_PKEY_size(pkey);
396 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
397 || (PACKET_remaining(pkt) == 0)) {
398 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
399 al = SSL_AD_DECODE_ERROR;
402 if (!PACKET_get_bytes(pkt, &data, len)) {
403 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
404 al = SSL_AD_DECODE_ERROR;
408 if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
409 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
414 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
416 if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0) {
417 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
420 #ifndef OPENSSL_NO_GOST
422 int pktype = EVP_PKEY_id(pkey);
423 if (pktype == NID_id_GostR3410_2001
424 || pktype == NID_id_GostR3410_2012_256
425 || pktype == NID_id_GostR3410_2012_512) {
426 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
427 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
430 BUF_reverse(gost_data, data, len);
436 if (SSL_USE_PSS(s)) {
437 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
438 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
439 RSA_PSS_SALTLEN_DIGEST) <= 0) {
440 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
444 if (s->version == SSL3_VERSION) {
445 if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
446 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
447 (int)s->session->master_key_length,
448 s->session->master_key)) {
449 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
452 if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
453 al = SSL_AD_DECRYPT_ERROR;
454 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
458 j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
460 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
463 al = SSL_AD_DECRYPT_ERROR;
464 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
469 ret = MSG_PROCESS_CONTINUE_READING;
472 ssl3_send_alert(s, SSL3_AL_FATAL, al);
473 ossl_statem_set_error(s);
475 BIO_free(s->s3->handshake_buffer);
476 s->s3->handshake_buffer = NULL;
477 EVP_MD_CTX_free(mctx);
478 #ifndef OPENSSL_NO_GOST
479 OPENSSL_free(gost_data);
484 int tls_construct_finished(SSL *s, WPACKET *pkt)
486 size_t finish_md_len;
490 /* This is a real handshake so make sure we clean it up at the end */
492 s->statem.cleanuphand = 1;
495 * We only change the keys if we didn't already do this when we sent the
500 && s->s3->tmp.cert_req == 0
501 && (!s->method->ssl3_enc->change_cipher_state(s,
502 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
503 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
508 sender = s->method->ssl3_enc->server_finished_label;
509 slen = s->method->ssl3_enc->server_finished_label_len;
511 sender = s->method->ssl3_enc->client_finished_label;
512 slen = s->method->ssl3_enc->client_finished_label_len;
515 finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
517 s->s3->tmp.finish_md);
518 if (finish_md_len == 0) {
519 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
523 s->s3->tmp.finish_md_len = finish_md_len;
525 if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
526 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
531 * Log the master secret, if logging is enabled. We don't log it for
532 * TLSv1.3: there's a different key schedule for that.
534 if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
535 s->session->master_key,
536 s->session->master_key_length)) {
537 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
542 * Copy the finished so we can use it for renegotiation checks
544 if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
545 SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
549 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
551 s->s3->previous_client_finished_len = finish_md_len;
553 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
555 s->s3->previous_server_finished_len = finish_md_len;
560 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
564 int tls_construct_key_update(SSL *s, WPACKET *pkt)
566 if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
567 SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
571 s->key_update = SSL_KEY_UPDATE_NONE;
575 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
579 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
582 unsigned int updatetype;
584 s->key_update_count++;
585 if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
586 al = SSL_AD_ILLEGAL_PARAMETER;
587 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
592 * A KeyUpdate message signals a key change so the end of the message must
593 * be on a record boundary.
595 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
596 al = SSL_AD_UNEXPECTED_MESSAGE;
597 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
601 if (!PACKET_get_1(pkt, &updatetype)
602 || PACKET_remaining(pkt) != 0) {
603 al = SSL_AD_DECODE_ERROR;
604 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
609 * There are only two defined key update types. Fail if we get a value we
612 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
613 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
614 al = SSL_AD_ILLEGAL_PARAMETER;
615 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
620 * If we get a request for us to update our sending keys too then, we need
621 * to additionally send a KeyUpdate message. However that message should
622 * not also request an update (otherwise we get into an infinite loop).
624 if (updatetype == SSL_KEY_UPDATE_REQUESTED)
625 s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
627 if (!tls13_update_key(s, 0)) {
628 al = SSL_AD_INTERNAL_ERROR;
629 SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
633 return MSG_PROCESS_FINISHED_READING;
635 ssl3_send_alert(s, SSL3_AL_FATAL, al);
636 ossl_statem_set_error(s);
637 return MSG_PROCESS_ERROR;
640 #ifndef OPENSSL_NO_NEXTPROTONEG
642 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
645 static void ssl3_take_mac(SSL *s)
650 * If no new cipher setup return immediately: other functions will set
651 * the appropriate error.
653 if (s->s3->tmp.new_cipher == NULL)
656 sender = s->method->ssl3_enc->server_finished_label;
657 slen = s->method->ssl3_enc->server_finished_label_len;
659 sender = s->method->ssl3_enc->client_finished_label;
660 slen = s->method->ssl3_enc->client_finished_label_len;
663 s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
666 s->s3->tmp.peer_finish_md);
670 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
675 remain = PACKET_remaining(pkt);
677 * 'Change Cipher Spec' is just a single byte, which should already have
678 * been consumed by ssl_get_message() so there should be no bytes left,
679 * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
681 if (SSL_IS_DTLS(s)) {
682 if ((s->version == DTLS1_BAD_VER
683 && remain != DTLS1_CCS_HEADER_LENGTH + 1)
684 || (s->version != DTLS1_BAD_VER
685 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
686 al = SSL_AD_DECODE_ERROR;
687 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
688 SSL_R_BAD_CHANGE_CIPHER_SPEC);
693 al = SSL_AD_DECODE_ERROR;
694 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
695 SSL_R_BAD_CHANGE_CIPHER_SPEC);
700 /* Check we have a cipher to change to */
701 if (s->s3->tmp.new_cipher == NULL) {
702 al = SSL_AD_UNEXPECTED_MESSAGE;
703 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
707 s->s3->change_cipher_spec = 1;
708 if (!ssl3_do_change_cipher_spec(s)) {
709 al = SSL_AD_INTERNAL_ERROR;
710 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
714 if (SSL_IS_DTLS(s)) {
715 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
717 if (s->version == DTLS1_BAD_VER)
718 s->d1->handshake_read_seq++;
720 #ifndef OPENSSL_NO_SCTP
722 * Remember that a CCS has been received, so that an old key of
723 * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
726 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
730 return MSG_PROCESS_CONTINUE_READING;
732 ssl3_send_alert(s, SSL3_AL_FATAL, al);
733 ossl_statem_set_error(s);
734 return MSG_PROCESS_ERROR;
737 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
739 int al = SSL_AD_INTERNAL_ERROR;
743 /* This is a real handshake so make sure we clean it up at the end */
745 s->statem.cleanuphand = 1;
748 * In TLSv1.3 a Finished message signals a key change so the end of the
749 * message must be on a record boundary.
751 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
752 al = SSL_AD_UNEXPECTED_MESSAGE;
753 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
757 /* If this occurs, we have missed a message */
758 if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
759 al = SSL_AD_UNEXPECTED_MESSAGE;
760 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
763 s->s3->change_cipher_spec = 0;
765 md_len = s->s3->tmp.peer_finish_md_len;
767 if (md_len != PACKET_remaining(pkt)) {
768 al = SSL_AD_DECODE_ERROR;
769 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
773 if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
775 al = SSL_AD_DECRYPT_ERROR;
776 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
781 * Copy the finished so we can use it for renegotiation checks
783 if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
784 al = SSL_AD_INTERNAL_ERROR;
785 SSLerr(SSL_F_TLS_PROCESS_FINISHED, ERR_R_INTERNAL_ERROR);
789 memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
791 s->s3->previous_client_finished_len = md_len;
793 memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
795 s->s3->previous_server_finished_len = md_len;
799 * In TLS1.3 we also have to change cipher state and do any final processing
800 * of the initial server flight (if we are a client)
802 if (SSL_IS_TLS13(s)) {
804 if (!s->method->ssl3_enc->change_cipher_state(s,
805 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
806 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
810 if (!s->method->ssl3_enc->generate_master_secret(s,
811 s->master_secret, s->handshake_secret, 0,
812 &s->session->master_key_length)) {
813 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
816 if (!s->method->ssl3_enc->change_cipher_state(s,
817 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
818 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
821 if (!tls_process_initial_server_flight(s, &al))
826 return MSG_PROCESS_FINISHED_READING;
828 ssl3_send_alert(s, SSL3_AL_FATAL, al);
829 ossl_statem_set_error(s);
830 return MSG_PROCESS_ERROR;
833 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
835 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
836 SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
837 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
844 /* Add a certificate to the WPACKET */
845 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
849 unsigned char *outbytes;
851 len = i2d_X509(x, NULL);
853 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
854 *al = SSL_AD_INTERNAL_ERROR;
857 if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
858 || i2d_X509(x, &outbytes) != len) {
859 SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
860 *al = SSL_AD_INTERNAL_ERROR;
865 && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
872 /* Add certificate chain to provided WPACKET */
873 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
877 STACK_OF(X509) *extra_certs;
878 STACK_OF(X509) *chain = NULL;
879 X509_STORE *chain_store;
880 int tmpal = SSL_AD_INTERNAL_ERROR;
882 if (cpk == NULL || cpk->x509 == NULL)
888 * If we have a certificate specific chain use it, else use parent ctx.
890 if (cpk->chain != NULL)
891 extra_certs = cpk->chain;
893 extra_certs = s->ctx->extra_certs;
895 if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
897 else if (s->cert->chain_store)
898 chain_store = s->cert->chain_store;
900 chain_store = s->ctx->cert_store;
902 if (chain_store != NULL) {
903 X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
905 if (xs_ctx == NULL) {
906 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
909 if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
910 X509_STORE_CTX_free(xs_ctx);
911 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
915 * It is valid for the chain not to be complete (because normally we
916 * don't include the root cert in the chain). Therefore we deliberately
917 * ignore the error return from this call. We're not actually verifying
918 * the cert - we're just building as much of the chain as we can
920 (void)X509_verify_cert(xs_ctx);
921 /* Don't leave errors in the queue */
923 chain = X509_STORE_CTX_get0_chain(xs_ctx);
924 i = ssl_security_cert_chain(s, chain, NULL, 0);
927 /* Dummy error calls so mkerr generates them */
928 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
929 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
930 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
932 X509_STORE_CTX_free(xs_ctx);
933 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
936 chain_count = sk_X509_num(chain);
937 for (i = 0; i < chain_count; i++) {
938 x = sk_X509_value(chain, i);
940 if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
941 X509_STORE_CTX_free(xs_ctx);
945 X509_STORE_CTX_free(xs_ctx);
947 i = ssl_security_cert_chain(s, extra_certs, x, 0);
949 SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
952 if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
954 for (i = 0; i < sk_X509_num(extra_certs); i++) {
955 x = sk_X509_value(extra_certs, i);
956 if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
967 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
970 int tmpal = SSL_AD_INTERNAL_ERROR;
972 if (!WPACKET_start_sub_packet_u24(pkt)
973 || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
974 || !WPACKET_close(pkt)) {
975 SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
983 * Tidy up after the end of a handshake. In the case of SCTP this may result
984 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
987 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
989 void (*cb) (const SSL *ssl, int type, int val) = NULL;
991 #ifndef OPENSSL_NO_SCTP
992 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
994 ret = dtls_wait_for_dry(s);
995 if (ret != WORK_FINISHED_CONTINUE)
1001 if (!SSL_IS_DTLS(s)) {
1003 * We don't do this in DTLS because we may still need the init_buf
1004 * in case there are any unexpected retransmits
1006 BUF_MEM_free(s->init_buf);
1009 if (!ssl_free_wbio_buffer(s))
1014 if (s->statem.cleanuphand) {
1015 /* skipped if we just sent a HelloRequest */
1018 s->statem.cleanuphand = 0;
1020 ssl3_cleanup_key_block(s);
1023 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1025 s->ctx->stats.sess_accept_good++;
1026 s->handshake_func = ossl_statem_accept;
1028 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1030 s->ctx->stats.sess_hit++;
1032 s->handshake_func = ossl_statem_connect;
1033 s->ctx->stats.sess_connect_good++;
1036 if (s->info_callback != NULL)
1037 cb = s->info_callback;
1038 else if (s->ctx->info_callback != NULL)
1039 cb = s->ctx->info_callback;
1042 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1044 if (SSL_IS_DTLS(s)) {
1045 /* done with handshaking */
1046 s->d1->handshake_read_seq = 0;
1047 s->d1->handshake_write_seq = 0;
1048 s->d1->next_handshake_write_seq = 0;
1049 dtls1_clear_received_buffer(s);
1054 * If we've not cleared the buffers its because we've got more work to do,
1058 return WORK_FINISHED_CONTINUE;
1060 ossl_statem_set_in_init(s, 0);
1061 return WORK_FINISHED_STOP;
1064 int tls_get_message_header(SSL *s, int *mt)
1066 /* s->init_num < SSL3_HM_HEADER_LENGTH */
1067 int skip_message, i, recvd_type, al;
1069 size_t l, readbytes;
1071 p = (unsigned char *)s->init_buf->data;
1074 while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1075 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1077 SSL3_HM_HEADER_LENGTH - s->init_num,
1080 s->rwstate = SSL_READING;
1083 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1085 * A ChangeCipherSpec must be a single byte and may not occur
1086 * in the middle of a handshake message.
1088 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1089 al = SSL_AD_UNEXPECTED_MESSAGE;
1090 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1091 SSL_R_BAD_CHANGE_CIPHER_SPEC);
1094 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1095 s->init_num = readbytes - 1;
1096 s->init_msg = s->init_buf->data;
1097 s->s3->tmp.message_size = readbytes;
1099 } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1100 al = SSL_AD_UNEXPECTED_MESSAGE;
1101 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1104 s->init_num += readbytes;
1109 if (s->statem.hand_state != TLS_ST_OK
1110 && p[0] == SSL3_MT_HELLO_REQUEST)
1112 * The server may always send 'Hello Request' messages --
1113 * we are doing a handshake anyway now, so ignore them if
1114 * their format is correct. Does not count for 'Finished'
1117 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1121 if (s->msg_callback)
1122 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1123 p, SSL3_HM_HEADER_LENGTH, s,
1124 s->msg_callback_arg);
1126 } while (skip_message);
1127 /* s->init_num == SSL3_HM_HEADER_LENGTH */
1130 s->s3->tmp.message_type = *(p++);
1132 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1134 * Only happens with SSLv3+ in an SSLv2 backward compatible
1137 * Total message size is the remaining record bytes to read
1138 * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1140 l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1141 + SSL3_HM_HEADER_LENGTH;
1142 s->s3->tmp.message_size = l;
1144 s->init_msg = s->init_buf->data;
1145 s->init_num = SSL3_HM_HEADER_LENGTH;
1148 /* BUF_MEM_grow takes an 'int' parameter */
1149 if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1150 al = SSL_AD_ILLEGAL_PARAMETER;
1151 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1154 s->s3->tmp.message_size = l;
1156 s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1162 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1166 int tls_get_message_body(SSL *s, size_t *len)
1168 size_t n, readbytes;
1172 if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1173 /* We've already read everything in */
1174 *len = (unsigned long)s->init_num;
1179 n = s->s3->tmp.message_size - s->init_num;
1181 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1182 &p[s->init_num], n, 0, &readbytes);
1184 s->rwstate = SSL_READING;
1188 s->init_num += readbytes;
1192 #ifndef OPENSSL_NO_NEXTPROTONEG
1194 * If receiving Finished, record MAC of prior handshake messages for
1195 * Finished verification.
1197 if (*s->init_buf->data == SSL3_MT_FINISHED)
1201 /* Feed this message into MAC computation. */
1202 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1203 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1205 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1206 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1210 if (s->msg_callback)
1211 s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1212 (size_t)s->init_num, s, s->msg_callback_arg);
1215 * We defer feeding in the HRR until later. We'll do it as part of
1216 * processing the message
1218 if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1219 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1220 s->init_num + SSL3_HM_HEADER_LENGTH)) {
1221 SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1222 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1226 if (s->msg_callback)
1227 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1228 (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1229 s->msg_callback_arg);
1236 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1238 if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1241 switch (EVP_PKEY_id(pk)) {
1245 return SSL_PKEY_RSA;
1247 return SSL_PKEY_DSA_SIGN;
1248 #ifndef OPENSSL_NO_EC
1250 return SSL_PKEY_ECC;
1252 #ifndef OPENSSL_NO_GOST
1253 case NID_id_GostR3410_2001:
1254 return SSL_PKEY_GOST01;
1255 case NID_id_GostR3410_2012_256:
1256 return SSL_PKEY_GOST12_256;
1257 case NID_id_GostR3410_2012_512:
1258 return SSL_PKEY_GOST12_512;
1263 int ssl_verify_alarm_type(long type)
1268 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1269 case X509_V_ERR_UNABLE_TO_GET_CRL:
1270 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1271 al = SSL_AD_UNKNOWN_CA;
1273 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1274 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1275 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1276 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1277 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1278 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1279 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1280 case X509_V_ERR_CERT_NOT_YET_VALID:
1281 case X509_V_ERR_CRL_NOT_YET_VALID:
1282 case X509_V_ERR_CERT_UNTRUSTED:
1283 case X509_V_ERR_CERT_REJECTED:
1284 case X509_V_ERR_HOSTNAME_MISMATCH:
1285 case X509_V_ERR_EMAIL_MISMATCH:
1286 case X509_V_ERR_IP_ADDRESS_MISMATCH:
1287 case X509_V_ERR_DANE_NO_MATCH:
1288 case X509_V_ERR_EE_KEY_TOO_SMALL:
1289 case X509_V_ERR_CA_KEY_TOO_SMALL:
1290 case X509_V_ERR_CA_MD_TOO_WEAK:
1291 al = SSL_AD_BAD_CERTIFICATE;
1293 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1294 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1295 al = SSL_AD_DECRYPT_ERROR;
1297 case X509_V_ERR_CERT_HAS_EXPIRED:
1298 case X509_V_ERR_CRL_HAS_EXPIRED:
1299 al = SSL_AD_CERTIFICATE_EXPIRED;
1301 case X509_V_ERR_CERT_REVOKED:
1302 al = SSL_AD_CERTIFICATE_REVOKED;
1304 case X509_V_ERR_UNSPECIFIED:
1305 case X509_V_ERR_OUT_OF_MEM:
1306 case X509_V_ERR_INVALID_CALL:
1307 case X509_V_ERR_STORE_LOOKUP:
1308 al = SSL_AD_INTERNAL_ERROR;
1310 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1311 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1312 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1313 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1314 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1315 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1316 case X509_V_ERR_INVALID_CA:
1317 al = SSL_AD_UNKNOWN_CA;
1319 case X509_V_ERR_APPLICATION_VERIFICATION:
1320 al = SSL_AD_HANDSHAKE_FAILURE;
1322 case X509_V_ERR_INVALID_PURPOSE:
1323 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1326 al = SSL_AD_CERTIFICATE_UNKNOWN;
1332 int ssl_allow_compression(SSL *s)
1334 if (s->options & SSL_OP_NO_COMPRESSION)
1336 return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1339 static int version_cmp(const SSL *s, int a, int b)
1341 int dtls = SSL_IS_DTLS(s);
1346 return a < b ? -1 : 1;
1347 return DTLS_VERSION_LT(a, b) ? -1 : 1;
1352 const SSL_METHOD *(*cmeth) (void);
1353 const SSL_METHOD *(*smeth) (void);
1356 #if TLS_MAX_VERSION != TLS1_3_VERSION
1357 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1360 /* Must be in order high to low */
1361 static const version_info tls_version_table[] = {
1362 #ifndef OPENSSL_NO_TLS1_3
1363 {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1365 {TLS1_3_VERSION, NULL, NULL},
1367 #ifndef OPENSSL_NO_TLS1_2
1368 {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1370 {TLS1_2_VERSION, NULL, NULL},
1372 #ifndef OPENSSL_NO_TLS1_1
1373 {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1375 {TLS1_1_VERSION, NULL, NULL},
1377 #ifndef OPENSSL_NO_TLS1
1378 {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1380 {TLS1_VERSION, NULL, NULL},
1382 #ifndef OPENSSL_NO_SSL3
1383 {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1385 {SSL3_VERSION, NULL, NULL},
1390 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1391 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1394 /* Must be in order high to low */
1395 static const version_info dtls_version_table[] = {
1396 #ifndef OPENSSL_NO_DTLS1_2
1397 {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1399 {DTLS1_2_VERSION, NULL, NULL},
1401 #ifndef OPENSSL_NO_DTLS1
1402 {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1403 {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1405 {DTLS1_VERSION, NULL, NULL},
1406 {DTLS1_BAD_VER, NULL, NULL},
1412 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1414 * @s: The SSL handle for the candidate method
1415 * @method: the intended method.
1417 * Returns 0 on success, or an SSL error reason on failure.
1419 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1421 int version = method->version;
1423 if ((s->min_proto_version != 0 &&
1424 version_cmp(s, version, s->min_proto_version) < 0) ||
1425 ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1426 return SSL_R_VERSION_TOO_LOW;
1428 if (s->max_proto_version != 0 &&
1429 version_cmp(s, version, s->max_proto_version) > 0)
1430 return SSL_R_VERSION_TOO_HIGH;
1432 if ((s->options & method->mask) != 0)
1433 return SSL_R_UNSUPPORTED_PROTOCOL;
1434 if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1435 return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1441 * ssl_version_supported - Check that the specified `version` is supported by
1444 * @s: The SSL handle for the candidate method
1445 * @version: Protocol version to test against
1447 * Returns 1 when supported, otherwise 0
1449 int ssl_version_supported(const SSL *s, int version)
1451 const version_info *vent;
1452 const version_info *table;
1454 switch (s->method->version) {
1456 /* Version should match method version for non-ANY method */
1457 return version_cmp(s, version, s->version) == 0;
1458 case TLS_ANY_VERSION:
1459 table = tls_version_table;
1461 case DTLS_ANY_VERSION:
1462 table = dtls_version_table;
1467 vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1469 if (vent->cmeth != NULL &&
1470 version_cmp(s, version, vent->version) == 0 &&
1471 ssl_method_error(s, vent->cmeth()) == 0) {
1479 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1480 * fallback indication from a client check whether we're using the highest
1481 * supported protocol version.
1483 * @s server SSL handle.
1485 * Returns 1 when using the highest enabled version, 0 otherwise.
1487 int ssl_check_version_downgrade(SSL *s)
1489 const version_info *vent;
1490 const version_info *table;
1493 * Check that the current protocol is the highest enabled version
1494 * (according to s->ctx->method, as version negotiation may have changed
1497 if (s->version == s->ctx->method->version)
1501 * Apparently we're using a version-flexible SSL_METHOD (not at its
1502 * highest protocol version).
1504 if (s->ctx->method->version == TLS_method()->version)
1505 table = tls_version_table;
1506 else if (s->ctx->method->version == DTLS_method()->version)
1507 table = dtls_version_table;
1509 /* Unexpected state; fail closed. */
1513 for (vent = table; vent->version != 0; ++vent) {
1514 if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1515 return s->version == vent->version;
1521 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1522 * protocols, provided the initial (D)TLS method is version-flexible. This
1523 * function sanity-checks the proposed value and makes sure the method is
1524 * version-flexible, then sets the limit if all is well.
1526 * @method_version: The version of the current SSL_METHOD.
1527 * @version: the intended limit.
1528 * @bound: pointer to limit to be updated.
1530 * Returns 1 on success, 0 on failure.
1532 int ssl_set_version_bound(int method_version, int version, int *bound)
1540 * Restrict TLS methods to TLS protocol versions.
1541 * Restrict DTLS methods to DTLS protocol versions.
1542 * Note, DTLS version numbers are decreasing, use comparison macros.
1544 * Note that for both lower-bounds we use explicit versions, not
1545 * (D)TLS_MIN_VERSION. This is because we don't want to break user
1546 * configurations. If the MIN (supported) version ever rises, the user's
1547 * "floor" remains valid even if no longer available. We don't expect the
1548 * MAX ceiling to ever get lower, so making that variable makes sense.
1550 switch (method_version) {
1553 * XXX For fixed version methods, should we always fail and not set any
1554 * bounds, always succeed and not set any bounds, or set the bounds and
1555 * arrange to fail later if they are not met? At present fixed-version
1556 * methods are not subject to controls that disable individual protocol
1561 case TLS_ANY_VERSION:
1562 if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1566 case DTLS_ANY_VERSION:
1567 if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1568 DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1577 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1579 if (vers == TLS1_2_VERSION
1580 && ssl_version_supported(s, TLS1_3_VERSION)) {
1581 *dgrd = DOWNGRADE_TO_1_2;
1582 } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1583 && (ssl_version_supported(s, TLS1_2_VERSION)
1584 || ssl_version_supported(s, TLS1_3_VERSION))) {
1585 *dgrd = DOWNGRADE_TO_1_1;
1587 *dgrd = DOWNGRADE_NONE;
1592 * ssl_choose_server_version - Choose server (D)TLS version. Called when the
1593 * client HELLO is received to select the final server protocol version and
1594 * the version specific method.
1596 * @s: server SSL handle.
1598 * Returns 0 on success or an SSL error reason number on failure.
1600 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1603 * With version-flexible methods we have an initial state with:
1605 * s->method->version == (D)TLS_ANY_VERSION,
1606 * s->version == (D)TLS_MAX_VERSION.
1608 * So we detect version-flexible methods via the method version, not the
1611 int server_version = s->method->version;
1612 int client_version = hello->legacy_version;
1613 const version_info *vent;
1614 const version_info *table;
1616 RAW_EXTENSION *suppversions;
1618 s->client_version = client_version;
1620 switch (server_version) {
1622 if (!SSL_IS_TLS13(s)) {
1623 if (version_cmp(s, client_version, s->version) < 0)
1624 return SSL_R_WRONG_SSL_VERSION;
1625 *dgrd = DOWNGRADE_NONE;
1627 * If this SSL handle is not from a version flexible method we don't
1628 * (and never did) check min/max FIPS or Suite B constraints. Hope
1629 * that's OK. It is up to the caller to not choose fixed protocol
1630 * versions they don't want. If not, then easy to fix, just return
1631 * ssl_method_error(s, s->method)
1636 * Fall through if we are TLSv1.3 already (this means we must be after
1637 * a HelloRetryRequest
1640 case TLS_ANY_VERSION:
1641 table = tls_version_table;
1643 case DTLS_ANY_VERSION:
1644 table = dtls_version_table;
1648 suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1650 if (suppversions->present && !SSL_IS_DTLS(s)) {
1651 unsigned int candidate_vers = 0;
1652 unsigned int best_vers = 0;
1653 const SSL_METHOD *best_method = NULL;
1654 PACKET versionslist;
1656 suppversions->parsed = 1;
1658 if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1659 /* Trailing or invalid data? */
1660 return SSL_R_LENGTH_MISMATCH;
1663 while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1664 /* TODO(TLS1.3): Remove this before release */
1665 if (candidate_vers == TLS1_3_VERSION_DRAFT)
1666 candidate_vers = TLS1_3_VERSION;
1668 * TODO(TLS1.3): There is some discussion on the TLS list about
1669 * whether to ignore versions <TLS1.2 in supported_versions. At the
1670 * moment we honour them if present. To be reviewed later
1672 if (version_cmp(s, candidate_vers, best_vers) <= 0)
1675 vent->version != 0 && vent->version != (int)candidate_vers;
1678 if (vent->version != 0 && vent->smeth != NULL) {
1679 const SSL_METHOD *method;
1681 method = vent->smeth();
1682 if (ssl_method_error(s, method) == 0) {
1683 best_vers = candidate_vers;
1684 best_method = method;
1688 if (PACKET_remaining(&versionslist) != 0) {
1689 /* Trailing data? */
1690 return SSL_R_LENGTH_MISMATCH;
1693 if (best_vers > 0) {
1694 if (SSL_IS_TLS13(s)) {
1696 * We get here if this is after a HelloRetryRequest. In this
1697 * case we just check that we still negotiated TLSv1.3
1699 if (best_vers != TLS1_3_VERSION)
1700 return SSL_R_UNSUPPORTED_PROTOCOL;
1703 check_for_downgrade(s, best_vers, dgrd);
1704 s->version = best_vers;
1705 s->method = best_method;
1708 return SSL_R_UNSUPPORTED_PROTOCOL;
1712 * If the supported versions extension isn't present, then the highest
1713 * version we can negotiate is TLSv1.2
1715 if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1716 client_version = TLS1_2_VERSION;
1719 * No supported versions extension, so we just use the version supplied in
1722 for (vent = table; vent->version != 0; ++vent) {
1723 const SSL_METHOD *method;
1725 if (vent->smeth == NULL ||
1726 version_cmp(s, client_version, vent->version) < 0)
1728 method = vent->smeth();
1729 if (ssl_method_error(s, method) == 0) {
1730 check_for_downgrade(s, vent->version, dgrd);
1731 s->version = vent->version;
1737 return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1741 * ssl_choose_client_version - Choose client (D)TLS version. Called when the
1742 * server HELLO is received to select the final client protocol version and
1743 * the version specific method.
1745 * @s: client SSL handle.
1746 * @version: The proposed version from the server's HELLO.
1747 * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1748 * @al: Where to store any alert value that may be generated
1750 * Returns 0 on success or an SSL error reason number on failure.
1752 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1754 const version_info *vent;
1755 const version_info *table;
1758 /* TODO(TLS1.3): Remove this before release */
1759 if (version == TLS1_3_VERSION_DRAFT)
1760 version = TLS1_3_VERSION;
1762 if (s->hello_retry_request && version != TLS1_3_VERSION) {
1763 *al = SSL_AD_PROTOCOL_VERSION;
1764 return SSL_R_WRONG_SSL_VERSION;
1767 switch (s->method->version) {
1769 if (version != s->version) {
1770 *al = SSL_AD_PROTOCOL_VERSION;
1771 return SSL_R_WRONG_SSL_VERSION;
1774 * If this SSL handle is not from a version flexible method we don't
1775 * (and never did) check min/max, FIPS or Suite B constraints. Hope
1776 * that's OK. It is up to the caller to not choose fixed protocol
1777 * versions they don't want. If not, then easy to fix, just return
1778 * ssl_method_error(s, s->method)
1781 case TLS_ANY_VERSION:
1782 table = tls_version_table;
1784 case DTLS_ANY_VERSION:
1785 table = dtls_version_table;
1789 for (vent = table; vent->version != 0; ++vent) {
1790 const SSL_METHOD *method;
1793 if (vent->cmeth == NULL)
1796 if (highver != 0 && version != vent->version)
1799 method = vent->cmeth();
1800 err = ssl_method_error(s, method);
1802 if (version == vent->version) {
1803 *al = SSL_AD_PROTOCOL_VERSION;
1810 highver = vent->version;
1812 if (version != vent->version)
1815 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1816 /* Check for downgrades */
1818 if (version == TLS1_2_VERSION && highver > version) {
1819 if (memcmp(tls12downgrade,
1820 s->s3->server_random + SSL3_RANDOM_SIZE
1821 - sizeof(tls12downgrade),
1822 sizeof(tls12downgrade)) == 0) {
1823 *al = SSL_AD_ILLEGAL_PARAMETER;
1824 return SSL_R_INAPPROPRIATE_FALLBACK;
1826 } else if (!SSL_IS_DTLS(s)
1827 && version < TLS1_2_VERSION
1828 && highver > version) {
1829 if (memcmp(tls11downgrade,
1830 s->s3->server_random + SSL3_RANDOM_SIZE
1831 - sizeof(tls11downgrade),
1832 sizeof(tls11downgrade)) == 0) {
1833 *al = SSL_AD_ILLEGAL_PARAMETER;
1834 return SSL_R_INAPPROPRIATE_FALLBACK;
1841 s->version = version;
1845 *al = SSL_AD_PROTOCOL_VERSION;
1846 return SSL_R_UNSUPPORTED_PROTOCOL;
1850 * ssl_get_min_max_version - get minimum and maximum protocol version
1851 * @s: The SSL connection
1852 * @min_version: The minimum supported version
1853 * @max_version: The maximum supported version
1855 * Work out what version we should be using for the initial ClientHello if the
1856 * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
1857 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1858 * constraints and any floor imposed by the security level here,
1859 * so we don't advertise the wrong protocol version to only reject the outcome later.
1861 * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
1862 * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
1863 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1865 * Returns 0 on success or an SSL error reason number on failure. On failure
1866 * min_version and max_version will also be set to 0.
1868 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1872 const SSL_METHOD *single = NULL;
1873 const SSL_METHOD *method;
1874 const version_info *table;
1875 const version_info *vent;
1877 switch (s->method->version) {
1880 * If this SSL handle is not from a version flexible method we don't
1881 * (and never did) check min/max FIPS or Suite B constraints. Hope
1882 * that's OK. It is up to the caller to not choose fixed protocol
1883 * versions they don't want. If not, then easy to fix, just return
1884 * ssl_method_error(s, s->method)
1886 *min_version = *max_version = s->version;
1888 case TLS_ANY_VERSION:
1889 table = tls_version_table;
1891 case DTLS_ANY_VERSION:
1892 table = dtls_version_table;
1897 * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1898 * below X enabled. This is required in order to maintain the "version
1899 * capability" vector contiguous. Any versions with a NULL client method
1900 * (protocol version client is disabled at compile-time) is also a "hole".
1902 * Our initial state is hole == 1, version == 0. That is, versions above
1903 * the first version in the method table are disabled (a "hole" above
1904 * the valid protocol entries) and we don't have a selected version yet.
1906 * Whenever "hole == 1", and we hit an enabled method, its version becomes
1907 * the selected version, and the method becomes a candidate "single"
1908 * method. We're no longer in a hole, so "hole" becomes 0.
1910 * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1911 * as we support a contiguous range of at least two methods. If we hit
1912 * a disabled method, then hole becomes true again, but nothing else
1913 * changes yet, because all the remaining methods may be disabled too.
1914 * If we again hit an enabled method after the new hole, it becomes
1915 * selected, as we start from scratch.
1917 *min_version = version = 0;
1919 for (vent = table; vent->version != 0; ++vent) {
1921 * A table entry with a NULL client method is still a hole in the
1922 * "version capability" vector.
1924 if (vent->cmeth == NULL) {
1928 method = vent->cmeth();
1929 if (ssl_method_error(s, method) != 0) {
1933 *min_version = method->version;
1935 version = (single = method)->version;
1936 *min_version = version;
1941 *max_version = version;
1943 /* Fail if everything is disabled */
1945 return SSL_R_NO_PROTOCOLS_AVAILABLE;
1951 * ssl_set_client_hello_version - Work out what version we should be using for
1952 * the initial ClientHello.legacy_version field.
1954 * @s: client SSL handle.
1956 * Returns 0 on success or an SSL error reason number on failure.
1958 int ssl_set_client_hello_version(SSL *s)
1960 int ver_min, ver_max, ret;
1962 ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
1967 s->version = ver_max;
1969 /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1970 if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1971 ver_max = TLS1_2_VERSION;
1973 s->client_version = ver_max;
1978 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1979 * and |checkallow| is 1 then additionally check if the group is allowed to be
1980 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1981 * 1) or 0 otherwise.
1983 #ifndef OPENSSL_NO_EC
1984 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1985 size_t num_groups, int checkallow)
1989 if (groups == NULL || num_groups == 0)
1992 for (i = 0; i < num_groups; i++, groups += 2) {
1993 if (group_id == GET_GROUP_ID(groups, 0)
1995 || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
2004 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2005 int create_synthetic_message_hash(SSL *s)
2007 unsigned char hashval[EVP_MAX_MD_SIZE];
2009 unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2011 memset(msghdr, 0, sizeof(msghdr));
2013 /* Get the hash of the initial ClientHello */
2014 if (!ssl3_digest_cached_records(s, 0)
2015 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
2016 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2020 /* Reinitialise the transcript hash */
2021 if (!ssl3_init_finished_mac(s))
2024 /* Inject the synthetic message_hash message */
2025 msghdr[0] = SSL3_MT_MESSAGE_HASH;
2026 msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
2027 if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2028 || !ssl3_finish_mac(s, hashval, hashlen)) {
2029 SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
2036 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2038 return X509_NAME_cmp(*a, *b);
2041 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
2043 STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2044 X509_NAME *xn = NULL;
2047 if (ca_sk == NULL) {
2048 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2051 /* get the CA RDNs */
2052 if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2053 *al = SSL_AD_DECODE_ERROR;
2054 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2058 while (PACKET_remaining(&cadns)) {
2059 const unsigned char *namestart, *namebytes;
2060 unsigned int name_len;
2062 if (!PACKET_get_net_2(&cadns, &name_len)
2063 || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2064 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2068 namestart = namebytes;
2069 if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2070 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2073 if (namebytes != (namestart + name_len)) {
2074 SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2078 if (!sk_X509_NAME_push(ca_sk, xn)) {
2079 SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2080 *al = SSL_AD_INTERNAL_ERROR;
2086 sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2087 s->s3->tmp.peer_ca_names = ca_sk;
2092 *al = SSL_AD_DECODE_ERROR;
2094 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2099 int construct_ca_names(SSL *s, WPACKET *pkt)
2101 const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2103 /* Start sub-packet for client CA list */
2104 if (!WPACKET_start_sub_packet_u16(pkt))
2107 if (ca_sk != NULL) {
2110 for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2111 unsigned char *namebytes;
2112 X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2116 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2117 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2119 || i2d_X509_NAME(name, &namebytes) != namelen) {
2125 if (!WPACKET_close(pkt))