1 /* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
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
153 #include "ssl_locl.h"
154 #include "kssl_lcl.h"
155 #include "../crypto/constant_time_locl.h"
156 #include <openssl/buffer.h>
157 #include <openssl/rand.h>
158 #include <openssl/objects.h>
159 #include <openssl/evp.h>
160 #include <openssl/hmac.h>
161 #include <openssl/x509.h>
162 #ifndef OPENSSL_NO_DH
163 # include <openssl/dh.h>
165 #include <openssl/bn.h>
166 #ifndef OPENSSL_NO_KRB5
167 # include <openssl/krb5_asn.h>
169 #include <openssl/md5.h>
171 #ifndef OPENSSL_NO_SSL3_METHOD
172 static const SSL_METHOD *ssl3_get_server_method(int ver);
174 static const SSL_METHOD *ssl3_get_server_method(int ver)
176 if (ver == SSL3_VERSION)
177 return (SSLv3_server_method());
182 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
184 ssl_undefined_function, ssl3_get_server_method)
186 #ifndef OPENSSL_NO_SRP
187 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
189 int ret = SSL_ERROR_NONE;
191 *al = SSL_AD_UNRECOGNIZED_NAME;
193 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
194 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
195 if (s->srp_ctx.login == NULL) {
197 * RFC 5054 says SHOULD reject, we do so if There is no srp
201 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
203 ret = SSL_srp_server_param_with_username(s, al);
210 int ssl3_accept(SSL *s)
213 unsigned long alg_k, Time = (unsigned long)time(NULL);
214 void (*cb) (const SSL *ssl, int type, int val) = NULL;
216 int new_state, state, skip = 0;
218 RAND_add(&Time, sizeof(Time), 0);
222 if (s->info_callback != NULL)
223 cb = s->info_callback;
224 else if (s->ctx->info_callback != NULL)
225 cb = s->ctx->info_callback;
227 /* init things to blank */
229 if (!SSL_in_init(s) || SSL_in_before(s)) {
234 #ifndef OPENSSL_NO_HEARTBEATS
236 * If we're awaiting a HeartbeatResponse, pretend we already got and
237 * don't await it anymore, because Heartbeats don't make sense during
240 if (s->tlsext_hb_pending) {
241 s->tlsext_hb_pending = 0;
250 case SSL_ST_RENEGOTIATE:
252 /* s->state=SSL_ST_ACCEPT; */
256 case SSL_ST_BEFORE | SSL_ST_ACCEPT:
257 case SSL_ST_OK | SSL_ST_ACCEPT:
261 cb(s, SSL_CB_HANDSHAKE_START, 1);
263 if ((s->version >> 8) != 3) {
264 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
265 s->state = SSL_ST_ERR;
269 if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
270 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
274 s->type = SSL_ST_ACCEPT;
276 if (s->init_buf == NULL) {
277 if ((buf = BUF_MEM_new()) == NULL) {
279 s->state = SSL_ST_ERR;
282 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
285 s->state = SSL_ST_ERR;
291 if (!ssl3_setup_buffers(s)) {
293 s->state = SSL_ST_ERR;
298 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
299 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
301 * Should have been reset by ssl3_get_finished, too.
303 s->s3->change_cipher_spec = 0;
305 if (s->state != SSL_ST_RENEGOTIATE) {
307 * Ok, we now need to push on a buffering BIO so that the
308 * output is sent in a way that TCP likes :-)
310 if (!ssl_init_wbio_buffer(s, 1)) {
312 s->state = SSL_ST_ERR;
316 ssl3_init_finished_mac(s);
317 s->state = SSL3_ST_SR_CLNT_HELLO_A;
318 s->ctx->stats.sess_accept++;
319 } else if (!s->s3->send_connection_binding &&
321 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
323 * Server attempting to renegotiate with client that doesn't
324 * support secure renegotiation.
326 SSLerr(SSL_F_SSL3_ACCEPT,
327 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
328 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
330 s->state = SSL_ST_ERR;
334 * s->state == SSL_ST_RENEGOTIATE, we will just send a
337 s->ctx->stats.sess_accept_renegotiate++;
338 s->state = SSL3_ST_SW_HELLO_REQ_A;
342 case SSL3_ST_SW_HELLO_REQ_A:
343 case SSL3_ST_SW_HELLO_REQ_B:
346 ret = ssl3_send_hello_request(s);
349 s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
350 s->state = SSL3_ST_SW_FLUSH;
353 ssl3_init_finished_mac(s);
356 case SSL3_ST_SW_HELLO_REQ_C:
357 s->state = SSL_ST_OK;
360 case SSL3_ST_SR_CLNT_HELLO_A:
361 case SSL3_ST_SR_CLNT_HELLO_B:
362 case SSL3_ST_SR_CLNT_HELLO_C:
364 ret = ssl3_get_client_hello(s);
367 #ifndef OPENSSL_NO_SRP
368 s->state = SSL3_ST_SR_CLNT_HELLO_D;
369 case SSL3_ST_SR_CLNT_HELLO_D:
372 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
374 * callback indicates firther work to be done
376 s->rwstate = SSL_X509_LOOKUP;
379 if (ret != SSL_ERROR_NONE) {
380 ssl3_send_alert(s, SSL3_AL_FATAL, al);
382 * This is not really an error but the only means to for
383 * a client to detect whether srp is supported.
385 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
386 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
387 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
389 s->state = SSL_ST_ERR;
396 s->state = SSL3_ST_SW_SRVR_HELLO_A;
400 case SSL3_ST_SW_SRVR_HELLO_A:
401 case SSL3_ST_SW_SRVR_HELLO_B:
402 ret = ssl3_send_server_hello(s);
405 #ifndef OPENSSL_NO_TLSEXT
407 if (s->tlsext_ticket_expected)
408 s->state = SSL3_ST_SW_SESSION_TICKET_A;
410 s->state = SSL3_ST_SW_CHANGE_A;
414 s->state = SSL3_ST_SW_CHANGE_A;
417 s->state = SSL3_ST_SW_CERT_A;
421 case SSL3_ST_SW_CERT_A:
422 case SSL3_ST_SW_CERT_B:
423 /* Check if it is anon DH or anon ECDH, */
424 /* normal PSK or KRB5 or SRP */
427 new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
429 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
430 ret = ssl3_send_server_certificate(s);
433 #ifndef OPENSSL_NO_TLSEXT
434 if (s->tlsext_status_expected)
435 s->state = SSL3_ST_SW_CERT_STATUS_A;
437 s->state = SSL3_ST_SW_KEY_EXCH_A;
440 s->state = SSL3_ST_SW_KEY_EXCH_A;
446 s->state = SSL3_ST_SW_KEY_EXCH_A;
451 case SSL3_ST_SW_KEY_EXCH_A:
452 case SSL3_ST_SW_KEY_EXCH_B:
453 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
456 * clear this, it may get reset by
457 * send_server_key_exchange
459 s->s3->tmp.use_rsa_tmp = 0;
462 * only send if a DH key exchange, fortezza or RSA but we have a
463 * sign only certificate PSK: may send PSK identity hints For
464 * ECC ciphersuites, we send a serverKeyExchange message only if
465 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
466 * the server certificate contains the server's public key for
471 * PSK: send ServerKeyExchange if PSK identity hint if
474 #ifndef OPENSSL_NO_PSK
475 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
477 #ifndef OPENSSL_NO_SRP
478 /* SRP: send ServerKeyExchange */
479 || (alg_k & SSL_kSRP)
481 || (alg_k & SSL_kDHE)
482 || (alg_k & SSL_kECDHE)
483 || ((alg_k & SSL_kRSA)
484 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
485 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
486 && EVP_PKEY_size(s->cert->pkeys
487 [SSL_PKEY_RSA_ENC].privatekey) *
488 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
493 ret = ssl3_send_server_key_exchange(s);
499 s->state = SSL3_ST_SW_CERT_REQ_A;
503 case SSL3_ST_SW_CERT_REQ_A:
504 case SSL3_ST_SW_CERT_REQ_B:
505 if ( /* don't request cert unless asked for it: */
506 !(s->verify_mode & SSL_VERIFY_PEER) ||
508 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
509 * during re-negotiation:
511 ((s->session->peer != NULL) &&
512 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
514 * never request cert in anonymous ciphersuites (see
515 * section "Certificate request" in SSL 3 drafts and in
518 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
520 * ... except when the application insists on
521 * verification (against the specs, but s3_clnt.c accepts
524 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
526 * never request cert in Kerberos ciphersuites
528 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
529 /* don't request certificate for SRP auth */
530 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
532 * With normal PSK Certificates and Certificate Requests
535 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
536 /* no cert request */
538 s->s3->tmp.cert_request = 0;
539 s->state = SSL3_ST_SW_SRVR_DONE_A;
540 if (s->s3->handshake_buffer) {
541 if (!ssl3_digest_cached_records(s)) {
542 s->state = SSL_ST_ERR;
547 s->s3->tmp.cert_request = 1;
548 ret = ssl3_send_certificate_request(s);
551 s->state = SSL3_ST_SW_SRVR_DONE_A;
556 case SSL3_ST_SW_SRVR_DONE_A:
557 case SSL3_ST_SW_SRVR_DONE_B:
558 ret = ssl3_send_server_done(s);
561 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
562 s->state = SSL3_ST_SW_FLUSH;
566 case SSL3_ST_SW_FLUSH:
569 * This code originally checked to see if any data was pending
570 * using BIO_CTRL_INFO and then flushed. This caused problems as
571 * documented in PR#1939. The proposed fix doesn't completely
572 * resolve this issue as buggy implementations of
573 * BIO_CTRL_PENDING still exist. So instead we just flush
577 s->rwstate = SSL_WRITING;
578 if (BIO_flush(s->wbio) <= 0) {
582 s->rwstate = SSL_NOTHING;
584 s->state = s->s3->tmp.next_state;
587 case SSL3_ST_SR_CERT_A:
588 case SSL3_ST_SR_CERT_B:
589 if (s->s3->tmp.cert_request) {
590 ret = ssl3_get_client_certificate(s);
595 s->state = SSL3_ST_SR_KEY_EXCH_A;
598 case SSL3_ST_SR_KEY_EXCH_A:
599 case SSL3_ST_SR_KEY_EXCH_B:
600 ret = ssl3_get_client_key_exchange(s);
605 * For the ECDH ciphersuites when the client sends its ECDH
606 * pub key in a certificate, the CertificateVerify message is
607 * not sent. Also for GOST ciphersuites when the client uses
608 * its key from the certificate for key exchange.
610 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
611 s->state = SSL3_ST_SR_FINISHED_A;
613 if (s->s3->next_proto_neg_seen)
614 s->state = SSL3_ST_SR_NEXT_PROTO_A;
616 s->state = SSL3_ST_SR_FINISHED_A;
619 } else if (SSL_USE_SIGALGS(s)) {
620 s->state = SSL3_ST_SR_CERT_VRFY_A;
622 if (!s->session->peer)
624 if (!s->s3->handshake_buffer) {
625 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
626 s->state = SSL_ST_ERR;
630 * For sigalgs freeze the handshake buffer. If we support
631 * extms we've done this already.
633 if (!(s->s3->flags & SSL_SESS_FLAG_EXTMS)) {
634 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
635 if (!ssl3_digest_cached_records(s)) {
636 s->state = SSL_ST_ERR;
644 s->state = SSL3_ST_SR_CERT_VRFY_A;
648 * We need to get hashes here so if there is a client cert,
649 * it can be verified FIXME - digest processing for
650 * CertificateVerify should be generalized. But it is next
653 if (s->s3->handshake_buffer) {
654 if (!ssl3_digest_cached_records(s)) {
655 s->state = SSL_ST_ERR;
659 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
660 if (s->s3->handshake_dgst[dgst_num]) {
663 s->method->ssl3_enc->cert_verify_mac(s,
672 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
674 s->state = SSL_ST_ERR;
683 case SSL3_ST_SR_CERT_VRFY_A:
684 case SSL3_ST_SR_CERT_VRFY_B:
685 ret = ssl3_get_cert_verify(s);
689 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
690 s->state = SSL3_ST_SR_FINISHED_A;
692 if (s->s3->next_proto_neg_seen)
693 s->state = SSL3_ST_SR_NEXT_PROTO_A;
695 s->state = SSL3_ST_SR_FINISHED_A;
700 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
701 case SSL3_ST_SR_NEXT_PROTO_A:
702 case SSL3_ST_SR_NEXT_PROTO_B:
704 * Enable CCS for NPN. Receiving a CCS clears the flag, so make
705 * sure not to re-enable it to ban duplicates. This *should* be the
706 * first time we have received one - but we check anyway to be
708 * s->s3->change_cipher_spec is set when a CCS is
709 * processed in s3_pkt.c, and remains set until
710 * the client's Finished message is read.
712 if (!s->s3->change_cipher_spec)
713 s->s3->flags |= SSL3_FLAGS_CCS_OK;
715 ret = ssl3_get_next_proto(s);
719 s->state = SSL3_ST_SR_FINISHED_A;
723 case SSL3_ST_SR_FINISHED_A:
724 case SSL3_ST_SR_FINISHED_B:
726 * Enable CCS for handshakes without NPN. In NPN the CCS flag has
727 * already been set. Receiving a CCS clears the flag, so make
728 * sure not to re-enable it to ban duplicates.
729 * s->s3->change_cipher_spec is set when a CCS is
730 * processed in s3_pkt.c, and remains set until
731 * the client's Finished message is read.
733 if (!s->s3->change_cipher_spec)
734 s->s3->flags |= SSL3_FLAGS_CCS_OK;
735 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
736 SSL3_ST_SR_FINISHED_B);
740 s->state = SSL_ST_OK;
741 #ifndef OPENSSL_NO_TLSEXT
742 else if (s->tlsext_ticket_expected)
743 s->state = SSL3_ST_SW_SESSION_TICKET_A;
746 s->state = SSL3_ST_SW_CHANGE_A;
750 #ifndef OPENSSL_NO_TLSEXT
751 case SSL3_ST_SW_SESSION_TICKET_A:
752 case SSL3_ST_SW_SESSION_TICKET_B:
753 ret = ssl3_send_newsession_ticket(s);
756 s->state = SSL3_ST_SW_CHANGE_A;
760 case SSL3_ST_SW_CERT_STATUS_A:
761 case SSL3_ST_SW_CERT_STATUS_B:
762 ret = ssl3_send_cert_status(s);
765 s->state = SSL3_ST_SW_KEY_EXCH_A;
771 case SSL3_ST_SW_CHANGE_A:
772 case SSL3_ST_SW_CHANGE_B:
774 s->session->cipher = s->s3->tmp.new_cipher;
775 if (!s->method->ssl3_enc->setup_key_block(s)) {
777 s->state = SSL_ST_ERR;
781 ret = ssl3_send_change_cipher_spec(s,
783 SSL3_ST_SW_CHANGE_B);
787 s->state = SSL3_ST_SW_FINISHED_A;
790 if (!s->method->ssl3_enc->change_cipher_state(s,
791 SSL3_CHANGE_CIPHER_SERVER_WRITE))
794 s->state = SSL_ST_ERR;
800 case SSL3_ST_SW_FINISHED_A:
801 case SSL3_ST_SW_FINISHED_B:
802 ret = ssl3_send_finished(s,
803 SSL3_ST_SW_FINISHED_A,
804 SSL3_ST_SW_FINISHED_B,
806 ssl3_enc->server_finished_label,
808 ssl3_enc->server_finished_label_len);
811 s->state = SSL3_ST_SW_FLUSH;
813 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
814 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
816 if (s->s3->next_proto_neg_seen) {
817 s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
819 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
822 s->s3->tmp.next_state = SSL_ST_OK;
827 /* clean a few things up */
828 ssl3_cleanup_key_block(s);
830 BUF_MEM_free(s->init_buf);
833 /* remove buffering on output */
834 ssl_free_wbio_buffer(s);
838 if (s->renegotiate == 2) { /* skipped if we just sent a
843 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
845 s->ctx->stats.sess_accept_good++;
847 s->handshake_func = ssl3_accept;
850 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
859 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
865 if (!s->s3->tmp.reuse_message && !skip) {
867 if ((ret = BIO_flush(s->wbio)) <= 0)
871 if ((cb != NULL) && (s->state != state)) {
872 new_state = s->state;
874 cb(s, SSL_CB_ACCEPT_LOOP, 1);
875 s->state = new_state;
881 /* BIO_flush(s->wbio); */
885 cb(s, SSL_CB_ACCEPT_EXIT, ret);
889 int ssl3_send_hello_request(SSL *s)
892 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
893 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
894 SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
897 s->state = SSL3_ST_SW_HELLO_REQ_B;
900 /* SSL3_ST_SW_HELLO_REQ_B */
901 return ssl_do_write(s);
904 int ssl3_get_client_hello(SSL *s)
906 int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
907 unsigned int cookie_len;
910 unsigned char *p, *d;
912 #ifndef OPENSSL_NO_COMP
914 SSL_COMP *comp = NULL;
916 STACK_OF(SSL_CIPHER) *ciphers = NULL;
918 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
922 * We do this so that we will respond with our native type. If we are
923 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
924 * switching should be handled by a different method. If we are SSLv3, we
925 * will respond with SSLv3, even if prompted with TLSv1.
927 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
928 s->state = SSL3_ST_SR_CLNT_HELLO_B;
931 n = s->method->ssl_get_message(s,
932 SSL3_ST_SR_CLNT_HELLO_B,
933 SSL3_ST_SR_CLNT_HELLO_C,
934 SSL3_MT_CLIENT_HELLO,
935 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
940 d = p = (unsigned char *)s->init_msg;
943 * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
944 * for session id length
946 if (n < 2 + SSL3_RANDOM_SIZE + 1) {
947 al = SSL_AD_DECODE_ERROR;
948 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
953 * use version from inside client hello, not from record header (may
954 * differ: see RFC 2246, Appendix E, second paragraph)
956 s->client_version = (((int)p[0]) << 8) | (int)p[1];
959 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
960 s->method->version != DTLS_ANY_VERSION)
961 : (s->client_version < s->version)) {
962 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
963 if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
964 !s->enc_write_ctx && !s->write_hash) {
966 * similar to ssl3_get_record, send alert using remote version
969 s->version = s->client_version;
971 al = SSL_AD_PROTOCOL_VERSION;
976 * If we require cookies and this ClientHello doesn't contain one, just
977 * return since we do not want to allocate any memory yet. So check
980 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
981 unsigned int session_length, cookie_length;
983 session_length = *(p + SSL3_RANDOM_SIZE);
985 if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
986 al = SSL_AD_DECODE_ERROR;
987 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
990 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
992 if (cookie_length == 0)
996 /* load the client random */
997 memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
998 p += SSL3_RANDOM_SIZE;
1000 /* get the session-id */
1003 if (p + j > d + n) {
1004 al = SSL_AD_DECODE_ERROR;
1005 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1011 * Versions before 0.9.7 always allow clients to resume sessions in
1012 * renegotiation. 0.9.7 and later allow this by default, but optionally
1013 * ignore resumption requests with flag
1014 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1015 * than a change to default behavior so that applications relying on this
1016 * for security won't even compile against older library versions).
1017 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1018 * request renegotiation but not a new session (s->new_session remains
1019 * unset): for servers, this essentially just means that the
1020 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
1023 && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1024 if (!ssl_get_new_session(s, 1))
1027 i = ssl_get_prev_session(s, p, j, d + n);
1029 * Only resume if the session's version matches the negotiated
1031 * RFC 5246 does not provide much useful advice on resumption
1032 * with a different protocol version. It doesn't forbid it but
1033 * the sanity of such behaviour would be questionable.
1034 * In practice, clients do not accept a version mismatch and
1035 * will abort the handshake with an error.
1037 if (i == 1 && s->version == s->session->ssl_version) { /* previous
1044 if (!ssl_get_new_session(s, 1))
1051 if (SSL_IS_DTLS(s)) {
1053 if (p + 1 > d + n) {
1054 al = SSL_AD_DECODE_ERROR;
1055 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1058 cookie_len = *(p++);
1060 if (p + cookie_len > d + n) {
1061 al = SSL_AD_DECODE_ERROR;
1062 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1067 * The ClientHello may contain a cookie even if the
1068 * HelloVerify message has not been sent--make sure that it
1069 * does not cause an overflow.
1071 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1073 al = SSL_AD_DECODE_ERROR;
1074 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1078 /* verify the cookie if appropriate option is set. */
1079 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1080 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1082 if (s->ctx->app_verify_cookie_cb != NULL) {
1083 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1085 al = SSL_AD_HANDSHAKE_FAILURE;
1086 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1087 SSL_R_COOKIE_MISMATCH);
1090 /* else cookie verification succeeded */
1092 /* default verification */
1093 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1094 s->d1->cookie_len) != 0) {
1095 al = SSL_AD_HANDSHAKE_FAILURE;
1096 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1099 /* Set to -2 so if successful we return 2 */
1104 if (s->method->version == DTLS_ANY_VERSION) {
1105 /* Select version to use */
1106 if (s->client_version <= DTLS1_2_VERSION &&
1107 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1108 s->version = DTLS1_2_VERSION;
1109 s->method = DTLSv1_2_server_method();
1110 } else if (tls1_suiteb(s)) {
1111 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1112 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1113 s->version = s->client_version;
1114 al = SSL_AD_PROTOCOL_VERSION;
1116 } else if (s->client_version <= DTLS1_VERSION &&
1117 !(s->options & SSL_OP_NO_DTLSv1)) {
1118 s->version = DTLS1_VERSION;
1119 s->method = DTLSv1_server_method();
1121 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1122 SSL_R_WRONG_VERSION_NUMBER);
1123 s->version = s->client_version;
1124 al = SSL_AD_PROTOCOL_VERSION;
1127 s->session->ssl_version = s->version;
1131 if (p + 2 > d + n) {
1132 al = SSL_AD_DECODE_ERROR;
1133 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1139 al = SSL_AD_ILLEGAL_PARAMETER;
1140 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1144 /* i bytes of cipher data + 1 byte for compression length later */
1145 if ((p + i + 1) > (d + n)) {
1146 /* not enough data */
1147 al = SSL_AD_DECODE_ERROR;
1148 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1151 if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1156 /* If it is a hit, check that the cipher is in the list */
1159 id = s->session->cipher->id;
1162 fprintf(stderr, "client sent %d ciphers\n",
1163 sk_SSL_CIPHER_num(ciphers));
1165 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1166 c = sk_SSL_CIPHER_value(ciphers, i);
1168 fprintf(stderr, "client [%2d of %2d]:%s\n",
1169 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1177 * Disabled because it can be used in a ciphersuite downgrade attack:
1181 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1182 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1184 * Special case as client bug workaround: the previously used
1185 * cipher may not be in the current list, the client instead
1186 * might be trying to continue using a cipher that before wasn't
1187 * chosen due to server preferences. We'll have to reject the
1188 * connection if the cipher is not enabled, though.
1190 c = sk_SSL_CIPHER_value(ciphers, 0);
1191 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1192 s->session->cipher = c;
1199 * we need to have the cipher in the cipher list if we are asked
1202 al = SSL_AD_ILLEGAL_PARAMETER;
1203 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1204 SSL_R_REQUIRED_CIPHER_MISSING);
1211 if ((p + i) > (d + n)) {
1212 /* not enough data */
1213 al = SSL_AD_DECODE_ERROR;
1214 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1217 #ifndef OPENSSL_NO_COMP
1220 for (j = 0; j < i; j++) {
1228 al = SSL_AD_DECODE_ERROR;
1229 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1232 #ifndef OPENSSL_NO_TLSEXT
1233 /* TLS extensions */
1234 if (s->version >= SSL3_VERSION) {
1235 if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1236 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1242 * Check if we want to use external pre-shared secret for this handshake
1243 * for not reused session only. We need to generate server_random before
1244 * calling tls_session_secret_cb in order to allow SessionTicket
1245 * processing to use it in key derivation.
1249 pos = s->s3->server_random;
1250 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1255 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1256 SSL_CIPHER *pref_cipher = NULL;
1258 s->session->master_key_length = sizeof(s->session->master_key);
1259 if (s->tls_session_secret_cb(s, s->session->master_key,
1260 &s->session->master_key_length, ciphers,
1262 s->tls_session_secret_cb_arg)) {
1264 s->session->ciphers = ciphers;
1265 s->session->verify_result = X509_V_OK;
1269 /* check if some cipher was preferred by call back */
1271 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1276 if (pref_cipher == NULL) {
1277 al = SSL_AD_HANDSHAKE_FAILURE;
1278 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1282 s->session->cipher = pref_cipher;
1283 sk_SSL_CIPHER_free(s->cipher_list);
1284 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1285 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1286 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1292 * Worst case, we will use the NULL compression, but if we have other
1293 * options, we will now look for them. We have i-1 compression
1294 * algorithms from the client, starting at q.
1296 s->s3->tmp.new_compression = NULL;
1297 #ifndef OPENSSL_NO_COMP
1298 /* This only happens if we have a cache hit */
1299 if (s->session->compress_meth != 0) {
1300 int m, comp_id = s->session->compress_meth;
1301 /* Perform sanity checks on resumed compression algorithm */
1302 /* Can't disable compression */
1303 if (!ssl_allow_compression(s)) {
1304 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1305 SSL_R_INCONSISTENT_COMPRESSION);
1308 /* Look for resumed compression method */
1309 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1310 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1311 if (comp_id == comp->id) {
1312 s->s3->tmp.new_compression = comp;
1316 if (s->s3->tmp.new_compression == NULL) {
1317 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1318 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1321 /* Look for resumed method in compression list */
1322 for (m = 0; m < i; m++) {
1323 if (q[m] == comp_id)
1327 al = SSL_AD_ILLEGAL_PARAMETER;
1328 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1329 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1334 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1335 /* See if we have a match */
1336 int m, nn, o, v, done = 0;
1338 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1339 for (m = 0; m < nn; m++) {
1340 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1342 for (o = 0; o < i; o++) {
1352 s->s3->tmp.new_compression = comp;
1358 * If compression is disabled we'd better not try to resume a session
1359 * using compression.
1361 if (s->session->compress_meth != 0) {
1362 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1368 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1372 #ifdef OPENSSL_NO_COMP
1373 s->session->compress_meth = 0;
1375 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1377 sk_SSL_CIPHER_free(s->session->ciphers);
1378 s->session->ciphers = ciphers;
1379 if (ciphers == NULL) {
1380 al = SSL_AD_INTERNAL_ERROR;
1381 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1385 if (!tls1_set_server_sigalgs(s)) {
1386 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1389 /* Let cert callback update server certificates if required */
1391 if (s->cert->cert_cb) {
1392 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1394 al = SSL_AD_INTERNAL_ERROR;
1395 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1399 s->rwstate = SSL_X509_LOOKUP;
1402 s->rwstate = SSL_NOTHING;
1404 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1407 al = SSL_AD_HANDSHAKE_FAILURE;
1408 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1411 s->s3->tmp.new_cipher = c;
1412 /* check whether we should disable session resumption */
1413 if (s->not_resumable_session_cb != NULL)
1414 s->session->not_resumable = s->not_resumable_session_cb(s,
1415 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1417 if (s->session->not_resumable)
1418 /* do not send a session ticket */
1419 s->tlsext_ticket_expected = 0;
1421 /* Session-id reuse */
1422 s->s3->tmp.new_cipher = s->session->cipher;
1425 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1426 if (!ssl3_digest_cached_records(s))
1431 * we now have the following setup.
1433 * cipher_list - our prefered list of ciphers
1434 * ciphers - the clients prefered list of ciphers
1435 * compression - basically ignored right now
1436 * ssl version is set - sslv3
1437 * s->session - The ssl session has been setup.
1438 * s->hit - session reuse flag
1439 * s->s3->tmp.new_cipher- the new cipher to use.
1442 /* Handles TLS extensions that we couldn't check earlier */
1443 if (s->version >= SSL3_VERSION) {
1444 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1445 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1454 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1456 s->state = SSL_ST_ERR;
1459 sk_SSL_CIPHER_free(ciphers);
1460 return ret < 0 ? -1 : ret;
1463 int ssl3_send_server_hello(SSL *s)
1466 unsigned char *p, *d;
1471 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1472 buf = (unsigned char *)s->init_buf->data;
1473 #ifdef OPENSSL_NO_TLSEXT
1474 p = s->s3->server_random;
1475 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1476 s->state = SSL_ST_ERR;
1480 /* Do the message type and length last */
1481 d = p = ssl_handshake_start(s);
1483 *(p++) = s->version >> 8;
1484 *(p++) = s->version & 0xff;
1487 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1488 p += SSL3_RANDOM_SIZE;
1491 * There are several cases for the session ID to send
1492 * back in the server hello:
1493 * - For session reuse from the session cache,
1494 * we send back the old session ID.
1495 * - If stateless session reuse (using a session ticket)
1496 * is successful, we send back the client's "session ID"
1497 * (which doesn't actually identify the session).
1498 * - If it is a new session, we send back the new
1500 * - However, if we want the new session to be single-use,
1501 * we send back a 0-length session ID.
1502 * s->hit is non-zero in either case of session reuse,
1503 * so the following won't overwrite an ID that we're supposed
1506 if (s->session->not_resumable ||
1507 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1509 s->session->session_id_length = 0;
1511 sl = s->session->session_id_length;
1512 if (sl > (int)sizeof(s->session->session_id)) {
1513 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1514 s->state = SSL_ST_ERR;
1518 memcpy(p, s->session->session_id, sl);
1521 /* put the cipher */
1522 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1525 /* put the compression method */
1526 #ifdef OPENSSL_NO_COMP
1529 if (s->s3->tmp.new_compression == NULL)
1532 *(p++) = s->s3->tmp.new_compression->id;
1534 #ifndef OPENSSL_NO_TLSEXT
1535 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1536 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1537 s->state = SSL_ST_ERR;
1541 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1543 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1544 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1545 s->state = SSL_ST_ERR;
1551 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1552 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1555 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1558 /* SSL3_ST_SW_SRVR_HELLO_B */
1559 return ssl_do_write(s);
1562 int ssl3_send_server_done(SSL *s)
1565 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1566 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1567 SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1570 s->state = SSL3_ST_SW_SRVR_DONE_B;
1573 /* SSL3_ST_SW_SRVR_DONE_B */
1574 return ssl_do_write(s);
1577 int ssl3_send_server_key_exchange(SSL *s)
1579 #ifndef OPENSSL_NO_RSA
1583 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1586 #ifndef OPENSSL_NO_DH
1587 DH *dh = NULL, *dhp;
1589 #ifndef OPENSSL_NO_EC
1590 EC_KEY *ecdh = NULL, *ecdhp;
1591 unsigned char *encodedPoint = NULL;
1594 BN_CTX *bn_ctx = NULL;
1597 const EVP_MD *md = NULL;
1598 unsigned char *p, *d;
1608 EVP_MD_CTX_init(&md_ctx);
1609 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1610 type = s->s3->tmp.new_cipher->algorithm_mkey;
1615 r[0] = r[1] = r[2] = r[3] = NULL;
1617 #ifndef OPENSSL_NO_RSA
1618 if (type & SSL_kRSA) {
1619 rsa = cert->rsa_tmp;
1620 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1621 rsa = s->cert->rsa_tmp_cb(s,
1622 SSL_C_IS_EXPORT(s->s3->
1624 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1627 al = SSL_AD_HANDSHAKE_FAILURE;
1628 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1629 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1633 cert->rsa_tmp = rsa;
1636 al = SSL_AD_HANDSHAKE_FAILURE;
1637 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1638 SSL_R_MISSING_TMP_RSA_KEY);
1643 s->s3->tmp.use_rsa_tmp = 1;
1646 #ifndef OPENSSL_NO_DH
1647 if (type & SSL_kDHE) {
1648 if (s->cert->dh_tmp_auto) {
1649 dhp = ssl_get_auto_dh(s);
1651 al = SSL_AD_INTERNAL_ERROR;
1652 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1653 ERR_R_INTERNAL_ERROR);
1658 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1659 dhp = s->cert->dh_tmp_cb(s,
1660 SSL_C_IS_EXPORT(s->s3->
1662 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1665 al = SSL_AD_HANDSHAKE_FAILURE;
1666 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1667 SSL_R_MISSING_TMP_DH_KEY);
1670 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1671 DH_security_bits(dhp), 0, dhp)) {
1672 al = SSL_AD_HANDSHAKE_FAILURE;
1673 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1674 SSL_R_DH_KEY_TOO_SMALL);
1677 if (s->s3->tmp.dh != NULL) {
1678 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1679 ERR_R_INTERNAL_ERROR);
1683 if (s->cert->dh_tmp_auto)
1685 else if ((dh = DHparams_dup(dhp)) == NULL) {
1686 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1691 if ((dhp->pub_key == NULL ||
1692 dhp->priv_key == NULL ||
1693 (s->options & SSL_OP_SINGLE_DH_USE))) {
1694 if (!DH_generate_key(dh)) {
1695 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1699 dh->pub_key = BN_dup(dhp->pub_key);
1700 dh->priv_key = BN_dup(dhp->priv_key);
1701 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1702 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1711 #ifndef OPENSSL_NO_EC
1712 if (type & SSL_kECDHE) {
1713 const EC_GROUP *group;
1715 ecdhp = cert->ecdh_tmp;
1716 if (s->cert->ecdh_tmp_auto) {
1717 /* Get NID of appropriate shared curve */
1718 int nid = tls1_shared_curve(s, -2);
1719 if (nid != NID_undef)
1720 ecdhp = EC_KEY_new_by_curve_name(nid);
1721 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1722 ecdhp = s->cert->ecdh_tmp_cb(s,
1723 SSL_C_IS_EXPORT(s->s3->
1725 SSL_C_EXPORT_PKEYLENGTH(s->
1726 s3->tmp.new_cipher));
1728 if (ecdhp == NULL) {
1729 al = SSL_AD_HANDSHAKE_FAILURE;
1730 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1731 SSL_R_MISSING_TMP_ECDH_KEY);
1735 if (s->s3->tmp.ecdh != NULL) {
1736 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1737 ERR_R_INTERNAL_ERROR);
1741 /* Duplicate the ECDH structure. */
1742 if (ecdhp == NULL) {
1743 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1746 if (s->cert->ecdh_tmp_auto)
1748 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1749 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1753 s->s3->tmp.ecdh = ecdh;
1754 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1755 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1756 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1757 if (!EC_KEY_generate_key(ecdh)) {
1758 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1764 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1765 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1766 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1767 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1771 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1772 (EC_GROUP_get_degree(group) > 163)) {
1773 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1774 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1779 * XXX: For now, we only support ephemeral ECDH keys over named
1780 * (not generic) curves. For supported named curves, curve_id is
1784 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1786 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1787 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1792 * Encode the public key. First check the size of encoding and
1793 * allocate memory accordingly.
1795 encodedlen = EC_POINT_point2oct(group,
1796 EC_KEY_get0_public_key(ecdh),
1797 POINT_CONVERSION_UNCOMPRESSED,
1800 encodedPoint = (unsigned char *)
1801 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1802 bn_ctx = BN_CTX_new();
1803 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1804 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1805 ERR_R_MALLOC_FAILURE);
1809 encodedlen = EC_POINT_point2oct(group,
1810 EC_KEY_get0_public_key(ecdh),
1811 POINT_CONVERSION_UNCOMPRESSED,
1812 encodedPoint, encodedlen, bn_ctx);
1814 if (encodedlen == 0) {
1815 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1819 BN_CTX_free(bn_ctx);
1823 * XXX: For now, we only support named (not generic) curves in
1824 * ECDH ephemeral key exchanges. In this situation, we need four
1825 * additional bytes to encode the entire ServerECDHParams
1831 * We'll generate the serverKeyExchange message explicitly so we
1832 * can set these to NULLs
1839 #endif /* !OPENSSL_NO_EC */
1840 #ifndef OPENSSL_NO_PSK
1841 if (type & SSL_kPSK) {
1843 * reserve size for record length and PSK identity hint
1845 n += 2 + strlen(s->ctx->psk_identity_hint);
1847 #endif /* !OPENSSL_NO_PSK */
1848 #ifndef OPENSSL_NO_SRP
1849 if (type & SSL_kSRP) {
1850 if ((s->srp_ctx.N == NULL) ||
1851 (s->srp_ctx.g == NULL) ||
1852 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1853 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1854 SSL_R_MISSING_SRP_PARAM);
1857 r[0] = s->srp_ctx.N;
1858 r[1] = s->srp_ctx.g;
1859 r[2] = s->srp_ctx.s;
1860 r[3] = s->srp_ctx.B;
1864 al = SSL_AD_HANDSHAKE_FAILURE;
1865 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1866 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1869 for (i = 0; i < 4 && r[i] != NULL; i++) {
1870 nr[i] = BN_num_bytes(r[i]);
1871 #ifndef OPENSSL_NO_SRP
1872 if ((i == 2) && (type & SSL_kSRP))
1879 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1880 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1881 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1883 al = SSL_AD_DECODE_ERROR;
1886 kn = EVP_PKEY_size(pkey);
1892 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1893 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1896 d = p = ssl_handshake_start(s);
1898 for (i = 0; i < 4 && r[i] != NULL; i++) {
1899 #ifndef OPENSSL_NO_SRP
1900 if ((i == 2) && (type & SSL_kSRP)) {
1910 #ifndef OPENSSL_NO_EC
1911 if (type & SSL_kECDHE) {
1913 * XXX: For now, we only support named (not generic) curves. In
1914 * this situation, the serverKeyExchange message has: [1 byte
1915 * CurveType], [2 byte CurveName] [1 byte length of encoded
1916 * point], followed by the actual encoded point itself
1918 *p = NAMED_CURVE_TYPE;
1926 memcpy(p, encodedPoint, encodedlen);
1927 OPENSSL_free(encodedPoint);
1928 encodedPoint = NULL;
1933 #ifndef OPENSSL_NO_PSK
1934 if (type & SSL_kPSK) {
1935 /* copy PSK identity hint */
1936 s2n(strlen(s->ctx->psk_identity_hint), p);
1937 strncpy((char *)p, s->ctx->psk_identity_hint,
1938 strlen(s->ctx->psk_identity_hint));
1939 p += strlen(s->ctx->psk_identity_hint);
1946 * n is the length of the params, they start at &(d[4]) and p
1947 * points to the space at the end.
1949 #ifndef OPENSSL_NO_RSA
1950 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1953 for (num = 2; num > 0; num--) {
1954 EVP_MD_CTX_set_flags(&md_ctx,
1955 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1956 EVP_DigestInit_ex(&md_ctx, (num == 2)
1957 ? s->ctx->md5 : s->ctx->sha1, NULL);
1958 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1960 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1962 EVP_DigestUpdate(&md_ctx, d, n);
1963 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1967 if (RSA_sign(NID_md5_sha1, md_buf, j,
1968 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1969 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1977 /* send signature algorithm */
1978 if (SSL_USE_SIGALGS(s)) {
1979 if (!tls12_get_sigandhash(p, pkey, md)) {
1980 /* Should never happen */
1981 al = SSL_AD_INTERNAL_ERROR;
1982 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1983 ERR_R_INTERNAL_ERROR);
1989 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1991 EVP_SignInit_ex(&md_ctx, md, NULL);
1992 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1994 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1996 EVP_SignUpdate(&md_ctx, d, n);
1997 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1998 (unsigned int *)&i, pkey)) {
1999 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2004 if (SSL_USE_SIGALGS(s))
2007 /* Is this error check actually needed? */
2008 al = SSL_AD_HANDSHAKE_FAILURE;
2009 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2010 SSL_R_UNKNOWN_PKEY_TYPE);
2015 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2016 al = SSL_AD_HANDSHAKE_FAILURE;
2017 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
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_EC
2029 OPENSSL_free(encodedPoint);
2030 BN_CTX_free(bn_ctx);
2032 EVP_MD_CTX_cleanup(&md_ctx);
2033 s->state = SSL_ST_ERR;
2037 int ssl3_send_certificate_request(SSL *s)
2039 unsigned char *p, *d;
2040 int i, j, nl, off, n;
2041 STACK_OF(X509_NAME) *sk = NULL;
2045 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2048 d = p = ssl_handshake_start(s);
2050 /* get the list of acceptable cert types */
2052 n = ssl3_get_req_cert_type(s, p);
2057 if (SSL_USE_SIGALGS(s)) {
2058 const unsigned char *psigs;
2059 unsigned char *etmp = p;
2060 nl = tls12_get_psigalgs(s, &psigs);
2061 /* Skip over length for now */
2063 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2064 /* Now fill in length */
2074 sk = SSL_get_client_CA_list(s);
2077 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2078 name = sk_X509_NAME_value(sk, i);
2079 j = i2d_X509_NAME(name, NULL);
2080 if (!BUF_MEM_grow_clean
2081 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2082 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2086 p = ssl_handshake_start(s) + n;
2088 i2d_X509_NAME(name, &p);
2093 /* else no CA names */
2094 p = ssl_handshake_start(s) + off;
2097 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2098 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2102 s->state = SSL3_ST_SW_CERT_REQ_B;
2105 /* SSL3_ST_SW_CERT_REQ_B */
2106 return ssl_do_write(s);
2108 s->state = SSL_ST_ERR;
2112 int ssl3_get_client_key_exchange(SSL *s)
2116 unsigned long alg_k;
2118 #ifndef OPENSSL_NO_RSA
2120 EVP_PKEY *pkey = NULL;
2122 #ifndef OPENSSL_NO_DH
2124 DH *dh_srvr, *dh_clnt = NULL;
2126 #ifndef OPENSSL_NO_KRB5
2128 #endif /* OPENSSL_NO_KRB5 */
2130 #ifndef OPENSSL_NO_EC
2131 EC_KEY *srvr_ecdh = NULL;
2132 EVP_PKEY *clnt_pub_pkey = NULL;
2133 EC_POINT *clnt_ecpoint = NULL;
2134 BN_CTX *bn_ctx = NULL;
2137 n = s->method->ssl_get_message(s,
2138 SSL3_ST_SR_KEY_EXCH_A,
2139 SSL3_ST_SR_KEY_EXCH_B,
2140 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2144 p = (unsigned char *)s->init_msg;
2146 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2148 #ifndef OPENSSL_NO_RSA
2149 if (alg_k & SSL_kRSA) {
2150 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2152 unsigned char decrypt_good, version_good;
2155 /* FIX THIS UP EAY EAY EAY EAY */
2156 if (s->s3->tmp.use_rsa_tmp) {
2157 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2158 rsa = s->cert->rsa_tmp;
2160 * Don't do a callback because rsa_tmp should be sent already
2163 al = SSL_AD_HANDSHAKE_FAILURE;
2164 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2165 SSL_R_MISSING_TMP_RSA_PKEY);
2170 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2171 if ((pkey == NULL) ||
2172 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2173 al = SSL_AD_HANDSHAKE_FAILURE;
2174 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2175 SSL_R_MISSING_RSA_CERTIFICATE);
2178 rsa = pkey->pkey.rsa;
2181 /* TLS and [incidentally] DTLS{0xFEFF} */
2182 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2185 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2186 al = SSL_AD_DECODE_ERROR;
2187 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2188 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2197 * Reject overly short RSA ciphertext because we want to be sure
2198 * that the buffer size makes it safe to iterate over the entire
2199 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2200 * actual expected size is larger due to RSA padding, but the
2201 * bound is sufficient to be safe.
2203 if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2204 al = SSL_AD_DECRYPT_ERROR;
2205 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2206 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2211 * We must not leak whether a decryption failure occurs because of
2212 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2213 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2214 * generates a random premaster secret for the case that the decrypt
2215 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2218 if (RAND_bytes(rand_premaster_secret,
2219 sizeof(rand_premaster_secret)) <= 0)
2222 RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2226 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2227 * be 0xff if so and zero otherwise.
2230 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2233 * If the version in the decrypted pre-master secret is correct then
2234 * version_good will be 0xff, otherwise it'll be zero. The
2235 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2236 * (http://eprint.iacr.org/2003/052/) exploits the version number
2237 * check as a "bad version oracle". Thus version checks are done in
2238 * constant time and are treated like any other decryption error.
2241 constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2243 constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2246 * The premaster secret must contain the same version number as the
2247 * ClientHello to detect version rollback attacks (strangely, the
2248 * protocol does not offer such protection for DH ciphersuites).
2249 * However, buggy clients exist that send the negotiated protocol
2250 * version instead if the server does not support the requested
2251 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2254 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2255 unsigned char workaround_good;
2257 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2259 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2260 version_good |= workaround_good;
2264 * Both decryption and version must be good for decrypt_good to
2265 * remain non-zero (0xff).
2267 decrypt_good &= version_good;
2270 * Now copy rand_premaster_secret over from p using
2271 * decrypt_good_mask. If decryption failed, then p does not
2272 * contain valid plaintext, however, a check above guarantees
2273 * it is still sufficiently large to read from.
2275 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2276 p[j] = constant_time_select_8(decrypt_good, p[j],
2277 rand_premaster_secret[j]);
2280 s->session->master_key_length =
2281 s->method->ssl3_enc->generate_master_secret(s,
2283 session->master_key,
2286 (rand_premaster_secret));
2287 OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2288 if (s->session->master_key_length < 0) {
2289 al = SSL_AD_INTERNAL_ERROR;
2290 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2295 #ifndef OPENSSL_NO_DH
2296 if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) {
2298 EVP_PKEY *skey = NULL;
2302 if (alg_k & SSL_kDHE) {
2303 al = SSL_AD_HANDSHAKE_FAILURE;
2304 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2305 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2310 if (n && n != i + 2) {
2311 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2312 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2313 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2320 if (alg_k & SSL_kDHr)
2321 idx = SSL_PKEY_DH_RSA;
2322 else if (alg_k & SSL_kDHd)
2323 idx = SSL_PKEY_DH_DSA;
2325 skey = s->cert->pkeys[idx].privatekey;
2326 if ((skey == NULL) ||
2327 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2328 al = SSL_AD_HANDSHAKE_FAILURE;
2329 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2330 SSL_R_MISSING_RSA_CERTIFICATE);
2333 dh_srvr = skey->pkey.dh;
2334 } else if (s->s3->tmp.dh == NULL) {
2335 al = SSL_AD_HANDSHAKE_FAILURE;
2336 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2337 SSL_R_MISSING_TMP_DH_KEY);
2340 dh_srvr = s->s3->tmp.dh;
2343 /* Get pubkey from cert */
2344 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2346 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2347 dh_clnt = EVP_PKEY_get1_DH(clkey);
2349 if (dh_clnt == NULL) {
2350 al = SSL_AD_HANDSHAKE_FAILURE;
2351 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2352 SSL_R_MISSING_TMP_DH_KEY);
2355 EVP_PKEY_free(clkey);
2356 pub = dh_clnt->pub_key;
2358 pub = BN_bin2bn(p, i, NULL);
2360 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2364 i = DH_compute_key(p, pub, dh_srvr);
2367 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2372 DH_free(s->s3->tmp.dh);
2373 s->s3->tmp.dh = NULL;
2379 s->session->master_key_length =
2380 s->method->ssl3_enc->generate_master_secret(s,
2382 session->master_key,
2384 OPENSSL_cleanse(p, i);
2385 if (s->session->master_key_length < 0) {
2386 al = SSL_AD_INTERNAL_ERROR;
2387 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2394 #ifndef OPENSSL_NO_KRB5
2395 if (alg_k & SSL_kKRB5) {
2396 krb5_error_code krb5rc;
2397 krb5_data enc_ticket;
2398 krb5_data authenticator;
2400 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2401 EVP_CIPHER_CTX ciph_ctx;
2402 const EVP_CIPHER *enc = NULL;
2403 unsigned char iv[EVP_MAX_IV_LENGTH];
2404 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2406 krb5_timestamp authtime = 0;
2407 krb5_ticket_times ttimes;
2409 EVP_CIPHER_CTX_init(&ciph_ctx);
2412 kssl_ctx = kssl_ctx_new();
2415 enc_ticket.length = i;
2417 if (n < (long)(enc_ticket.length + 6)) {
2418 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2419 SSL_R_DATA_LENGTH_TOO_LONG);
2423 enc_ticket.data = (char *)p;
2424 p += enc_ticket.length;
2427 authenticator.length = i;
2429 if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2430 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2431 SSL_R_DATA_LENGTH_TOO_LONG);
2435 authenticator.data = (char *)p;
2436 p += authenticator.length;
2440 enc_pms.data = (char *)p;
2441 p += enc_pms.length;
2444 * Note that the length is checked again below, ** after decryption
2446 if (enc_pms.length > sizeof pms) {
2447 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2448 SSL_R_DATA_LENGTH_TOO_LONG);
2452 if (n != (long)(enc_ticket.length + authenticator.length +
2453 enc_pms.length + 6)) {
2454 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2455 SSL_R_DATA_LENGTH_TOO_LONG);
2459 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2462 fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2463 krb5rc, kssl_err.reason);
2465 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2466 # endif /* KSSL_DEBUG */
2467 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2472 * Note: no authenticator is not considered an error, ** but will
2473 * return authtime == 0.
2475 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2476 &authtime, &kssl_err)) != 0) {
2478 fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2479 krb5rc, kssl_err.reason);
2481 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2482 # endif /* KSSL_DEBUG */
2483 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2487 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2488 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2492 kssl_ctx_show(kssl_ctx);
2493 # endif /* KSSL_DEBUG */
2495 enc = kssl_map_enc(kssl_ctx->enctype);
2499 memset(iv, 0, sizeof(iv)); /* per RFC 1510 */
2501 if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2502 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2503 SSL_R_DECRYPTION_FAILED);
2506 if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2507 (unsigned char *)enc_pms.data, enc_pms.length))
2509 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2510 SSL_R_DECRYPTION_FAILED);
2513 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2514 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2515 SSL_R_DATA_LENGTH_TOO_LONG);
2518 if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2519 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2520 SSL_R_DECRYPTION_FAILED);
2524 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2525 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2526 SSL_R_DATA_LENGTH_TOO_LONG);
2529 if (!((pms[0] == (s->client_version >> 8))
2530 && (pms[1] == (s->client_version & 0xff)))) {
2532 * The premaster secret must contain the same version number as
2533 * the ClientHello to detect version rollback attacks (strangely,
2534 * the protocol does not offer such protection for DH
2535 * ciphersuites). However, buggy clients exist that send random
2536 * bytes instead of the protocol version. If
2537 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2538 * (Perhaps we should have a separate BUG value for the Kerberos
2541 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2542 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2543 SSL_AD_DECODE_ERROR);
2548 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2550 s->session->master_key_length =
2551 s->method->ssl3_enc->generate_master_secret(s,
2553 session->master_key,
2555 if (s->session->master_key_length < 0) {
2556 al = SSL_AD_INTERNAL_ERROR;
2557 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2561 if (kssl_ctx->client_princ) {
2562 size_t len = strlen(kssl_ctx->client_princ);
2563 if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2564 s->session->krb5_client_princ_len = len;
2565 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2570 /*- Was doing kssl_ctx_free() here,
2571 * but it caused problems for apache.
2572 * kssl_ctx = kssl_ctx_free(kssl_ctx);
2573 * if (s->kssl_ctx) s->kssl_ctx = NULL;
2576 #endif /* OPENSSL_NO_KRB5 */
2578 #ifndef OPENSSL_NO_EC
2579 if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe)) {
2583 const EC_GROUP *group;
2584 const BIGNUM *priv_key;
2586 /* initialize structures for server's ECDH key pair */
2587 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2588 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2592 /* Let's get server private key and group information */
2593 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2594 /* use the certificate */
2595 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2598 * use the ephermeral values we saved when generating the
2599 * ServerKeyExchange msg.
2601 tkey = s->s3->tmp.ecdh;
2604 group = EC_KEY_get0_group(tkey);
2605 priv_key = EC_KEY_get0_private_key(tkey);
2607 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2608 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2609 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2613 /* Let's get client's public key */
2614 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2615 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2620 /* Client Publickey was in Client Certificate */
2622 if (alg_k & SSL_kECDHE) {
2623 al = SSL_AD_HANDSHAKE_FAILURE;
2624 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2625 SSL_R_MISSING_TMP_ECDH_KEY);
2628 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2629 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2631 * XXX: For now, we do not support client authentication
2632 * using ECDH certificates so this branch (n == 0L) of the
2633 * code is never executed. When that support is added, we
2634 * ought to ensure the key received in the certificate is
2635 * authorized for key agreement. ECDH_compute_key implicitly
2636 * checks that the two ECDH shares are for the same group.
2638 al = SSL_AD_HANDSHAKE_FAILURE;
2639 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2640 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2644 if (EC_POINT_copy(clnt_ecpoint,
2645 EC_KEY_get0_public_key(clnt_pub_pkey->
2647 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2650 ret = 2; /* Skip certificate verify processing */
2653 * Get client's public key from encoded point in the
2654 * ClientKeyExchange message.
2656 if ((bn_ctx = BN_CTX_new()) == NULL) {
2657 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2658 ERR_R_MALLOC_FAILURE);
2662 /* Get encoded point length */
2666 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2669 if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2670 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2674 * p is pointing to somewhere in the buffer currently, so set it
2677 p = (unsigned char *)s->init_buf->data;
2680 /* Compute the shared pre-master secret */
2681 field_size = EC_GROUP_get_degree(group);
2682 if (field_size <= 0) {
2683 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2686 i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2689 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2693 EVP_PKEY_free(clnt_pub_pkey);
2694 EC_POINT_free(clnt_ecpoint);
2695 EC_KEY_free(srvr_ecdh);
2696 BN_CTX_free(bn_ctx);
2697 EC_KEY_free(s->s3->tmp.ecdh);
2698 s->s3->tmp.ecdh = NULL;
2700 /* Compute the master secret */
2701 s->session->master_key_length =
2702 s->method->ssl3_enc->generate_master_secret(s,
2704 session->master_key,
2707 OPENSSL_cleanse(p, i);
2708 if (s->session->master_key_length < 0) {
2709 al = SSL_AD_INTERNAL_ERROR;
2710 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2716 #ifndef OPENSSL_NO_PSK
2717 if (alg_k & SSL_kPSK) {
2718 unsigned char *t = NULL;
2719 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2720 unsigned int pre_ms_len = 0, psk_len = 0;
2722 char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2724 al = SSL_AD_HANDSHAKE_FAILURE;
2728 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2731 if (i > PSK_MAX_IDENTITY_LEN) {
2732 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2733 SSL_R_DATA_LENGTH_TOO_LONG);
2736 if (s->psk_server_callback == NULL) {
2737 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2738 SSL_R_PSK_NO_SERVER_CB);
2743 * Create guaranteed NULL-terminated identity string for the callback
2745 memcpy(tmp_id, p, i);
2746 memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2747 psk_len = s->psk_server_callback(s, tmp_id,
2749 sizeof(psk_or_pre_ms));
2750 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2752 if (psk_len > PSK_MAX_PSK_LEN) {
2753 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2755 } else if (psk_len == 0) {
2757 * PSK related to the given identity not found
2759 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2760 SSL_R_PSK_IDENTITY_NOT_FOUND);
2761 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2765 /* create PSK pre_master_secret */
2766 pre_ms_len = 2 + psk_len + 2 + psk_len;
2768 memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2770 memset(t, 0, psk_len);
2774 OPENSSL_free(s->session->psk_identity);
2775 s->session->psk_identity = BUF_strdup((char *)p);
2776 if (s->session->psk_identity == NULL) {
2777 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2781 OPENSSL_free(s->session->psk_identity_hint);
2782 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2783 if (s->ctx->psk_identity_hint != NULL &&
2784 s->session->psk_identity_hint == NULL) {
2785 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2789 s->session->master_key_length =
2790 s->method->ssl3_enc->generate_master_secret(s,
2792 session->master_key,
2795 if (s->session->master_key_length < 0) {
2796 al = SSL_AD_INTERNAL_ERROR;
2797 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2802 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2807 #ifndef OPENSSL_NO_SRP
2808 if (alg_k & SSL_kSRP) {
2813 if (param_len > n) {
2814 al = SSL_AD_DECODE_ERROR;
2815 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2816 SSL_R_BAD_SRP_A_LENGTH);
2819 if ((s->srp_ctx.A = BN_bin2bn(p, i, NULL)) == NULL) {
2820 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2823 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2824 || BN_is_zero(s->srp_ctx.A)) {
2825 al = SSL_AD_ILLEGAL_PARAMETER;
2826 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2827 SSL_R_BAD_SRP_PARAMETERS);
2830 OPENSSL_free(s->session->srp_username);
2831 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2832 if (s->session->srp_username == NULL) {
2833 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2837 if ((s->session->master_key_length =
2838 SRP_generate_server_master_secret(s,
2839 s->session->master_key)) < 0) {
2840 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2846 #endif /* OPENSSL_NO_SRP */
2847 if (alg_k & SSL_kGOST) {
2849 EVP_PKEY_CTX *pkey_ctx;
2850 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2851 unsigned char premaster_secret[32], *start;
2852 size_t outlen = 32, inlen;
2853 unsigned long alg_a;
2857 /* Get our certificate private key */
2858 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2859 if (alg_a & SSL_aGOST94)
2860 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2861 else if (alg_a & SSL_aGOST01)
2862 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2864 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2865 EVP_PKEY_decrypt_init(pkey_ctx);
2867 * If client certificate is present and is of the same type, maybe
2868 * use it for key exchange. Don't mind errors from
2869 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2870 * client certificate for authorization only.
2872 client_pub_pkey = X509_get_pubkey(s->session->peer);
2873 if (client_pub_pkey) {
2874 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2877 /* Decrypt session key */
2879 ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2880 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2881 || Tclass != V_ASN1_UNIVERSAL) {
2882 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2883 SSL_R_DECRYPTION_FAILED);
2888 if (EVP_PKEY_decrypt
2889 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2890 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2891 SSL_R_DECRYPTION_FAILED);
2894 /* Generate master secret */
2895 s->session->master_key_length =
2896 s->method->ssl3_enc->generate_master_secret(s,
2898 session->master_key,
2899 premaster_secret, 32);
2900 if (s->session->master_key_length < 0) {
2901 al = SSL_AD_INTERNAL_ERROR;
2902 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2905 /* Check if pubkey from client certificate was used */
2906 if (EVP_PKEY_CTX_ctrl
2907 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2912 EVP_PKEY_free(client_pub_pkey);
2913 EVP_PKEY_CTX_free(pkey_ctx);
2918 al = SSL_AD_HANDSHAKE_FAILURE;
2919 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2925 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2926 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2929 #ifndef OPENSSL_NO_EC
2930 EVP_PKEY_free(clnt_pub_pkey);
2931 EC_POINT_free(clnt_ecpoint);
2932 EC_KEY_free(srvr_ecdh);
2933 BN_CTX_free(bn_ctx);
2935 s->state = SSL_ST_ERR;
2939 int ssl3_get_cert_verify(SSL *s)
2941 EVP_PKEY *pkey = NULL;
2943 int al, ok, ret = 0;
2947 const EVP_MD *md = NULL;
2949 EVP_MD_CTX_init(&mctx);
2952 * We should only process a CertificateVerify message if we have received
2953 * a Certificate from the client. If so then |s->session->peer| will be non
2954 * NULL. In some instances a CertificateVerify message is not required even
2955 * if the peer has sent a Certificate (e.g. such as in the case of static
2956 * DH). In that case the ClientKeyExchange processing will skip the
2957 * CertificateVerify state so we should not arrive here.
2959 if (s->session->peer == NULL) {
2964 n = s->method->ssl_get_message(s,
2965 SSL3_ST_SR_CERT_VRFY_A,
2966 SSL3_ST_SR_CERT_VRFY_B,
2967 SSL3_MT_CERTIFICATE_VERIFY,
2968 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2973 peer = s->session->peer;
2974 pkey = X509_get_pubkey(peer);
2975 type = X509_certificate_type(peer, pkey);
2977 if (!(type & EVP_PKT_SIGN)) {
2978 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2979 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2980 al = SSL_AD_ILLEGAL_PARAMETER;
2984 /* we now have a signature that we need to verify */
2985 p = (unsigned char *)s->init_msg;
2986 /* Check for broken implementations of GOST ciphersuites */
2988 * If key is GOST and n is exactly 64, it is bare signature without
2991 if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2992 pkey->type == NID_id_GostR3410_2001)) {
2995 if (SSL_USE_SIGALGS(s)) {
2996 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2998 al = SSL_AD_INTERNAL_ERROR;
3000 } else if (rv == 0) {
3001 al = SSL_AD_DECODE_ERROR;
3005 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3013 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3014 al = SSL_AD_DECODE_ERROR;
3018 j = EVP_PKEY_size(pkey);
3019 if ((i > j) || (n > j) || (n <= 0)) {
3020 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3021 al = SSL_AD_DECODE_ERROR;
3025 if (SSL_USE_SIGALGS(s)) {
3028 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3029 if (hdatalen <= 0) {
3030 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3031 al = SSL_AD_INTERNAL_ERROR;
3035 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3038 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3039 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3040 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3041 al = SSL_AD_INTERNAL_ERROR;
3045 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
3046 al = SSL_AD_DECRYPT_ERROR;
3047 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3051 #ifndef OPENSSL_NO_RSA
3052 if (pkey->type == EVP_PKEY_RSA) {
3053 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3054 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3057 al = SSL_AD_DECRYPT_ERROR;
3058 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3062 al = SSL_AD_DECRYPT_ERROR;
3063 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3068 #ifndef OPENSSL_NO_DSA
3069 if (pkey->type == EVP_PKEY_DSA) {
3070 j = DSA_verify(pkey->save_type,
3071 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3072 SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3075 al = SSL_AD_DECRYPT_ERROR;
3076 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3081 #ifndef OPENSSL_NO_EC
3082 if (pkey->type == EVP_PKEY_EC) {
3083 j = ECDSA_verify(pkey->save_type,
3084 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3085 SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3088 al = SSL_AD_DECRYPT_ERROR;
3089 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3094 if (pkey->type == NID_id_GostR3410_94
3095 || pkey->type == NID_id_GostR3410_2001) {
3096 unsigned char signature[64];
3098 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3099 EVP_PKEY_verify_init(pctx);
3101 fprintf(stderr, "GOST signature length is %d", i);
3103 for (idx = 0; idx < 64; idx++) {
3104 signature[63 - idx] = p[idx];
3106 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3108 EVP_PKEY_CTX_free(pctx);
3110 al = SSL_AD_DECRYPT_ERROR;
3111 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3115 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3116 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3123 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3124 s->state = SSL_ST_ERR;
3127 BIO_free(s->s3->handshake_buffer);
3128 s->s3->handshake_buffer = NULL;
3129 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3130 EVP_MD_CTX_cleanup(&mctx);
3131 EVP_PKEY_free(pkey);
3135 int ssl3_get_client_certificate(SSL *s)
3137 int i, ok, al, ret = -1;
3139 unsigned long l, nc, llen, n;
3140 const unsigned char *p, *q;
3142 STACK_OF(X509) *sk = NULL;
3144 n = s->method->ssl_get_message(s,
3147 -1, s->max_cert_list, &ok);
3152 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3153 if ((s->verify_mode & SSL_VERIFY_PEER) &&
3154 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3155 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3156 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3157 al = SSL_AD_HANDSHAKE_FAILURE;
3161 * If tls asked for a client cert, the client must return a 0 list
3163 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3164 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3165 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3166 al = SSL_AD_UNEXPECTED_MESSAGE;
3169 s->s3->tmp.reuse_message = 1;
3173 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3174 al = SSL_AD_UNEXPECTED_MESSAGE;
3175 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3178 p = d = (unsigned char *)s->init_msg;
3180 if ((sk = sk_X509_new_null()) == NULL) {
3181 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3186 if (llen + 3 != n) {
3187 al = SSL_AD_DECODE_ERROR;
3188 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3191 for (nc = 0; nc < llen;) {
3193 if ((l + nc + 3) > llen) {
3194 al = SSL_AD_DECODE_ERROR;
3195 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3196 SSL_R_CERT_LENGTH_MISMATCH);
3201 x = d2i_X509(NULL, &p, l);
3203 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3207 al = SSL_AD_DECODE_ERROR;
3208 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3209 SSL_R_CERT_LENGTH_MISMATCH);
3212 if (!sk_X509_push(sk, x)) {
3213 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3220 if (sk_X509_num(sk) <= 0) {
3221 /* TLS does not mind 0 certs returned */
3222 if (s->version == SSL3_VERSION) {
3223 al = SSL_AD_HANDSHAKE_FAILURE;
3224 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3225 SSL_R_NO_CERTIFICATES_RETURNED);
3228 /* Fail for TLS only if we required a certificate */
3229 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3230 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3231 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3232 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3233 al = SSL_AD_HANDSHAKE_FAILURE;
3236 /* No client certificate so digest cached records */
3237 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3238 al = SSL_AD_INTERNAL_ERROR;
3243 i = ssl_verify_cert_chain(s, sk);
3245 al = ssl_verify_alarm_type(s->verify_result);
3246 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3247 SSL_R_CERTIFICATE_VERIFY_FAILED);
3251 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3252 al = SSL_AD_HANDSHAKE_FAILURE;
3255 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3257 al = SSL3_AD_HANDSHAKE_FAILURE;
3258 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3259 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3262 EVP_PKEY_free(pkey);
3265 X509_free(s->session->peer);
3266 s->session->peer = sk_X509_shift(sk);
3267 s->session->verify_result = s->verify_result;
3270 * With the current implementation, sess_cert will always be NULL when we
3273 if (s->session->sess_cert == NULL) {
3274 s->session->sess_cert = ssl_sess_cert_new();
3275 if (s->session->sess_cert == NULL) {
3276 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3280 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3281 s->session->sess_cert->cert_chain = sk;
3283 * Inconsistency alert: cert_chain does *not* include the peer's own
3284 * certificate, while we do include it in s3_clnt.c
3291 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3293 s->state = SSL_ST_ERR;
3295 sk_X509_pop_free(sk, X509_free);
3299 int ssl3_send_server_certificate(SSL *s)
3303 if (s->state == SSL3_ST_SW_CERT_A) {
3304 cpk = ssl_get_server_send_pkey(s);
3306 /* VRS: allow null cert if auth == KRB5 */
3307 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3308 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3309 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3310 ERR_R_INTERNAL_ERROR);
3311 s->state = SSL_ST_ERR;
3316 if (!ssl3_output_cert_chain(s, cpk)) {
3317 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3318 s->state = SSL_ST_ERR;
3321 s->state = SSL3_ST_SW_CERT_B;
3324 /* SSL3_ST_SW_CERT_B */
3325 return ssl_do_write(s);
3328 #ifndef OPENSSL_NO_TLSEXT
3329 /* send a new session ticket (not necessarily for a new session) */
3330 int ssl3_send_newsession_ticket(SSL *s)
3332 unsigned char *senc = NULL;
3336 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3337 unsigned char *p, *macstart;
3338 const unsigned char *const_p;
3339 int len, slen_full, slen;
3342 SSL_CTX *tctx = s->initial_ctx;
3343 unsigned char iv[EVP_MAX_IV_LENGTH];
3344 unsigned char key_name[16];
3346 /* get session encoding length */
3347 slen_full = i2d_SSL_SESSION(s->session, NULL);
3349 * Some length values are 16 bits, so forget it if session is too
3352 if (slen_full == 0 || slen_full > 0xFF00) {
3353 s->state = SSL_ST_ERR;
3356 senc = OPENSSL_malloc(slen_full);
3358 s->state = SSL_ST_ERR;
3362 EVP_CIPHER_CTX_init(&ctx);
3363 HMAC_CTX_init(&hctx);
3366 if (!i2d_SSL_SESSION(s->session, &p))
3370 * create a fresh copy (not shared with other threads) to clean up
3373 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3376 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3378 slen = i2d_SSL_SESSION(sess, NULL);
3379 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3380 SSL_SESSION_free(sess);
3384 if (!i2d_SSL_SESSION(sess, &p)) {
3385 SSL_SESSION_free(sess);
3388 SSL_SESSION_free(sess);
3391 * Grow buffer if need be: the length calculation is as
3392 * follows handshake_header_length +
3393 * 4 (ticket lifetime hint) + 2 (ticket length) +
3394 * 16 (key name) + max_iv_len (iv length) +
3395 * session_length + max_enc_block_size (max encrypted session
3396 * length) + max_md_size (HMAC).
3398 if (!BUF_MEM_grow(s->init_buf,
3399 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3400 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3403 p = ssl_handshake_start(s);
3405 * Initialize HMAC and cipher contexts. If callback present it does
3406 * all the work otherwise use generated values from parent ctx.
3408 if (tctx->tlsext_ticket_key_cb) {
3409 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3413 if (RAND_bytes(iv, 16) <= 0)
3415 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3416 tctx->tlsext_tick_aes_key, iv))
3418 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3419 EVP_sha256(), NULL))
3421 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3425 * Ticket lifetime hint (advisory only): We leave this unspecified
3426 * for resumed session (for simplicity), and guess that tickets for
3427 * new sessions will live as long as their sessions.
3429 l2n(s->hit ? 0 : s->session->timeout, p);
3431 /* Skip ticket length for now */
3433 /* Output key name */
3435 memcpy(p, key_name, 16);
3438 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3439 p += EVP_CIPHER_CTX_iv_length(&ctx);
3440 /* Encrypt session data */
3441 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3444 if (!EVP_EncryptFinal(&ctx, p, &len))
3448 if (!HMAC_Update(&hctx, macstart, p - macstart))
3450 if (!HMAC_Final(&hctx, p, &hlen))
3453 EVP_CIPHER_CTX_cleanup(&ctx);
3454 HMAC_CTX_cleanup(&hctx);
3457 /* Now write out lengths: p points to end of data written */
3459 len = p - ssl_handshake_start(s);
3460 /* Skip ticket lifetime hint */
3461 p = ssl_handshake_start(s) + 4;
3463 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3465 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3469 /* SSL3_ST_SW_SESSION_TICKET_B */
3470 return ssl_do_write(s);
3473 EVP_CIPHER_CTX_cleanup(&ctx);
3474 HMAC_CTX_cleanup(&hctx);
3475 s->state = SSL_ST_ERR;
3479 int ssl3_send_cert_status(SSL *s)
3481 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3484 * Grow buffer if need be: the length calculation is as
3485 * follows 1 (message type) + 3 (message length) +
3486 * 1 (ocsp response type) + 3 (ocsp response length)
3489 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3490 s->state = SSL_ST_ERR;
3494 p = (unsigned char *)s->init_buf->data;
3497 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3498 /* message length */
3499 l2n3(s->tlsext_ocsp_resplen + 4, p);
3501 *(p++) = s->tlsext_status_type;
3502 /* length of OCSP response */
3503 l2n3(s->tlsext_ocsp_resplen, p);
3504 /* actual response */
3505 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3506 /* number of bytes to write */
3507 s->init_num = 8 + s->tlsext_ocsp_resplen;
3508 s->state = SSL3_ST_SW_CERT_STATUS_B;
3512 /* SSL3_ST_SW_CERT_STATUS_B */
3513 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3516 # ifndef OPENSSL_NO_NEXTPROTONEG
3518 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3519 * It sets the next_proto member in s if found
3521 int ssl3_get_next_proto(SSL *s)
3524 int proto_len, padding_len;
3526 const unsigned char *p;
3529 * Clients cannot send a NextProtocol message if we didn't see the
3530 * extension in their ClientHello
3532 if (!s->s3->next_proto_neg_seen) {
3533 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3534 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3535 s->state = SSL_ST_ERR;
3539 /* See the payload format below */
3540 n = s->method->ssl_get_message(s,
3541 SSL3_ST_SR_NEXT_PROTO_A,
3542 SSL3_ST_SR_NEXT_PROTO_B,
3543 SSL3_MT_NEXT_PROTO, 514, &ok);
3549 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3550 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3551 * ssl3_get_finished).
3553 if (!s->s3->change_cipher_spec) {
3554 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3555 s->state = SSL_ST_ERR;
3560 s->state = SSL_ST_ERR;
3561 return 0; /* The body must be > 1 bytes long */
3564 p = (unsigned char *)s->init_msg;
3567 * The payload looks like:
3569 * uint8 proto[proto_len];
3570 * uint8 padding_len;
3571 * uint8 padding[padding_len];
3574 if (proto_len + 2 > s->init_num) {
3575 s->state = SSL_ST_ERR;
3578 padding_len = p[proto_len + 1];
3579 if (proto_len + padding_len + 2 != s->init_num) {
3580 s->state = SSL_ST_ERR;
3584 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3585 if (!s->next_proto_negotiated) {
3586 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3587 s->state = SSL_ST_ERR;
3590 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3591 s->next_proto_negotiated_len = proto_len;