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, unsigned char *p,
168 int num, STACK_OF(SSL_CIPHER) **skp, int sslv2format);
171 #ifndef OPENSSL_NO_SRP
172 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
174 int ret = SSL_ERROR_NONE;
176 *al = SSL_AD_UNRECOGNIZED_NAME;
178 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
179 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
180 if (s->srp_ctx.login == NULL) {
182 * RFC 5054 says SHOULD reject, we do so if There is no srp
186 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
188 ret = SSL_srp_server_param_with_username(s, al);
195 int ssl3_accept(SSL *s)
198 unsigned long alg_k, Time = (unsigned long)time(NULL);
199 void (*cb) (const SSL *ssl, int type, int val) = NULL;
201 int new_state, state, skip = 0;
203 RAND_add(&Time, sizeof(Time), 0);
207 if (s->info_callback != NULL)
208 cb = s->info_callback;
209 else if (s->ctx->info_callback != NULL)
210 cb = s->ctx->info_callback;
212 /* init things to blank */
214 if (!SSL_in_init(s) || SSL_in_before(s)) {
219 #ifndef OPENSSL_NO_HEARTBEATS
221 * If we're awaiting a HeartbeatResponse, pretend we already got and
222 * don't await it anymore, because Heartbeats don't make sense during
225 if (s->tlsext_hb_pending) {
226 s->tlsext_hb_pending = 0;
235 case SSL_ST_RENEGOTIATE:
237 /* s->state=SSL_ST_ACCEPT; */
241 case SSL_ST_BEFORE | SSL_ST_ACCEPT:
242 case SSL_ST_OK | SSL_ST_ACCEPT:
246 cb(s, SSL_CB_HANDSHAKE_START, 1);
248 if ((s->version >> 8 != 3) && s->version != TLS_ANY_VERSION) {
249 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
250 s->state = SSL_ST_ERR;
254 if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
255 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
259 s->type = SSL_ST_ACCEPT;
261 if (s->init_buf == NULL) {
262 if ((buf = BUF_MEM_new()) == NULL) {
264 s->state = SSL_ST_ERR;
267 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
270 s->state = SSL_ST_ERR;
276 if (!ssl3_setup_buffers(s)) {
278 s->state = SSL_ST_ERR;
283 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
284 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
286 * Should have been reset by ssl3_get_finished, too.
288 s->s3->change_cipher_spec = 0;
290 if (s->state != SSL_ST_RENEGOTIATE) {
292 * Ok, we now need to push on a buffering BIO so that the
293 * output is sent in a way that TCP likes :-)
295 if (!ssl_init_wbio_buffer(s, 1)) {
297 s->state = SSL_ST_ERR;
301 ssl3_init_finished_mac(s);
302 s->state = SSL3_ST_SR_CLNT_HELLO_A;
303 s->ctx->stats.sess_accept++;
304 } else if (!s->s3->send_connection_binding &&
306 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
308 * Server attempting to renegotiate with client that doesn't
309 * support secure renegotiation.
311 SSLerr(SSL_F_SSL3_ACCEPT,
312 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
313 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
315 s->state = SSL_ST_ERR;
319 * s->state == SSL_ST_RENEGOTIATE, we will just send a
322 s->ctx->stats.sess_accept_renegotiate++;
323 s->state = SSL3_ST_SW_HELLO_REQ_A;
327 case SSL3_ST_SW_HELLO_REQ_A:
328 case SSL3_ST_SW_HELLO_REQ_B:
331 ret = ssl3_send_hello_request(s);
334 s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
335 s->state = SSL3_ST_SW_FLUSH;
338 ssl3_init_finished_mac(s);
341 case SSL3_ST_SW_HELLO_REQ_C:
342 s->state = SSL_ST_OK;
345 case SSL3_ST_SR_CLNT_HELLO_A:
346 case SSL3_ST_SR_CLNT_HELLO_B:
347 case SSL3_ST_SR_CLNT_HELLO_C:
349 ret = ssl3_get_client_hello(s);
352 #ifndef OPENSSL_NO_SRP
353 s->state = SSL3_ST_SR_CLNT_HELLO_D;
354 case SSL3_ST_SR_CLNT_HELLO_D:
357 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
359 * callback indicates firther work to be done
361 s->rwstate = SSL_X509_LOOKUP;
364 if (ret != SSL_ERROR_NONE) {
365 ssl3_send_alert(s, SSL3_AL_FATAL, al);
367 * This is not really an error but the only means to for
368 * a client to detect whether srp is supported.
370 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
371 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
372 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
374 s->state = SSL_ST_ERR;
381 s->state = SSL3_ST_SW_SRVR_HELLO_A;
385 case SSL3_ST_SW_SRVR_HELLO_A:
386 case SSL3_ST_SW_SRVR_HELLO_B:
387 ret = ssl3_send_server_hello(s);
392 if (s->tlsext_ticket_expected)
393 s->state = SSL3_ST_SW_SESSION_TICKET_A;
395 s->state = SSL3_ST_SW_CHANGE_A;
397 s->state = SSL3_ST_SW_CERT_A;
402 case SSL3_ST_SW_CERT_A:
403 case SSL3_ST_SW_CERT_B:
404 /* Check if it is anon DH or anon ECDH, */
405 /* normal PSK or SRP */
406 if (!(s->s3->tmp.new_cipher->algorithm_auth &
407 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
408 ret = ssl3_send_server_certificate(s);
412 if (s->tlsext_status_expected)
413 s->state = SSL3_ST_SW_CERT_STATUS_A;
415 s->state = SSL3_ST_SW_KEY_EXCH_A;
418 s->state = SSL3_ST_SW_KEY_EXCH_A;
423 case SSL3_ST_SW_KEY_EXCH_A:
424 case SSL3_ST_SW_KEY_EXCH_B:
425 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
428 * clear this, it may get reset by
429 * send_server_key_exchange
431 s->s3->tmp.use_rsa_tmp = 0;
434 * only send if a DH key exchange, fortezza or RSA but we have a
435 * sign only certificate PSK: may send PSK identity hints For
436 * ECC ciphersuites, we send a serverKeyExchange message only if
437 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
438 * the server certificate contains the server's public key for
443 * PSK: send ServerKeyExchange if PSK identity hint if
446 #ifndef OPENSSL_NO_PSK
447 /* Only send SKE if we have identity hint for plain PSK */
448 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK)) && s->ctx->psk_identity_hint)
449 /* For other PSK always send SKE */
450 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
452 #ifndef OPENSSL_NO_SRP
453 /* SRP: send ServerKeyExchange */
454 || (alg_k & SSL_kSRP)
456 || (alg_k & SSL_kDHE)
457 || (alg_k & SSL_kECDHE)
458 || ((alg_k & SSL_kRSA)
459 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
460 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
461 && EVP_PKEY_size(s->cert->pkeys
462 [SSL_PKEY_RSA_ENC].privatekey) *
463 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
468 ret = ssl3_send_server_key_exchange(s);
474 s->state = SSL3_ST_SW_CERT_REQ_A;
478 case SSL3_ST_SW_CERT_REQ_A:
479 case SSL3_ST_SW_CERT_REQ_B:
480 if ( /* don't request cert unless asked for it: */
481 !(s->verify_mode & SSL_VERIFY_PEER) ||
483 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
484 * during re-negotiation:
486 ((s->session->peer != NULL) &&
487 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
489 * never request cert in anonymous ciphersuites (see
490 * section "Certificate request" in SSL 3 drafts and in
493 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
495 * ... except when the application insists on
496 * verification (against the specs, but s3_clnt.c accepts
499 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
500 /* don't request certificate for SRP auth */
501 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
503 * With normal PSK Certificates and Certificate Requests
506 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
507 /* no cert request */
509 s->s3->tmp.cert_request = 0;
510 s->state = SSL3_ST_SW_SRVR_DONE_A;
511 if (!ssl3_digest_cached_records(s, 0)) {
512 s->state = SSL_ST_ERR;
516 s->s3->tmp.cert_request = 1;
517 ret = ssl3_send_certificate_request(s);
520 s->state = SSL3_ST_SW_SRVR_DONE_A;
525 case SSL3_ST_SW_SRVR_DONE_A:
526 case SSL3_ST_SW_SRVR_DONE_B:
527 ret = ssl3_send_server_done(s);
530 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
531 s->state = SSL3_ST_SW_FLUSH;
535 case SSL3_ST_SW_FLUSH:
538 * This code originally checked to see if any data was pending
539 * using BIO_CTRL_INFO and then flushed. This caused problems as
540 * documented in PR#1939. The proposed fix doesn't completely
541 * resolve this issue as buggy implementations of
542 * BIO_CTRL_PENDING still exist. So instead we just flush
546 s->rwstate = SSL_WRITING;
547 if (BIO_flush(s->wbio) <= 0) {
551 s->rwstate = SSL_NOTHING;
553 s->state = s->s3->tmp.next_state;
556 case SSL3_ST_SR_CERT_A:
557 case SSL3_ST_SR_CERT_B:
558 if (s->s3->tmp.cert_request) {
559 ret = ssl3_get_client_certificate(s);
564 s->state = SSL3_ST_SR_KEY_EXCH_A;
567 case SSL3_ST_SR_KEY_EXCH_A:
568 case SSL3_ST_SR_KEY_EXCH_B:
569 ret = ssl3_get_client_key_exchange(s);
574 * For the ECDH ciphersuites when the client sends its ECDH
575 * pub key in a certificate, the CertificateVerify message is
576 * not sent. Also for GOST ciphersuites when the client uses
577 * its key from the certificate for key exchange.
579 #if defined(OPENSSL_NO_NEXTPROTONEG)
580 s->state = SSL3_ST_SR_FINISHED_A;
582 if (s->s3->next_proto_neg_seen)
583 s->state = SSL3_ST_SR_NEXT_PROTO_A;
585 s->state = SSL3_ST_SR_FINISHED_A;
588 } else if (SSL_USE_SIGALGS(s)) {
589 s->state = SSL3_ST_SR_CERT_VRFY_A;
591 if (!s->session->peer)
593 if (!s->s3->handshake_buffer) {
594 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
595 s->state = SSL_ST_ERR;
599 * For sigalgs freeze the handshake buffer. If we support
600 * extms we've done this already so this is a no-op
602 if (!ssl3_digest_cached_records(s, 1)) {
603 s->state = SSL_ST_ERR;
610 s->state = SSL3_ST_SR_CERT_VRFY_A;
614 * We need to get hashes here so if there is a client cert,
615 * it can be verified FIXME - digest processing for
616 * CertificateVerify should be generalized. But it is next
619 if (!ssl3_digest_cached_records(s, 0)) {
620 s->state = SSL_ST_ERR;
623 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
624 if (s->s3->handshake_dgst[dgst_num]) {
627 s->method->ssl3_enc->cert_verify_mac(s,
636 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
638 s->state = SSL_ST_ERR;
647 case SSL3_ST_SR_CERT_VRFY_A:
648 case SSL3_ST_SR_CERT_VRFY_B:
649 ret = ssl3_get_cert_verify(s);
653 #if defined(OPENSSL_NO_NEXTPROTONEG)
654 s->state = SSL3_ST_SR_FINISHED_A;
656 if (s->s3->next_proto_neg_seen)
657 s->state = SSL3_ST_SR_NEXT_PROTO_A;
659 s->state = SSL3_ST_SR_FINISHED_A;
664 #if !defined(OPENSSL_NO_NEXTPROTONEG)
665 case SSL3_ST_SR_NEXT_PROTO_A:
666 case SSL3_ST_SR_NEXT_PROTO_B:
668 * Enable CCS for NPN. Receiving a CCS clears the flag, so make
669 * sure not to re-enable it to ban duplicates. This *should* be the
670 * first time we have received one - but we check anyway to be
672 * s->s3->change_cipher_spec is set when a CCS is
673 * processed in s3_pkt.c, and remains set until
674 * the client's Finished message is read.
676 if (!s->s3->change_cipher_spec)
677 s->s3->flags |= SSL3_FLAGS_CCS_OK;
679 ret = ssl3_get_next_proto(s);
683 s->state = SSL3_ST_SR_FINISHED_A;
687 case SSL3_ST_SR_FINISHED_A:
688 case SSL3_ST_SR_FINISHED_B:
690 * Enable CCS for handshakes without NPN. In NPN the CCS flag has
691 * already been set. Receiving a CCS clears the flag, so make
692 * sure not to re-enable it to ban duplicates.
693 * s->s3->change_cipher_spec is set when a CCS is
694 * processed in s3_pkt.c, and remains set until
695 * the client's Finished message is read.
697 if (!s->s3->change_cipher_spec)
698 s->s3->flags |= SSL3_FLAGS_CCS_OK;
699 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
700 SSL3_ST_SR_FINISHED_B);
704 s->state = SSL_ST_OK;
705 else if (s->tlsext_ticket_expected)
706 s->state = SSL3_ST_SW_SESSION_TICKET_A;
708 s->state = SSL3_ST_SW_CHANGE_A;
712 case SSL3_ST_SW_SESSION_TICKET_A:
713 case SSL3_ST_SW_SESSION_TICKET_B:
714 ret = ssl3_send_newsession_ticket(s);
717 s->state = SSL3_ST_SW_CHANGE_A;
721 case SSL3_ST_SW_CERT_STATUS_A:
722 case SSL3_ST_SW_CERT_STATUS_B:
723 ret = ssl3_send_cert_status(s);
726 s->state = SSL3_ST_SW_KEY_EXCH_A;
730 case SSL3_ST_SW_CHANGE_A:
731 case SSL3_ST_SW_CHANGE_B:
733 s->session->cipher = s->s3->tmp.new_cipher;
734 if (!s->method->ssl3_enc->setup_key_block(s)) {
736 s->state = SSL_ST_ERR;
740 ret = ssl3_send_change_cipher_spec(s,
742 SSL3_ST_SW_CHANGE_B);
746 s->state = SSL3_ST_SW_FINISHED_A;
749 if (!s->method->ssl3_enc->change_cipher_state(s,
750 SSL3_CHANGE_CIPHER_SERVER_WRITE))
753 s->state = SSL_ST_ERR;
759 case SSL3_ST_SW_FINISHED_A:
760 case SSL3_ST_SW_FINISHED_B:
761 ret = ssl3_send_finished(s,
762 SSL3_ST_SW_FINISHED_A,
763 SSL3_ST_SW_FINISHED_B,
765 ssl3_enc->server_finished_label,
767 ssl3_enc->server_finished_label_len);
770 s->state = SSL3_ST_SW_FLUSH;
772 #if defined(OPENSSL_NO_NEXTPROTONEG)
773 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
775 if (s->s3->next_proto_neg_seen) {
776 s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
778 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
781 s->s3->tmp.next_state = SSL_ST_OK;
786 /* clean a few things up */
787 ssl3_cleanup_key_block(s);
789 BUF_MEM_free(s->init_buf);
792 /* remove buffering on output */
793 ssl_free_wbio_buffer(s);
797 if (s->renegotiate == 2) { /* skipped if we just sent a
802 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
804 s->ctx->stats.sess_accept_good++;
806 s->handshake_func = ssl3_accept;
809 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
818 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
824 if (!s->s3->tmp.reuse_message && !skip) {
826 if ((ret = BIO_flush(s->wbio)) <= 0)
830 if ((cb != NULL) && (s->state != state)) {
831 new_state = s->state;
833 cb(s, SSL_CB_ACCEPT_LOOP, 1);
834 s->state = new_state;
840 /* BIO_flush(s->wbio); */
844 cb(s, SSL_CB_ACCEPT_EXIT, ret);
848 int ssl3_send_hello_request(SSL *s)
851 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
852 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
853 SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
856 s->state = SSL3_ST_SW_HELLO_REQ_B;
859 /* SSL3_ST_SW_HELLO_REQ_B */
860 return ssl_do_write(s);
863 int ssl3_get_client_hello(SSL *s)
865 int i, complen, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
866 unsigned int cookie_len;
869 unsigned char *p, *d;
871 #ifndef OPENSSL_NO_COMP
872 unsigned char *q = NULL;
873 SSL_COMP *comp = NULL;
875 STACK_OF(SSL_CIPHER) *ciphers = NULL;
878 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
882 * We do this so that we will respond with our native type. If we are
883 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
884 * switching should be handled by a different method. If we are SSLv3, we
885 * will respond with SSLv3, even if prompted with TLSv1.
887 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
888 s->state = SSL3_ST_SR_CLNT_HELLO_B;
891 n = s->method->ssl_get_message(s,
892 SSL3_ST_SR_CLNT_HELLO_B,
893 SSL3_ST_SR_CLNT_HELLO_C,
894 SSL3_MT_CLIENT_HELLO,
895 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
900 d = p = (unsigned char *)s->init_msg;
902 /* First lets get s->client_version set correctly */
903 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
905 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
906 * header is sent directly on the wire, not wrapped as a TLS
907 * record. Our record layer just processes the message length and passes
908 * the rest right through. Its format is:
910 * 0-1 msg_length - decoded by the record layer
911 * 2 msg_type - s->init_msg points here
913 * 5-6 cipher_spec_length
914 * 7-8 session_id_length
915 * 9-10 challenge_length
919 if (p[0] != SSL2_MT_CLIENT_HELLO) {
921 * Should never happen. We should have tested this in the record
922 * layer in order to have determined that this is a SSLv2 record
925 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
929 if ((p[1] == 0x00) && (p[2] == 0x02)) {
930 /* This is real SSLv2. We don't support it. */
931 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
933 } else if (p[1] == SSL3_VERSION_MAJOR) {
935 s->client_version = (((int)p[1]) << 8) | (int)p[2];
937 /* No idea what protocol this is */
938 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
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 /* Do SSL/TLS version negotiation if applicable */
960 if (!SSL_IS_DTLS(s)) {
961 if (s->version != TLS_ANY_VERSION) {
962 if (s->client_version >= s->version) {
965 } else if (s->client_version >= SSL3_VERSION) {
966 switch(s->client_version) {
969 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
970 s->version = TLS1_2_VERSION;
971 s->method = TLSv1_2_server_method();
975 /* Deliberately fall through */
977 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
978 s->version = TLS1_1_VERSION;
979 s->method = TLSv1_1_server_method();
983 /* Deliberately fall through */
985 if(!(s->options & SSL_OP_NO_TLSv1)) {
986 s->version = TLS1_VERSION;
987 s->method = TLSv1_server_method();
991 /* Deliberately fall through */
993 #ifndef OPENSSL_NO_SSL3
994 if(!(s->options & SSL_OP_NO_SSLv3)) {
995 s->version = SSL3_VERSION;
996 s->method = SSLv3_server_method();
1005 } else if (s->client_version <= s->version
1006 || s->method->version == DTLS_ANY_VERSION) {
1008 * For DTLS we just check versions are potentially compatible. Version
1009 * negotiation comes later.
1015 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1016 if ((!s->enc_write_ctx && !s->write_hash)) {
1018 * similar to ssl3_get_record, send alert using remote version
1021 s->version = s->client_version;
1023 al = SSL_AD_PROTOCOL_VERSION;
1027 if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1029 * Handle an SSLv2 backwards compatible ClientHello
1030 * Note, this is only for SSLv3+ using the backward compatible format.
1031 * Real SSLv2 is not supported, and is rejected above.
1033 unsigned int csl, sil, cl;
1040 if (csl + sil + cl + MIN_SSL2_RECORD_LEN != (unsigned int) n) {
1041 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1042 al = SSL_AD_DECODE_ERROR;
1047 /* we need at least one cipher */
1048 al = SSL_AD_ILLEGAL_PARAMETER;
1049 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1053 if (ssl_bytes_to_cipher_list(s, p, csl, &(ciphers), 1) == NULL) {
1058 * Ignore any session id. We don't allow resumption in a backwards
1059 * compatible ClientHello
1063 if (!ssl_get_new_session(s, 1))
1066 /* Load the client random */
1067 i = (cl > SSL3_RANDOM_SIZE) ? SSL3_RANDOM_SIZE : cl;
1068 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1069 memcpy(s->s3->client_random, &(p[csl + sil]), i);
1071 /* Set p to end of packet to ensure we don't look for extensions */
1074 /* No compression, so set complen to 0 */
1077 /* If we get here we've got SSLv3+ in an SSLv3+ record */
1082 * If we require cookies and this ClientHello doesn't contain one, just
1083 * return since we do not want to allocate any memory yet. So check
1086 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1087 unsigned int session_length, cookie_length;
1089 session_length = *(p + SSL3_RANDOM_SIZE);
1091 if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
1092 al = SSL_AD_DECODE_ERROR;
1093 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1096 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1098 if (cookie_length == 0)
1102 /* load the client random */
1103 memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
1104 p += SSL3_RANDOM_SIZE;
1106 /* get the session-id */
1109 if (p + j > d + n) {
1110 al = SSL_AD_DECODE_ERROR;
1111 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1117 * Versions before 0.9.7 always allow clients to resume sessions in
1118 * renegotiation. 0.9.7 and later allow this by default, but optionally
1119 * ignore resumption requests with flag
1120 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1121 * than a change to default behavior so that applications relying on
1122 * this for security won't even compile against older library versions).
1123 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1124 * request renegotiation but not a new session (s->new_session remains
1125 * unset): for servers, this essentially just means that the
1126 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1130 && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1131 if (!ssl_get_new_session(s, 1))
1134 i = ssl_get_prev_session(s, p, j, d + n);
1136 * Only resume if the session's version matches the negotiated
1138 * RFC 5246 does not provide much useful advice on resumption
1139 * with a different protocol version. It doesn't forbid it but
1140 * the sanity of such behaviour would be questionable.
1141 * In practice, clients do not accept a version mismatch and
1142 * will abort the handshake with an error.
1144 if (i == 1 && s->version == s->session->ssl_version) {
1145 /* previous session */
1151 if (!ssl_get_new_session(s, 1))
1158 if (SSL_IS_DTLS(s)) {
1160 if (p + 1 > d + n) {
1161 al = SSL_AD_DECODE_ERROR;
1162 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1165 cookie_len = *(p++);
1167 if (p + cookie_len > d + n) {
1168 al = SSL_AD_DECODE_ERROR;
1169 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1174 * The ClientHello may contain a cookie even if the
1175 * HelloVerify message has not been sent--make sure that it
1176 * does not cause an overflow.
1178 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1180 al = SSL_AD_DECODE_ERROR;
1181 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1185 /* verify the cookie if appropriate option is set. */
1186 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1187 && cookie_len > 0) {
1188 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1190 if (s->ctx->app_verify_cookie_cb != NULL) {
1191 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1193 al = SSL_AD_HANDSHAKE_FAILURE;
1194 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1195 SSL_R_COOKIE_MISMATCH);
1198 /* else cookie verification succeeded */
1200 /* default verification */
1201 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1202 s->d1->cookie_len) != 0) {
1203 al = SSL_AD_HANDSHAKE_FAILURE;
1204 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1207 /* Set to -2 so if successful we return 2 */
1212 if (s->method->version == DTLS_ANY_VERSION) {
1213 /* Select version to use */
1214 if (s->client_version <= DTLS1_2_VERSION &&
1215 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1216 s->version = DTLS1_2_VERSION;
1217 s->method = DTLSv1_2_server_method();
1218 } else if (tls1_suiteb(s)) {
1219 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1220 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1221 s->version = s->client_version;
1222 al = SSL_AD_PROTOCOL_VERSION;
1224 } else if (s->client_version <= DTLS1_VERSION &&
1225 !(s->options & SSL_OP_NO_DTLSv1)) {
1226 s->version = DTLS1_VERSION;
1227 s->method = DTLSv1_server_method();
1229 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1230 SSL_R_WRONG_VERSION_NUMBER);
1231 s->version = s->client_version;
1232 al = SSL_AD_PROTOCOL_VERSION;
1235 s->session->ssl_version = s->version;
1239 if (p + 2 > d + n) {
1240 al = SSL_AD_DECODE_ERROR;
1241 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1247 al = SSL_AD_ILLEGAL_PARAMETER;
1248 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1252 /* i bytes of cipher data + 1 byte for compression length later */
1253 if ((p + i + 1) > (d + n)) {
1254 /* not enough data */
1255 al = SSL_AD_DECODE_ERROR;
1256 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1259 if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers), 0) == NULL) {
1264 /* If it is a hit, check that the cipher is in the list */
1267 id = s->session->cipher->id;
1270 fprintf(stderr, "client sent %d ciphers\n",
1271 sk_SSL_CIPHER_num(ciphers));
1273 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1274 c = sk_SSL_CIPHER_value(ciphers, i);
1276 fprintf(stderr, "client [%2d of %2d]:%s\n",
1277 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1285 * Disabled because it can be used in a ciphersuite downgrade
1290 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1291 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1293 * Special case as client bug workaround: the previously used
1294 * cipher may not be in the current list, the client instead
1295 * might be trying to continue using a cipher that before wasn't
1296 * chosen due to server preferences. We'll have to reject the
1297 * connection if the cipher is not enabled, though.
1299 c = sk_SSL_CIPHER_value(ciphers, 0);
1300 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1301 s->session->cipher = c;
1308 * we need to have the cipher in the cipher list if we are asked
1311 al = SSL_AD_ILLEGAL_PARAMETER;
1312 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1313 SSL_R_REQUIRED_CIPHER_MISSING);
1320 if ((p + complen) > (d + n)) {
1321 /* not enough data */
1322 al = SSL_AD_DECODE_ERROR;
1323 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1326 #ifndef OPENSSL_NO_COMP
1329 for (j = 0; j < complen; j++) {
1337 al = SSL_AD_DECODE_ERROR;
1338 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1343 /* TLS extensions */
1344 if (s->version >= SSL3_VERSION) {
1345 if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1346 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1352 * Check if we want to use external pre-shared secret for this handshake
1353 * for not reused session only. We need to generate server_random before
1354 * calling tls_session_secret_cb in order to allow SessionTicket
1355 * processing to use it in key derivation.
1359 pos = s->s3->server_random;
1360 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1365 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1366 SSL_CIPHER *pref_cipher = NULL;
1368 s->session->master_key_length = sizeof(s->session->master_key);
1369 if (s->tls_session_secret_cb(s, s->session->master_key,
1370 &s->session->master_key_length, ciphers,
1372 s->tls_session_secret_cb_arg)) {
1374 s->session->ciphers = ciphers;
1375 s->session->verify_result = X509_V_OK;
1379 /* check if some cipher was preferred by call back */
1381 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1386 if (pref_cipher == NULL) {
1387 al = SSL_AD_HANDSHAKE_FAILURE;
1388 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1392 s->session->cipher = pref_cipher;
1393 sk_SSL_CIPHER_free(s->cipher_list);
1394 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1395 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1396 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1401 * Worst case, we will use the NULL compression, but if we have other
1402 * options, we will now look for them. We have complen-1 compression
1403 * algorithms from the client, starting at q.
1405 s->s3->tmp.new_compression = NULL;
1406 #ifndef OPENSSL_NO_COMP
1407 /* This only happens if we have a cache hit */
1408 if (s->session->compress_meth != 0) {
1409 int m, comp_id = s->session->compress_meth;
1410 /* Perform sanity checks on resumed compression algorithm */
1411 /* Can't disable compression */
1412 if (!ssl_allow_compression(s)) {
1413 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1414 SSL_R_INCONSISTENT_COMPRESSION);
1417 /* Look for resumed compression method */
1418 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1419 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1420 if (comp_id == comp->id) {
1421 s->s3->tmp.new_compression = comp;
1425 if (s->s3->tmp.new_compression == NULL) {
1426 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1427 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1430 /* Look for resumed method in compression list */
1431 for (m = 0; m < complen; m++) {
1432 if (q[m] == comp_id)
1436 al = SSL_AD_ILLEGAL_PARAMETER;
1437 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1438 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1443 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1444 /* See if we have a match */
1445 int m, nn, o, v, done = 0;
1447 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1448 for (m = 0; m < nn; m++) {
1449 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1451 for (o = 0; o < complen; o++) {
1461 s->s3->tmp.new_compression = comp;
1467 * If compression is disabled we'd better not try to resume a session
1468 * using compression.
1470 if (s->session->compress_meth != 0) {
1471 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1477 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1481 #ifdef OPENSSL_NO_COMP
1482 s->session->compress_meth = 0;
1484 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1486 sk_SSL_CIPHER_free(s->session->ciphers);
1487 s->session->ciphers = ciphers;
1488 if (ciphers == NULL) {
1489 al = SSL_AD_INTERNAL_ERROR;
1490 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1494 if (!tls1_set_server_sigalgs(s)) {
1495 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1498 /* Let cert callback update server certificates if required */
1500 if (s->cert->cert_cb) {
1501 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1503 al = SSL_AD_INTERNAL_ERROR;
1504 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1508 s->rwstate = SSL_X509_LOOKUP;
1511 s->rwstate = SSL_NOTHING;
1513 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1516 al = SSL_AD_HANDSHAKE_FAILURE;
1517 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1520 s->s3->tmp.new_cipher = c;
1521 /* check whether we should disable session resumption */
1522 if (s->not_resumable_session_cb != NULL)
1523 s->session->not_resumable = s->not_resumable_session_cb(s,
1524 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1526 if (s->session->not_resumable)
1527 /* do not send a session ticket */
1528 s->tlsext_ticket_expected = 0;
1530 /* Session-id reuse */
1531 s->s3->tmp.new_cipher = s->session->cipher;
1534 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1535 if (!ssl3_digest_cached_records(s, 0))
1540 * we now have the following setup.
1542 * cipher_list - our prefered list of ciphers
1543 * ciphers - the clients prefered list of ciphers
1544 * compression - basically ignored right now
1545 * ssl version is set - sslv3
1546 * s->session - The ssl session has been setup.
1547 * s->hit - session reuse flag
1548 * s->s3->tmp.new_cipher- the new cipher to use.
1551 /* Handles TLS extensions that we couldn't check earlier */
1552 if (s->version >= SSL3_VERSION) {
1553 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1554 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1563 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1565 s->state = SSL_ST_ERR;
1568 sk_SSL_CIPHER_free(ciphers);
1569 return ret < 0 ? -1 : ret;
1572 int ssl3_send_server_hello(SSL *s)
1575 unsigned char *p, *d;
1580 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1581 buf = (unsigned char *)s->init_buf->data;
1583 p = s->s3->server_random;
1584 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1585 s->state = SSL_ST_ERR;
1589 /* Do the message type and length last */
1590 d = p = ssl_handshake_start(s);
1592 *(p++) = s->version >> 8;
1593 *(p++) = s->version & 0xff;
1596 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1597 p += SSL3_RANDOM_SIZE;
1600 * There are several cases for the session ID to send
1601 * back in the server hello:
1602 * - For session reuse from the session cache,
1603 * we send back the old session ID.
1604 * - If stateless session reuse (using a session ticket)
1605 * is successful, we send back the client's "session ID"
1606 * (which doesn't actually identify the session).
1607 * - If it is a new session, we send back the new
1609 * - However, if we want the new session to be single-use,
1610 * we send back a 0-length session ID.
1611 * s->hit is non-zero in either case of session reuse,
1612 * so the following won't overwrite an ID that we're supposed
1615 if (s->session->not_resumable ||
1616 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1618 s->session->session_id_length = 0;
1620 sl = s->session->session_id_length;
1621 if (sl > (int)sizeof(s->session->session_id)) {
1622 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1623 s->state = SSL_ST_ERR;
1627 memcpy(p, s->session->session_id, sl);
1630 /* put the cipher */
1631 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1634 /* put the compression method */
1635 #ifdef OPENSSL_NO_COMP
1638 if (s->s3->tmp.new_compression == NULL)
1641 *(p++) = s->s3->tmp.new_compression->id;
1644 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1645 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1646 s->state = SSL_ST_ERR;
1650 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1652 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1653 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1654 s->state = SSL_ST_ERR;
1660 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1661 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1664 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1667 /* SSL3_ST_SW_SRVR_HELLO_B */
1668 return ssl_do_write(s);
1671 int ssl3_send_server_done(SSL *s)
1674 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1675 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1676 SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1679 s->state = SSL3_ST_SW_SRVR_DONE_B;
1682 /* SSL3_ST_SW_SRVR_DONE_B */
1683 return ssl_do_write(s);
1686 int ssl3_send_server_key_exchange(SSL *s)
1688 #ifndef OPENSSL_NO_RSA
1692 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1695 #ifndef OPENSSL_NO_DH
1696 DH *dh = NULL, *dhp;
1698 #ifndef OPENSSL_NO_EC
1699 EC_KEY *ecdh = NULL, *ecdhp;
1700 unsigned char *encodedPoint = NULL;
1703 BN_CTX *bn_ctx = NULL;
1706 const EVP_MD *md = NULL;
1707 unsigned char *p, *d;
1717 EVP_MD_CTX_init(&md_ctx);
1718 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1719 type = s->s3->tmp.new_cipher->algorithm_mkey;
1724 r[0] = r[1] = r[2] = r[3] = NULL;
1726 #ifndef OPENSSL_NO_PSK
1727 if (type & SSL_PSK) {
1729 * reserve size for record length and PSK identity hint
1732 if (s->ctx->psk_identity_hint)
1733 n += strlen(s->ctx->psk_identity_hint);
1735 /* Plain PSK or RSAPSK nothing to do */
1736 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1738 #endif /* !OPENSSL_NO_PSK */
1739 #ifndef OPENSSL_NO_RSA
1740 if (type & SSL_kRSA) {
1741 rsa = cert->rsa_tmp;
1742 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1743 rsa = s->cert->rsa_tmp_cb(s,
1744 SSL_C_IS_EXPORT(s->s3->
1746 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1749 al = SSL_AD_HANDSHAKE_FAILURE;
1750 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1751 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1755 cert->rsa_tmp = rsa;
1758 al = SSL_AD_HANDSHAKE_FAILURE;
1759 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1760 SSL_R_MISSING_TMP_RSA_KEY);
1765 s->s3->tmp.use_rsa_tmp = 1;
1768 #ifndef OPENSSL_NO_DH
1769 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1770 if (s->cert->dh_tmp_auto) {
1771 dhp = ssl_get_auto_dh(s);
1773 al = SSL_AD_INTERNAL_ERROR;
1774 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1775 ERR_R_INTERNAL_ERROR);
1780 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1781 dhp = s->cert->dh_tmp_cb(s,
1782 SSL_C_IS_EXPORT(s->s3->
1784 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1787 al = SSL_AD_HANDSHAKE_FAILURE;
1788 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1789 SSL_R_MISSING_TMP_DH_KEY);
1792 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1793 DH_security_bits(dhp), 0, dhp)) {
1794 al = SSL_AD_HANDSHAKE_FAILURE;
1795 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1796 SSL_R_DH_KEY_TOO_SMALL);
1799 if (s->s3->tmp.dh != NULL) {
1800 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1801 ERR_R_INTERNAL_ERROR);
1805 if (s->cert->dh_tmp_auto)
1807 else if ((dh = DHparams_dup(dhp)) == NULL) {
1808 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1813 if ((dhp->pub_key == NULL ||
1814 dhp->priv_key == NULL ||
1815 (s->options & SSL_OP_SINGLE_DH_USE))) {
1816 if (!DH_generate_key(dh)) {
1817 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1821 dh->pub_key = BN_dup(dhp->pub_key);
1822 dh->priv_key = BN_dup(dhp->priv_key);
1823 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1824 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1833 #ifndef OPENSSL_NO_EC
1834 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1835 const EC_GROUP *group;
1837 ecdhp = cert->ecdh_tmp;
1838 if (s->cert->ecdh_tmp_auto) {
1839 /* Get NID of appropriate shared curve */
1840 int nid = tls1_shared_curve(s, -2);
1841 if (nid != NID_undef)
1842 ecdhp = EC_KEY_new_by_curve_name(nid);
1843 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1844 ecdhp = s->cert->ecdh_tmp_cb(s,
1845 SSL_C_IS_EXPORT(s->s3->
1847 SSL_C_EXPORT_PKEYLENGTH(s->
1848 s3->tmp.new_cipher));
1850 if (ecdhp == NULL) {
1851 al = SSL_AD_HANDSHAKE_FAILURE;
1852 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1853 SSL_R_MISSING_TMP_ECDH_KEY);
1857 if (s->s3->tmp.ecdh != NULL) {
1858 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1859 ERR_R_INTERNAL_ERROR);
1863 /* Duplicate the ECDH structure. */
1864 if (ecdhp == NULL) {
1865 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1868 if (s->cert->ecdh_tmp_auto)
1870 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1871 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1875 s->s3->tmp.ecdh = ecdh;
1876 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1877 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1878 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1879 if (!EC_KEY_generate_key(ecdh)) {
1880 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1886 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1887 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1888 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1889 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1893 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1894 (EC_GROUP_get_degree(group) > 163)) {
1895 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1896 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1901 * XXX: For now, we only support ephemeral ECDH keys over named
1902 * (not generic) curves. For supported named curves, curve_id is
1906 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1908 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1909 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1914 * Encode the public key. First check the size of encoding and
1915 * allocate memory accordingly.
1917 encodedlen = EC_POINT_point2oct(group,
1918 EC_KEY_get0_public_key(ecdh),
1919 POINT_CONVERSION_UNCOMPRESSED,
1922 encodedPoint = (unsigned char *)
1923 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1924 bn_ctx = BN_CTX_new();
1925 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1926 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1927 ERR_R_MALLOC_FAILURE);
1931 encodedlen = EC_POINT_point2oct(group,
1932 EC_KEY_get0_public_key(ecdh),
1933 POINT_CONVERSION_UNCOMPRESSED,
1934 encodedPoint, encodedlen, bn_ctx);
1936 if (encodedlen == 0) {
1937 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1941 BN_CTX_free(bn_ctx);
1945 * XXX: For now, we only support named (not generic) curves in
1946 * ECDH ephemeral key exchanges. In this situation, we need four
1947 * additional bytes to encode the entire ServerECDHParams
1950 n += 4 + encodedlen;
1953 * We'll generate the serverKeyExchange message explicitly so we
1954 * can set these to NULLs
1961 #endif /* !OPENSSL_NO_EC */
1962 #ifndef OPENSSL_NO_SRP
1963 if (type & SSL_kSRP) {
1964 if ((s->srp_ctx.N == NULL) ||
1965 (s->srp_ctx.g == NULL) ||
1966 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1967 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1968 SSL_R_MISSING_SRP_PARAM);
1971 r[0] = s->srp_ctx.N;
1972 r[1] = s->srp_ctx.g;
1973 r[2] = s->srp_ctx.s;
1974 r[3] = s->srp_ctx.B;
1978 al = SSL_AD_HANDSHAKE_FAILURE;
1979 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1980 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1983 for (i = 0; i < 4 && r[i] != NULL; i++) {
1984 nr[i] = BN_num_bytes(r[i]);
1985 #ifndef OPENSSL_NO_SRP
1986 if ((i == 2) && (type & SSL_kSRP))
1993 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1994 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1995 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1997 al = SSL_AD_DECODE_ERROR;
2000 kn = EVP_PKEY_size(pkey);
2006 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
2007 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
2010 d = p = ssl_handshake_start(s);
2012 #ifndef OPENSSL_NO_PSK
2013 if (type & SSL_PSK) {
2014 /* copy PSK identity hint */
2015 if (s->ctx->psk_identity_hint) {
2016 s2n(strlen(s->ctx->psk_identity_hint), p);
2017 strncpy((char *)p, s->ctx->psk_identity_hint,
2018 strlen(s->ctx->psk_identity_hint));
2019 p += strlen(s->ctx->psk_identity_hint);
2026 for (i = 0; i < 4 && r[i] != NULL; i++) {
2027 #ifndef OPENSSL_NO_SRP
2028 if ((i == 2) && (type & SSL_kSRP)) {
2038 #ifndef OPENSSL_NO_EC
2039 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2041 * XXX: For now, we only support named (not generic) curves. In
2042 * this situation, the serverKeyExchange message has: [1 byte
2043 * CurveType], [2 byte CurveName] [1 byte length of encoded
2044 * point], followed by the actual encoded point itself
2046 *p = NAMED_CURVE_TYPE;
2054 memcpy(p, encodedPoint, encodedlen);
2055 OPENSSL_free(encodedPoint);
2056 encodedPoint = NULL;
2064 * n is the length of the params, they start at &(d[4]) and p
2065 * points to the space at the end.
2067 #ifndef OPENSSL_NO_RSA
2068 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
2071 for (num = 2; num > 0; num--) {
2072 EVP_MD_CTX_set_flags(&md_ctx,
2073 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2074 EVP_DigestInit_ex(&md_ctx, (num == 2)
2075 ? s->ctx->md5 : s->ctx->sha1, NULL);
2076 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
2078 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
2080 EVP_DigestUpdate(&md_ctx, d, n);
2081 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
2085 if (RSA_sign(NID_md5_sha1, md_buf, j,
2086 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2087 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
2095 /* send signature algorithm */
2096 if (SSL_USE_SIGALGS(s)) {
2097 if (!tls12_get_sigandhash(p, pkey, md)) {
2098 /* Should never happen */
2099 al = SSL_AD_INTERNAL_ERROR;
2100 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2101 ERR_R_INTERNAL_ERROR);
2107 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2109 EVP_SignInit_ex(&md_ctx, md, NULL);
2110 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2112 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2114 EVP_SignUpdate(&md_ctx, d, n);
2115 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2116 (unsigned int *)&i, pkey)) {
2117 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2122 if (SSL_USE_SIGALGS(s))
2125 /* Is this error check actually needed? */
2126 al = SSL_AD_HANDSHAKE_FAILURE;
2127 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2128 SSL_R_UNKNOWN_PKEY_TYPE);
2133 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2134 al = SSL_AD_HANDSHAKE_FAILURE;
2135 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2140 s->state = SSL3_ST_SW_KEY_EXCH_B;
2141 EVP_MD_CTX_cleanup(&md_ctx);
2142 return ssl_do_write(s);
2144 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2146 #ifndef OPENSSL_NO_EC
2147 OPENSSL_free(encodedPoint);
2148 BN_CTX_free(bn_ctx);
2150 EVP_MD_CTX_cleanup(&md_ctx);
2151 s->state = SSL_ST_ERR;
2155 int ssl3_send_certificate_request(SSL *s)
2157 unsigned char *p, *d;
2158 int i, j, nl, off, n;
2159 STACK_OF(X509_NAME) *sk = NULL;
2163 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2166 d = p = ssl_handshake_start(s);
2168 /* get the list of acceptable cert types */
2170 n = ssl3_get_req_cert_type(s, p);
2175 if (SSL_USE_SIGALGS(s)) {
2176 const unsigned char *psigs;
2177 unsigned char *etmp = p;
2178 nl = tls12_get_psigalgs(s, &psigs);
2179 /* Skip over length for now */
2181 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2182 /* Now fill in length */
2192 sk = SSL_get_client_CA_list(s);
2195 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2196 name = sk_X509_NAME_value(sk, i);
2197 j = i2d_X509_NAME(name, NULL);
2198 if (!BUF_MEM_grow_clean
2199 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2200 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2204 p = ssl_handshake_start(s) + n;
2206 i2d_X509_NAME(name, &p);
2211 /* else no CA names */
2212 p = ssl_handshake_start(s) + off;
2215 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2216 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2220 s->state = SSL3_ST_SW_CERT_REQ_B;
2223 /* SSL3_ST_SW_CERT_REQ_B */
2224 return ssl_do_write(s);
2226 s->state = SSL_ST_ERR;
2230 int ssl3_get_client_key_exchange(SSL *s)
2234 unsigned long alg_k;
2236 #ifndef OPENSSL_NO_RSA
2238 EVP_PKEY *pkey = NULL;
2240 #ifndef OPENSSL_NO_DH
2242 DH *dh_srvr, *dh_clnt = NULL;
2244 #ifndef OPENSSL_NO_EC
2245 EC_KEY *srvr_ecdh = NULL;
2246 EVP_PKEY *clnt_pub_pkey = NULL;
2247 EC_POINT *clnt_ecpoint = NULL;
2248 BN_CTX *bn_ctx = NULL;
2251 n = s->method->ssl_get_message(s,
2252 SSL3_ST_SR_KEY_EXCH_A,
2253 SSL3_ST_SR_KEY_EXCH_B,
2254 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2258 p = (unsigned char *)s->init_msg;
2260 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2262 #ifndef OPENSSL_NO_PSK
2263 /* For PSK parse and retrieve identity, obtain PSK key */
2264 if (alg_k & SSL_PSK) {
2265 unsigned char psk[PSK_MAX_PSK_LEN];
2268 al = SSL_AD_DECODE_ERROR;
2269 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2274 al = SSL_AD_DECODE_ERROR;
2275 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2278 if (i > PSK_MAX_IDENTITY_LEN) {
2279 al = SSL_AD_DECODE_ERROR;
2280 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2281 SSL_R_DATA_LENGTH_TOO_LONG);
2284 if (s->psk_server_callback == NULL) {
2285 al = SSL_AD_INTERNAL_ERROR;
2286 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2287 SSL_R_PSK_NO_SERVER_CB);
2291 OPENSSL_free(s->session->psk_identity);
2292 s->session->psk_identity = BUF_strndup((char *)p, i);
2294 if (s->session->psk_identity == NULL) {
2295 al = SSL_AD_INTERNAL_ERROR;
2296 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2297 ERR_R_MALLOC_FAILURE);
2301 psklen = s->psk_server_callback(s, s->session->psk_identity,
2304 if (psklen > PSK_MAX_PSK_LEN) {
2305 al = SSL_AD_INTERNAL_ERROR;
2306 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2308 } else if (psklen == 0) {
2310 * PSK related to the given identity not found
2312 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2313 SSL_R_PSK_IDENTITY_NOT_FOUND);
2314 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2318 OPENSSL_free(s->s3->tmp.psk);
2319 s->s3->tmp.psk = BUF_memdup(psk, psklen);
2320 OPENSSL_cleanse(psk, psklen);
2322 if (s->s3->tmp.psk == NULL) {
2323 al = SSL_AD_INTERNAL_ERROR;
2324 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2328 s->s3->tmp.psklen = psklen;
2333 if (alg_k & SSL_kPSK) {
2334 /* Identity extracted earlier: should be nothing left */
2336 al = SSL_AD_HANDSHAKE_FAILURE;
2337 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2340 /* PSK handled by ssl_generate_master_secret */
2341 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2342 al = SSL_AD_INTERNAL_ERROR;
2343 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2348 #ifndef OPENSSL_NO_RSA
2349 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2350 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2352 unsigned char decrypt_good, version_good;
2355 /* FIX THIS UP EAY EAY EAY EAY */
2356 if (s->s3->tmp.use_rsa_tmp) {
2357 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2358 rsa = s->cert->rsa_tmp;
2360 * Don't do a callback because rsa_tmp should be sent already
2363 al = SSL_AD_HANDSHAKE_FAILURE;
2364 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2365 SSL_R_MISSING_TMP_RSA_PKEY);
2370 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2371 if ((pkey == NULL) ||
2372 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2373 al = SSL_AD_HANDSHAKE_FAILURE;
2374 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2375 SSL_R_MISSING_RSA_CERTIFICATE);
2378 rsa = pkey->pkey.rsa;
2381 /* TLS and [incidentally] DTLS{0xFEFF} */
2382 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2385 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2386 al = SSL_AD_DECODE_ERROR;
2387 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2388 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2397 * Reject overly short RSA ciphertext because we want to be sure
2398 * that the buffer size makes it safe to iterate over the entire
2399 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2400 * actual expected size is larger due to RSA padding, but the
2401 * bound is sufficient to be safe.
2403 if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2404 al = SSL_AD_DECRYPT_ERROR;
2405 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2406 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2411 * We must not leak whether a decryption failure occurs because of
2412 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2413 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2414 * generates a random premaster secret for the case that the decrypt
2415 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2418 if (RAND_bytes(rand_premaster_secret,
2419 sizeof(rand_premaster_secret)) <= 0)
2422 RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2426 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2427 * be 0xff if so and zero otherwise.
2430 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2433 * If the version in the decrypted pre-master secret is correct then
2434 * version_good will be 0xff, otherwise it'll be zero. The
2435 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2436 * (http://eprint.iacr.org/2003/052/) exploits the version number
2437 * check as a "bad version oracle". Thus version checks are done in
2438 * constant time and are treated like any other decryption error.
2441 constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2443 constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2446 * The premaster secret must contain the same version number as the
2447 * ClientHello to detect version rollback attacks (strangely, the
2448 * protocol does not offer such protection for DH ciphersuites).
2449 * However, buggy clients exist that send the negotiated protocol
2450 * version instead if the server does not support the requested
2451 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2454 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2455 unsigned char workaround_good;
2457 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2459 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2460 version_good |= workaround_good;
2464 * Both decryption and version must be good for decrypt_good to
2465 * remain non-zero (0xff).
2467 decrypt_good &= version_good;
2470 * Now copy rand_premaster_secret over from p using
2471 * decrypt_good_mask. If decryption failed, then p does not
2472 * contain valid plaintext, however, a check above guarantees
2473 * it is still sufficiently large to read from.
2475 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2476 p[j] = constant_time_select_8(decrypt_good, p[j],
2477 rand_premaster_secret[j]);
2480 if (!ssl_generate_master_secret(s, p, sizeof(rand_premaster_secret), 0)) {
2481 al = SSL_AD_INTERNAL_ERROR;
2482 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2487 #ifndef OPENSSL_NO_DH
2488 if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2490 EVP_PKEY *skey = NULL;
2494 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2495 al = SSL_AD_HANDSHAKE_FAILURE;
2496 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2497 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2502 if (n && n != i + 2) {
2503 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2504 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2505 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2512 if (alg_k & SSL_kDHr)
2513 idx = SSL_PKEY_DH_RSA;
2514 else if (alg_k & SSL_kDHd)
2515 idx = SSL_PKEY_DH_DSA;
2517 skey = s->cert->pkeys[idx].privatekey;
2518 if ((skey == NULL) ||
2519 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2520 al = SSL_AD_HANDSHAKE_FAILURE;
2521 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2522 SSL_R_MISSING_RSA_CERTIFICATE);
2525 dh_srvr = skey->pkey.dh;
2526 } else if (s->s3->tmp.dh == NULL) {
2527 al = SSL_AD_HANDSHAKE_FAILURE;
2528 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2529 SSL_R_MISSING_TMP_DH_KEY);
2532 dh_srvr = s->s3->tmp.dh;
2535 /* Get pubkey from cert */
2536 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2538 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2539 dh_clnt = EVP_PKEY_get1_DH(clkey);
2541 if (dh_clnt == NULL) {
2542 al = SSL_AD_HANDSHAKE_FAILURE;
2543 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2544 SSL_R_MISSING_TMP_DH_KEY);
2547 EVP_PKEY_free(clkey);
2548 pub = dh_clnt->pub_key;
2550 pub = BN_bin2bn(p, i, NULL);
2552 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2556 i = DH_compute_key(p, pub, dh_srvr);
2559 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2564 DH_free(s->s3->tmp.dh);
2565 s->s3->tmp.dh = NULL;
2571 if (!ssl_generate_master_secret(s, p, i, 0)) {
2572 al = SSL_AD_INTERNAL_ERROR;
2573 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2581 #ifndef OPENSSL_NO_EC
2582 if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2586 const EC_GROUP *group;
2587 const BIGNUM *priv_key;
2589 /* initialize structures for server's ECDH key pair */
2590 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2591 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2595 /* Let's get server private key and group information */
2596 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2597 /* use the certificate */
2598 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2601 * use the ephermeral values we saved when generating the
2602 * ServerKeyExchange msg.
2604 tkey = s->s3->tmp.ecdh;
2607 group = EC_KEY_get0_group(tkey);
2608 priv_key = EC_KEY_get0_private_key(tkey);
2610 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2611 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2612 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2616 /* Let's get client's public key */
2617 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2618 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2623 /* Client Publickey was in Client Certificate */
2625 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2626 al = SSL_AD_HANDSHAKE_FAILURE;
2627 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2628 SSL_R_MISSING_TMP_ECDH_KEY);
2631 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2632 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2634 * XXX: For now, we do not support client authentication
2635 * using ECDH certificates so this branch (n == 0L) of the
2636 * code is never executed. When that support is added, we
2637 * ought to ensure the key received in the certificate is
2638 * authorized for key agreement. ECDH_compute_key implicitly
2639 * checks that the two ECDH shares are for the same group.
2641 al = SSL_AD_HANDSHAKE_FAILURE;
2642 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2643 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2647 if (EC_POINT_copy(clnt_ecpoint,
2648 EC_KEY_get0_public_key(clnt_pub_pkey->
2650 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2653 ret = 2; /* Skip certificate verify processing */
2656 * Get client's public key from encoded point in the
2657 * ClientKeyExchange message.
2659 if ((bn_ctx = BN_CTX_new()) == NULL) {
2660 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2661 ERR_R_MALLOC_FAILURE);
2665 /* Get encoded point length */
2669 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2672 if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2673 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2677 * p is pointing to somewhere in the buffer currently, so set it
2680 p = (unsigned char *)s->init_buf->data;
2683 /* Compute the shared pre-master secret */
2684 field_size = EC_GROUP_get_degree(group);
2685 if (field_size <= 0) {
2686 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2689 i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2692 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2696 EVP_PKEY_free(clnt_pub_pkey);
2697 EC_POINT_free(clnt_ecpoint);
2698 EC_KEY_free(srvr_ecdh);
2699 BN_CTX_free(bn_ctx);
2700 EC_KEY_free(s->s3->tmp.ecdh);
2701 s->s3->tmp.ecdh = NULL;
2703 if (!ssl_generate_master_secret(s, p, i, 0)) {
2704 al = SSL_AD_INTERNAL_ERROR;
2705 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2711 #ifndef OPENSSL_NO_SRP
2712 if (alg_k & SSL_kSRP) {
2717 if (param_len > n) {
2718 al = SSL_AD_DECODE_ERROR;
2719 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2720 SSL_R_BAD_SRP_A_LENGTH);
2723 if ((s->srp_ctx.A = BN_bin2bn(p, i, NULL)) == NULL) {
2724 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2727 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2728 || BN_is_zero(s->srp_ctx.A)) {
2729 al = SSL_AD_ILLEGAL_PARAMETER;
2730 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2731 SSL_R_BAD_SRP_PARAMETERS);
2734 OPENSSL_free(s->session->srp_username);
2735 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2736 if (s->session->srp_username == NULL) {
2737 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2741 if (!srp_generate_server_master_secret(s)) {
2742 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2748 #endif /* OPENSSL_NO_SRP */
2749 if (alg_k & SSL_kGOST) {
2751 EVP_PKEY_CTX *pkey_ctx;
2752 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2753 unsigned char premaster_secret[32], *start;
2754 size_t outlen = 32, inlen;
2755 unsigned long alg_a;
2759 /* Get our certificate private key */
2760 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2761 if (alg_a & SSL_aGOST94)
2762 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2763 else if (alg_a & SSL_aGOST01)
2764 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2766 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2767 EVP_PKEY_decrypt_init(pkey_ctx);
2769 * If client certificate is present and is of the same type, maybe
2770 * use it for key exchange. Don't mind errors from
2771 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2772 * client certificate for authorization only.
2774 client_pub_pkey = X509_get_pubkey(s->session->peer);
2775 if (client_pub_pkey) {
2776 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2779 /* Decrypt session key */
2781 ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2782 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2783 || Tclass != V_ASN1_UNIVERSAL) {
2784 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2785 SSL_R_DECRYPTION_FAILED);
2790 if (EVP_PKEY_decrypt
2791 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2792 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2793 SSL_R_DECRYPTION_FAILED);
2796 /* Generate master secret */
2797 if (!ssl_generate_master_secret(s, premaster_secret,
2798 sizeof(premaster_secret), 0)) {
2799 al = SSL_AD_INTERNAL_ERROR;
2800 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2803 /* Check if pubkey from client certificate was used */
2804 if (EVP_PKEY_CTX_ctrl
2805 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2810 EVP_PKEY_free(client_pub_pkey);
2811 EVP_PKEY_CTX_free(pkey_ctx);
2816 al = SSL_AD_HANDSHAKE_FAILURE;
2817 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2823 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2824 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2827 #ifndef OPENSSL_NO_EC
2828 EVP_PKEY_free(clnt_pub_pkey);
2829 EC_POINT_free(clnt_ecpoint);
2830 EC_KEY_free(srvr_ecdh);
2831 BN_CTX_free(bn_ctx);
2833 #ifndef OPENSSL_NO_PSK
2834 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2835 s->s3->tmp.psk = NULL;
2837 s->state = SSL_ST_ERR;
2841 int ssl3_get_cert_verify(SSL *s)
2843 EVP_PKEY *pkey = NULL;
2845 int al, ok, ret = 0;
2849 const EVP_MD *md = NULL;
2851 EVP_MD_CTX_init(&mctx);
2854 * We should only process a CertificateVerify message if we have received
2855 * a Certificate from the client. If so then |s->session->peer| will be non
2856 * NULL. In some instances a CertificateVerify message is not required even
2857 * if the peer has sent a Certificate (e.g. such as in the case of static
2858 * DH). In that case the ClientKeyExchange processing will skip the
2859 * CertificateVerify state so we should not arrive here.
2861 if (s->session->peer == NULL) {
2866 n = s->method->ssl_get_message(s,
2867 SSL3_ST_SR_CERT_VRFY_A,
2868 SSL3_ST_SR_CERT_VRFY_B,
2869 SSL3_MT_CERTIFICATE_VERIFY,
2870 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2875 peer = s->session->peer;
2876 pkey = X509_get_pubkey(peer);
2877 type = X509_certificate_type(peer, pkey);
2879 if (!(type & EVP_PKT_SIGN)) {
2880 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2881 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2882 al = SSL_AD_ILLEGAL_PARAMETER;
2886 /* we now have a signature that we need to verify */
2887 p = (unsigned char *)s->init_msg;
2888 /* Check for broken implementations of GOST ciphersuites */
2890 * If key is GOST and n is exactly 64, it is bare signature without
2893 if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2894 pkey->type == NID_id_GostR3410_2001)) {
2897 if (SSL_USE_SIGALGS(s)) {
2898 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2900 al = SSL_AD_INTERNAL_ERROR;
2902 } else if (rv == 0) {
2903 al = SSL_AD_DECODE_ERROR;
2907 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2915 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2916 al = SSL_AD_DECODE_ERROR;
2920 j = EVP_PKEY_size(pkey);
2921 if ((i > j) || (n > j) || (n <= 0)) {
2922 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2923 al = SSL_AD_DECODE_ERROR;
2927 if (SSL_USE_SIGALGS(s)) {
2930 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2931 if (hdatalen <= 0) {
2932 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2933 al = SSL_AD_INTERNAL_ERROR;
2937 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2940 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2941 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2942 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2943 al = SSL_AD_INTERNAL_ERROR;
2947 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2948 al = SSL_AD_DECRYPT_ERROR;
2949 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2953 #ifndef OPENSSL_NO_RSA
2954 if (pkey->type == EVP_PKEY_RSA) {
2955 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2956 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2959 al = SSL_AD_DECRYPT_ERROR;
2960 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2964 al = SSL_AD_DECRYPT_ERROR;
2965 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2970 #ifndef OPENSSL_NO_DSA
2971 if (pkey->type == EVP_PKEY_DSA) {
2972 j = DSA_verify(pkey->save_type,
2973 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2974 SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2977 al = SSL_AD_DECRYPT_ERROR;
2978 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
2983 #ifndef OPENSSL_NO_EC
2984 if (pkey->type == EVP_PKEY_EC) {
2985 j = ECDSA_verify(pkey->save_type,
2986 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2987 SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2990 al = SSL_AD_DECRYPT_ERROR;
2991 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2996 if (pkey->type == NID_id_GostR3410_94
2997 || pkey->type == NID_id_GostR3410_2001) {
2998 unsigned char signature[64];
3000 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3001 EVP_PKEY_verify_init(pctx);
3003 fprintf(stderr, "GOST signature length is %d", i);
3005 for (idx = 0; idx < 64; idx++) {
3006 signature[63 - idx] = p[idx];
3008 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3010 EVP_PKEY_CTX_free(pctx);
3012 al = SSL_AD_DECRYPT_ERROR;
3013 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3017 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3018 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3025 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3026 s->state = SSL_ST_ERR;
3029 BIO_free(s->s3->handshake_buffer);
3030 s->s3->handshake_buffer = NULL;
3031 EVP_MD_CTX_cleanup(&mctx);
3032 EVP_PKEY_free(pkey);
3036 int ssl3_get_client_certificate(SSL *s)
3038 int i, ok, al, ret = -1;
3040 unsigned long l, nc, llen, n;
3041 const unsigned char *p, *q;
3043 STACK_OF(X509) *sk = NULL;
3045 n = s->method->ssl_get_message(s,
3048 -1, s->max_cert_list, &ok);
3053 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3054 if ((s->verify_mode & SSL_VERIFY_PEER) &&
3055 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3056 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3057 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3058 al = SSL_AD_HANDSHAKE_FAILURE;
3062 * If tls asked for a client cert, the client must return a 0 list
3064 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3065 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3066 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3067 al = SSL_AD_UNEXPECTED_MESSAGE;
3070 s->s3->tmp.reuse_message = 1;
3074 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3075 al = SSL_AD_UNEXPECTED_MESSAGE;
3076 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3079 p = d = (unsigned char *)s->init_msg;
3081 if ((sk = sk_X509_new_null()) == NULL) {
3082 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3087 if (llen + 3 != n) {
3088 al = SSL_AD_DECODE_ERROR;
3089 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3092 for (nc = 0; nc < llen;) {
3094 if ((l + nc + 3) > llen) {
3095 al = SSL_AD_DECODE_ERROR;
3096 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3097 SSL_R_CERT_LENGTH_MISMATCH);
3102 x = d2i_X509(NULL, &p, l);
3104 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3108 al = SSL_AD_DECODE_ERROR;
3109 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3110 SSL_R_CERT_LENGTH_MISMATCH);
3113 if (!sk_X509_push(sk, x)) {
3114 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3121 if (sk_X509_num(sk) <= 0) {
3122 /* TLS does not mind 0 certs returned */
3123 if (s->version == SSL3_VERSION) {
3124 al = SSL_AD_HANDSHAKE_FAILURE;
3125 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3126 SSL_R_NO_CERTIFICATES_RETURNED);
3129 /* Fail for TLS only if we required a certificate */
3130 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3131 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3132 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3133 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3134 al = SSL_AD_HANDSHAKE_FAILURE;
3137 /* No client certificate so digest cached records */
3138 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3139 al = SSL_AD_INTERNAL_ERROR;
3144 i = ssl_verify_cert_chain(s, sk);
3146 al = ssl_verify_alarm_type(s->verify_result);
3147 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3148 SSL_R_CERTIFICATE_VERIFY_FAILED);
3152 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3153 al = SSL_AD_HANDSHAKE_FAILURE;
3156 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3158 al = SSL3_AD_HANDSHAKE_FAILURE;
3159 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3160 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3163 EVP_PKEY_free(pkey);
3166 X509_free(s->session->peer);
3167 s->session->peer = sk_X509_shift(sk);
3168 s->session->verify_result = s->verify_result;
3170 sk_X509_pop_free(s->session->peer_chain, X509_free);
3171 s->session->peer_chain = sk;
3173 * Inconsistency alert: cert_chain does *not* include the peer's own
3174 * certificate, while we do include it in s3_clnt.c
3181 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3183 s->state = SSL_ST_ERR;
3185 sk_X509_pop_free(sk, X509_free);
3189 int ssl3_send_server_certificate(SSL *s)
3193 if (s->state == SSL3_ST_SW_CERT_A) {
3194 cpk = ssl_get_server_send_pkey(s);
3196 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3197 s->state = SSL_ST_ERR;
3201 if (!ssl3_output_cert_chain(s, cpk)) {
3202 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3203 s->state = SSL_ST_ERR;
3206 s->state = SSL3_ST_SW_CERT_B;
3209 /* SSL3_ST_SW_CERT_B */
3210 return ssl_do_write(s);
3213 /* send a new session ticket (not necessarily for a new session) */
3214 int ssl3_send_newsession_ticket(SSL *s)
3216 unsigned char *senc = NULL;
3220 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3221 unsigned char *p, *macstart;
3222 const unsigned char *const_p;
3223 int len, slen_full, slen;
3226 SSL_CTX *tctx = s->initial_ctx;
3227 unsigned char iv[EVP_MAX_IV_LENGTH];
3228 unsigned char key_name[16];
3230 /* get session encoding length */
3231 slen_full = i2d_SSL_SESSION(s->session, NULL);
3233 * Some length values are 16 bits, so forget it if session is too
3236 if (slen_full == 0 || slen_full > 0xFF00) {
3237 s->state = SSL_ST_ERR;
3240 senc = OPENSSL_malloc(slen_full);
3242 s->state = SSL_ST_ERR;
3246 EVP_CIPHER_CTX_init(&ctx);
3247 HMAC_CTX_init(&hctx);
3250 if (!i2d_SSL_SESSION(s->session, &p))
3254 * create a fresh copy (not shared with other threads) to clean up
3257 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3260 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3262 slen = i2d_SSL_SESSION(sess, NULL);
3263 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3264 SSL_SESSION_free(sess);
3268 if (!i2d_SSL_SESSION(sess, &p)) {
3269 SSL_SESSION_free(sess);
3272 SSL_SESSION_free(sess);
3275 * Grow buffer if need be: the length calculation is as
3276 * follows handshake_header_length +
3277 * 4 (ticket lifetime hint) + 2 (ticket length) +
3278 * 16 (key name) + max_iv_len (iv length) +
3279 * session_length + max_enc_block_size (max encrypted session
3280 * length) + max_md_size (HMAC).
3282 if (!BUF_MEM_grow(s->init_buf,
3283 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3284 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3287 p = ssl_handshake_start(s);
3289 * Initialize HMAC and cipher contexts. If callback present it does
3290 * all the work otherwise use generated values from parent ctx.
3292 if (tctx->tlsext_ticket_key_cb) {
3293 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3297 if (RAND_bytes(iv, 16) <= 0)
3299 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3300 tctx->tlsext_tick_aes_key, iv))
3302 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3303 EVP_sha256(), NULL))
3305 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3309 * Ticket lifetime hint (advisory only): We leave this unspecified
3310 * for resumed session (for simplicity), and guess that tickets for
3311 * new sessions will live as long as their sessions.
3313 l2n(s->hit ? 0 : s->session->timeout, p);
3315 /* Skip ticket length for now */
3317 /* Output key name */
3319 memcpy(p, key_name, 16);
3322 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3323 p += EVP_CIPHER_CTX_iv_length(&ctx);
3324 /* Encrypt session data */
3325 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3328 if (!EVP_EncryptFinal(&ctx, p, &len))
3332 if (!HMAC_Update(&hctx, macstart, p - macstart))
3334 if (!HMAC_Final(&hctx, p, &hlen))
3337 EVP_CIPHER_CTX_cleanup(&ctx);
3338 HMAC_CTX_cleanup(&hctx);
3341 /* Now write out lengths: p points to end of data written */
3343 len = p - ssl_handshake_start(s);
3344 /* Skip ticket lifetime hint */
3345 p = ssl_handshake_start(s) + 4;
3347 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3349 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3353 /* SSL3_ST_SW_SESSION_TICKET_B */
3354 return ssl_do_write(s);
3357 EVP_CIPHER_CTX_cleanup(&ctx);
3358 HMAC_CTX_cleanup(&hctx);
3359 s->state = SSL_ST_ERR;
3363 int ssl3_send_cert_status(SSL *s)
3365 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3368 * Grow buffer if need be: the length calculation is as
3369 * follows 1 (message type) + 3 (message length) +
3370 * 1 (ocsp response type) + 3 (ocsp response length)
3373 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3374 s->state = SSL_ST_ERR;
3378 p = (unsigned char *)s->init_buf->data;
3381 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3382 /* message length */
3383 l2n3(s->tlsext_ocsp_resplen + 4, p);
3385 *(p++) = s->tlsext_status_type;
3386 /* length of OCSP response */
3387 l2n3(s->tlsext_ocsp_resplen, p);
3388 /* actual response */
3389 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3390 /* number of bytes to write */
3391 s->init_num = 8 + s->tlsext_ocsp_resplen;
3392 s->state = SSL3_ST_SW_CERT_STATUS_B;
3396 /* SSL3_ST_SW_CERT_STATUS_B */
3397 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3400 #ifndef OPENSSL_NO_NEXTPROTONEG
3402 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3403 * It sets the next_proto member in s if found
3405 int ssl3_get_next_proto(SSL *s)
3408 int proto_len, padding_len;
3410 const unsigned char *p;
3413 * Clients cannot send a NextProtocol message if we didn't see the
3414 * extension in their ClientHello
3416 if (!s->s3->next_proto_neg_seen) {
3417 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3418 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3419 s->state = SSL_ST_ERR;
3423 /* See the payload format below */
3424 n = s->method->ssl_get_message(s,
3425 SSL3_ST_SR_NEXT_PROTO_A,
3426 SSL3_ST_SR_NEXT_PROTO_B,
3427 SSL3_MT_NEXT_PROTO, 514, &ok);
3433 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3434 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3435 * ssl3_get_finished).
3437 if (!s->s3->change_cipher_spec) {
3438 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3439 s->state = SSL_ST_ERR;
3444 s->state = SSL_ST_ERR;
3445 return 0; /* The body must be > 1 bytes long */
3448 p = (unsigned char *)s->init_msg;
3451 * The payload looks like:
3453 * uint8 proto[proto_len];
3454 * uint8 padding_len;
3455 * uint8 padding[padding_len];
3458 if (proto_len + 2 > s->init_num) {
3459 s->state = SSL_ST_ERR;
3462 padding_len = p[proto_len + 1];
3463 if (proto_len + padding_len + 2 != s->init_num) {
3464 s->state = SSL_ST_ERR;
3468 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3469 if (!s->next_proto_negotiated) {
3470 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3471 s->state = SSL_ST_ERR;
3474 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3475 s->next_proto_negotiated_len = proto_len;
3481 #define SSLV2_CIPHER_LEN 3
3483 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
3485 STACK_OF(SSL_CIPHER) **skp,
3488 const SSL_CIPHER *c;
3489 STACK_OF(SSL_CIPHER) *sk;
3493 s->s3->send_connection_binding = 0;
3496 n = SSLV2_CIPHER_LEN;
3498 n = ssl_put_cipher_by_char(s, NULL, NULL);
3500 if (n == 0 || (num % n) != 0) {
3501 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3502 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3505 if ((skp == NULL) || (*skp == NULL)) {
3506 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3508 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3513 sk_SSL_CIPHER_zero(sk);
3516 OPENSSL_free(s->s3->tmp.ciphers_raw);
3517 s->s3->tmp.ciphers_raw = BUF_memdup(p, num);
3518 if (s->s3->tmp.ciphers_raw == NULL) {
3519 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3522 s->s3->tmp.ciphers_rawlen = (size_t)num;
3524 for (i = 0; i < num; i += n) {
3525 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3526 if (s->s3 && (n != 3 || !p[0]) &&
3527 (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3528 (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3529 /* SCSV fatal if renegotiating */
3530 if (s->renegotiate) {
3531 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3532 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3533 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3536 s->s3->send_connection_binding = 1;
3538 #ifdef OPENSSL_RI_DEBUG
3539 fprintf(stderr, "SCSV received by server\n");
3544 /* Check for TLS_FALLBACK_SCSV */
3545 if ((n != 3 || !p[0]) &&
3546 (p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3547 (p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3549 * The SCSV indicates that the client previously tried a higher
3550 * version. Fail if the current version is an unexpected
3553 if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
3554 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3555 SSL_R_INAPPROPRIATE_FALLBACK);
3557 ssl3_send_alert(s, SSL3_AL_FATAL,
3558 SSL_AD_INAPPROPRIATE_FALLBACK);
3567 * We only support SSLv2 format ciphers in SSLv3+ using a
3568 * SSLv2 backward compatible ClientHello. In this case the first
3569 * byte is always 0 for SSLv3 compatible ciphers. Anything else
3570 * is an SSLv2 cipher and we ignore it
3573 c = ssl_get_cipher_by_char(s, &p[1]);
3577 c = ssl_get_cipher_by_char(s, p);
3581 if (!sk_SSL_CIPHER_push(sk, c)) {
3582 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3592 if ((skp == NULL) || (*skp == NULL))
3593 sk_SSL_CIPHER_free(sk);