2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
111 /* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
124 /* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
151 #define REUSE_CIPHER_BUG
152 #define NETSCAPE_HANG_BUG
155 #include "ssl_locl.h"
156 #include "kssl_lcl.h"
157 #include "../crypto/constant_time_locl.h"
158 #include <openssl/buffer.h>
159 #include <openssl/rand.h>
160 #include <openssl/objects.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/x509.h>
164 #ifndef OPENSSL_NO_DH
165 # include <openssl/dh.h>
167 #include <openssl/bn.h>
168 #ifndef OPENSSL_NO_KRB5
169 # include <openssl/krb5_asn.h>
171 #include <openssl/md5.h>
173 #ifndef OPENSSL_NO_SSL3_METHOD
174 static const SSL_METHOD *ssl3_get_server_method(int ver);
176 static const SSL_METHOD *ssl3_get_server_method(int ver)
178 if (ver == SSL3_VERSION)
179 return (SSLv3_server_method());
184 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
186 ssl_undefined_function, ssl3_get_server_method)
188 #ifndef OPENSSL_NO_SRP
189 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
191 int ret = SSL_ERROR_NONE;
193 *al = SSL_AD_UNRECOGNIZED_NAME;
195 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
196 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
197 if (s->srp_ctx.login == NULL) {
199 * RFC 5054 says SHOULD reject, we do so if There is no srp
203 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
205 ret = SSL_srp_server_param_with_username(s, al);
212 int ssl3_accept(SSL *s)
215 unsigned long alg_k, Time = (unsigned long)time(NULL);
216 void (*cb) (const SSL *ssl, int type, int val) = NULL;
218 int new_state, state, skip = 0;
220 RAND_add(&Time, sizeof(Time), 0);
224 if (s->info_callback != NULL)
225 cb = s->info_callback;
226 else if (s->ctx->info_callback != NULL)
227 cb = s->ctx->info_callback;
229 /* init things to blank */
231 if (!SSL_in_init(s) || SSL_in_before(s))
234 if (s->cert == NULL) {
235 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
238 #ifndef OPENSSL_NO_HEARTBEATS
240 * If we're awaiting a HeartbeatResponse, pretend we already got and
241 * don't await it anymore, because Heartbeats don't make sense during
244 if (s->tlsext_hb_pending) {
245 s->tlsext_hb_pending = 0;
254 case SSL_ST_RENEGOTIATE:
256 /* s->state=SSL_ST_ACCEPT; */
260 case SSL_ST_BEFORE | SSL_ST_ACCEPT:
261 case SSL_ST_OK | SSL_ST_ACCEPT:
265 cb(s, SSL_CB_HANDSHAKE_START, 1);
267 if ((s->version >> 8) != 3) {
268 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
269 s->state = SSL_ST_ERR;
272 s->type = SSL_ST_ACCEPT;
274 if (s->init_buf == NULL) {
275 if ((buf = BUF_MEM_new()) == NULL) {
277 s->state = SSL_ST_ERR;
280 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
283 s->state = SSL_ST_ERR;
289 if (!ssl3_setup_buffers(s)) {
291 s->state = SSL_ST_ERR;
296 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
297 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
299 * Should have been reset by ssl3_get_finished, too.
301 s->s3->change_cipher_spec = 0;
303 if (s->state != SSL_ST_RENEGOTIATE) {
305 * Ok, we now need to push on a buffering BIO so that the
306 * output is sent in a way that TCP likes :-)
308 if (!ssl_init_wbio_buffer(s, 1)) {
310 s->state = SSL_ST_ERR;
314 ssl3_init_finished_mac(s);
315 s->state = SSL3_ST_SR_CLNT_HELLO_A;
316 s->ctx->stats.sess_accept++;
317 } else if (!s->s3->send_connection_binding &&
319 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
321 * Server attempting to renegotiate with client that doesn't
322 * support secure renegotiation.
324 SSLerr(SSL_F_SSL3_ACCEPT,
325 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
326 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
328 s->state = SSL_ST_ERR;
332 * s->state == SSL_ST_RENEGOTIATE, we will just send a
335 s->ctx->stats.sess_accept_renegotiate++;
336 s->state = SSL3_ST_SW_HELLO_REQ_A;
340 case SSL3_ST_SW_HELLO_REQ_A:
341 case SSL3_ST_SW_HELLO_REQ_B:
344 ret = ssl3_send_hello_request(s);
347 s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
348 s->state = SSL3_ST_SW_FLUSH;
351 ssl3_init_finished_mac(s);
354 case SSL3_ST_SW_HELLO_REQ_C:
355 s->state = SSL_ST_OK;
358 case SSL3_ST_SR_CLNT_HELLO_A:
359 case SSL3_ST_SR_CLNT_HELLO_B:
360 case SSL3_ST_SR_CLNT_HELLO_C:
363 ret = ssl3_get_client_hello(s);
366 #ifndef OPENSSL_NO_SRP
367 s->state = SSL3_ST_SR_CLNT_HELLO_D;
368 case SSL3_ST_SR_CLNT_HELLO_D:
371 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
373 * callback indicates firther work to be done
375 s->rwstate = SSL_X509_LOOKUP;
378 if (ret != SSL_ERROR_NONE) {
379 ssl3_send_alert(s, SSL3_AL_FATAL, al);
381 * This is not really an error but the only means to for
382 * a client to detect whether srp is supported.
384 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
385 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
387 s->state = SSL_ST_ERR;
394 s->state = SSL3_ST_SW_SRVR_HELLO_A;
398 case SSL3_ST_SW_SRVR_HELLO_A:
399 case SSL3_ST_SW_SRVR_HELLO_B:
400 ret = ssl3_send_server_hello(s);
403 #ifndef OPENSSL_NO_TLSEXT
405 if (s->tlsext_ticket_expected)
406 s->state = SSL3_ST_SW_SESSION_TICKET_A;
408 s->state = SSL3_ST_SW_CHANGE_A;
412 s->state = SSL3_ST_SW_CHANGE_A;
415 s->state = SSL3_ST_SW_CERT_A;
419 case SSL3_ST_SW_CERT_A:
420 case SSL3_ST_SW_CERT_B:
421 /* Check if it is anon DH or anon ECDH, */
422 /* normal PSK or KRB5 or SRP */
425 new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
427 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
428 ret = ssl3_send_server_certificate(s);
431 #ifndef OPENSSL_NO_TLSEXT
432 if (s->tlsext_status_expected)
433 s->state = SSL3_ST_SW_CERT_STATUS_A;
435 s->state = SSL3_ST_SW_KEY_EXCH_A;
438 s->state = SSL3_ST_SW_KEY_EXCH_A;
444 s->state = SSL3_ST_SW_KEY_EXCH_A;
449 case SSL3_ST_SW_KEY_EXCH_A:
450 case SSL3_ST_SW_KEY_EXCH_B:
451 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
454 * clear this, it may get reset by
455 * send_server_key_exchange
457 s->s3->tmp.use_rsa_tmp = 0;
460 * only send if a DH key exchange, fortezza or RSA but we have a
461 * sign only certificate PSK: may send PSK identity hints For
462 * ECC ciphersuites, we send a serverKeyExchange message only if
463 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
464 * the server certificate contains the server's public key for
469 * PSK: send ServerKeyExchange if PSK identity hint if
472 #ifndef OPENSSL_NO_PSK
473 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
475 #ifndef OPENSSL_NO_SRP
476 /* SRP: send ServerKeyExchange */
477 || (alg_k & SSL_kSRP)
479 || (alg_k & SSL_kEDH)
480 || (alg_k & SSL_kEECDH)
481 || ((alg_k & SSL_kRSA)
482 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
483 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
484 && EVP_PKEY_size(s->cert->pkeys
485 [SSL_PKEY_RSA_ENC].privatekey) *
486 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
491 ret = ssl3_send_server_key_exchange(s);
497 s->state = SSL3_ST_SW_CERT_REQ_A;
501 case SSL3_ST_SW_CERT_REQ_A:
502 case SSL3_ST_SW_CERT_REQ_B:
503 if ( /* don't request cert unless asked for it: */
504 !(s->verify_mode & SSL_VERIFY_PEER) ||
506 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
507 * during re-negotiation:
509 ((s->session->peer != NULL) &&
510 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
512 * never request cert in anonymous ciphersuites (see
513 * section "Certificate request" in SSL 3 drafts and in
516 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
518 * ... except when the application insists on
519 * verification (against the specs, but s3_clnt.c accepts
522 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
524 * never request cert in Kerberos ciphersuites
526 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
527 /* don't request certificate for SRP auth */
528 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
530 * With normal PSK Certificates and Certificate Requests
533 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
534 /* no cert request */
536 s->s3->tmp.cert_request = 0;
537 s->state = SSL3_ST_SW_SRVR_DONE_A;
538 if (s->s3->handshake_buffer) {
539 if (!ssl3_digest_cached_records(s)) {
540 s->state = SSL_ST_ERR;
545 s->s3->tmp.cert_request = 1;
546 ret = ssl3_send_certificate_request(s);
549 #ifndef NETSCAPE_HANG_BUG
550 s->state = SSL3_ST_SW_SRVR_DONE_A;
552 s->state = SSL3_ST_SW_FLUSH;
553 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
559 case SSL3_ST_SW_SRVR_DONE_A:
560 case SSL3_ST_SW_SRVR_DONE_B:
561 ret = ssl3_send_server_done(s);
564 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
565 s->state = SSL3_ST_SW_FLUSH;
569 case SSL3_ST_SW_FLUSH:
572 * This code originally checked to see if any data was pending
573 * using BIO_CTRL_INFO and then flushed. This caused problems as
574 * documented in PR#1939. The proposed fix doesn't completely
575 * resolve this issue as buggy implementations of
576 * BIO_CTRL_PENDING still exist. So instead we just flush
580 s->rwstate = SSL_WRITING;
581 if (BIO_flush(s->wbio) <= 0) {
585 s->rwstate = SSL_NOTHING;
587 s->state = s->s3->tmp.next_state;
590 case SSL3_ST_SR_CERT_A:
591 case SSL3_ST_SR_CERT_B:
592 if (s->s3->tmp.cert_request) {
593 ret = ssl3_get_client_certificate(s);
598 s->state = SSL3_ST_SR_KEY_EXCH_A;
601 case SSL3_ST_SR_KEY_EXCH_A:
602 case SSL3_ST_SR_KEY_EXCH_B:
603 ret = ssl3_get_client_key_exchange(s);
608 * For the ECDH ciphersuites when the client sends its ECDH
609 * pub key in a certificate, the CertificateVerify message is
610 * not sent. Also for GOST ciphersuites when the client uses
611 * its key from the certificate for key exchange.
613 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
614 s->state = SSL3_ST_SR_FINISHED_A;
616 if (s->s3->next_proto_neg_seen)
617 s->state = SSL3_ST_SR_NEXT_PROTO_A;
619 s->state = SSL3_ST_SR_FINISHED_A;
622 } else if (SSL_USE_SIGALGS(s)) {
623 s->state = SSL3_ST_SR_CERT_VRFY_A;
625 if (!s->session->peer)
628 * For sigalgs freeze the handshake buffer at this point and
629 * digest cached records.
631 if (!s->s3->handshake_buffer) {
632 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
633 s->state = SSL_ST_ERR;
636 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
637 if (!ssl3_digest_cached_records(s)) {
638 s->state = SSL_ST_ERR;
645 s->state = SSL3_ST_SR_CERT_VRFY_A;
649 * We need to get hashes here so if there is a client cert,
650 * it can be verified FIXME - digest processing for
651 * CertificateVerify should be generalized. But it is next
654 if (s->s3->handshake_buffer) {
655 if (!ssl3_digest_cached_records(s)) {
656 s->state = SSL_ST_ERR;
660 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
661 if (s->s3->handshake_dgst[dgst_num]) {
664 s->method->ssl3_enc->cert_verify_mac(s,
673 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
675 s->state = SSL_ST_ERR;
684 case SSL3_ST_SR_CERT_VRFY_A:
685 case SSL3_ST_SR_CERT_VRFY_B:
686 ret = ssl3_get_cert_verify(s);
690 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
691 s->state = SSL3_ST_SR_FINISHED_A;
693 if (s->s3->next_proto_neg_seen)
694 s->state = SSL3_ST_SR_NEXT_PROTO_A;
696 s->state = SSL3_ST_SR_FINISHED_A;
701 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
702 case SSL3_ST_SR_NEXT_PROTO_A:
703 case SSL3_ST_SR_NEXT_PROTO_B:
705 * Enable CCS for NPN. Receiving a CCS clears the flag, so make
706 * sure not to re-enable it to ban duplicates. This *should* be the
707 * first time we have received one - but we check anyway to be
709 * s->s3->change_cipher_spec is set when a CCS is
710 * processed in s3_pkt.c, and remains set until
711 * the client's Finished message is read.
713 if (!s->s3->change_cipher_spec)
714 s->s3->flags |= SSL3_FLAGS_CCS_OK;
716 ret = ssl3_get_next_proto(s);
720 s->state = SSL3_ST_SR_FINISHED_A;
724 case SSL3_ST_SR_FINISHED_A:
725 case SSL3_ST_SR_FINISHED_B:
727 * Enable CCS for handshakes without NPN. In NPN the CCS flag has
728 * already been set. Receiving a CCS clears the flag, so make
729 * sure not to re-enable it to ban duplicates.
730 * s->s3->change_cipher_spec is set when a CCS is
731 * processed in s3_pkt.c, and remains set until
732 * the client's Finished message is read.
734 if (!s->s3->change_cipher_spec)
735 s->s3->flags |= SSL3_FLAGS_CCS_OK;
736 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
737 SSL3_ST_SR_FINISHED_B);
741 s->state = SSL_ST_OK;
742 #ifndef OPENSSL_NO_TLSEXT
743 else if (s->tlsext_ticket_expected)
744 s->state = SSL3_ST_SW_SESSION_TICKET_A;
747 s->state = SSL3_ST_SW_CHANGE_A;
751 #ifndef OPENSSL_NO_TLSEXT
752 case SSL3_ST_SW_SESSION_TICKET_A:
753 case SSL3_ST_SW_SESSION_TICKET_B:
754 ret = ssl3_send_newsession_ticket(s);
757 s->state = SSL3_ST_SW_CHANGE_A;
761 case SSL3_ST_SW_CERT_STATUS_A:
762 case SSL3_ST_SW_CERT_STATUS_B:
763 ret = ssl3_send_cert_status(s);
766 s->state = SSL3_ST_SW_KEY_EXCH_A;
772 case SSL3_ST_SW_CHANGE_A:
773 case SSL3_ST_SW_CHANGE_B:
775 s->session->cipher = s->s3->tmp.new_cipher;
776 if (!s->method->ssl3_enc->setup_key_block(s)) {
778 s->state = SSL_ST_ERR;
782 ret = ssl3_send_change_cipher_spec(s,
784 SSL3_ST_SW_CHANGE_B);
788 s->state = SSL3_ST_SW_FINISHED_A;
791 if (!s->method->ssl3_enc->change_cipher_state(s,
792 SSL3_CHANGE_CIPHER_SERVER_WRITE))
795 s->state = SSL_ST_ERR;
801 case SSL3_ST_SW_FINISHED_A:
802 case SSL3_ST_SW_FINISHED_B:
803 ret = ssl3_send_finished(s,
804 SSL3_ST_SW_FINISHED_A,
805 SSL3_ST_SW_FINISHED_B,
807 ssl3_enc->server_finished_label,
809 ssl3_enc->server_finished_label_len);
812 s->state = SSL3_ST_SW_FLUSH;
814 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
815 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
817 if (s->s3->next_proto_neg_seen) {
818 s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
820 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
823 s->s3->tmp.next_state = SSL_ST_OK;
828 /* clean a few things up */
829 ssl3_cleanup_key_block(s);
831 BUF_MEM_free(s->init_buf);
834 /* remove buffering on output */
835 ssl_free_wbio_buffer(s);
839 if (s->renegotiate == 2) { /* skipped if we just sent a
844 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
846 s->ctx->stats.sess_accept_good++;
848 s->handshake_func = ssl3_accept;
851 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
860 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
866 if (!s->s3->tmp.reuse_message && !skip) {
868 if ((ret = BIO_flush(s->wbio)) <= 0)
872 if ((cb != NULL) && (s->state != state)) {
873 new_state = s->state;
875 cb(s, SSL_CB_ACCEPT_LOOP, 1);
876 s->state = new_state;
882 /* BIO_flush(s->wbio); */
886 cb(s, SSL_CB_ACCEPT_EXIT, ret);
890 int ssl3_send_hello_request(SSL *s)
893 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
894 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
895 s->state = SSL3_ST_SW_HELLO_REQ_B;
898 /* SSL3_ST_SW_HELLO_REQ_B */
899 return ssl_do_write(s);
902 int ssl3_get_client_hello(SSL *s)
904 int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0;
905 unsigned int cookie_len;
908 unsigned char *p, *d;
910 #ifndef OPENSSL_NO_COMP
912 SSL_COMP *comp = NULL;
914 STACK_OF(SSL_CIPHER) *ciphers = NULL;
916 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
920 * We do this so that we will respond with our native type. If we are
921 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
922 * switching should be handled by a different method. If we are SSLv3, we
923 * will respond with SSLv3, even if prompted with TLSv1.
925 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
926 s->state = SSL3_ST_SR_CLNT_HELLO_B;
929 n = s->method->ssl_get_message(s,
930 SSL3_ST_SR_CLNT_HELLO_B,
931 SSL3_ST_SR_CLNT_HELLO_C,
932 SSL3_MT_CLIENT_HELLO,
933 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
938 d = p = (unsigned char *)s->init_msg;
941 * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
942 * for session id length
944 if (n < 2 + SSL3_RANDOM_SIZE + 1) {
945 al = SSL_AD_DECODE_ERROR;
946 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
951 * use version from inside client hello, not from record header (may
952 * differ: see RFC 2246, Appendix E, second paragraph)
954 s->client_version = (((int)p[0]) << 8) | (int)p[1];
957 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
958 s->method->version != DTLS_ANY_VERSION)
959 : (s->client_version < s->version)) {
960 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
961 if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
962 !s->enc_write_ctx && !s->write_hash) {
964 * similar to ssl3_get_record, send alert using remote version
967 s->version = s->client_version;
969 al = SSL_AD_PROTOCOL_VERSION;
974 * If we require cookies and this ClientHello doesn't contain one, just
975 * return since we do not want to allocate any memory yet. So check
978 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
979 unsigned int session_length, cookie_length;
981 session_length = *(p + SSL3_RANDOM_SIZE);
983 if (SSL3_RANDOM_SIZE + session_length + 1
984 >= (unsigned int)((d + n) - p)) {
985 al = SSL_AD_DECODE_ERROR;
986 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
989 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
991 if (cookie_length == 0)
995 /* load the client random */
996 memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
997 p += SSL3_RANDOM_SIZE;
999 /* get the session-id */
1002 if ((d + n) - p < j) {
1003 al = SSL_AD_DECODE_ERROR;
1004 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1008 if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
1009 al = SSL_AD_DECODE_ERROR;
1010 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1016 * Versions before 0.9.7 always allow clients to resume sessions in
1017 * renegotiation. 0.9.7 and later allow this by default, but optionally
1018 * ignore resumption requests with flag
1019 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1020 * than a change to default behavior so that applications relying on this
1021 * for security won't even compile against older library versions).
1022 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1023 * request renegotiation but not a new session (s->new_session remains
1024 * unset): for servers, this essentially just means that the
1025 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
1028 && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1029 if (!ssl_get_new_session(s, 1))
1032 i = ssl_get_prev_session(s, p, j, d + n);
1034 * Only resume if the session's version matches the negotiated
1036 * RFC 5246 does not provide much useful advice on resumption
1037 * with a different protocol version. It doesn't forbid it but
1038 * the sanity of such behaviour would be questionable.
1039 * In practice, clients do not accept a version mismatch and
1040 * will abort the handshake with an error.
1042 if (i == 1 && s->version == s->session->ssl_version) { /* previous
1049 if (!ssl_get_new_session(s, 1))
1056 if (SSL_IS_DTLS(s)) {
1058 if ((d + n) - p < 1) {
1059 al = SSL_AD_DECODE_ERROR;
1060 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1063 cookie_len = *(p++);
1065 if ((unsigned int)((d + n ) - p) < cookie_len) {
1066 al = SSL_AD_DECODE_ERROR;
1067 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1072 * The ClientHello may contain a cookie even if the
1073 * HelloVerify message has not been sent--make sure that it
1074 * does not cause an overflow.
1076 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1078 al = SSL_AD_DECODE_ERROR;
1079 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1083 /* verify the cookie if appropriate option is set. */
1084 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1085 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1087 if (s->ctx->app_verify_cookie_cb != NULL) {
1088 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1090 al = SSL_AD_HANDSHAKE_FAILURE;
1091 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1092 SSL_R_COOKIE_MISMATCH);
1095 /* else cookie verification succeeded */
1097 /* default verification */
1098 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1099 s->d1->cookie_len) != 0) {
1100 al = SSL_AD_HANDSHAKE_FAILURE;
1101 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1108 if (s->method->version == DTLS_ANY_VERSION) {
1109 /* Select version to use */
1110 if (s->client_version <= DTLS1_2_VERSION &&
1111 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1112 s->version = DTLS1_2_VERSION;
1113 s->method = DTLSv1_2_server_method();
1114 } else if (tls1_suiteb(s)) {
1115 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1116 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1117 s->version = s->client_version;
1118 al = SSL_AD_PROTOCOL_VERSION;
1120 } else if (s->client_version <= DTLS1_VERSION &&
1121 !(s->options & SSL_OP_NO_DTLSv1)) {
1122 s->version = DTLS1_VERSION;
1123 s->method = DTLSv1_server_method();
1125 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1126 SSL_R_WRONG_VERSION_NUMBER);
1127 s->version = s->client_version;
1128 al = SSL_AD_PROTOCOL_VERSION;
1131 s->session->ssl_version = s->version;
1135 if ((d + n ) - p < 2) {
1136 al = SSL_AD_DECODE_ERROR;
1137 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1143 al = SSL_AD_ILLEGAL_PARAMETER;
1144 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1148 /* i bytes of cipher data + 1 byte for compression length later */
1149 if ((d + n) - p < i + 1) {
1150 /* not enough data */
1151 al = SSL_AD_DECODE_ERROR;
1152 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1155 if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1160 /* If it is a hit, check that the cipher is in the list */
1163 id = s->session->cipher->id;
1166 fprintf(stderr, "client sent %d ciphers\n",
1167 sk_SSL_CIPHER_num(ciphers));
1169 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1170 c = sk_SSL_CIPHER_value(ciphers, i);
1172 fprintf(stderr, "client [%2d of %2d]:%s\n",
1173 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1181 * Disabled because it can be used in a ciphersuite downgrade attack:
1185 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1186 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1188 * Special case as client bug workaround: the previously used
1189 * cipher may not be in the current list, the client instead
1190 * might be trying to continue using a cipher that before wasn't
1191 * chosen due to server preferences. We'll have to reject the
1192 * connection if the cipher is not enabled, though.
1194 c = sk_SSL_CIPHER_value(ciphers, 0);
1195 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1196 s->session->cipher = c;
1203 * we need to have the cipher in the cipher list if we are asked
1206 al = SSL_AD_ILLEGAL_PARAMETER;
1207 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1208 SSL_R_REQUIRED_CIPHER_MISSING);
1215 if ((d + n) - p < i) {
1216 /* not enough data */
1217 al = SSL_AD_DECODE_ERROR;
1218 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1221 #ifndef OPENSSL_NO_COMP
1224 for (j = 0; j < i; j++) {
1232 al = SSL_AD_DECODE_ERROR;
1233 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1236 #ifndef OPENSSL_NO_TLSEXT
1237 /* TLS extensions */
1238 if (s->version >= SSL3_VERSION) {
1239 if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) {
1240 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1246 * Check if we want to use external pre-shared secret for this handshake
1247 * for not reused session only. We need to generate server_random before
1248 * calling tls_session_secret_cb in order to allow SessionTicket
1249 * processing to use it in key derivation.
1253 pos = s->s3->server_random;
1254 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1259 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1260 SSL_CIPHER *pref_cipher = NULL;
1262 s->session->master_key_length = sizeof(s->session->master_key);
1263 if (s->tls_session_secret_cb(s, s->session->master_key,
1264 &s->session->master_key_length, ciphers,
1266 s->tls_session_secret_cb_arg)) {
1268 s->session->ciphers = ciphers;
1269 s->session->verify_result = X509_V_OK;
1273 /* check if some cipher was preferred by call back */
1275 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1280 if (pref_cipher == NULL) {
1281 al = SSL_AD_HANDSHAKE_FAILURE;
1282 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1286 s->session->cipher = pref_cipher;
1289 sk_SSL_CIPHER_free(s->cipher_list);
1291 if (s->cipher_list_by_id)
1292 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1294 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1295 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1301 * Worst case, we will use the NULL compression, but if we have other
1302 * options, we will now look for them. We have i-1 compression
1303 * algorithms from the client, starting at q.
1305 s->s3->tmp.new_compression = NULL;
1306 #ifndef OPENSSL_NO_COMP
1307 /* This only happens if we have a cache hit */
1308 if (s->session->compress_meth != 0) {
1309 int m, comp_id = s->session->compress_meth;
1310 /* Perform sanity checks on resumed compression algorithm */
1311 /* Can't disable compression */
1312 if (s->options & SSL_OP_NO_COMPRESSION) {
1313 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1314 SSL_R_INCONSISTENT_COMPRESSION);
1317 /* Look for resumed compression method */
1318 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1319 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1320 if (comp_id == comp->id) {
1321 s->s3->tmp.new_compression = comp;
1325 if (s->s3->tmp.new_compression == NULL) {
1326 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1327 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1330 /* Look for resumed method in compression list */
1331 for (m = 0; m < i; m++) {
1332 if (q[m] == comp_id)
1336 al = SSL_AD_ILLEGAL_PARAMETER;
1337 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1338 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1343 else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
1344 /* See if we have a match */
1345 int m, nn, o, v, done = 0;
1347 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1348 for (m = 0; m < nn; m++) {
1349 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1351 for (o = 0; o < i; o++) {
1361 s->s3->tmp.new_compression = comp;
1367 * If compression is disabled we'd better not try to resume a session
1368 * using compression.
1370 if (s->session->compress_meth != 0) {
1371 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1377 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1381 #ifdef OPENSSL_NO_COMP
1382 s->session->compress_meth = 0;
1384 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1386 if (s->session->ciphers != NULL)
1387 sk_SSL_CIPHER_free(s->session->ciphers);
1388 s->session->ciphers = ciphers;
1389 if (ciphers == NULL) {
1390 al = SSL_AD_INTERNAL_ERROR;
1391 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1395 if (!tls1_set_server_sigalgs(s)) {
1396 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1399 /* Let cert callback update server certificates if required */
1401 if (s->cert->cert_cb) {
1402 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1404 al = SSL_AD_INTERNAL_ERROR;
1405 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1409 s->rwstate = SSL_X509_LOOKUP;
1412 s->rwstate = SSL_NOTHING;
1414 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1417 al = SSL_AD_HANDSHAKE_FAILURE;
1418 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1421 s->s3->tmp.new_cipher = c;
1423 /* Session-id reuse */
1424 #ifdef REUSE_CIPHER_BUG
1425 STACK_OF(SSL_CIPHER) *sk;
1426 SSL_CIPHER *nc = NULL;
1427 SSL_CIPHER *ec = NULL;
1429 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1430 sk = s->session->ciphers;
1431 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1432 c = sk_SSL_CIPHER_value(sk, i);
1433 if (c->algorithm_enc & SSL_eNULL)
1435 if (SSL_C_IS_EXPORT(c))
1439 s->s3->tmp.new_cipher = nc;
1440 else if (ec != NULL)
1441 s->s3->tmp.new_cipher = ec;
1443 s->s3->tmp.new_cipher = s->session->cipher;
1446 s->s3->tmp.new_cipher = s->session->cipher;
1449 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1450 if (!ssl3_digest_cached_records(s))
1455 * we now have the following setup.
1457 * cipher_list - our prefered list of ciphers
1458 * ciphers - the clients prefered list of ciphers
1459 * compression - basically ignored right now
1460 * ssl version is set - sslv3
1461 * s->session - The ssl session has been setup.
1462 * s->hit - session reuse flag
1463 * s->tmp.new_cipher - the new cipher to use.
1466 /* Handles TLS extensions that we couldn't check earlier */
1467 if (s->version >= SSL3_VERSION) {
1468 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1469 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1474 ret = cookie_valid ? 2 : 1;
1477 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1479 s->state = SSL_ST_ERR;
1482 if (ciphers != NULL)
1483 sk_SSL_CIPHER_free(ciphers);
1487 int ssl3_send_server_hello(SSL *s)
1490 unsigned char *p, *d;
1495 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1496 buf = (unsigned char *)s->init_buf->data;
1497 #ifdef OPENSSL_NO_TLSEXT
1498 p = s->s3->server_random;
1499 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1500 s->state = SSL_ST_ERR;
1504 /* Do the message type and length last */
1505 d = p = ssl_handshake_start(s);
1507 *(p++) = s->version >> 8;
1508 *(p++) = s->version & 0xff;
1511 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1512 p += SSL3_RANDOM_SIZE;
1515 * There are several cases for the session ID to send
1516 * back in the server hello:
1517 * - For session reuse from the session cache,
1518 * we send back the old session ID.
1519 * - If stateless session reuse (using a session ticket)
1520 * is successful, we send back the client's "session ID"
1521 * (which doesn't actually identify the session).
1522 * - If it is a new session, we send back the new
1524 * - However, if we want the new session to be single-use,
1525 * we send back a 0-length session ID.
1526 * s->hit is non-zero in either case of session reuse,
1527 * so the following won't overwrite an ID that we're supposed
1530 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1532 s->session->session_id_length = 0;
1534 sl = s->session->session_id_length;
1535 if (sl > (int)sizeof(s->session->session_id)) {
1536 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1537 s->state = SSL_ST_ERR;
1541 memcpy(p, s->session->session_id, sl);
1544 /* put the cipher */
1545 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1548 /* put the compression method */
1549 #ifdef OPENSSL_NO_COMP
1552 if (s->s3->tmp.new_compression == NULL)
1555 *(p++) = s->s3->tmp.new_compression->id;
1557 #ifndef OPENSSL_NO_TLSEXT
1558 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1559 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1560 s->state = SSL_ST_ERR;
1564 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1566 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1567 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1568 s->state = SSL_ST_ERR;
1574 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1575 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1578 /* SSL3_ST_SW_SRVR_HELLO_B */
1579 return ssl_do_write(s);
1582 int ssl3_send_server_done(SSL *s)
1585 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1586 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1587 s->state = SSL3_ST_SW_SRVR_DONE_B;
1590 /* SSL3_ST_SW_SRVR_DONE_B */
1591 return ssl_do_write(s);
1594 int ssl3_send_server_key_exchange(SSL *s)
1596 #ifndef OPENSSL_NO_RSA
1600 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1603 #ifndef OPENSSL_NO_DH
1604 DH *dh = NULL, *dhp;
1606 #ifndef OPENSSL_NO_ECDH
1607 EC_KEY *ecdh = NULL, *ecdhp;
1608 unsigned char *encodedPoint = NULL;
1611 BN_CTX *bn_ctx = NULL;
1614 const EVP_MD *md = NULL;
1615 unsigned char *p, *d;
1625 EVP_MD_CTX_init(&md_ctx);
1626 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1627 type = s->s3->tmp.new_cipher->algorithm_mkey;
1632 r[0] = r[1] = r[2] = r[3] = NULL;
1634 #ifndef OPENSSL_NO_RSA
1635 if (type & SSL_kRSA) {
1636 rsa = cert->rsa_tmp;
1637 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1638 rsa = s->cert->rsa_tmp_cb(s,
1639 SSL_C_IS_EXPORT(s->s3->
1641 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1644 al = SSL_AD_HANDSHAKE_FAILURE;
1645 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1646 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1650 cert->rsa_tmp = rsa;
1653 al = SSL_AD_HANDSHAKE_FAILURE;
1654 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1655 SSL_R_MISSING_TMP_RSA_KEY);
1660 s->s3->tmp.use_rsa_tmp = 1;
1663 #ifndef OPENSSL_NO_DH
1664 if (type & SSL_kEDH) {
1666 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1667 dhp = s->cert->dh_tmp_cb(s,
1668 SSL_C_IS_EXPORT(s->s3->
1670 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1673 al = SSL_AD_HANDSHAKE_FAILURE;
1674 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1675 SSL_R_MISSING_TMP_DH_KEY);
1679 if (s->s3->tmp.dh != NULL) {
1680 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1681 ERR_R_INTERNAL_ERROR);
1685 if ((dh = DHparams_dup(dhp)) == NULL) {
1686 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1691 if (!DH_generate_key(dh)) {
1692 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1700 #ifndef OPENSSL_NO_ECDH
1701 if (type & SSL_kEECDH) {
1702 const EC_GROUP *group;
1704 ecdhp = cert->ecdh_tmp;
1705 if (s->cert->ecdh_tmp_auto) {
1706 /* Get NID of appropriate shared curve */
1707 int nid = tls1_shared_curve(s, -2);
1708 if (nid != NID_undef)
1709 ecdhp = EC_KEY_new_by_curve_name(nid);
1710 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1711 ecdhp = s->cert->ecdh_tmp_cb(s,
1712 SSL_C_IS_EXPORT(s->s3->
1714 SSL_C_EXPORT_PKEYLENGTH(s->
1715 s3->tmp.new_cipher));
1717 if (ecdhp == NULL) {
1718 al = SSL_AD_HANDSHAKE_FAILURE;
1719 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1720 SSL_R_MISSING_TMP_ECDH_KEY);
1724 if (s->s3->tmp.ecdh != NULL) {
1725 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1726 ERR_R_INTERNAL_ERROR);
1730 /* Duplicate the ECDH structure. */
1731 if (ecdhp == NULL) {
1732 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1735 if (s->cert->ecdh_tmp_auto)
1737 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1738 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1742 s->s3->tmp.ecdh = ecdh;
1743 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1744 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1745 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1746 if (!EC_KEY_generate_key(ecdh)) {
1747 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1753 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1754 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1755 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1756 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1760 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1761 (EC_GROUP_get_degree(group) > 163)) {
1762 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1763 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1768 * XXX: For now, we only support ephemeral ECDH keys over named
1769 * (not generic) curves. For supported named curves, curve_id is
1773 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1775 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1776 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1781 * Encode the public key. First check the size of encoding and
1782 * allocate memory accordingly.
1784 encodedlen = EC_POINT_point2oct(group,
1785 EC_KEY_get0_public_key(ecdh),
1786 POINT_CONVERSION_UNCOMPRESSED,
1789 encodedPoint = (unsigned char *)
1790 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1791 bn_ctx = BN_CTX_new();
1792 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1793 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1794 ERR_R_MALLOC_FAILURE);
1798 encodedlen = EC_POINT_point2oct(group,
1799 EC_KEY_get0_public_key(ecdh),
1800 POINT_CONVERSION_UNCOMPRESSED,
1801 encodedPoint, encodedlen, bn_ctx);
1803 if (encodedlen == 0) {
1804 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1808 BN_CTX_free(bn_ctx);
1812 * XXX: For now, we only support named (not generic) curves in
1813 * ECDH ephemeral key exchanges. In this situation, we need four
1814 * additional bytes to encode the entire ServerECDHParams
1820 * We'll generate the serverKeyExchange message explicitly so we
1821 * can set these to NULLs
1828 #endif /* !OPENSSL_NO_ECDH */
1829 #ifndef OPENSSL_NO_PSK
1830 if (type & SSL_kPSK) {
1832 * reserve size for record length and PSK identity hint
1834 n += 2 + strlen(s->ctx->psk_identity_hint);
1836 #endif /* !OPENSSL_NO_PSK */
1837 #ifndef OPENSSL_NO_SRP
1838 if (type & SSL_kSRP) {
1839 if ((s->srp_ctx.N == NULL) ||
1840 (s->srp_ctx.g == NULL) ||
1841 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1842 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1843 SSL_R_MISSING_SRP_PARAM);
1846 r[0] = s->srp_ctx.N;
1847 r[1] = s->srp_ctx.g;
1848 r[2] = s->srp_ctx.s;
1849 r[3] = s->srp_ctx.B;
1853 al = SSL_AD_HANDSHAKE_FAILURE;
1854 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1855 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1858 for (i = 0; i < 4 && r[i] != NULL; i++) {
1859 nr[i] = BN_num_bytes(r[i]);
1860 #ifndef OPENSSL_NO_SRP
1861 if ((i == 2) && (type & SSL_kSRP))
1868 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1869 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1870 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1872 al = SSL_AD_DECODE_ERROR;
1875 kn = EVP_PKEY_size(pkey);
1876 /* Allow space for signature algorithm */
1877 if (SSL_USE_SIGALGS(s))
1879 /* Allow space for signature length */
1886 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1887 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1890 d = p = ssl_handshake_start(s);
1892 for (i = 0; i < 4 && r[i] != NULL; i++) {
1893 #ifndef OPENSSL_NO_SRP
1894 if ((i == 2) && (type & SSL_kSRP)) {
1904 #ifndef OPENSSL_NO_ECDH
1905 if (type & SSL_kEECDH) {
1907 * XXX: For now, we only support named (not generic) curves. In
1908 * this situation, the serverKeyExchange message has: [1 byte
1909 * CurveType], [2 byte CurveName] [1 byte length of encoded
1910 * point], followed by the actual encoded point itself
1912 *p = NAMED_CURVE_TYPE;
1920 memcpy((unsigned char *)p,
1921 (unsigned char *)encodedPoint, encodedlen);
1922 OPENSSL_free(encodedPoint);
1923 encodedPoint = NULL;
1928 #ifndef OPENSSL_NO_PSK
1929 if (type & SSL_kPSK) {
1930 /* copy PSK identity hint */
1931 s2n(strlen(s->ctx->psk_identity_hint), p);
1932 strncpy((char *)p, s->ctx->psk_identity_hint,
1933 strlen(s->ctx->psk_identity_hint));
1934 p += strlen(s->ctx->psk_identity_hint);
1941 * n is the length of the params, they start at &(d[4]) and p
1942 * points to the space at the end.
1944 #ifndef OPENSSL_NO_RSA
1945 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1948 for (num = 2; num > 0; num--) {
1949 EVP_MD_CTX_set_flags(&md_ctx,
1950 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1951 if (EVP_DigestInit_ex(&md_ctx,
1952 (num == 2) ? s->ctx->md5
1955 || EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1956 SSL3_RANDOM_SIZE) <= 0
1957 || EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1958 SSL3_RANDOM_SIZE) <= 0
1959 || EVP_DigestUpdate(&md_ctx, d, n) <= 0
1960 || EVP_DigestFinal_ex(&md_ctx, q,
1961 (unsigned int *)&i) <= 0) {
1962 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1964 al = SSL_AD_INTERNAL_ERROR;
1970 if (RSA_sign(NID_md5_sha1, md_buf, j,
1971 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1972 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1980 /* send signature algorithm */
1981 if (SSL_USE_SIGALGS(s)) {
1982 if (!tls12_get_sigandhash(p, pkey, md)) {
1983 /* Should never happen */
1984 al = SSL_AD_INTERNAL_ERROR;
1985 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1986 ERR_R_INTERNAL_ERROR);
1992 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1994 if (EVP_SignInit_ex(&md_ctx, md, NULL) <= 0
1995 || EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1996 SSL3_RANDOM_SIZE) <= 0
1997 || EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1998 SSL3_RANDOM_SIZE) <= 0
1999 || EVP_SignUpdate(&md_ctx, d, n) <= 0
2000 || EVP_SignFinal(&md_ctx, &(p[2]),
2001 (unsigned int *)&i, pkey) <= 0) {
2002 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2003 al = SSL_AD_INTERNAL_ERROR;
2008 if (SSL_USE_SIGALGS(s))
2011 /* Is this error check actually needed? */
2012 al = SSL_AD_HANDSHAKE_FAILURE;
2013 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2014 SSL_R_UNKNOWN_PKEY_TYPE);
2019 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2022 s->state = SSL3_ST_SW_KEY_EXCH_B;
2023 EVP_MD_CTX_cleanup(&md_ctx);
2024 return ssl_do_write(s);
2026 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2028 #ifndef OPENSSL_NO_ECDH
2029 if (encodedPoint != NULL)
2030 OPENSSL_free(encodedPoint);
2031 BN_CTX_free(bn_ctx);
2033 EVP_MD_CTX_cleanup(&md_ctx);
2034 s->state = SSL_ST_ERR;
2038 int ssl3_send_certificate_request(SSL *s)
2040 unsigned char *p, *d;
2041 int i, j, nl, off, n;
2042 STACK_OF(X509_NAME) *sk = NULL;
2046 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2049 d = p = ssl_handshake_start(s);
2051 /* get the list of acceptable cert types */
2053 n = ssl3_get_req_cert_type(s, p);
2058 if (SSL_USE_SIGALGS(s)) {
2059 const unsigned char *psigs;
2060 nl = tls12_get_psigalgs(s, &psigs);
2062 memcpy(p, psigs, nl);
2071 sk = SSL_get_client_CA_list(s);
2074 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2075 name = sk_X509_NAME_value(sk, i);
2076 j = i2d_X509_NAME(name, NULL);
2077 if (!BUF_MEM_grow_clean
2078 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2079 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2083 p = ssl_handshake_start(s) + n;
2084 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
2086 i2d_X509_NAME(name, &p);
2091 i2d_X509_NAME(name, &p);
2100 /* else no CA names */
2101 p = ssl_handshake_start(s) + off;
2104 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2106 #ifdef NETSCAPE_HANG_BUG
2107 if (!SSL_IS_DTLS(s)) {
2108 if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
2109 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
2112 p = (unsigned char *)s->init_buf->data + s->init_num;
2114 *(p++) = SSL3_MT_SERVER_DONE;
2122 s->state = SSL3_ST_SW_CERT_REQ_B;
2125 /* SSL3_ST_SW_CERT_REQ_B */
2126 return ssl_do_write(s);
2128 s->state = SSL_ST_ERR;
2132 int ssl3_get_client_key_exchange(SSL *s)
2136 unsigned long alg_k;
2138 #ifndef OPENSSL_NO_RSA
2140 EVP_PKEY *pkey = NULL;
2142 #ifndef OPENSSL_NO_DH
2144 DH *dh_srvr, *dh_clnt = NULL;
2146 #ifndef OPENSSL_NO_KRB5
2148 #endif /* OPENSSL_NO_KRB5 */
2150 #ifndef OPENSSL_NO_ECDH
2151 EC_KEY *srvr_ecdh = NULL;
2152 EVP_PKEY *clnt_pub_pkey = NULL;
2153 EC_POINT *clnt_ecpoint = NULL;
2154 BN_CTX *bn_ctx = NULL;
2157 n = s->method->ssl_get_message(s,
2158 SSL3_ST_SR_KEY_EXCH_A,
2159 SSL3_ST_SR_KEY_EXCH_B,
2160 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2164 p = (unsigned char *)s->init_msg;
2166 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2168 #ifndef OPENSSL_NO_RSA
2169 if (alg_k & SSL_kRSA) {
2170 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2172 unsigned char decrypt_good, version_good;
2175 /* FIX THIS UP EAY EAY EAY EAY */
2176 if (s->s3->tmp.use_rsa_tmp) {
2177 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2178 rsa = s->cert->rsa_tmp;
2180 * Don't do a callback because rsa_tmp should be sent already
2183 al = SSL_AD_HANDSHAKE_FAILURE;
2184 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2185 SSL_R_MISSING_TMP_RSA_PKEY);
2190 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2191 if ((pkey == NULL) ||
2192 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2193 al = SSL_AD_HANDSHAKE_FAILURE;
2194 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2195 SSL_R_MISSING_RSA_CERTIFICATE);
2198 rsa = pkey->pkey.rsa;
2201 /* TLS and [incidentally] DTLS{0xFEFF} */
2202 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2205 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2206 al = SSL_AD_DECODE_ERROR;
2207 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2208 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2217 * Reject overly short RSA ciphertext because we want to be sure
2218 * that the buffer size makes it safe to iterate over the entire
2219 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2220 * actual expected size is larger due to RSA padding, but the
2221 * bound is sufficient to be safe.
2223 if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2224 al = SSL_AD_DECRYPT_ERROR;
2225 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2226 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2231 * We must not leak whether a decryption failure occurs because of
2232 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2233 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2234 * generates a random premaster secret for the case that the decrypt
2235 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2238 if (RAND_bytes(rand_premaster_secret,
2239 sizeof(rand_premaster_secret)) <= 0)
2242 RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2246 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2247 * be 0xff if so and zero otherwise.
2250 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2253 * If the version in the decrypted pre-master secret is correct then
2254 * version_good will be 0xff, otherwise it'll be zero. The
2255 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2256 * (http://eprint.iacr.org/2003/052/) exploits the version number
2257 * check as a "bad version oracle". Thus version checks are done in
2258 * constant time and are treated like any other decryption error.
2261 constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2263 constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2266 * The premaster secret must contain the same version number as the
2267 * ClientHello to detect version rollback attacks (strangely, the
2268 * protocol does not offer such protection for DH ciphersuites).
2269 * However, buggy clients exist that send the negotiated protocol
2270 * version instead if the server does not support the requested
2271 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2274 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2275 unsigned char workaround_good;
2277 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2279 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2280 version_good |= workaround_good;
2284 * Both decryption and version must be good for decrypt_good to
2285 * remain non-zero (0xff).
2287 decrypt_good &= version_good;
2290 * Now copy rand_premaster_secret over from p using
2291 * decrypt_good_mask. If decryption failed, then p does not
2292 * contain valid plaintext, however, a check above guarantees
2293 * it is still sufficiently large to read from.
2295 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2296 p[j] = constant_time_select_8(decrypt_good, p[j],
2297 rand_premaster_secret[j]);
2300 s->session->master_key_length =
2301 s->method->ssl3_enc->generate_master_secret(s,
2303 session->master_key,
2306 (rand_premaster_secret));
2307 OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2310 #ifndef OPENSSL_NO_DH
2311 if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2313 EVP_PKEY *skey = NULL;
2317 if (alg_k & SSL_kDHE) {
2318 al = SSL_AD_HANDSHAKE_FAILURE;
2319 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2320 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2325 if (n && n != i + 2) {
2326 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2327 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2328 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2329 al = SSL_AD_HANDSHAKE_FAILURE;
2336 if (alg_k & SSL_kDHr)
2337 idx = SSL_PKEY_DH_RSA;
2338 else if (alg_k & SSL_kDHd)
2339 idx = SSL_PKEY_DH_DSA;
2341 skey = s->cert->pkeys[idx].privatekey;
2342 if ((skey == NULL) ||
2343 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2344 al = SSL_AD_HANDSHAKE_FAILURE;
2345 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2346 SSL_R_MISSING_RSA_CERTIFICATE);
2349 dh_srvr = skey->pkey.dh;
2350 } else if (s->s3->tmp.dh == NULL) {
2351 al = SSL_AD_HANDSHAKE_FAILURE;
2352 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2353 SSL_R_MISSING_TMP_DH_KEY);
2356 dh_srvr = s->s3->tmp.dh;
2359 /* Get pubkey from cert */
2360 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2362 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2363 dh_clnt = EVP_PKEY_get1_DH(clkey);
2365 if (dh_clnt == NULL) {
2366 al = SSL_AD_HANDSHAKE_FAILURE;
2367 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2368 SSL_R_MISSING_TMP_DH_KEY);
2371 EVP_PKEY_free(clkey);
2372 pub = dh_clnt->pub_key;
2374 pub = BN_bin2bn(p, i, NULL);
2376 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2380 i = DH_compute_key(p, pub, dh_srvr);
2383 al = SSL_AD_HANDSHAKE_FAILURE;
2384 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2389 DH_free(s->s3->tmp.dh);
2390 s->s3->tmp.dh = NULL;
2396 s->session->master_key_length =
2397 s->method->ssl3_enc->generate_master_secret(s,
2399 session->master_key,
2401 OPENSSL_cleanse(p, i);
2406 #ifndef OPENSSL_NO_KRB5
2407 if (alg_k & SSL_kKRB5) {
2408 krb5_error_code krb5rc;
2409 krb5_data enc_ticket;
2410 krb5_data authenticator;
2412 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2413 EVP_CIPHER_CTX ciph_ctx;
2414 const EVP_CIPHER *enc = NULL;
2415 unsigned char iv[EVP_MAX_IV_LENGTH];
2416 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2418 krb5_timestamp authtime = 0;
2419 krb5_ticket_times ttimes;
2422 EVP_CIPHER_CTX_init(&ciph_ctx);
2425 kssl_ctx = kssl_ctx_new();
2428 enc_ticket.length = i;
2430 if (n < (long)(enc_ticket.length + 6)) {
2431 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2432 SSL_R_DATA_LENGTH_TOO_LONG);
2436 enc_ticket.data = (char *)p;
2437 p += enc_ticket.length;
2440 authenticator.length = i;
2442 if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2443 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2444 SSL_R_DATA_LENGTH_TOO_LONG);
2448 authenticator.data = (char *)p;
2449 p += authenticator.length;
2453 enc_pms.data = (char *)p;
2454 p += enc_pms.length;
2457 * Note that the length is checked again below, ** after decryption
2459 if (enc_pms.length > sizeof pms) {
2460 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2461 SSL_R_DATA_LENGTH_TOO_LONG);
2465 if (n != (long)(enc_ticket.length + authenticator.length +
2466 enc_pms.length + 6)) {
2467 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2468 SSL_R_DATA_LENGTH_TOO_LONG);
2472 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2475 fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2476 krb5rc, kssl_err.reason);
2478 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2479 # endif /* KSSL_DEBUG */
2480 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2485 * Note: no authenticator is not considered an error, ** but will
2486 * return authtime == 0.
2488 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2489 &authtime, &kssl_err)) != 0) {
2491 fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2492 krb5rc, kssl_err.reason);
2494 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2495 # endif /* KSSL_DEBUG */
2496 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2500 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2501 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2505 kssl_ctx_show(kssl_ctx);
2506 # endif /* KSSL_DEBUG */
2508 enc = kssl_map_enc(kssl_ctx->enctype);
2512 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2514 if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2515 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2516 SSL_R_DECRYPTION_FAILED);
2519 if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2520 (unsigned char *)enc_pms.data, enc_pms.length))
2522 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2523 SSL_R_DECRYPTION_FAILED);
2527 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2528 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2529 SSL_R_DATA_LENGTH_TOO_LONG);
2533 if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2534 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2535 SSL_R_DECRYPTION_FAILED);
2540 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2541 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2542 SSL_R_DATA_LENGTH_TOO_LONG);
2546 if (!((pms[0] == (s->client_version >> 8))
2547 && (pms[1] == (s->client_version & 0xff)))) {
2549 * The premaster secret must contain the same version number as
2550 * the ClientHello to detect version rollback attacks (strangely,
2551 * the protocol does not offer such protection for DH
2552 * ciphersuites). However, buggy clients exist that send random
2553 * bytes instead of the protocol version. If
2554 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2555 * (Perhaps we should have a separate BUG value for the Kerberos
2558 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2559 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2560 SSL_AD_DECODE_ERROR);
2566 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2568 s->session->master_key_length =
2569 s->method->ssl3_enc->generate_master_secret(s,
2571 session->master_key,
2574 if (kssl_ctx->client_princ) {
2575 size_t len = strlen(kssl_ctx->client_princ);
2576 if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2577 s->session->krb5_client_princ_len = len;
2578 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2583 /*- Was doing kssl_ctx_free() here,
2584 * but it caused problems for apache.
2585 * kssl_ctx = kssl_ctx_free(kssl_ctx);
2586 * if (s->kssl_ctx) s->kssl_ctx = NULL;
2590 OPENSSL_cleanse(pms, sizeof(pms));
2594 #endif /* OPENSSL_NO_KRB5 */
2596 #ifndef OPENSSL_NO_ECDH
2597 if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2601 const EC_GROUP *group;
2602 const BIGNUM *priv_key;
2604 /* initialize structures for server's ECDH key pair */
2605 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2606 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2610 /* Let's get server private key and group information */
2611 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2612 /* use the certificate */
2613 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2616 * use the ephermeral values we saved when generating the
2617 * ServerKeyExchange msg.
2619 tkey = s->s3->tmp.ecdh;
2622 group = EC_KEY_get0_group(tkey);
2623 priv_key = EC_KEY_get0_private_key(tkey);
2625 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2626 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2627 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2631 /* Let's get client's public key */
2632 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2633 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2638 /* Client Publickey was in Client Certificate */
2640 if (alg_k & SSL_kEECDH) {
2641 al = SSL_AD_HANDSHAKE_FAILURE;
2642 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2643 SSL_R_MISSING_TMP_ECDH_KEY);
2646 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2647 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2649 * XXX: For now, we do not support client authentication
2650 * using ECDH certificates so this branch (n == 0L) of the
2651 * code is never executed. When that support is added, we
2652 * ought to ensure the key received in the certificate is
2653 * authorized for key agreement. ECDH_compute_key implicitly
2654 * checks that the two ECDH shares are for the same group.
2656 al = SSL_AD_HANDSHAKE_FAILURE;
2657 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2658 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2662 if (EC_POINT_copy(clnt_ecpoint,
2663 EC_KEY_get0_public_key(clnt_pub_pkey->
2665 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2668 ret = 2; /* Skip certificate verify processing */
2671 * Get client's public key from encoded point in the
2672 * ClientKeyExchange message.
2674 if ((bn_ctx = BN_CTX_new()) == NULL) {
2675 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2676 ERR_R_MALLOC_FAILURE);
2680 /* Get encoded point length */
2684 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2685 al = SSL_AD_DECODE_ERROR;
2688 if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2689 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2690 al = SSL_AD_HANDSHAKE_FAILURE;
2694 * p is pointing to somewhere in the buffer currently, so set it
2697 p = (unsigned char *)s->init_buf->data;
2700 /* Compute the shared pre-master secret */
2701 field_size = EC_GROUP_get_degree(group);
2702 if (field_size <= 0) {
2703 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2706 i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2709 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2713 EVP_PKEY_free(clnt_pub_pkey);
2714 EC_POINT_free(clnt_ecpoint);
2715 EC_KEY_free(srvr_ecdh);
2716 BN_CTX_free(bn_ctx);
2717 EC_KEY_free(s->s3->tmp.ecdh);
2718 s->s3->tmp.ecdh = NULL;
2720 /* Compute the master secret */
2721 s->session->master_key_length =
2722 s->method->ssl3_enc->generate_master_secret(s,
2724 session->master_key,
2727 OPENSSL_cleanse(p, i);
2731 #ifndef OPENSSL_NO_PSK
2732 if (alg_k & SSL_kPSK) {
2733 unsigned char *t = NULL;
2734 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2735 unsigned int pre_ms_len = 0, psk_len = 0;
2737 char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2739 al = SSL_AD_HANDSHAKE_FAILURE;
2743 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2746 if (i > PSK_MAX_IDENTITY_LEN) {
2747 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2748 SSL_R_DATA_LENGTH_TOO_LONG);
2751 if (s->psk_server_callback == NULL) {
2752 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2753 SSL_R_PSK_NO_SERVER_CB);
2758 * Create guaranteed NULL-terminated identity string for the callback
2760 memcpy(tmp_id, p, i);
2761 memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2762 psk_len = s->psk_server_callback(s, tmp_id,
2764 sizeof(psk_or_pre_ms));
2765 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2767 if (psk_len > PSK_MAX_PSK_LEN) {
2768 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2770 } else if (psk_len == 0) {
2772 * PSK related to the given identity not found
2774 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2775 SSL_R_PSK_IDENTITY_NOT_FOUND);
2776 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2780 /* create PSK pre_master_secret */
2781 pre_ms_len = 2 + psk_len + 2 + psk_len;
2783 memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2785 memset(t, 0, psk_len);
2789 if (s->session->psk_identity != NULL)
2790 OPENSSL_free(s->session->psk_identity);
2791 s->session->psk_identity = BUF_strndup((char *)p, i);
2792 if (s->session->psk_identity == NULL) {
2793 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2797 if (s->session->psk_identity_hint != NULL)
2798 OPENSSL_free(s->session->psk_identity_hint);
2799 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2800 if (s->ctx->psk_identity_hint != NULL &&
2801 s->session->psk_identity_hint == NULL) {
2802 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2806 s->session->master_key_length =
2807 s->method->ssl3_enc->generate_master_secret(s,
2809 session->master_key,
2814 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2819 #ifndef OPENSSL_NO_SRP
2820 if (alg_k & SSL_kSRP) {
2825 if (param_len > n) {
2826 al = SSL_AD_DECODE_ERROR;
2827 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2828 SSL_R_BAD_SRP_A_LENGTH);
2831 if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
2832 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2835 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2836 || BN_is_zero(s->srp_ctx.A)) {
2837 al = SSL_AD_ILLEGAL_PARAMETER;
2838 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2839 SSL_R_BAD_SRP_PARAMETERS);
2842 if (s->session->srp_username != NULL)
2843 OPENSSL_free(s->session->srp_username);
2844 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2845 if (s->session->srp_username == NULL) {
2846 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2850 if ((s->session->master_key_length =
2851 SRP_generate_server_master_secret(s,
2852 s->session->master_key)) < 0) {
2853 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2859 #endif /* OPENSSL_NO_SRP */
2860 if (alg_k & SSL_kGOST) {
2862 EVP_PKEY_CTX *pkey_ctx;
2863 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2864 unsigned char premaster_secret[32], *start;
2865 size_t outlen = 32, inlen;
2866 unsigned long alg_a;
2870 /* Get our certificate private key */
2871 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2872 if (alg_a & SSL_aGOST94)
2873 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2874 else if (alg_a & SSL_aGOST01)
2875 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2877 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2878 if (pkey_ctx == NULL) {
2879 al = SSL_AD_INTERNAL_ERROR;
2880 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2883 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2884 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2888 * If client certificate is present and is of the same type, maybe
2889 * use it for key exchange. Don't mind errors from
2890 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2891 * client certificate for authorization only.
2893 client_pub_pkey = X509_get_pubkey(s->session->peer);
2894 if (client_pub_pkey) {
2895 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2898 /* Decrypt session key */
2900 ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2901 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2902 || Tclass != V_ASN1_UNIVERSAL) {
2903 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2904 SSL_R_DECRYPTION_FAILED);
2909 if (EVP_PKEY_decrypt
2910 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2911 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2912 SSL_R_DECRYPTION_FAILED);
2915 /* Generate master secret */
2916 s->session->master_key_length =
2917 s->method->ssl3_enc->generate_master_secret(s,
2919 session->master_key,
2920 premaster_secret, 32);
2921 OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
2922 /* Check if pubkey from client certificate was used */
2923 if (EVP_PKEY_CTX_ctrl
2924 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2929 EVP_PKEY_free(client_pub_pkey);
2930 EVP_PKEY_CTX_free(pkey_ctx);
2936 al = SSL_AD_HANDSHAKE_FAILURE;
2937 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2943 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2944 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2947 #ifndef OPENSSL_NO_ECDH
2948 EVP_PKEY_free(clnt_pub_pkey);
2949 EC_POINT_free(clnt_ecpoint);
2950 if (srvr_ecdh != NULL)
2951 EC_KEY_free(srvr_ecdh);
2952 BN_CTX_free(bn_ctx);
2954 s->state = SSL_ST_ERR;
2958 int ssl3_get_cert_verify(SSL *s)
2960 EVP_PKEY *pkey = NULL;
2962 int al, ok, ret = 0;
2966 const EVP_MD *md = NULL;
2968 EVP_MD_CTX_init(&mctx);
2971 * We should only process a CertificateVerify message if we have received
2972 * a Certificate from the client. If so then |s->session->peer| will be non
2973 * NULL. In some instances a CertificateVerify message is not required even
2974 * if the peer has sent a Certificate (e.g. such as in the case of static
2975 * DH). In that case the ClientKeyExchange processing will skip the
2976 * CertificateVerify state so we should not arrive here.
2978 if (s->session->peer == NULL) {
2983 n = s->method->ssl_get_message(s,
2984 SSL3_ST_SR_CERT_VRFY_A,
2985 SSL3_ST_SR_CERT_VRFY_B,
2986 SSL3_MT_CERTIFICATE_VERIFY,
2987 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2992 peer = s->session->peer;
2993 pkey = X509_get_pubkey(peer);
2994 type = X509_certificate_type(peer, pkey);
2996 if (!(type & EVP_PKT_SIGN)) {
2997 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2998 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2999 al = SSL_AD_ILLEGAL_PARAMETER;
3003 /* we now have a signature that we need to verify */
3004 p = (unsigned char *)s->init_msg;
3005 /* Check for broken implementations of GOST ciphersuites */
3007 * If key is GOST and n is exactly 64, it is bare signature without
3010 if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
3011 pkey->type == NID_id_GostR3410_2001)) {
3014 if (SSL_USE_SIGALGS(s)) {
3015 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3017 al = SSL_AD_INTERNAL_ERROR;
3019 } else if (rv == 0) {
3020 al = SSL_AD_DECODE_ERROR;
3024 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3032 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3033 al = SSL_AD_DECODE_ERROR;
3037 j = EVP_PKEY_size(pkey);
3038 if ((i > j) || (n > j) || (n <= 0)) {
3039 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3040 al = SSL_AD_DECODE_ERROR;
3044 if (SSL_USE_SIGALGS(s)) {
3047 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3048 if (hdatalen <= 0) {
3049 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3050 al = SSL_AD_INTERNAL_ERROR;
3054 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3057 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3058 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3059 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3060 al = SSL_AD_INTERNAL_ERROR;
3064 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
3065 al = SSL_AD_DECRYPT_ERROR;
3066 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3070 #ifndef OPENSSL_NO_RSA
3071 if (pkey->type == EVP_PKEY_RSA) {
3072 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3073 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3076 al = SSL_AD_DECRYPT_ERROR;
3077 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3081 al = SSL_AD_DECRYPT_ERROR;
3082 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3087 #ifndef OPENSSL_NO_DSA
3088 if (pkey->type == EVP_PKEY_DSA) {
3089 j = DSA_verify(pkey->save_type,
3090 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3091 SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3094 al = SSL_AD_DECRYPT_ERROR;
3095 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3100 #ifndef OPENSSL_NO_ECDSA
3101 if (pkey->type == EVP_PKEY_EC) {
3102 j = ECDSA_verify(pkey->save_type,
3103 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3104 SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3107 al = SSL_AD_DECRYPT_ERROR;
3108 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3113 if (pkey->type == NID_id_GostR3410_94
3114 || pkey->type == NID_id_GostR3410_2001) {
3115 unsigned char signature[64];
3117 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3119 al = SSL_AD_INTERNAL_ERROR;
3120 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
3123 if (EVP_PKEY_verify_init(pctx) <= 0) {
3124 EVP_PKEY_CTX_free(pctx);
3125 al = SSL_AD_INTERNAL_ERROR;
3126 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3130 fprintf(stderr, "GOST signature length is %d", i);
3132 for (idx = 0; idx < 64; idx++) {
3133 signature[63 - idx] = p[idx];
3135 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3137 EVP_PKEY_CTX_free(pctx);
3139 al = SSL_AD_DECRYPT_ERROR;
3140 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3144 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3145 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3152 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3153 s->state = SSL_ST_ERR;
3156 if (s->s3->handshake_buffer) {
3157 BIO_free(s->s3->handshake_buffer);
3158 s->s3->handshake_buffer = NULL;
3159 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3161 EVP_MD_CTX_cleanup(&mctx);
3162 EVP_PKEY_free(pkey);
3166 int ssl3_get_client_certificate(SSL *s)
3168 int i, ok, al, ret = -1;
3170 unsigned long l, nc, llen, n;
3171 const unsigned char *p, *q;
3173 STACK_OF(X509) *sk = NULL;
3175 n = s->method->ssl_get_message(s,
3178 -1, s->max_cert_list, &ok);
3183 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3184 if ((s->verify_mode & SSL_VERIFY_PEER) &&
3185 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3186 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3187 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3188 al = SSL_AD_HANDSHAKE_FAILURE;
3192 * If tls asked for a client cert, the client must return a 0 list
3194 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3195 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3196 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3197 al = SSL_AD_UNEXPECTED_MESSAGE;
3200 s->s3->tmp.reuse_message = 1;
3204 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3205 al = SSL_AD_UNEXPECTED_MESSAGE;
3206 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3209 p = d = (unsigned char *)s->init_msg;
3211 if ((sk = sk_X509_new_null()) == NULL) {
3212 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3217 if (llen + 3 != n) {
3218 al = SSL_AD_DECODE_ERROR;
3219 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3222 for (nc = 0; nc < llen;) {
3223 if (nc + 3 > llen) {
3224 al = SSL_AD_DECODE_ERROR;
3225 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3226 SSL_R_CERT_LENGTH_MISMATCH);
3230 if ((l + nc + 3) > llen) {
3231 al = SSL_AD_DECODE_ERROR;
3232 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3233 SSL_R_CERT_LENGTH_MISMATCH);
3238 x = d2i_X509(NULL, &p, l);
3240 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3244 al = SSL_AD_DECODE_ERROR;
3245 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3246 SSL_R_CERT_LENGTH_MISMATCH);
3249 if (!sk_X509_push(sk, x)) {
3250 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3257 if (sk_X509_num(sk) <= 0) {
3258 /* TLS does not mind 0 certs returned */
3259 if (s->version == SSL3_VERSION) {
3260 al = SSL_AD_HANDSHAKE_FAILURE;
3261 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3262 SSL_R_NO_CERTIFICATES_RETURNED);
3265 /* Fail for TLS only if we required a certificate */
3266 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3267 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3268 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3269 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3270 al = SSL_AD_HANDSHAKE_FAILURE;
3273 /* No client certificate so digest cached records */
3274 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3275 al = SSL_AD_INTERNAL_ERROR;
3279 i = ssl_verify_cert_chain(s, sk);
3281 al = ssl_verify_alarm_type(s->verify_result);
3282 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3283 SSL_R_CERTIFICATE_VERIFY_FAILED);
3288 if (s->session->peer != NULL) /* This should not be needed */
3289 X509_free(s->session->peer);
3290 s->session->peer = sk_X509_shift(sk);
3291 s->session->verify_result = s->verify_result;
3294 * With the current implementation, sess_cert will always be NULL when we
3297 if (s->session->sess_cert == NULL) {
3298 s->session->sess_cert = ssl_sess_cert_new();
3299 if (s->session->sess_cert == NULL) {
3300 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3304 if (s->session->sess_cert->cert_chain != NULL)
3305 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3306 s->session->sess_cert->cert_chain = sk;
3308 * Inconsistency alert: cert_chain does *not* include the peer's own
3309 * certificate, while we do include it in s3_clnt.c
3317 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3319 s->state = SSL_ST_ERR;
3325 sk_X509_pop_free(sk, X509_free);
3329 int ssl3_send_server_certificate(SSL *s)
3333 if (s->state == SSL3_ST_SW_CERT_A) {
3334 cpk = ssl_get_server_send_pkey(s);
3336 /* VRS: allow null cert if auth == KRB5 */
3337 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3338 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3339 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3340 ERR_R_INTERNAL_ERROR);
3341 s->state = SSL_ST_ERR;
3346 if (!ssl3_output_cert_chain(s, cpk)) {
3347 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3348 s->state = SSL_ST_ERR;
3351 s->state = SSL3_ST_SW_CERT_B;
3354 /* SSL3_ST_SW_CERT_B */
3355 return ssl_do_write(s);
3358 #ifndef OPENSSL_NO_TLSEXT
3359 /* send a new session ticket (not necessarily for a new session) */
3360 int ssl3_send_newsession_ticket(SSL *s)
3362 unsigned char *senc = NULL;
3366 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3367 unsigned char *p, *macstart;
3368 const unsigned char *const_p;
3369 int len, slen_full, slen;
3372 SSL_CTX *tctx = s->initial_ctx;
3373 unsigned char iv[EVP_MAX_IV_LENGTH];
3374 unsigned char key_name[16];
3376 /* get session encoding length */
3377 slen_full = i2d_SSL_SESSION(s->session, NULL);
3379 * Some length values are 16 bits, so forget it if session is too
3382 if (slen_full == 0 || slen_full > 0xFF00) {
3383 s->state = SSL_ST_ERR;
3386 senc = OPENSSL_malloc(slen_full);
3388 s->state = SSL_ST_ERR;
3392 EVP_CIPHER_CTX_init(&ctx);
3393 HMAC_CTX_init(&hctx);
3396 if (!i2d_SSL_SESSION(s->session, &p))
3400 * create a fresh copy (not shared with other threads) to clean up
3403 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3406 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3408 slen = i2d_SSL_SESSION(sess, NULL);
3409 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3410 SSL_SESSION_free(sess);
3414 if (!i2d_SSL_SESSION(sess, &p)) {
3415 SSL_SESSION_free(sess);
3418 SSL_SESSION_free(sess);
3421 * Grow buffer if need be: the length calculation is as
3422 * follows handshake_header_length +
3423 * 4 (ticket lifetime hint) + 2 (ticket length) +
3424 * 16 (key name) + max_iv_len (iv length) +
3425 * session_length + max_enc_block_size (max encrypted session
3426 * length) + max_md_size (HMAC).
3428 if (!BUF_MEM_grow(s->init_buf,
3429 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3430 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3433 p = ssl_handshake_start(s);
3435 * Initialize HMAC and cipher contexts. If callback present it does
3436 * all the work otherwise use generated values from parent ctx.
3438 if (tctx->tlsext_ticket_key_cb) {
3439 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3443 if (RAND_bytes(iv, 16) <= 0)
3445 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3446 tctx->tlsext_tick_aes_key, iv))
3448 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3449 tlsext_tick_md(), NULL))
3451 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3455 * Ticket lifetime hint (advisory only): We leave this unspecified
3456 * for resumed session (for simplicity), and guess that tickets for
3457 * new sessions will live as long as their sessions.
3459 l2n(s->hit ? 0 : s->session->timeout, p);
3461 /* Skip ticket length for now */
3463 /* Output key name */
3465 memcpy(p, key_name, 16);
3468 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3469 p += EVP_CIPHER_CTX_iv_length(&ctx);
3470 /* Encrypt session data */
3471 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3474 if (!EVP_EncryptFinal(&ctx, p, &len))
3478 if (!HMAC_Update(&hctx, macstart, p - macstart))
3480 if (!HMAC_Final(&hctx, p, &hlen))
3483 EVP_CIPHER_CTX_cleanup(&ctx);
3484 HMAC_CTX_cleanup(&hctx);
3487 /* Now write out lengths: p points to end of data written */
3489 len = p - ssl_handshake_start(s);
3490 /* Skip ticket lifetime hint */
3491 p = ssl_handshake_start(s) + 4;
3493 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3494 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3498 /* SSL3_ST_SW_SESSION_TICKET_B */
3499 return ssl_do_write(s);
3503 EVP_CIPHER_CTX_cleanup(&ctx);
3504 HMAC_CTX_cleanup(&hctx);
3505 s->state = SSL_ST_ERR;
3509 int ssl3_send_cert_status(SSL *s)
3511 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3516 * Grow buffer if need be: the length calculation is as
3517 * follows handshake_header_length +
3518 * 1 (ocsp response type) + 3 (ocsp response length)
3521 msglen = 4 + s->tlsext_ocsp_resplen;
3522 if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + msglen)) {
3523 s->state = SSL_ST_ERR;
3527 p = ssl_handshake_start(s);
3530 *(p++) = s->tlsext_status_type;
3531 /* length of OCSP response */
3532 l2n3(s->tlsext_ocsp_resplen, p);
3533 /* actual response */
3534 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3536 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_STATUS, msglen);
3539 /* SSL3_ST_SW_CERT_STATUS_B */
3540 return (ssl_do_write(s));
3543 # ifndef OPENSSL_NO_NEXTPROTONEG
3545 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3546 * It sets the next_proto member in s if found
3548 int ssl3_get_next_proto(SSL *s)
3551 int proto_len, padding_len;
3553 const unsigned char *p;
3556 * Clients cannot send a NextProtocol message if we didn't see the
3557 * extension in their ClientHello
3559 if (!s->s3->next_proto_neg_seen) {
3560 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3561 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3562 s->state = SSL_ST_ERR;
3566 /* See the payload format below */
3567 n = s->method->ssl_get_message(s,
3568 SSL3_ST_SR_NEXT_PROTO_A,
3569 SSL3_ST_SR_NEXT_PROTO_B,
3570 SSL3_MT_NEXT_PROTO, 514, &ok);
3576 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3577 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3578 * ssl3_get_finished).
3580 if (!s->s3->change_cipher_spec) {
3581 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3582 s->state = SSL_ST_ERR;
3587 s->state = SSL_ST_ERR;
3588 return 0; /* The body must be > 1 bytes long */
3591 p = (unsigned char *)s->init_msg;
3594 * The payload looks like:
3596 * uint8 proto[proto_len];
3597 * uint8 padding_len;
3598 * uint8 padding[padding_len];
3601 if (proto_len + 2 > s->init_num) {
3602 s->state = SSL_ST_ERR;
3605 padding_len = p[proto_len + 1];
3606 if (proto_len + padding_len + 2 != s->init_num) {
3607 s->state = SSL_ST_ERR;
3611 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3612 if (!s->next_proto_negotiated) {
3613 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3614 s->state = SSL_ST_ERR;
3617 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3618 s->next_proto_negotiated_len = proto_len;