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 "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #ifndef OPENSSL_NO_DH
162 # include <openssl/dh.h>
164 #include <openssl/bn.h>
165 #include <openssl/md5.h>
167 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
168 PACKET *cipher_suites,
169 STACK_OF(SSL_CIPHER) **skp,
170 int sslv2format, int *al);
173 #ifndef OPENSSL_NO_SRP
174 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
176 int ret = SSL_ERROR_NONE;
178 *al = SSL_AD_UNRECOGNIZED_NAME;
180 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
181 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
182 if (s->srp_ctx.login == NULL) {
184 * RFC 5054 says SHOULD reject, we do so if There is no srp
188 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
190 ret = SSL_srp_server_param_with_username(s, al);
197 int ssl3_accept(SSL *s)
200 unsigned long alg_k, Time = (unsigned long)time(NULL);
201 void (*cb) (const SSL *ssl, int type, int val) = NULL;
203 int new_state, state, skip = 0;
205 RAND_add(&Time, sizeof(Time), 0);
209 if (s->info_callback != NULL)
210 cb = s->info_callback;
211 else if (s->ctx->info_callback != NULL)
212 cb = s->ctx->info_callback;
214 /* init things to blank */
216 if (!SSL_in_init(s) || SSL_in_before(s)) {
221 #ifndef OPENSSL_NO_HEARTBEATS
223 * If we're awaiting a HeartbeatResponse, pretend we already got and
224 * don't await it anymore, because Heartbeats don't make sense during
227 if (s->tlsext_hb_pending) {
228 s->tlsext_hb_pending = 0;
237 case SSL_ST_RENEGOTIATE:
239 /* s->state=SSL_ST_ACCEPT; */
243 case SSL_ST_BEFORE | SSL_ST_ACCEPT:
244 case SSL_ST_OK | SSL_ST_ACCEPT:
248 cb(s, SSL_CB_HANDSHAKE_START, 1);
250 if ((s->version >> 8 != 3) && s->version != TLS_ANY_VERSION) {
251 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
252 s->state = SSL_ST_ERR;
256 if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
257 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
261 s->type = SSL_ST_ACCEPT;
263 if (s->init_buf == NULL) {
264 if ((buf = BUF_MEM_new()) == NULL) {
266 s->state = SSL_ST_ERR;
269 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
272 s->state = SSL_ST_ERR;
278 if (!ssl3_setup_buffers(s)) {
280 s->state = SSL_ST_ERR;
285 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
287 * Should have been reset by ssl3_get_finished, too.
289 s->s3->change_cipher_spec = 0;
291 if (s->state != SSL_ST_RENEGOTIATE) {
293 * Ok, we now need to push on a buffering BIO so that the
294 * output is sent in a way that TCP likes :-)
296 if (!ssl_init_wbio_buffer(s, 1)) {
298 s->state = SSL_ST_ERR;
302 ssl3_init_finished_mac(s);
303 s->state = SSL3_ST_SR_CLNT_HELLO_A;
304 s->ctx->stats.sess_accept++;
305 } else if (!s->s3->send_connection_binding &&
307 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
309 * Server attempting to renegotiate with client that doesn't
310 * support secure renegotiation.
312 SSLerr(SSL_F_SSL3_ACCEPT,
313 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
314 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
316 s->state = SSL_ST_ERR;
320 * s->state == SSL_ST_RENEGOTIATE, we will just send a
323 s->ctx->stats.sess_accept_renegotiate++;
324 s->state = SSL3_ST_SW_HELLO_REQ_A;
328 case SSL3_ST_SW_HELLO_REQ_A:
329 case SSL3_ST_SW_HELLO_REQ_B:
332 ret = ssl3_send_hello_request(s);
335 s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
336 s->state = SSL3_ST_SW_FLUSH;
339 ssl3_init_finished_mac(s);
342 case SSL3_ST_SW_HELLO_REQ_C:
343 s->state = SSL_ST_OK;
346 case SSL3_ST_SR_CLNT_HELLO_A:
347 case SSL3_ST_SR_CLNT_HELLO_B:
348 case SSL3_ST_SR_CLNT_HELLO_C:
350 ret = ssl3_get_client_hello(s);
353 #ifndef OPENSSL_NO_SRP
354 s->state = SSL3_ST_SR_CLNT_HELLO_D;
355 case SSL3_ST_SR_CLNT_HELLO_D:
358 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
360 * callback indicates firther work to be done
362 s->rwstate = SSL_X509_LOOKUP;
365 if (ret != SSL_ERROR_NONE) {
366 ssl3_send_alert(s, SSL3_AL_FATAL, al);
368 * This is not really an error but the only means to for
369 * a client to detect whether srp is supported.
371 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
372 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
373 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
375 s->state = SSL_ST_ERR;
382 s->state = SSL3_ST_SW_SRVR_HELLO_A;
386 case SSL3_ST_SW_SRVR_HELLO_A:
387 case SSL3_ST_SW_SRVR_HELLO_B:
388 ret = ssl3_send_server_hello(s);
393 if (s->tlsext_ticket_expected)
394 s->state = SSL3_ST_SW_SESSION_TICKET_A;
396 s->state = SSL3_ST_SW_CHANGE_A;
398 s->state = SSL3_ST_SW_CERT_A;
403 case SSL3_ST_SW_CERT_A:
404 case SSL3_ST_SW_CERT_B:
405 /* Check if it is anon DH or anon ECDH, */
406 /* normal PSK or SRP */
407 if (!(s->s3->tmp.new_cipher->algorithm_auth &
408 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
409 ret = ssl3_send_server_certificate(s);
413 if (s->tlsext_status_expected)
414 s->state = SSL3_ST_SW_CERT_STATUS_A;
416 s->state = SSL3_ST_SW_KEY_EXCH_A;
419 s->state = SSL3_ST_SW_KEY_EXCH_A;
424 case SSL3_ST_SW_KEY_EXCH_A:
425 case SSL3_ST_SW_KEY_EXCH_B:
426 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
429 * clear this, it may get reset by
430 * send_server_key_exchange
432 s->s3->tmp.use_rsa_tmp = 0;
435 * only send if a DH key exchange, fortezza or RSA but we have a
436 * sign only certificate PSK: may send PSK identity hints For
437 * ECC ciphersuites, we send a serverKeyExchange message only if
438 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
439 * the server certificate contains the server's public key for
444 * PSK: send ServerKeyExchange if PSK identity hint if
447 #ifndef OPENSSL_NO_PSK
448 /* Only send SKE if we have identity hint for plain PSK */
449 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK)) && s->cert->psk_identity_hint)
450 /* For other PSK always send SKE */
451 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
453 #ifndef OPENSSL_NO_SRP
454 /* SRP: send ServerKeyExchange */
455 || (alg_k & SSL_kSRP)
457 || (alg_k & SSL_kDHE)
458 || (alg_k & SSL_kECDHE)
459 || ((alg_k & SSL_kRSA)
460 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
461 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
462 && EVP_PKEY_size(s->cert->pkeys
463 [SSL_PKEY_RSA_ENC].privatekey) *
464 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
469 ret = ssl3_send_server_key_exchange(s);
475 s->state = SSL3_ST_SW_CERT_REQ_A;
479 case SSL3_ST_SW_CERT_REQ_A:
480 case SSL3_ST_SW_CERT_REQ_B:
481 if ( /* don't request cert unless asked for it: */
482 !(s->verify_mode & SSL_VERIFY_PEER) ||
484 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
485 * during re-negotiation:
487 ((s->session->peer != NULL) &&
488 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
490 * never request cert in anonymous ciphersuites (see
491 * section "Certificate request" in SSL 3 drafts and in
494 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
496 * ... except when the application insists on
497 * verification (against the specs, but s3_clnt.c accepts
500 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
501 /* don't request certificate for SRP auth */
502 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
504 * With normal PSK Certificates and Certificate Requests
507 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
508 /* no cert request */
510 s->s3->tmp.cert_request = 0;
511 s->state = SSL3_ST_SW_SRVR_DONE_A;
512 if (!ssl3_digest_cached_records(s, 0)) {
513 s->state = SSL_ST_ERR;
517 s->s3->tmp.cert_request = 1;
518 ret = ssl3_send_certificate_request(s);
521 s->state = SSL3_ST_SW_SRVR_DONE_A;
526 case SSL3_ST_SW_SRVR_DONE_A:
527 case SSL3_ST_SW_SRVR_DONE_B:
528 ret = ssl3_send_server_done(s);
531 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
532 s->state = SSL3_ST_SW_FLUSH;
536 case SSL3_ST_SW_FLUSH:
539 * This code originally checked to see if any data was pending
540 * using BIO_CTRL_INFO and then flushed. This caused problems as
541 * documented in PR#1939. The proposed fix doesn't completely
542 * resolve this issue as buggy implementations of
543 * BIO_CTRL_PENDING still exist. So instead we just flush
547 s->rwstate = SSL_WRITING;
548 if (BIO_flush(s->wbio) <= 0) {
552 s->rwstate = SSL_NOTHING;
554 s->state = s->s3->tmp.next_state;
557 case SSL3_ST_SR_CERT_A:
558 case SSL3_ST_SR_CERT_B:
559 if (s->s3->tmp.cert_request) {
560 ret = ssl3_get_client_certificate(s);
565 s->state = SSL3_ST_SR_KEY_EXCH_A;
568 case SSL3_ST_SR_KEY_EXCH_A:
569 case SSL3_ST_SR_KEY_EXCH_B:
570 ret = ssl3_get_client_key_exchange(s);
575 * For the ECDH ciphersuites when the client sends its ECDH
576 * pub key in a certificate, the CertificateVerify message is
577 * not sent. Also for GOST ciphersuites when the client uses
578 * its key from the certificate for key exchange.
580 s->state = SSL3_ST_SR_CHANGE_A;
582 } else if (SSL_USE_SIGALGS(s)) {
583 s->state = SSL3_ST_SR_CERT_VRFY_A;
585 if (!s->session->peer)
587 if (!s->s3->handshake_buffer) {
588 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
589 s->state = SSL_ST_ERR;
593 * For sigalgs freeze the handshake buffer. If we support
594 * extms we've done this already so this is a no-op
596 if (!ssl3_digest_cached_records(s, 1)) {
597 s->state = SSL_ST_ERR;
604 s->state = SSL3_ST_SR_CERT_VRFY_A;
608 * We need to get hashes here so if there is a client cert,
609 * it can be verified FIXME - digest processing for
610 * CertificateVerify should be generalized. But it is next
613 if (!ssl3_digest_cached_records(s, 0)) {
614 s->state = SSL_ST_ERR;
617 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
618 if (s->s3->handshake_dgst[dgst_num]) {
621 s->method->ssl3_enc->cert_verify_mac(s,
630 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
632 s->state = SSL_ST_ERR;
641 case SSL3_ST_SR_CERT_VRFY_A:
642 case SSL3_ST_SR_CERT_VRFY_B:
643 ret = ssl3_get_cert_verify(s);
647 s->state = SSL3_ST_SR_CHANGE_A;
651 #if !defined(OPENSSL_NO_NEXTPROTONEG)
652 case SSL3_ST_SR_NEXT_PROTO_A:
653 case SSL3_ST_SR_NEXT_PROTO_B:
654 ret = ssl3_get_next_proto(s);
658 s->state = SSL3_ST_SR_FINISHED_A;
663 case SSL3_ST_SR_CHANGE_A:
664 case SSL3_ST_SR_CHANGE_B:
665 ret = ssl3_get_change_cipher_spec(s, SSL3_ST_SR_CHANGE_A,
666 SSL3_ST_SR_CHANGE_B);
670 #if defined(OPENSSL_NO_NEXTPROTONEG)
671 s->state = SSL3_ST_SR_FINISHED_A;
673 if (s->s3->next_proto_neg_seen)
674 s->state = SSL3_ST_SR_NEXT_PROTO_A;
676 s->state = SSL3_ST_SR_FINISHED_A;
681 case SSL3_ST_SR_FINISHED_A:
682 case SSL3_ST_SR_FINISHED_B:
683 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
684 SSL3_ST_SR_FINISHED_B);
688 s->state = SSL_ST_OK;
689 else if (s->tlsext_ticket_expected)
690 s->state = SSL3_ST_SW_SESSION_TICKET_A;
692 s->state = SSL3_ST_SW_CHANGE_A;
696 case SSL3_ST_SW_SESSION_TICKET_A:
697 case SSL3_ST_SW_SESSION_TICKET_B:
698 ret = ssl3_send_newsession_ticket(s);
701 s->state = SSL3_ST_SW_CHANGE_A;
705 case SSL3_ST_SW_CERT_STATUS_A:
706 case SSL3_ST_SW_CERT_STATUS_B:
707 ret = ssl3_send_cert_status(s);
710 s->state = SSL3_ST_SW_KEY_EXCH_A;
714 case SSL3_ST_SW_CHANGE_A:
715 case SSL3_ST_SW_CHANGE_B:
717 s->session->cipher = s->s3->tmp.new_cipher;
718 if (!s->method->ssl3_enc->setup_key_block(s)) {
720 s->state = SSL_ST_ERR;
724 ret = ssl3_send_change_cipher_spec(s,
726 SSL3_ST_SW_CHANGE_B);
730 s->state = SSL3_ST_SW_FINISHED_A;
733 if (!s->method->ssl3_enc->change_cipher_state(s,
734 SSL3_CHANGE_CIPHER_SERVER_WRITE))
737 s->state = SSL_ST_ERR;
743 case SSL3_ST_SW_FINISHED_A:
744 case SSL3_ST_SW_FINISHED_B:
745 ret = ssl3_send_finished(s,
746 SSL3_ST_SW_FINISHED_A,
747 SSL3_ST_SW_FINISHED_B,
749 ssl3_enc->server_finished_label,
751 ssl3_enc->server_finished_label_len);
754 s->state = SSL3_ST_SW_FLUSH;
756 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE_A;
758 s->s3->tmp.next_state = SSL_ST_OK;
763 /* clean a few things up */
764 ssl3_cleanup_key_block(s);
766 BUF_MEM_free(s->init_buf);
769 /* remove buffering on output */
770 ssl_free_wbio_buffer(s);
774 if (s->renegotiate == 2) { /* skipped if we just sent a
779 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
781 s->ctx->stats.sess_accept_good++;
783 s->handshake_func = ssl3_accept;
786 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
795 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
801 if (!s->s3->tmp.reuse_message && !skip) {
803 if ((ret = BIO_flush(s->wbio)) <= 0)
807 if ((cb != NULL) && (s->state != state)) {
808 new_state = s->state;
810 cb(s, SSL_CB_ACCEPT_LOOP, 1);
811 s->state = new_state;
817 /* BIO_flush(s->wbio); */
821 cb(s, SSL_CB_ACCEPT_EXIT, ret);
825 int ssl3_send_hello_request(SSL *s)
828 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
829 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
830 SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
833 s->state = SSL3_ST_SW_HELLO_REQ_B;
836 /* SSL3_ST_SW_HELLO_REQ_B */
837 return ssl_do_write(s);
840 int ssl3_get_client_hello(SSL *s)
842 int i, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
843 unsigned int j, complen = 0;
847 #ifndef OPENSSL_NO_COMP
848 SSL_COMP *comp = NULL;
850 STACK_OF(SSL_CIPHER) *ciphers = NULL;
852 /* |cookie| will only be initialized for DTLS. */
853 PACKET pkt, session_id, cipher_suites, compression, extensions, cookie;
856 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
860 * We do this so that we will respond with our native type. If we are
861 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
862 * switching should be handled by a different method. If we are SSLv3, we
863 * will respond with SSLv3, even if prompted with TLSv1.
865 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
866 s->state = SSL3_ST_SR_CLNT_HELLO_B;
869 n = s->method->ssl_get_message(s,
870 SSL3_ST_SR_CLNT_HELLO_B,
871 SSL3_ST_SR_CLNT_HELLO_C,
872 SSL3_MT_CLIENT_HELLO,
873 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
878 if (!PACKET_buf_init(&pkt, s->init_msg, n)) {
879 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
880 al = SSL_AD_INTERNAL_ERROR;
884 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
886 /* First lets get s->client_version set correctly */
888 unsigned int version;
891 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
892 * header is sent directly on the wire, not wrapped as a TLS
893 * record. Our record layer just processes the message length and passes
894 * the rest right through. Its format is:
896 * 0-1 msg_length - decoded by the record layer
897 * 2 msg_type - s->init_msg points here
899 * 5-6 cipher_spec_length
900 * 7-8 session_id_length
901 * 9-10 challenge_length
905 if (!PACKET_get_1(&pkt, &mt)
906 || mt != SSL2_MT_CLIENT_HELLO) {
908 * Should never happen. We should have tested this in the record
909 * layer in order to have determined that this is a SSLv2 record
912 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
916 if (!PACKET_get_net_2(&pkt, &version)) {
917 /* No protocol version supplied! */
918 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
921 if (version == 0x0002) {
922 /* This is real SSLv2. We don't support it. */
923 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
925 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
927 s->client_version = version;
929 /* No idea what protocol this is */
930 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
935 * use version from inside client hello, not from record header (may
936 * differ: see RFC 2246, Appendix E, second paragraph)
938 if(!PACKET_get_net_2(&pkt, (unsigned int *)&s->client_version)) {
939 al = SSL_AD_DECODE_ERROR;
940 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
945 /* Do SSL/TLS version negotiation if applicable */
946 if (!SSL_IS_DTLS(s)) {
947 if (s->version != TLS_ANY_VERSION) {
948 if (s->client_version >= s->version) {
951 } else if (s->client_version >= SSL3_VERSION) {
952 switch(s->client_version) {
955 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
956 s->version = TLS1_2_VERSION;
957 s->method = TLSv1_2_server_method();
961 /* Deliberately fall through */
963 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
964 s->version = TLS1_1_VERSION;
965 s->method = TLSv1_1_server_method();
969 /* Deliberately fall through */
971 if(!(s->options & SSL_OP_NO_TLSv1)) {
972 s->version = TLS1_VERSION;
973 s->method = TLSv1_server_method();
977 /* Deliberately fall through */
979 #ifndef OPENSSL_NO_SSL3
980 if(!(s->options & SSL_OP_NO_SSLv3)) {
981 s->version = SSL3_VERSION;
982 s->method = SSLv3_server_method();
991 } else if (s->client_version <= s->version
992 || s->method->version == DTLS_ANY_VERSION) {
994 * For DTLS we just check versions are potentially compatible. Version
995 * negotiation comes later.
1001 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1002 if ((!s->enc_write_ctx && !s->write_hash)) {
1004 * similar to ssl3_get_record, send alert using remote version
1007 s->version = s->client_version;
1009 al = SSL_AD_PROTOCOL_VERSION;
1013 /* Parse the message and load client random. */
1016 * Handle an SSLv2 backwards compatible ClientHello
1017 * Note, this is only for SSLv3+ using the backward compatible format.
1018 * Real SSLv2 is not supported, and is rejected above.
1020 unsigned int cipher_len, session_id_len, challenge_len;
1023 if (!PACKET_get_net_2(&pkt, &cipher_len)
1024 || !PACKET_get_net_2(&pkt, &session_id_len)
1025 || !PACKET_get_net_2(&pkt, &challenge_len)) {
1026 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1027 al = SSL_AD_DECODE_ERROR;
1031 if (!PACKET_get_sub_packet(&pkt, &cipher_suites, cipher_len)
1032 || !PACKET_get_sub_packet(&pkt, &session_id, session_id_len)
1033 || !PACKET_get_sub_packet(&pkt, &challenge, challenge_len)
1034 /* No extensions. */
1035 || PACKET_remaining(&pkt) != 0) {
1036 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1037 al = SSL_AD_DECODE_ERROR;
1041 /* Load the client random */
1042 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1044 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1045 if (!PACKET_copy_bytes(&challenge,
1046 s->s3->client_random + SSL3_RANDOM_SIZE -
1047 challenge_len, challenge_len)) {
1048 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1049 al = SSL_AD_INTERNAL_ERROR;
1053 PACKET_null_init(&compression);
1054 PACKET_null_init(&extensions);
1055 /* We're never DTLS here but just play safe and initialize. */
1056 PACKET_null_init(&cookie);
1058 /* Regular ClientHello. */
1059 if (!PACKET_copy_bytes(&pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1060 || !PACKET_get_length_prefixed_1(&pkt, &session_id)) {
1061 al = SSL_AD_DECODE_ERROR;
1062 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1066 if (SSL_IS_DTLS(s)) {
1067 if (!PACKET_get_length_prefixed_1(&pkt, &cookie)) {
1068 al = SSL_AD_DECODE_ERROR;
1069 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1073 * If we require cookies and this ClientHello doesn't contain one,
1074 * just return since we do not want to allocate any memory yet.
1075 * So check cookie length...
1077 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1078 if (PACKET_remaining(&cookie) == 0)
1083 if (!PACKET_get_length_prefixed_2(&pkt, &cipher_suites)
1084 || !PACKET_get_length_prefixed_1(&pkt, &compression)) {
1085 al = SSL_AD_DECODE_ERROR;
1086 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1089 /* Could be empty. */
1096 * We don't allow resumption in a backwards compatible ClientHello.
1097 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1099 * Versions before 0.9.7 always allow clients to resume sessions in
1100 * renegotiation. 0.9.7 and later allow this by default, but optionally
1101 * ignore resumption requests with flag
1102 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1103 * than a change to default behavior so that applications relying on
1104 * this for security won't even compile against older library versions).
1105 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1106 * request renegotiation but not a new session (s->new_session remains
1107 * unset): for servers, this essentially just means that the
1108 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1113 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1114 if (!ssl_get_new_session(s, 1))
1117 i = ssl_get_prev_session(s, &extensions, &session_id);
1119 * Only resume if the session's version matches the negotiated
1121 * RFC 5246 does not provide much useful advice on resumption
1122 * with a different protocol version. It doesn't forbid it but
1123 * the sanity of such behaviour would be questionable.
1124 * In practice, clients do not accept a version mismatch and
1125 * will abort the handshake with an error.
1127 if (i == 1 && s->version == s->session->ssl_version) {
1128 /* previous session */
1130 } else if (i == -1) {
1134 if (!ssl_get_new_session(s, 1))
1139 if (SSL_IS_DTLS(s)) {
1140 /* Empty cookie was already handled above by returning early. */
1141 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1142 if (s->ctx->app_verify_cookie_cb != NULL) {
1143 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1144 PACKET_remaining(&cookie)) == 0) {
1145 al = SSL_AD_HANDSHAKE_FAILURE;
1146 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1147 SSL_R_COOKIE_MISMATCH);
1149 /* else cookie verification succeeded */
1151 /* default verification */
1152 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1153 s->d1->cookie_len)) {
1154 al = SSL_AD_HANDSHAKE_FAILURE;
1155 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1158 /* Set to -2 so if successful we return 2 */
1161 if (s->method->version == DTLS_ANY_VERSION) {
1162 /* Select version to use */
1163 if (s->client_version <= DTLS1_2_VERSION &&
1164 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1165 s->version = DTLS1_2_VERSION;
1166 s->method = DTLSv1_2_server_method();
1167 } else if (tls1_suiteb(s)) {
1168 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1169 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1170 s->version = s->client_version;
1171 al = SSL_AD_PROTOCOL_VERSION;
1173 } else if (s->client_version <= DTLS1_VERSION &&
1174 !(s->options & SSL_OP_NO_DTLSv1)) {
1175 s->version = DTLS1_VERSION;
1176 s->method = DTLSv1_server_method();
1178 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1179 SSL_R_WRONG_VERSION_NUMBER);
1180 s->version = s->client_version;
1181 al = SSL_AD_PROTOCOL_VERSION;
1184 s->session->ssl_version = s->version;
1188 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1189 is_v2_record, &al) == NULL) {
1193 /* If it is a hit, check that the cipher is in the list */
1196 id = s->session->cipher->id;
1199 fprintf(stderr, "client sent %d ciphers\n",
1200 sk_SSL_CIPHER_num(ciphers));
1202 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1203 c = sk_SSL_CIPHER_value(ciphers, i);
1205 fprintf(stderr, "client [%2d of %2d]:%s\n",
1206 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1215 * we need to have the cipher in the cipher list if we are asked
1218 al = SSL_AD_ILLEGAL_PARAMETER;
1219 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1220 SSL_R_REQUIRED_CIPHER_MISSING);
1225 complen = PACKET_remaining(&compression);
1226 for (j = 0; j < complen; j++) {
1227 if (PACKET_data(&compression)[j] == 0)
1233 al = SSL_AD_DECODE_ERROR;
1234 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1238 /* TLS extensions */
1239 if (s->version >= SSL3_VERSION) {
1240 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1241 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1247 * Check if we want to use external pre-shared secret for this handshake
1248 * for not reused session only. We need to generate server_random before
1249 * calling tls_session_secret_cb in order to allow SessionTicket
1250 * processing to use it in key derivation.
1254 pos = s->s3->server_random;
1255 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1260 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1261 SSL_CIPHER *pref_cipher = NULL;
1263 s->session->master_key_length = sizeof(s->session->master_key);
1264 if (s->tls_session_secret_cb(s, s->session->master_key,
1265 &s->session->master_key_length, ciphers,
1267 s->tls_session_secret_cb_arg)) {
1269 s->session->ciphers = ciphers;
1270 s->session->verify_result = X509_V_OK;
1274 /* check if some cipher was preferred by call back */
1276 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1281 if (pref_cipher == NULL) {
1282 al = SSL_AD_HANDSHAKE_FAILURE;
1283 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1287 s->session->cipher = pref_cipher;
1288 sk_SSL_CIPHER_free(s->cipher_list);
1289 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1290 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1291 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1296 * Worst case, we will use the NULL compression, but if we have other
1297 * options, we will now look for them. We have complen-1 compression
1298 * algorithms from the client, starting at q.
1300 s->s3->tmp.new_compression = NULL;
1301 #ifndef OPENSSL_NO_COMP
1302 /* This only happens if we have a cache hit */
1303 if (s->session->compress_meth != 0) {
1304 int m, comp_id = s->session->compress_meth;
1306 /* Perform sanity checks on resumed compression algorithm */
1307 /* Can't disable compression */
1308 if (!ssl_allow_compression(s)) {
1309 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1310 SSL_R_INCONSISTENT_COMPRESSION);
1313 /* Look for resumed compression method */
1314 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1315 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1316 if (comp_id == comp->id) {
1317 s->s3->tmp.new_compression = comp;
1321 if (s->s3->tmp.new_compression == NULL) {
1322 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1323 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1326 /* Look for resumed method in compression list */
1327 for (k = 0; k < complen; k++) {
1328 if (PACKET_data(&compression)[k] == comp_id)
1332 al = SSL_AD_ILLEGAL_PARAMETER;
1333 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1334 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1339 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1340 /* See if we have a match */
1341 int m, nn, v, done = 0;
1344 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1345 for (m = 0; m < nn; m++) {
1346 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1348 for (o = 0; o < complen; o++) {
1349 if (v == PACKET_data(&compression)[o]) {
1358 s->s3->tmp.new_compression = comp;
1364 * If compression is disabled we'd better not try to resume a session
1365 * using compression.
1367 if (s->session->compress_meth != 0) {
1368 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1374 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1378 #ifdef OPENSSL_NO_COMP
1379 s->session->compress_meth = 0;
1381 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1383 sk_SSL_CIPHER_free(s->session->ciphers);
1384 s->session->ciphers = ciphers;
1385 if (ciphers == NULL) {
1386 al = SSL_AD_INTERNAL_ERROR;
1387 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1391 if (!tls1_set_server_sigalgs(s)) {
1392 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1395 /* Let cert callback update server certificates if required */
1397 if (s->cert->cert_cb) {
1398 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1400 al = SSL_AD_INTERNAL_ERROR;
1401 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1405 s->rwstate = SSL_X509_LOOKUP;
1408 s->rwstate = SSL_NOTHING;
1410 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1413 al = SSL_AD_HANDSHAKE_FAILURE;
1414 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1417 s->s3->tmp.new_cipher = c;
1418 /* check whether we should disable session resumption */
1419 if (s->not_resumable_session_cb != NULL)
1420 s->session->not_resumable = s->not_resumable_session_cb(s,
1421 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1423 if (s->session->not_resumable)
1424 /* do not send a session ticket */
1425 s->tlsext_ticket_expected = 0;
1427 /* Session-id reuse */
1428 s->s3->tmp.new_cipher = s->session->cipher;
1431 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1432 if (!ssl3_digest_cached_records(s, 0))
1437 * we now have the following setup.
1439 * cipher_list - our prefered list of ciphers
1440 * ciphers - the clients prefered list of ciphers
1441 * compression - basically ignored right now
1442 * ssl version is set - sslv3
1443 * s->session - The ssl session has been setup.
1444 * s->hit - session reuse flag
1445 * s->s3->tmp.new_cipher- the new cipher to use.
1448 /* Handles TLS extensions that we couldn't check earlier */
1449 if (s->version >= SSL3_VERSION) {
1450 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1451 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1460 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1462 s->state = SSL_ST_ERR;
1465 sk_SSL_CIPHER_free(ciphers);
1466 return ret < 0 ? -1 : ret;
1469 int ssl3_send_server_hello(SSL *s)
1472 unsigned char *p, *d;
1477 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1478 buf = (unsigned char *)s->init_buf->data;
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 * Random stuff. Filling of the server_random takes place in
1488 * ssl3_get_client_hello()
1490 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1491 p += SSL3_RANDOM_SIZE;
1494 * There are several cases for the session ID to send
1495 * back in the server hello:
1496 * - For session reuse from the session cache,
1497 * we send back the old session ID.
1498 * - If stateless session reuse (using a session ticket)
1499 * is successful, we send back the client's "session ID"
1500 * (which doesn't actually identify the session).
1501 * - If it is a new session, we send back the new
1503 * - However, if we want the new session to be single-use,
1504 * we send back a 0-length session ID.
1505 * s->hit is non-zero in either case of session reuse,
1506 * so the following won't overwrite an ID that we're supposed
1509 if (s->session->not_resumable ||
1510 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1512 s->session->session_id_length = 0;
1514 sl = s->session->session_id_length;
1515 if (sl > (int)sizeof(s->session->session_id)) {
1516 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1517 s->state = SSL_ST_ERR;
1521 memcpy(p, s->session->session_id, sl);
1524 /* put the cipher */
1525 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1528 /* put the compression method */
1529 #ifdef OPENSSL_NO_COMP
1532 if (s->s3->tmp.new_compression == NULL)
1535 *(p++) = s->s3->tmp.new_compression->id;
1538 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1539 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1540 s->state = SSL_ST_ERR;
1544 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1546 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1547 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1548 s->state = SSL_ST_ERR;
1554 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1555 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1558 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1561 /* SSL3_ST_SW_SRVR_HELLO_B */
1562 return ssl_do_write(s);
1565 int ssl3_send_server_done(SSL *s)
1568 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1569 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1570 SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1573 s->state = SSL3_ST_SW_SRVR_DONE_B;
1576 /* SSL3_ST_SW_SRVR_DONE_B */
1577 return ssl_do_write(s);
1580 int ssl3_send_server_key_exchange(SSL *s)
1582 #ifndef OPENSSL_NO_RSA
1586 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1589 #ifndef OPENSSL_NO_DH
1590 DH *dh = NULL, *dhp;
1592 #ifndef OPENSSL_NO_EC
1593 EC_KEY *ecdh = NULL, *ecdhp;
1594 unsigned char *encodedPoint = NULL;
1597 BN_CTX *bn_ctx = NULL;
1600 const EVP_MD *md = NULL;
1601 unsigned char *p, *d;
1611 EVP_MD_CTX_init(&md_ctx);
1612 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1613 type = s->s3->tmp.new_cipher->algorithm_mkey;
1618 r[0] = r[1] = r[2] = r[3] = NULL;
1620 #ifndef OPENSSL_NO_PSK
1621 if (type & SSL_PSK) {
1623 * reserve size for record length and PSK identity hint
1626 if (s->cert->psk_identity_hint)
1627 n += strlen(s->cert->psk_identity_hint);
1629 /* Plain PSK or RSAPSK nothing to do */
1630 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1632 #endif /* !OPENSSL_NO_PSK */
1633 #ifndef OPENSSL_NO_RSA
1634 if (type & SSL_kRSA) {
1635 rsa = cert->rsa_tmp;
1636 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1637 rsa = s->cert->rsa_tmp_cb(s,
1638 SSL_C_IS_EXPORT(s->s3->
1640 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1643 al = SSL_AD_HANDSHAKE_FAILURE;
1644 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1645 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1649 cert->rsa_tmp = rsa;
1652 al = SSL_AD_HANDSHAKE_FAILURE;
1653 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1654 SSL_R_MISSING_TMP_RSA_KEY);
1659 s->s3->tmp.use_rsa_tmp = 1;
1662 #ifndef OPENSSL_NO_DH
1663 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1664 if (s->cert->dh_tmp_auto) {
1665 dhp = ssl_get_auto_dh(s);
1667 al = SSL_AD_INTERNAL_ERROR;
1668 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1669 ERR_R_INTERNAL_ERROR);
1674 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1675 dhp = s->cert->dh_tmp_cb(s,
1676 SSL_C_IS_EXPORT(s->s3->
1678 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1681 al = SSL_AD_HANDSHAKE_FAILURE;
1682 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1683 SSL_R_MISSING_TMP_DH_KEY);
1686 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1687 DH_security_bits(dhp), 0, dhp)) {
1688 al = SSL_AD_HANDSHAKE_FAILURE;
1689 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1690 SSL_R_DH_KEY_TOO_SMALL);
1693 if (s->s3->tmp.dh != NULL) {
1694 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1695 ERR_R_INTERNAL_ERROR);
1699 if (s->cert->dh_tmp_auto)
1701 else if ((dh = DHparams_dup(dhp)) == NULL) {
1702 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1707 if ((dhp->pub_key == NULL ||
1708 dhp->priv_key == NULL ||
1709 (s->options & SSL_OP_SINGLE_DH_USE))) {
1710 if (!DH_generate_key(dh)) {
1711 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1715 dh->pub_key = BN_dup(dhp->pub_key);
1716 dh->priv_key = BN_dup(dhp->priv_key);
1717 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1718 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1727 #ifndef OPENSSL_NO_EC
1728 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1729 const EC_GROUP *group;
1731 ecdhp = cert->ecdh_tmp;
1732 if (s->cert->ecdh_tmp_auto) {
1733 /* Get NID of appropriate shared curve */
1734 int nid = tls1_shared_curve(s, -2);
1735 if (nid != NID_undef)
1736 ecdhp = EC_KEY_new_by_curve_name(nid);
1737 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1738 ecdhp = s->cert->ecdh_tmp_cb(s,
1739 SSL_C_IS_EXPORT(s->s3->
1741 SSL_C_EXPORT_PKEYLENGTH(s->
1742 s3->tmp.new_cipher));
1744 if (ecdhp == NULL) {
1745 al = SSL_AD_HANDSHAKE_FAILURE;
1746 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1747 SSL_R_MISSING_TMP_ECDH_KEY);
1751 if (s->s3->tmp.ecdh != NULL) {
1752 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1753 ERR_R_INTERNAL_ERROR);
1757 /* Duplicate the ECDH structure. */
1758 if (ecdhp == NULL) {
1759 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1762 if (s->cert->ecdh_tmp_auto)
1764 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1765 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1769 s->s3->tmp.ecdh = ecdh;
1770 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1771 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1772 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1773 if (!EC_KEY_generate_key(ecdh)) {
1774 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1780 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1781 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1782 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1783 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1787 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1788 (EC_GROUP_get_degree(group) > 163)) {
1789 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1790 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1795 * XXX: For now, we only support ephemeral ECDH keys over named
1796 * (not generic) curves. For supported named curves, curve_id is
1800 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1802 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1803 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1808 * Encode the public key. First check the size of encoding and
1809 * allocate memory accordingly.
1811 encodedlen = EC_POINT_point2oct(group,
1812 EC_KEY_get0_public_key(ecdh),
1813 POINT_CONVERSION_UNCOMPRESSED,
1816 encodedPoint = (unsigned char *)
1817 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1818 bn_ctx = BN_CTX_new();
1819 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1820 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1821 ERR_R_MALLOC_FAILURE);
1825 encodedlen = EC_POINT_point2oct(group,
1826 EC_KEY_get0_public_key(ecdh),
1827 POINT_CONVERSION_UNCOMPRESSED,
1828 encodedPoint, encodedlen, bn_ctx);
1830 if (encodedlen == 0) {
1831 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1835 BN_CTX_free(bn_ctx);
1839 * XXX: For now, we only support named (not generic) curves in
1840 * ECDH ephemeral key exchanges. In this situation, we need four
1841 * additional bytes to encode the entire ServerECDHParams
1844 n += 4 + encodedlen;
1847 * We'll generate the serverKeyExchange message explicitly so we
1848 * can set these to NULLs
1855 #endif /* !OPENSSL_NO_EC */
1856 #ifndef OPENSSL_NO_SRP
1857 if (type & SSL_kSRP) {
1858 if ((s->srp_ctx.N == NULL) ||
1859 (s->srp_ctx.g == NULL) ||
1860 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1861 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1862 SSL_R_MISSING_SRP_PARAM);
1865 r[0] = s->srp_ctx.N;
1866 r[1] = s->srp_ctx.g;
1867 r[2] = s->srp_ctx.s;
1868 r[3] = s->srp_ctx.B;
1872 al = SSL_AD_HANDSHAKE_FAILURE;
1873 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1874 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1877 for (i = 0; i < 4 && r[i] != NULL; i++) {
1878 nr[i] = BN_num_bytes(r[i]);
1879 #ifndef OPENSSL_NO_SRP
1880 if ((i == 2) && (type & SSL_kSRP))
1887 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1888 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1889 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1891 al = SSL_AD_DECODE_ERROR;
1894 kn = EVP_PKEY_size(pkey);
1900 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1901 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1904 d = p = ssl_handshake_start(s);
1906 #ifndef OPENSSL_NO_PSK
1907 if (type & SSL_PSK) {
1908 /* copy PSK identity hint */
1909 if (s->cert->psk_identity_hint) {
1910 s2n(strlen(s->cert->psk_identity_hint), p);
1911 strncpy((char *)p, s->cert->psk_identity_hint,
1912 strlen(s->cert->psk_identity_hint));
1913 p += strlen(s->cert->psk_identity_hint);
1920 for (i = 0; i < 4 && r[i] != NULL; i++) {
1921 #ifndef OPENSSL_NO_SRP
1922 if ((i == 2) && (type & SSL_kSRP)) {
1932 #ifndef OPENSSL_NO_EC
1933 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1935 * XXX: For now, we only support named (not generic) curves. In
1936 * this situation, the serverKeyExchange message has: [1 byte
1937 * CurveType], [2 byte CurveName] [1 byte length of encoded
1938 * point], followed by the actual encoded point itself
1940 *p = NAMED_CURVE_TYPE;
1948 memcpy(p, encodedPoint, encodedlen);
1949 OPENSSL_free(encodedPoint);
1950 encodedPoint = NULL;
1958 * n is the length of the params, they start at &(d[4]) and p
1959 * points to the space at the end.
1961 #ifndef OPENSSL_NO_RSA
1962 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1965 for (num = 2; num > 0; num--) {
1966 EVP_MD_CTX_set_flags(&md_ctx,
1967 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1968 EVP_DigestInit_ex(&md_ctx, (num == 2)
1969 ? s->ctx->md5 : s->ctx->sha1, NULL);
1970 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1972 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1974 EVP_DigestUpdate(&md_ctx, d, n);
1975 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1979 if (RSA_sign(NID_md5_sha1, md_buf, j,
1980 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1981 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1989 /* send signature algorithm */
1990 if (SSL_USE_SIGALGS(s)) {
1991 if (!tls12_get_sigandhash(p, pkey, md)) {
1992 /* Should never happen */
1993 al = SSL_AD_INTERNAL_ERROR;
1994 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1995 ERR_R_INTERNAL_ERROR);
2001 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2003 EVP_SignInit_ex(&md_ctx, md, NULL);
2004 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2006 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2008 EVP_SignUpdate(&md_ctx, d, n);
2009 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2010 (unsigned int *)&i, pkey)) {
2011 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2016 if (SSL_USE_SIGALGS(s))
2019 /* Is this error check actually needed? */
2020 al = SSL_AD_HANDSHAKE_FAILURE;
2021 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2022 SSL_R_UNKNOWN_PKEY_TYPE);
2027 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2028 al = SSL_AD_HANDSHAKE_FAILURE;
2029 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2034 s->state = SSL3_ST_SW_KEY_EXCH_B;
2035 EVP_MD_CTX_cleanup(&md_ctx);
2036 return ssl_do_write(s);
2038 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2040 #ifndef OPENSSL_NO_EC
2041 OPENSSL_free(encodedPoint);
2042 BN_CTX_free(bn_ctx);
2044 EVP_MD_CTX_cleanup(&md_ctx);
2045 s->state = SSL_ST_ERR;
2049 int ssl3_send_certificate_request(SSL *s)
2051 unsigned char *p, *d;
2052 int i, j, nl, off, n;
2053 STACK_OF(X509_NAME) *sk = NULL;
2057 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2060 d = p = ssl_handshake_start(s);
2062 /* get the list of acceptable cert types */
2064 n = ssl3_get_req_cert_type(s, p);
2069 if (SSL_USE_SIGALGS(s)) {
2070 const unsigned char *psigs;
2071 unsigned char *etmp = p;
2072 nl = tls12_get_psigalgs(s, &psigs);
2073 /* Skip over length for now */
2075 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2076 /* Now fill in length */
2086 sk = SSL_get_client_CA_list(s);
2089 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2090 name = sk_X509_NAME_value(sk, i);
2091 j = i2d_X509_NAME(name, NULL);
2092 if (!BUF_MEM_grow_clean
2093 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2094 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2098 p = ssl_handshake_start(s) + n;
2100 i2d_X509_NAME(name, &p);
2105 /* else no CA names */
2106 p = ssl_handshake_start(s) + off;
2109 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2110 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2114 s->state = SSL3_ST_SW_CERT_REQ_B;
2117 /* SSL3_ST_SW_CERT_REQ_B */
2118 return ssl_do_write(s);
2120 s->state = SSL_ST_ERR;
2124 int ssl3_get_client_key_exchange(SSL *s)
2129 unsigned long alg_k;
2130 #ifndef OPENSSL_NO_RSA
2132 EVP_PKEY *pkey = NULL;
2134 #ifndef OPENSSL_NO_DH
2136 DH *dh_srvr, *dh_clnt = NULL;
2138 #ifndef OPENSSL_NO_EC
2139 EC_KEY *srvr_ecdh = NULL;
2140 EVP_PKEY *clnt_pub_pkey = NULL;
2141 EC_POINT *clnt_ecpoint = NULL;
2142 BN_CTX *bn_ctx = NULL;
2144 PACKET pkt, enc_premaster;
2145 unsigned char *data, *rsa_decrypt = NULL;
2147 n = s->method->ssl_get_message(s,
2148 SSL3_ST_SR_KEY_EXCH_A,
2149 SSL3_ST_SR_KEY_EXCH_B,
2150 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2154 if (!PACKET_buf_init(&pkt, s->init_msg, n)) {
2155 al = SSL_AD_INTERNAL_ERROR;
2156 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2160 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2162 #ifndef OPENSSL_NO_PSK
2163 /* For PSK parse and retrieve identity, obtain PSK key */
2164 if (alg_k & SSL_PSK) {
2165 unsigned char psk[PSK_MAX_PSK_LEN];
2167 PACKET psk_identity;
2169 if (!PACKET_get_length_prefixed_2(&pkt, &psk_identity)) {
2170 al = SSL_AD_DECODE_ERROR;
2171 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2174 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2175 al = SSL_AD_DECODE_ERROR;
2176 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2177 SSL_R_DATA_LENGTH_TOO_LONG);
2180 if (s->psk_server_callback == NULL) {
2181 al = SSL_AD_INTERNAL_ERROR;
2182 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2183 SSL_R_PSK_NO_SERVER_CB);
2187 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2188 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2189 al = SSL_AD_INTERNAL_ERROR;
2193 psklen = s->psk_server_callback(s, s->session->psk_identity,
2196 if (psklen > PSK_MAX_PSK_LEN) {
2197 al = SSL_AD_INTERNAL_ERROR;
2198 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2200 } else if (psklen == 0) {
2202 * PSK related to the given identity not found
2204 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2205 SSL_R_PSK_IDENTITY_NOT_FOUND);
2206 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2210 OPENSSL_free(s->s3->tmp.psk);
2211 s->s3->tmp.psk = BUF_memdup(psk, psklen);
2212 OPENSSL_cleanse(psk, psklen);
2214 if (s->s3->tmp.psk == NULL) {
2215 al = SSL_AD_INTERNAL_ERROR;
2216 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2220 s->s3->tmp.psklen = psklen;
2222 if (alg_k & SSL_kPSK) {
2223 /* Identity extracted earlier: should be nothing left */
2224 if (PACKET_remaining(&pkt) != 0) {
2225 al = SSL_AD_HANDSHAKE_FAILURE;
2226 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2229 /* PSK handled by ssl_generate_master_secret */
2230 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2231 al = SSL_AD_INTERNAL_ERROR;
2232 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2237 #ifndef OPENSSL_NO_RSA
2238 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2239 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2241 unsigned char decrypt_good, version_good;
2244 /* FIX THIS UP EAY EAY EAY EAY */
2245 if (s->s3->tmp.use_rsa_tmp) {
2246 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2247 rsa = s->cert->rsa_tmp;
2249 * Don't do a callback because rsa_tmp should be sent already
2252 al = SSL_AD_HANDSHAKE_FAILURE;
2253 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2254 SSL_R_MISSING_TMP_RSA_PKEY);
2259 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2260 if ((pkey == NULL) ||
2261 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2262 al = SSL_AD_HANDSHAKE_FAILURE;
2263 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2264 SSL_R_MISSING_RSA_CERTIFICATE);
2267 rsa = pkey->pkey.rsa;
2270 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2271 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2272 enc_premaster = pkt;
2275 if (!PACKET_get_length_prefixed_2(&pkt, &enc_premaster)
2276 || PACKET_remaining(&pkt) != 0) {
2277 /* Try SSLv3 behaviour for TLS. */
2278 if (s->options & SSL_OP_TLS_D5_BUG) {
2279 enc_premaster = orig;
2281 al = SSL_AD_DECODE_ERROR;
2282 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2289 * We want to be sure that the plaintext buffer size makes it safe to
2290 * iterate over the entire size of a premaster secret
2291 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2292 * their ciphertext cannot accommodate a premaster secret anyway.
2294 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2295 al = SSL_AD_INTERNAL_ERROR;
2296 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2297 RSA_R_KEY_SIZE_TOO_SMALL);
2301 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2302 if (rsa_decrypt == NULL) {
2303 al = SSL_AD_INTERNAL_ERROR;
2304 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2309 * We must not leak whether a decryption failure occurs because of
2310 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2311 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2312 * generates a random premaster secret for the case that the decrypt
2313 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2316 if (RAND_bytes(rand_premaster_secret,
2317 sizeof(rand_premaster_secret)) <= 0) {
2321 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2322 PACKET_data(&enc_premaster),
2323 rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2327 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2328 * be 0xff if so and zero otherwise.
2331 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2334 * If the version in the decrypted pre-master secret is correct then
2335 * version_good will be 0xff, otherwise it'll be zero. The
2336 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2337 * (http://eprint.iacr.org/2003/052/) exploits the version number
2338 * check as a "bad version oracle". Thus version checks are done in
2339 * constant time and are treated like any other decryption error.
2342 constant_time_eq_8(rsa_decrypt[0],
2343 (unsigned)(s->client_version >> 8));
2345 constant_time_eq_8(rsa_decrypt[1],
2346 (unsigned)(s->client_version & 0xff));
2349 * The premaster secret must contain the same version number as the
2350 * ClientHello to detect version rollback attacks (strangely, the
2351 * protocol does not offer such protection for DH ciphersuites).
2352 * However, buggy clients exist that send the negotiated protocol
2353 * version instead if the server does not support the requested
2354 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2357 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2358 unsigned char workaround_good;
2360 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2362 constant_time_eq_8(rsa_decrypt[1],
2363 (unsigned)(s->version & 0xff));
2364 version_good |= workaround_good;
2368 * Both decryption and version must be good for decrypt_good to
2369 * remain non-zero (0xff).
2371 decrypt_good &= version_good;
2374 * Now copy rand_premaster_secret over from p using
2375 * decrypt_good_mask. If decryption failed, then p does not
2376 * contain valid plaintext, however, a check above guarantees
2377 * it is still sufficiently large to read from.
2379 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2381 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2382 rand_premaster_secret[j]);
2385 if (!ssl_generate_master_secret(s, rsa_decrypt,
2386 sizeof(rand_premaster_secret), 0)) {
2387 al = SSL_AD_INTERNAL_ERROR;
2388 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2391 OPENSSL_free(rsa_decrypt);
2395 #ifndef OPENSSL_NO_DH
2396 if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2398 EVP_PKEY *skey = NULL;
2399 PACKET bookmark = pkt;
2400 unsigned char shared[(OPENSSL_DH_MAX_MODULUS_BITS + 7) / 8];
2402 if (!PACKET_get_net_2(&pkt, &i)) {
2403 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2404 al = SSL_AD_HANDSHAKE_FAILURE;
2405 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2406 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2411 if (PACKET_remaining(&pkt) != i) {
2412 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2413 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2414 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2418 i = PACKET_remaining(&pkt);
2421 if (alg_k & SSL_kDHr)
2422 idx = SSL_PKEY_DH_RSA;
2423 else if (alg_k & SSL_kDHd)
2424 idx = SSL_PKEY_DH_DSA;
2426 skey = s->cert->pkeys[idx].privatekey;
2427 if ((skey == NULL) ||
2428 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2429 al = SSL_AD_HANDSHAKE_FAILURE;
2430 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2431 SSL_R_MISSING_RSA_CERTIFICATE);
2434 dh_srvr = skey->pkey.dh;
2435 } else if (s->s3->tmp.dh == NULL) {
2436 al = SSL_AD_HANDSHAKE_FAILURE;
2437 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2438 SSL_R_MISSING_TMP_DH_KEY);
2441 dh_srvr = s->s3->tmp.dh;
2444 /* Get pubkey from cert */
2445 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2447 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2448 dh_clnt = EVP_PKEY_get1_DH(clkey);
2450 if (dh_clnt == NULL) {
2451 al = SSL_AD_HANDSHAKE_FAILURE;
2452 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2453 SSL_R_MISSING_TMP_DH_KEY);
2456 EVP_PKEY_free(clkey);
2457 pub = dh_clnt->pub_key;
2459 if (!PACKET_get_bytes(&pkt, &data, i)) {
2460 /* We already checked we have enough data */
2461 al = SSL_AD_INTERNAL_ERROR;
2462 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2463 ERR_R_INTERNAL_ERROR);
2466 pub = BN_bin2bn(data, i, NULL);
2469 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2473 i = DH_compute_key(shared, pub, dh_srvr);
2476 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2481 DH_free(s->s3->tmp.dh);
2482 s->s3->tmp.dh = NULL;
2488 if (!ssl_generate_master_secret(s, shared, i, 0)) {
2489 al = SSL_AD_INTERNAL_ERROR;
2490 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2498 #ifndef OPENSSL_NO_EC
2499 if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2503 const EC_GROUP *group;
2504 const BIGNUM *priv_key;
2505 unsigned char *shared;
2507 /* initialize structures for server's ECDH key pair */
2508 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2509 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2513 /* Let's get server private key and group information */
2514 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2515 /* use the certificate */
2516 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2519 * use the ephermeral values we saved when generating the
2520 * ServerKeyExchange msg.
2522 tkey = s->s3->tmp.ecdh;
2525 group = EC_KEY_get0_group(tkey);
2526 priv_key = EC_KEY_get0_private_key(tkey);
2528 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2529 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2530 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2534 /* Let's get client's public key */
2535 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2536 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2541 /* Client Publickey was in Client Certificate */
2543 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2544 al = SSL_AD_HANDSHAKE_FAILURE;
2545 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2546 SSL_R_MISSING_TMP_ECDH_KEY);
2549 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2550 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2552 * XXX: For now, we do not support client authentication
2553 * using ECDH certificates so this branch (n == 0L) of the
2554 * code is never executed. When that support is added, we
2555 * ought to ensure the key received in the certificate is
2556 * authorized for key agreement. ECDH_compute_key implicitly
2557 * checks that the two ECDH shares are for the same group.
2559 al = SSL_AD_HANDSHAKE_FAILURE;
2560 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2561 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2565 if (EC_POINT_copy(clnt_ecpoint,
2566 EC_KEY_get0_public_key(clnt_pub_pkey->
2568 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2571 ret = 2; /* Skip certificate verify processing */
2574 * Get client's public key from encoded point in the
2575 * ClientKeyExchange message.
2577 if ((bn_ctx = BN_CTX_new()) == NULL) {
2578 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2579 ERR_R_MALLOC_FAILURE);
2583 /* Get encoded point length */
2584 if (!PACKET_get_1(&pkt, &i)) {
2585 al = SSL_AD_DECODE_ERROR;
2586 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2587 SSL_R_LENGTH_MISMATCH);
2590 if (!PACKET_get_bytes(&pkt, &data, i)
2591 || PACKET_remaining(&pkt) != 0) {
2592 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2595 if (EC_POINT_oct2point(group, clnt_ecpoint, data, i, bn_ctx) == 0) {
2596 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2601 /* Compute the shared pre-master secret */
2602 field_size = EC_GROUP_get_degree(group);
2603 if (field_size <= 0) {
2604 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2607 shared = OPENSSL_malloc((field_size + 7) / 8);
2608 if (shared == NULL) {
2609 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2612 i = ECDH_compute_key(shared, (field_size + 7) / 8, clnt_ecpoint,
2615 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2616 OPENSSL_free(shared);
2620 EVP_PKEY_free(clnt_pub_pkey);
2621 EC_POINT_free(clnt_ecpoint);
2622 EC_KEY_free(srvr_ecdh);
2623 BN_CTX_free(bn_ctx);
2624 EC_KEY_free(s->s3->tmp.ecdh);
2625 s->s3->tmp.ecdh = NULL;
2627 if (!ssl_generate_master_secret(s, shared, i, 1)) {
2628 al = SSL_AD_INTERNAL_ERROR;
2629 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2635 #ifndef OPENSSL_NO_SRP
2636 if (alg_k & SSL_kSRP) {
2637 if (!PACKET_get_net_2(&pkt, &i)
2638 || !PACKET_get_bytes(&pkt, &data, i)) {
2639 al = SSL_AD_DECODE_ERROR;
2640 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2643 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2644 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2647 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2648 || BN_is_zero(s->srp_ctx.A)) {
2649 al = SSL_AD_ILLEGAL_PARAMETER;
2650 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2651 SSL_R_BAD_SRP_PARAMETERS);
2654 OPENSSL_free(s->session->srp_username);
2655 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2656 if (s->session->srp_username == NULL) {
2657 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2661 if (!srp_generate_server_master_secret(s)) {
2662 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2666 #endif /* OPENSSL_NO_SRP */
2667 if (alg_k & SSL_kGOST) {
2669 EVP_PKEY_CTX *pkey_ctx;
2670 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2671 unsigned char premaster_secret[32], *start;
2672 size_t outlen = 32, inlen;
2673 unsigned long alg_a;
2677 /* Get our certificate private key */
2678 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2679 if (alg_a & SSL_aGOST01)
2680 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2682 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2683 EVP_PKEY_decrypt_init(pkey_ctx);
2685 * If client certificate is present and is of the same type, maybe
2686 * use it for key exchange. Don't mind errors from
2687 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2688 * client certificate for authorization only.
2690 client_pub_pkey = X509_get_pubkey(s->session->peer);
2691 if (client_pub_pkey) {
2692 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2695 /* Decrypt session key */
2696 if (!PACKET_get_bytes(&pkt, &data, n)) {
2697 al = SSL_AD_INTERNAL_ERROR;
2698 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2702 ((const unsigned char **)&data, &Tlen, &Ttag, &Tclass,
2703 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2704 || Tclass != V_ASN1_UNIVERSAL) {
2705 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2706 SSL_R_DECRYPTION_FAILED);
2711 if (EVP_PKEY_decrypt
2712 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2713 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2714 SSL_R_DECRYPTION_FAILED);
2717 /* Generate master secret */
2718 if (!ssl_generate_master_secret(s, premaster_secret,
2719 sizeof(premaster_secret), 0)) {
2720 al = SSL_AD_INTERNAL_ERROR;
2721 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2724 /* Check if pubkey from client certificate was used */
2725 if (EVP_PKEY_CTX_ctrl
2726 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2731 EVP_PKEY_free(client_pub_pkey);
2732 EVP_PKEY_CTX_free(pkey_ctx);
2737 al = SSL_AD_HANDSHAKE_FAILURE;
2738 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2744 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2745 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2748 #ifndef OPENSSL_NO_EC
2749 EVP_PKEY_free(clnt_pub_pkey);
2750 EC_POINT_free(clnt_ecpoint);
2751 EC_KEY_free(srvr_ecdh);
2752 BN_CTX_free(bn_ctx);
2753 OPENSSL_free(rsa_decrypt);
2755 #ifndef OPENSSL_NO_PSK
2756 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2757 s->s3->tmp.psk = NULL;
2759 s->state = SSL_ST_ERR;
2763 int ssl3_get_cert_verify(SSL *s)
2765 EVP_PKEY *pkey = NULL;
2766 unsigned char *sig, *data;
2767 int al, ok, ret = 0;
2772 const EVP_MD *md = NULL;
2775 EVP_MD_CTX_init(&mctx);
2778 * We should only process a CertificateVerify message if we have received
2779 * a Certificate from the client. If so then |s->session->peer| will be non
2780 * NULL. In some instances a CertificateVerify message is not required even
2781 * if the peer has sent a Certificate (e.g. such as in the case of static
2782 * DH). In that case the ClientKeyExchange processing will skip the
2783 * CertificateVerify state so we should not arrive here.
2785 if (s->session->peer == NULL) {
2790 n = s->method->ssl_get_message(s,
2791 SSL3_ST_SR_CERT_VRFY_A,
2792 SSL3_ST_SR_CERT_VRFY_B,
2793 SSL3_MT_CERTIFICATE_VERIFY,
2794 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2799 peer = s->session->peer;
2800 pkey = X509_get_pubkey(peer);
2801 type = X509_certificate_type(peer, pkey);
2803 if (!(type & EVP_PKT_SIGN)) {
2804 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2805 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2806 al = SSL_AD_ILLEGAL_PARAMETER;
2810 /* we now have a signature that we need to verify */
2811 if (!PACKET_buf_init(&pkt, s->init_msg, n)) {
2812 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2813 al = SSL_AD_INTERNAL_ERROR;
2816 /* Check for broken implementations of GOST ciphersuites */
2818 * If key is GOST and n is exactly 64, it is bare signature without
2821 if (n == 64 && pkey->type == NID_id_GostR3410_2001) {
2824 if (SSL_USE_SIGALGS(s)) {
2827 if (!PACKET_get_bytes(&pkt, &sig, 2)) {
2828 al = SSL_AD_DECODE_ERROR;
2831 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2833 al = SSL_AD_INTERNAL_ERROR;
2835 } else if (rv == 0) {
2836 al = SSL_AD_DECODE_ERROR;
2840 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2843 if (!PACKET_get_net_2(&pkt, &len)) {
2844 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2845 al = SSL_AD_DECODE_ERROR;
2849 j = EVP_PKEY_size(pkey);
2850 if (((int)len > j) || ((int)PACKET_remaining(&pkt) > j) || (n <= 0)) {
2851 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2852 al = SSL_AD_DECODE_ERROR;
2855 if (!PACKET_get_bytes(&pkt, &data, len)) {
2856 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2857 al = SSL_AD_DECODE_ERROR;
2861 if (SSL_USE_SIGALGS(s)) {
2864 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2865 if (hdatalen <= 0) {
2866 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2867 al = SSL_AD_INTERNAL_ERROR;
2871 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2874 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2875 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2876 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2877 al = SSL_AD_INTERNAL_ERROR;
2881 if (EVP_VerifyFinal(&mctx, data, len, pkey) <= 0) {
2882 al = SSL_AD_DECRYPT_ERROR;
2883 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2887 #ifndef OPENSSL_NO_RSA
2888 if (pkey->type == EVP_PKEY_RSA) {
2889 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2890 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, data, len,
2893 al = SSL_AD_DECRYPT_ERROR;
2894 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2898 al = SSL_AD_DECRYPT_ERROR;
2899 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2904 #ifndef OPENSSL_NO_DSA
2905 if (pkey->type == EVP_PKEY_DSA) {
2906 j = DSA_verify(pkey->save_type,
2907 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2908 SHA_DIGEST_LENGTH, data, len, pkey->pkey.dsa);
2911 al = SSL_AD_DECRYPT_ERROR;
2912 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
2917 #ifndef OPENSSL_NO_EC
2918 if (pkey->type == EVP_PKEY_EC) {
2919 j = ECDSA_verify(pkey->save_type,
2920 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2921 SHA_DIGEST_LENGTH, data, len, pkey->pkey.ec);
2924 al = SSL_AD_DECRYPT_ERROR;
2925 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2930 if (pkey->type == NID_id_GostR3410_2001) {
2931 unsigned char signature[64];
2933 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
2934 EVP_PKEY_verify_init(pctx);
2936 fprintf(stderr, "GOST signature length is %d", len);
2938 for (idx = 0; idx < 64; idx++) {
2939 signature[63 - idx] = data[idx];
2941 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
2943 EVP_PKEY_CTX_free(pctx);
2945 al = SSL_AD_DECRYPT_ERROR;
2946 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2950 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2951 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2958 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2959 s->state = SSL_ST_ERR;
2962 BIO_free(s->s3->handshake_buffer);
2963 s->s3->handshake_buffer = NULL;
2964 EVP_MD_CTX_cleanup(&mctx);
2965 EVP_PKEY_free(pkey);
2969 int ssl3_get_client_certificate(SSL *s)
2971 int i, ok, al, ret = -1;
2973 unsigned long l, llen, n;
2974 const unsigned char *certstart;
2975 unsigned char *certbytes;
2976 STACK_OF(X509) *sk = NULL;
2979 n = s->method->ssl_get_message(s,
2982 -1, s->max_cert_list, &ok);
2987 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2988 if ((s->verify_mode & SSL_VERIFY_PEER) &&
2989 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2990 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2991 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2992 al = SSL_AD_HANDSHAKE_FAILURE;
2996 * If tls asked for a client cert, the client must return a 0 list
2998 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
2999 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3000 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3001 al = SSL_AD_UNEXPECTED_MESSAGE;
3004 s->s3->tmp.reuse_message = 1;
3008 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3009 al = SSL_AD_UNEXPECTED_MESSAGE;
3010 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3014 if (!PACKET_buf_init(&pkt, s->init_msg, n)) {
3015 al = SSL_AD_INTERNAL_ERROR;
3016 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3020 if ((sk = sk_X509_new_null()) == NULL) {
3021 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3025 if (!PACKET_get_net_3(&pkt, &llen)
3026 || !PACKET_get_sub_packet(&pkt, &spkt, llen)
3027 || PACKET_remaining(&pkt) != 0) {
3028 al = SSL_AD_DECODE_ERROR;
3029 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3033 while (PACKET_remaining(&spkt) > 0) {
3034 if (!PACKET_get_net_3(&spkt, &l)
3035 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3036 al = SSL_AD_DECODE_ERROR;
3037 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3038 SSL_R_CERT_LENGTH_MISMATCH);
3042 certstart = certbytes;
3043 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3045 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3048 if (certbytes != (certstart + l)) {
3049 al = SSL_AD_DECODE_ERROR;
3050 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3051 SSL_R_CERT_LENGTH_MISMATCH);
3054 if (!sk_X509_push(sk, x)) {
3055 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3061 if (sk_X509_num(sk) <= 0) {
3062 /* TLS does not mind 0 certs returned */
3063 if (s->version == SSL3_VERSION) {
3064 al = SSL_AD_HANDSHAKE_FAILURE;
3065 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3066 SSL_R_NO_CERTIFICATES_RETURNED);
3069 /* Fail for TLS only if we required a certificate */
3070 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3071 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3072 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3073 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3074 al = SSL_AD_HANDSHAKE_FAILURE;
3077 /* No client certificate so digest cached records */
3078 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3079 al = SSL_AD_INTERNAL_ERROR;
3084 i = ssl_verify_cert_chain(s, sk);
3086 al = ssl_verify_alarm_type(s->verify_result);
3087 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3088 SSL_R_CERTIFICATE_VERIFY_FAILED);
3092 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3093 al = SSL_AD_HANDSHAKE_FAILURE;
3096 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3098 al = SSL3_AD_HANDSHAKE_FAILURE;
3099 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3100 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3103 EVP_PKEY_free(pkey);
3106 X509_free(s->session->peer);
3107 s->session->peer = sk_X509_shift(sk);
3108 s->session->verify_result = s->verify_result;
3110 sk_X509_pop_free(s->session->peer_chain, X509_free);
3111 s->session->peer_chain = sk;
3113 * Inconsistency alert: cert_chain does *not* include the peer's own
3114 * certificate, while we do include it in s3_clnt.c
3121 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3123 s->state = SSL_ST_ERR;
3125 sk_X509_pop_free(sk, X509_free);
3129 int ssl3_send_server_certificate(SSL *s)
3133 if (s->state == SSL3_ST_SW_CERT_A) {
3134 cpk = ssl_get_server_send_pkey(s);
3136 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3137 s->state = SSL_ST_ERR;
3141 if (!ssl3_output_cert_chain(s, cpk)) {
3142 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3143 s->state = SSL_ST_ERR;
3146 s->state = SSL3_ST_SW_CERT_B;
3149 /* SSL3_ST_SW_CERT_B */
3150 return ssl_do_write(s);
3153 /* send a new session ticket (not necessarily for a new session) */
3154 int ssl3_send_newsession_ticket(SSL *s)
3156 unsigned char *senc = NULL;
3160 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3161 unsigned char *p, *macstart;
3162 const unsigned char *const_p;
3163 int len, slen_full, slen;
3166 SSL_CTX *tctx = s->initial_ctx;
3167 unsigned char iv[EVP_MAX_IV_LENGTH];
3168 unsigned char key_name[16];
3170 /* get session encoding length */
3171 slen_full = i2d_SSL_SESSION(s->session, NULL);
3173 * Some length values are 16 bits, so forget it if session is too
3176 if (slen_full == 0 || slen_full > 0xFF00) {
3177 s->state = SSL_ST_ERR;
3180 senc = OPENSSL_malloc(slen_full);
3182 s->state = SSL_ST_ERR;
3186 EVP_CIPHER_CTX_init(&ctx);
3187 HMAC_CTX_init(&hctx);
3190 if (!i2d_SSL_SESSION(s->session, &p))
3194 * create a fresh copy (not shared with other threads) to clean up
3197 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3200 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3202 slen = i2d_SSL_SESSION(sess, NULL);
3203 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3204 SSL_SESSION_free(sess);
3208 if (!i2d_SSL_SESSION(sess, &p)) {
3209 SSL_SESSION_free(sess);
3212 SSL_SESSION_free(sess);
3215 * Grow buffer if need be: the length calculation is as
3216 * follows handshake_header_length +
3217 * 4 (ticket lifetime hint) + 2 (ticket length) +
3218 * 16 (key name) + max_iv_len (iv length) +
3219 * session_length + max_enc_block_size (max encrypted session
3220 * length) + max_md_size (HMAC).
3222 if (!BUF_MEM_grow(s->init_buf,
3223 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3224 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3227 p = ssl_handshake_start(s);
3229 * Initialize HMAC and cipher contexts. If callback present it does
3230 * all the work otherwise use generated values from parent ctx.
3232 if (tctx->tlsext_ticket_key_cb) {
3233 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3237 if (RAND_bytes(iv, 16) <= 0)
3239 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3240 tctx->tlsext_tick_aes_key, iv))
3242 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3243 EVP_sha256(), NULL))
3245 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3249 * Ticket lifetime hint (advisory only): We leave this unspecified
3250 * for resumed session (for simplicity), and guess that tickets for
3251 * new sessions will live as long as their sessions.
3253 l2n(s->hit ? 0 : s->session->timeout, p);
3255 /* Skip ticket length for now */
3257 /* Output key name */
3259 memcpy(p, key_name, 16);
3262 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3263 p += EVP_CIPHER_CTX_iv_length(&ctx);
3264 /* Encrypt session data */
3265 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3268 if (!EVP_EncryptFinal(&ctx, p, &len))
3272 if (!HMAC_Update(&hctx, macstart, p - macstart))
3274 if (!HMAC_Final(&hctx, p, &hlen))
3277 EVP_CIPHER_CTX_cleanup(&ctx);
3278 HMAC_CTX_cleanup(&hctx);
3281 /* Now write out lengths: p points to end of data written */
3283 len = p - ssl_handshake_start(s);
3284 /* Skip ticket lifetime hint */
3285 p = ssl_handshake_start(s) + 4;
3287 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3289 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3293 /* SSL3_ST_SW_SESSION_TICKET_B */
3294 return ssl_do_write(s);
3297 EVP_CIPHER_CTX_cleanup(&ctx);
3298 HMAC_CTX_cleanup(&hctx);
3299 s->state = SSL_ST_ERR;
3303 int ssl3_send_cert_status(SSL *s)
3305 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3308 * Grow buffer if need be: the length calculation is as
3309 * follows 1 (message type) + 3 (message length) +
3310 * 1 (ocsp response type) + 3 (ocsp response length)
3313 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3314 s->state = SSL_ST_ERR;
3318 p = (unsigned char *)s->init_buf->data;
3321 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3322 /* message length */
3323 l2n3(s->tlsext_ocsp_resplen + 4, p);
3325 *(p++) = s->tlsext_status_type;
3326 /* length of OCSP response */
3327 l2n3(s->tlsext_ocsp_resplen, p);
3328 /* actual response */
3329 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3330 /* number of bytes to write */
3331 s->init_num = 8 + s->tlsext_ocsp_resplen;
3332 s->state = SSL3_ST_SW_CERT_STATUS_B;
3336 /* SSL3_ST_SW_CERT_STATUS_B */
3337 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3340 #ifndef OPENSSL_NO_NEXTPROTONEG
3342 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3343 * It sets the next_proto member in s if found
3345 int ssl3_get_next_proto(SSL *s)
3349 PACKET pkt, next_proto, padding;
3350 size_t next_proto_len;
3353 * Clients cannot send a NextProtocol message if we didn't see the
3354 * extension in their ClientHello
3356 if (!s->s3->next_proto_neg_seen) {
3357 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3358 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3359 s->state = SSL_ST_ERR;
3363 /* See the payload format below */
3364 n = s->method->ssl_get_message(s,
3365 SSL3_ST_SR_NEXT_PROTO_A,
3366 SSL3_ST_SR_NEXT_PROTO_B,
3367 SSL3_MT_NEXT_PROTO, 514, &ok);
3373 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3374 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3375 * ssl3_get_finished).
3377 if (!s->s3->change_cipher_spec) {
3378 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3379 s->state = SSL_ST_ERR;
3384 goto err; /* The body must be > 1 bytes long */
3387 if (!PACKET_buf_init(&pkt, s->init_msg, n)) {
3388 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
3393 * The payload looks like:
3395 * uint8 proto[proto_len];
3396 * uint8 padding_len;
3397 * uint8 padding[padding_len];
3399 if (!PACKET_get_length_prefixed_1(&pkt, &next_proto)
3400 || !PACKET_get_length_prefixed_1(&pkt, &padding)
3401 || PACKET_remaining(&pkt) > 0) {
3402 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3406 if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3408 s->next_proto_negotiated_len = 0;
3412 s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3416 s->state = SSL_ST_ERR;
3421 #define SSLV2_CIPHER_LEN 3
3423 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3424 PACKET *cipher_suites,
3425 STACK_OF(SSL_CIPHER) **skp,
3426 int sslv2format, int *al
3429 const SSL_CIPHER *c;
3430 STACK_OF(SSL_CIPHER) *sk;
3432 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3433 unsigned char cipher[SSLV2_CIPHER_LEN];
3435 s->s3->send_connection_binding = 0;
3437 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3439 if (PACKET_remaining(cipher_suites) == 0) {
3440 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3441 *al = SSL_AD_ILLEGAL_PARAMETER;
3445 if (PACKET_remaining(cipher_suites) % n != 0) {
3446 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3447 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3448 *al = SSL_AD_DECODE_ERROR;
3452 if ((skp == NULL) || (*skp == NULL)) {
3453 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3455 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3456 *al = SSL_AD_INTERNAL_ERROR;
3461 sk_SSL_CIPHER_zero(sk);
3464 if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3465 &s->s3->tmp.ciphers_rawlen)) {
3466 *al = SSL_AD_INTERNAL_ERROR;
3470 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3472 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3473 * first byte set to zero, while true SSLv2 ciphers have a non-zero
3474 * first byte. We don't support any true SSLv2 ciphers, so skip them.
3476 if (sslv2format && cipher[0] != '\0')
3479 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3480 if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3481 (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3482 /* SCSV fatal if renegotiating */
3483 if (s->renegotiate) {
3484 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3485 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3486 *al = SSL_AD_HANDSHAKE_FAILURE;
3489 s->s3->send_connection_binding = 1;
3490 #ifdef OPENSSL_RI_DEBUG
3491 fprintf(stderr, "SCSV received by server\n");
3496 /* Check for TLS_FALLBACK_SCSV */
3497 if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3498 (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3500 * The SCSV indicates that the client previously tried a higher
3501 * version. Fail if the current version is an unexpected
3504 if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
3505 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3506 SSL_R_INAPPROPRIATE_FALLBACK);
3507 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3513 /* For SSLv2-compat, ignore leading 0-byte. */
3514 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3516 if (!sk_SSL_CIPHER_push(sk, c)) {
3517 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3518 *al = SSL_AD_INTERNAL_ERROR;
3523 if (PACKET_remaining(cipher_suites) > 0) {
3524 *al = SSL_AD_INTERNAL_ERROR;
3525 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3533 if ((skp == NULL) || (*skp == NULL))
3534 sk_SSL_CIPHER_free(sk);