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
151 #define REUSE_CIPHER_BUG
152 #define NETSCAPE_HANG_BUG
155 #include "ssl_locl.h"
156 #include "kssl_lcl.h"
157 #include "../crypto/constant_time_locl.h"
158 #include <openssl/buffer.h>
159 #include <openssl/rand.h>
160 #include <openssl/objects.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/x509.h>
164 #ifndef OPENSSL_NO_DH
165 #include <openssl/dh.h>
167 #include <openssl/bn.h>
168 #ifndef OPENSSL_NO_KRB5
169 #include <openssl/krb5_asn.h>
171 #include <openssl/md5.h>
173 #ifndef OPENSSL_NO_SSL3_METHOD
174 static const SSL_METHOD *ssl3_get_server_method(int ver);
176 static const SSL_METHOD *ssl3_get_server_method(int ver)
178 if (ver == SSL3_VERSION)
179 return(SSLv3_server_method());
184 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
186 ssl_undefined_function,
187 ssl3_get_server_method)
190 #ifndef OPENSSL_NO_SRP
191 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
193 int ret = SSL_ERROR_NONE;
195 *al = SSL_AD_UNRECOGNIZED_NAME;
197 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
198 (s->srp_ctx.TLS_ext_srp_username_callback != NULL))
200 if(s->srp_ctx.login == NULL)
202 /* RFC 5054 says SHOULD reject,
203 we do so if There is no srp login name */
205 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
209 ret = SSL_srp_server_param_with_username(s,al);
216 int ssl3_accept(SSL *s)
219 unsigned long alg_k,Time=(unsigned long)time(NULL);
220 void (*cb)(const SSL *ssl,int type,int val)=NULL;
222 int new_state,state,skip=0;
224 RAND_add(&Time,sizeof(Time),0);
228 if (s->info_callback != NULL)
230 else if (s->ctx->info_callback != NULL)
231 cb=s->ctx->info_callback;
233 /* init things to blank */
235 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
239 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
243 #ifndef OPENSSL_NO_HEARTBEATS
244 /* If we're awaiting a HeartbeatResponse, pretend we
245 * already got and don't await it anymore, because
246 * Heartbeats don't make sense during handshakes anyway.
248 if (s->tlsext_hb_pending)
250 s->tlsext_hb_pending = 0;
261 case SSL_ST_RENEGOTIATE:
263 /* s->state=SSL_ST_ACCEPT; */
267 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
268 case SSL_ST_OK|SSL_ST_ACCEPT:
271 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
273 if ((s->version>>8) != 3)
275 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
279 if (!ssl_security(s, SSL_SECOP_VERSION, 0,
282 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
286 s->type=SSL_ST_ACCEPT;
288 if (s->init_buf == NULL)
290 if ((buf=BUF_MEM_new()) == NULL)
295 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
304 if (!ssl3_setup_buffers(s))
311 s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
312 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
313 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
314 /* Should have been reset by ssl3_get_finished, too. */
315 s->s3->change_cipher_spec = 0;
317 if (s->state != SSL_ST_RENEGOTIATE)
319 /* Ok, we now need to push on a buffering BIO so that
320 * the output is sent in a way that TCP likes :-)
322 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
324 ssl3_init_finished_mac(s);
325 s->state=SSL3_ST_SR_CLNT_HELLO_A;
326 s->ctx->stats.sess_accept++;
328 else if (!s->s3->send_connection_binding &&
329 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
331 /* Server attempting to renegotiate with
332 * client that doesn't support secure
335 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
336 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
342 /* s->state == SSL_ST_RENEGOTIATE,
343 * we will just send a HelloRequest */
344 s->ctx->stats.sess_accept_renegotiate++;
345 s->state=SSL3_ST_SW_HELLO_REQ_A;
349 case SSL3_ST_SW_HELLO_REQ_A:
350 case SSL3_ST_SW_HELLO_REQ_B:
353 ret=ssl3_send_hello_request(s);
354 if (ret <= 0) goto end;
355 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
356 s->state=SSL3_ST_SW_FLUSH;
359 ssl3_init_finished_mac(s);
362 case SSL3_ST_SW_HELLO_REQ_C:
366 case SSL3_ST_SR_CLNT_HELLO_A:
367 case SSL3_ST_SR_CLNT_HELLO_B:
368 case SSL3_ST_SR_CLNT_HELLO_C:
370 ret=ssl3_get_client_hello(s);
371 if (ret <= 0) goto end;
372 #ifndef OPENSSL_NO_SRP
373 s->state = SSL3_ST_SR_CLNT_HELLO_D;
374 case SSL3_ST_SR_CLNT_HELLO_D:
377 if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
379 /* callback indicates firther work to be done */
380 s->rwstate=SSL_X509_LOOKUP;
383 if (ret != SSL_ERROR_NONE)
385 ssl3_send_alert(s,SSL3_AL_FATAL,al);
386 /* This is not really an error but the only means to
387 for a client to detect whether srp is supported. */
388 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
389 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
390 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
398 s->state=SSL3_ST_SW_SRVR_HELLO_A;
402 case SSL3_ST_SW_SRVR_HELLO_A:
403 case SSL3_ST_SW_SRVR_HELLO_B:
404 ret=ssl3_send_server_hello(s);
405 if (ret <= 0) goto end;
406 #ifndef OPENSSL_NO_TLSEXT
409 if (s->tlsext_ticket_expected)
410 s->state=SSL3_ST_SW_SESSION_TICKET_A;
412 s->state=SSL3_ST_SW_CHANGE_A;
416 s->state=SSL3_ST_SW_CHANGE_A;
419 s->state = SSL3_ST_SW_CERT_A;
423 case SSL3_ST_SW_CERT_A:
424 case SSL3_ST_SW_CERT_B:
425 /* Check if it is anon DH or anon ECDH, */
426 /* normal PSK or KRB5 or SRP */
427 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
428 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
430 ret=ssl3_send_server_certificate(s);
431 if (ret <= 0) goto end;
432 #ifndef OPENSSL_NO_TLSEXT
433 if (s->tlsext_status_expected)
434 s->state=SSL3_ST_SW_CERT_STATUS_A;
436 s->state=SSL3_ST_SW_KEY_EXCH_A;
441 s->state=SSL3_ST_SW_KEY_EXCH_A;
448 s->state=SSL3_ST_SW_KEY_EXCH_A;
453 case SSL3_ST_SW_KEY_EXCH_A:
454 case SSL3_ST_SW_KEY_EXCH_B:
455 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
457 /* clear this, it may get reset by
458 * send_server_key_exchange */
459 if ((s->options & SSL_OP_EPHEMERAL_RSA)
460 #ifndef OPENSSL_NO_KRB5
461 && !(alg_k & SSL_kKRB5)
462 #endif /* OPENSSL_NO_KRB5 */
464 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
465 * even when forbidden by protocol specs
466 * (handshake may fail as clients are not required to
467 * be able to handle this) */
468 s->s3->tmp.use_rsa_tmp=1;
470 s->s3->tmp.use_rsa_tmp=0;
473 /* only send if a DH key exchange, fortezza or
474 * RSA but we have a sign only certificate
476 * PSK: may send PSK identity hints
478 * For ECC ciphersuites, we send a serverKeyExchange
479 * message only if the cipher suite is either
480 * ECDH-anon or ECDHE. In other cases, the
481 * server certificate contains the server's
482 * public key for key exchange.
484 if (s->s3->tmp.use_rsa_tmp
485 /* PSK: send ServerKeyExchange if PSK identity
486 * hint if provided */
487 #ifndef OPENSSL_NO_PSK
488 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
490 #ifndef OPENSSL_NO_SRP
491 /* SRP: send ServerKeyExchange */
492 || (alg_k & SSL_kSRP)
494 || (alg_k & SSL_kDHE)
495 || (alg_k & SSL_kECDHE)
496 || ((alg_k & SSL_kRSA)
497 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
498 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
499 && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
505 ret=ssl3_send_server_key_exchange(s);
506 if (ret <= 0) goto end;
511 s->state=SSL3_ST_SW_CERT_REQ_A;
515 case SSL3_ST_SW_CERT_REQ_A:
516 case SSL3_ST_SW_CERT_REQ_B:
517 if (/* don't request cert unless asked for it: */
518 !(s->verify_mode & SSL_VERIFY_PEER) ||
519 /* if SSL_VERIFY_CLIENT_ONCE is set,
520 * don't request cert during re-negotiation: */
521 ((s->session->peer != NULL) &&
522 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
523 /* never request cert in anonymous ciphersuites
524 * (see section "Certificate request" in SSL 3 drafts
525 * and in RFC 2246): */
526 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
527 /* ... except when the application insists on verification
528 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
529 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
530 /* never request cert in Kerberos ciphersuites */
531 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
532 /* don't request certificate for SRP auth */
533 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
534 /* With normal PSK Certificates and
535 * Certificate Requests are omitted */
536 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
538 /* no cert request */
540 s->s3->tmp.cert_request=0;
541 s->state=SSL3_ST_SW_SRVR_DONE_A;
542 if (s->s3->handshake_buffer)
543 if (!ssl3_digest_cached_records(s))
548 s->s3->tmp.cert_request=1;
549 ret=ssl3_send_certificate_request(s);
550 if (ret <= 0) goto end;
551 #ifndef NETSCAPE_HANG_BUG
552 s->state=SSL3_ST_SW_SRVR_DONE_A;
554 s->state=SSL3_ST_SW_FLUSH;
555 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
561 case SSL3_ST_SW_SRVR_DONE_A:
562 case SSL3_ST_SW_SRVR_DONE_B:
563 ret=ssl3_send_server_done(s);
564 if (ret <= 0) goto end;
565 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
566 s->state=SSL3_ST_SW_FLUSH;
570 case SSL3_ST_SW_FLUSH:
572 /* This code originally checked to see if
573 * any data was pending using BIO_CTRL_INFO
574 * and then flushed. This caused problems
575 * as documented in PR#1939. The proposed
576 * fix doesn't completely resolve this issue
577 * as buggy implementations of BIO_CTRL_PENDING
578 * still exist. So instead we just flush
582 s->rwstate=SSL_WRITING;
583 if (BIO_flush(s->wbio) <= 0)
588 s->rwstate=SSL_NOTHING;
590 s->state=s->s3->tmp.next_state;
593 case SSL3_ST_SR_CERT_A:
594 case SSL3_ST_SR_CERT_B:
595 /* Check for second client hello (MS SGC) */
596 ret = ssl3_check_client_hello(s);
600 s->state = SSL3_ST_SR_CLNT_HELLO_C;
602 if (s->s3->tmp.cert_request)
604 ret=ssl3_get_client_certificate(s);
605 if (ret <= 0) goto end;
608 s->state=SSL3_ST_SR_KEY_EXCH_A;
612 case SSL3_ST_SR_KEY_EXCH_A:
613 case SSL3_ST_SR_KEY_EXCH_B:
614 ret=ssl3_get_client_key_exchange(s);
619 /* For the ECDH ciphersuites when
620 * the client sends its ECDH pub key in
621 * a certificate, the CertificateVerify
622 * message is not sent.
623 * Also for GOST ciphersuites when
624 * the client uses its key from the certificate
627 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
628 s->state=SSL3_ST_SR_FINISHED_A;
630 if (s->s3->next_proto_neg_seen)
631 s->state=SSL3_ST_SR_NEXT_PROTO_A;
633 s->state=SSL3_ST_SR_FINISHED_A;
637 else if (SSL_USE_SIGALGS(s))
639 s->state=SSL3_ST_SR_CERT_VRFY_A;
641 if (!s->session->peer)
643 /* For sigalgs freeze the handshake buffer
644 * at this point and digest cached records.
646 if (!s->s3->handshake_buffer)
648 SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
651 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
652 if (!ssl3_digest_cached_records(s))
660 s->state=SSL3_ST_SR_CERT_VRFY_A;
663 /* We need to get hashes here so if there is
664 * a client cert, it can be verified
665 * FIXME - digest processing for CertificateVerify
666 * should be generalized. But it is next step
668 if (s->s3->handshake_buffer)
669 if (!ssl3_digest_cached_records(s))
671 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
672 if (s->s3->handshake_dgst[dgst_num])
676 s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
677 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
688 case SSL3_ST_SR_CERT_VRFY_A:
689 case SSL3_ST_SR_CERT_VRFY_B:
691 * This *should* be the first time we enable CCS, but be
692 * extra careful about surrounding code changes. We need
693 * to set this here because we don't know if we're
694 * expecting a CertificateVerify or not.
696 if (!s->s3->change_cipher_spec)
697 s->s3->flags |= SSL3_FLAGS_CCS_OK;
698 /* we should decide if we expected this one */
699 ret=ssl3_get_cert_verify(s);
700 if (ret <= 0) goto end;
702 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
703 s->state=SSL3_ST_SR_FINISHED_A;
705 if (s->s3->next_proto_neg_seen)
706 s->state=SSL3_ST_SR_NEXT_PROTO_A;
708 s->state=SSL3_ST_SR_FINISHED_A;
713 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
714 case SSL3_ST_SR_NEXT_PROTO_A:
715 case SSL3_ST_SR_NEXT_PROTO_B:
717 * Enable CCS for resumed handshakes with NPN.
718 * In a full handshake with NPN, we end up here through
719 * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
720 * already set. Receiving a CCS clears the flag, so make
721 * sure not to re-enable it to ban duplicates.
722 * s->s3->change_cipher_spec is set when a CCS is
723 * processed in s3_pkt.c, and remains set until
724 * the client's Finished message is read.
726 if (!s->s3->change_cipher_spec)
727 s->s3->flags |= SSL3_FLAGS_CCS_OK;
729 ret=ssl3_get_next_proto(s);
730 if (ret <= 0) goto end;
732 s->state=SSL3_ST_SR_FINISHED_A;
736 case SSL3_ST_SR_FINISHED_A:
737 case SSL3_ST_SR_FINISHED_B:
739 * Enable CCS for resumed handshakes without NPN.
740 * In a full handshake, we end up here through
741 * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
742 * already set. Receiving a CCS clears the flag, so make
743 * sure not to re-enable it to ban duplicates.
744 * s->s3->change_cipher_spec is set when a CCS is
745 * processed in s3_pkt.c, and remains set until
746 * the client's Finished message is read.
748 if (!s->s3->change_cipher_spec)
749 s->s3->flags |= SSL3_FLAGS_CCS_OK;
750 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
751 SSL3_ST_SR_FINISHED_B);
752 if (ret <= 0) goto end;
755 #ifndef OPENSSL_NO_TLSEXT
756 else if (s->tlsext_ticket_expected)
757 s->state=SSL3_ST_SW_SESSION_TICKET_A;
760 s->state=SSL3_ST_SW_CHANGE_A;
764 #ifndef OPENSSL_NO_TLSEXT
765 case SSL3_ST_SW_SESSION_TICKET_A:
766 case SSL3_ST_SW_SESSION_TICKET_B:
767 ret=ssl3_send_newsession_ticket(s);
768 if (ret <= 0) goto end;
769 s->state=SSL3_ST_SW_CHANGE_A;
773 case SSL3_ST_SW_CERT_STATUS_A:
774 case SSL3_ST_SW_CERT_STATUS_B:
775 ret=ssl3_send_cert_status(s);
776 if (ret <= 0) goto end;
777 s->state=SSL3_ST_SW_KEY_EXCH_A;
783 case SSL3_ST_SW_CHANGE_A:
784 case SSL3_ST_SW_CHANGE_B:
786 s->session->cipher=s->s3->tmp.new_cipher;
787 if (!s->method->ssl3_enc->setup_key_block(s))
788 { ret= -1; goto end; }
790 ret=ssl3_send_change_cipher_spec(s,
791 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
793 if (ret <= 0) goto end;
794 s->state=SSL3_ST_SW_FINISHED_A;
797 if (!s->method->ssl3_enc->change_cipher_state(s,
798 SSL3_CHANGE_CIPHER_SERVER_WRITE))
806 case SSL3_ST_SW_FINISHED_A:
807 case SSL3_ST_SW_FINISHED_B:
808 ret=ssl3_send_finished(s,
809 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
810 s->method->ssl3_enc->server_finished_label,
811 s->method->ssl3_enc->server_finished_label_len);
812 if (ret <= 0) goto end;
813 s->state=SSL3_ST_SW_FLUSH;
816 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
817 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
819 if (s->s3->next_proto_neg_seen)
821 s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
824 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
828 s->s3->tmp.next_state=SSL_ST_OK;
833 /* clean a few things up */
834 ssl3_cleanup_key_block(s);
836 BUF_MEM_free(s->init_buf);
839 /* remove buffering on output */
840 ssl_free_wbio_buffer(s);
844 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
849 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
851 s->ctx->stats.sess_accept_good++;
853 s->handshake_func=ssl3_accept;
855 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
863 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
869 if (!s->s3->tmp.reuse_message && !skip)
873 if ((ret=BIO_flush(s->wbio)) <= 0)
878 if ((cb != NULL) && (s->state != state))
882 cb(s,SSL_CB_ACCEPT_LOOP,1);
889 /* BIO_flush(s->wbio); */
893 cb(s,SSL_CB_ACCEPT_EXIT,ret);
897 int ssl3_send_hello_request(SSL *s)
900 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
902 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
903 s->state=SSL3_ST_SW_HELLO_REQ_B;
906 /* SSL3_ST_SW_HELLO_REQ_B */
907 return ssl_do_write(s);
910 int ssl3_check_client_hello(SSL *s)
915 /* this function is called when we really expect a Certificate message,
916 * so permit appropriate message length */
917 n=s->method->ssl_get_message(s,
923 if (!ok) return((int)n);
924 s->s3->tmp.reuse_message = 1;
925 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
927 /* We only allow the client to restart the handshake once per
929 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
931 SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
934 /* Throw away what we have done so far in the current handshake,
935 * which will now be aborted. (A full SSL_clear would be too much.) */
936 #ifndef OPENSSL_NO_DH
937 if (s->s3->tmp.dh != NULL)
939 DH_free(s->s3->tmp.dh);
940 s->s3->tmp.dh = NULL;
943 #ifndef OPENSSL_NO_ECDH
944 if (s->s3->tmp.ecdh != NULL)
946 EC_KEY_free(s->s3->tmp.ecdh);
947 s->s3->tmp.ecdh = NULL;
950 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
956 int ssl3_get_client_hello(SSL *s)
958 int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
959 unsigned int cookie_len;
964 #ifndef OPENSSL_NO_COMP
968 STACK_OF(SSL_CIPHER) *ciphers=NULL;
970 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
973 /* We do this so that we will respond with our native type.
974 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
975 * This down switching should be handled by a different method.
976 * If we are SSLv3, we will respond with SSLv3, even if prompted with
979 if (s->state == SSL3_ST_SR_CLNT_HELLO_A
982 s->state=SSL3_ST_SR_CLNT_HELLO_B;
985 n=s->method->ssl_get_message(s,
986 SSL3_ST_SR_CLNT_HELLO_B,
987 SSL3_ST_SR_CLNT_HELLO_C,
988 SSL3_MT_CLIENT_HELLO,
989 SSL3_RT_MAX_PLAIN_LENGTH,
992 if (!ok) return((int)n);
994 d=p=(unsigned char *)s->init_msg;
996 /* use version from inside client hello, not from record header
997 * (may differ: see RFC 2246, Appendix E, second paragraph) */
998 s->client_version=(((int)p[0])<<8)|(int)p[1];
1001 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
1002 s->method->version != DTLS_ANY_VERSION)
1003 : (s->client_version < s->version))
1005 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1006 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
1007 !s->enc_write_ctx && !s->write_hash)
1009 /* similar to ssl3_get_record, send alert using remote version number */
1010 s->version = s->client_version;
1012 al = SSL_AD_PROTOCOL_VERSION;
1016 /* If we require cookies and this ClientHello doesn't
1017 * contain one, just return since we do not want to
1018 * allocate any memory yet. So check cookie length...
1020 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1022 unsigned int session_length, cookie_length;
1024 session_length = *(p + SSL3_RANDOM_SIZE);
1025 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1027 if (cookie_length == 0)
1031 /* load the client random */
1032 memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1033 p+=SSL3_RANDOM_SIZE;
1035 /* get the session-id */
1039 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1040 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1041 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1042 * than a change to default behavior so that applications relying on this for security
1043 * won't even compile against older library versions).
1045 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1046 * renegotiation but not a new session (s->new_session remains unset): for servers,
1047 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1048 * setting will be ignored.
1050 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1052 if (!ssl_get_new_session(s,1))
1057 i=ssl_get_prev_session(s, p, j, d + n);
1059 * Only resume if the session's version matches the negotiated
1061 * RFC 5246 does not provide much useful advice on resumption
1062 * with a different protocol version. It doesn't forbid it but
1063 * the sanity of such behaviour would be questionable.
1064 * In practice, clients do not accept a version mismatch and
1065 * will abort the handshake with an error.
1067 if (i == 1 && s->version == s->session->ssl_version)
1068 { /* previous session */
1075 if (!ssl_get_new_session(s,1))
1085 cookie_len = *(p++);
1088 * The ClientHello may contain a cookie even if the
1089 * HelloVerify message has not been sent--make sure that it
1090 * does not cause an overflow.
1092 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1095 al = SSL_AD_DECODE_ERROR;
1096 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1100 /* verify the cookie if appropriate option is set. */
1101 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1104 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1106 if ( s->ctx->app_verify_cookie_cb != NULL)
1108 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1111 al=SSL_AD_HANDSHAKE_FAILURE;
1112 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1113 SSL_R_COOKIE_MISMATCH);
1116 /* else cookie verification succeeded */
1118 else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1119 s->d1->cookie_len) != 0) /* default verification */
1121 al=SSL_AD_HANDSHAKE_FAILURE;
1122 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1123 SSL_R_COOKIE_MISMATCH);
1126 /* Set to -2 so if successful we return 2 */
1131 if (s->method->version == DTLS_ANY_VERSION)
1133 /* Select version to use */
1134 if (s->client_version <= DTLS1_2_VERSION &&
1135 !(s->options & SSL_OP_NO_DTLSv1_2))
1137 s->version = DTLS1_2_VERSION;
1138 s->method = DTLSv1_2_server_method();
1140 else if (tls1_suiteb(s))
1142 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1143 s->version = s->client_version;
1144 al = SSL_AD_PROTOCOL_VERSION;
1147 else if (s->client_version <= DTLS1_VERSION &&
1148 !(s->options & SSL_OP_NO_DTLSv1))
1150 s->version = DTLS1_VERSION;
1151 s->method = DTLSv1_server_method();
1155 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1156 s->version = s->client_version;
1157 al = SSL_AD_PROTOCOL_VERSION;
1160 s->session->ssl_version = s->version;
1165 if ((i == 0) && (j != 0))
1167 /* we need a cipher if we are not resuming a session */
1168 al=SSL_AD_ILLEGAL_PARAMETER;
1169 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1174 /* not enough data */
1175 al=SSL_AD_DECODE_ERROR;
1176 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1179 if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1186 /* If it is a hit, check that the cipher is in the list */
1187 if ((s->hit) && (i > 0))
1190 id=s->session->cipher->id;
1193 fprintf(stderr,"client sent %d ciphers\n",sk_SSL_CIPHER_num(ciphers));
1195 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1197 c=sk_SSL_CIPHER_value(ciphers,i);
1199 fprintf(stderr,"client [%2d of %2d]:%s\n",
1200 i,sk_SSL_CIPHER_num(ciphers),
1201 SSL_CIPHER_get_name(c));
1209 /* Disabled because it can be used in a ciphersuite downgrade
1210 * attack: CVE-2010-4180.
1213 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1215 /* Special case as client bug workaround: the previously used cipher may
1216 * not be in the current list, the client instead might be trying to
1217 * continue using a cipher that before wasn't chosen due to server
1218 * preferences. We'll have to reject the connection if the cipher is not
1219 * enabled, though. */
1220 c = sk_SSL_CIPHER_value(ciphers, 0);
1221 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1223 s->session->cipher = c;
1230 /* we need to have the cipher in the cipher
1231 * list if we are asked to reuse it */
1232 al=SSL_AD_ILLEGAL_PARAMETER;
1233 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1242 /* not enough data */
1243 al=SSL_AD_DECODE_ERROR;
1244 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1247 #ifndef OPENSSL_NO_COMP
1252 if (p[j] == 0) break;
1259 al=SSL_AD_DECODE_ERROR;
1260 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1264 #ifndef OPENSSL_NO_TLSEXT
1266 if (s->version >= SSL3_VERSION)
1268 if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
1270 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1275 /* Check if we want to use external pre-shared secret for this
1276 * handshake for not reused session only. We need to generate
1277 * server_random before calling tls_session_secret_cb in order to allow
1278 * SessionTicket processing to use it in key derivation. */
1281 pos=s->s3->server_random;
1282 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1288 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1290 SSL_CIPHER *pref_cipher=NULL;
1292 s->session->master_key_length=sizeof(s->session->master_key);
1293 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1294 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1297 s->session->ciphers=ciphers;
1298 s->session->verify_result=X509_V_OK;
1302 /* check if some cipher was preferred by call back */
1303 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1304 if (pref_cipher == NULL)
1306 al=SSL_AD_HANDSHAKE_FAILURE;
1307 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1311 s->session->cipher=pref_cipher;
1314 sk_SSL_CIPHER_free(s->cipher_list);
1316 if (s->cipher_list_by_id)
1317 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1319 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1320 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1325 /* Worst case, we will use the NULL compression, but if we have other
1326 * options, we will now look for them. We have i-1 compression
1327 * algorithms from the client, starting at q. */
1328 s->s3->tmp.new_compression=NULL;
1329 #ifndef OPENSSL_NO_COMP
1330 /* This only happens if we have a cache hit */
1331 if (s->session->compress_meth != 0)
1333 int m, comp_id = s->session->compress_meth;
1334 /* Perform sanity checks on resumed compression algorithm */
1335 /* Can't disable compression */
1336 if (!ssl_allow_compression(s))
1338 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1341 /* Look for resumed compression method */
1342 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1344 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1345 if (comp_id == comp->id)
1347 s->s3->tmp.new_compression=comp;
1351 if (s->s3->tmp.new_compression == NULL)
1353 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1356 /* Look for resumed method in compression list */
1357 for (m = 0; m < i; m++)
1359 if (q[m] == comp_id)
1364 al=SSL_AD_ILLEGAL_PARAMETER;
1365 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1371 else if (ssl_allow_compression(s) && s->ctx->comp_methods)
1372 { /* See if we have a match */
1373 int m,nn,o,v,done=0;
1375 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1376 for (m=0; m<nn; m++)
1378 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1391 s->s3->tmp.new_compression=comp;
1396 /* If compression is disabled we'd better not try to resume a session
1397 * using compression.
1399 if (s->session->compress_meth != 0)
1401 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1406 /* Given s->session->ciphers and SSL_get_ciphers, we must
1411 #ifdef OPENSSL_NO_COMP
1412 s->session->compress_meth=0;
1414 s->session->compress_meth=(comp == NULL)?0:comp->id;
1416 if (s->session->ciphers != NULL)
1417 sk_SSL_CIPHER_free(s->session->ciphers);
1418 s->session->ciphers=ciphers;
1419 if (ciphers == NULL)
1421 al=SSL_AD_ILLEGAL_PARAMETER;
1422 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1426 if (!tls1_set_server_sigalgs(s))
1428 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1431 /* Let cert callback update server certificates if required */
1433 if (s->cert->cert_cb)
1435 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1438 al=SSL_AD_INTERNAL_ERROR;
1439 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
1444 s->rwstate=SSL_X509_LOOKUP;
1447 s->rwstate = SSL_NOTHING;
1449 c=ssl3_choose_cipher(s,s->session->ciphers,
1450 SSL_get_ciphers(s));
1454 al=SSL_AD_HANDSHAKE_FAILURE;
1455 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1458 s->s3->tmp.new_cipher=c;
1459 /* check whether we should disable session resumption */
1460 if (s->not_resumable_session_cb != NULL)
1461 s->session->not_resumable=s->not_resumable_session_cb(s,
1462 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1463 if (s->session->not_resumable)
1464 /* do not send a session ticket */
1465 s->tlsext_ticket_expected = 0;
1469 /* Session-id reuse */
1470 #ifdef REUSE_CIPHER_BUG
1471 STACK_OF(SSL_CIPHER) *sk;
1472 SSL_CIPHER *nc=NULL;
1473 SSL_CIPHER *ec=NULL;
1475 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1477 sk=s->session->ciphers;
1478 for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1480 c=sk_SSL_CIPHER_value(sk,i);
1481 if (c->algorithm_enc & SSL_eNULL)
1483 if (SSL_C_IS_EXPORT(c))
1487 s->s3->tmp.new_cipher=nc;
1488 else if (ec != NULL)
1489 s->s3->tmp.new_cipher=ec;
1491 s->s3->tmp.new_cipher=s->session->cipher;
1495 s->s3->tmp.new_cipher=s->session->cipher;
1498 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1500 if (!ssl3_digest_cached_records(s))
1505 * we now have the following setup.
1507 * cipher_list - our prefered list of ciphers
1508 * ciphers - the clients prefered list of ciphers
1509 * compression - basically ignored right now
1510 * ssl version is set - sslv3
1511 * s->session - The ssl session has been setup.
1512 * s->hit - session reuse flag
1513 * s->s3->tmp.new_cipher- the new cipher to use.
1516 /* Handles TLS extensions that we couldn't check earlier */
1517 if (s->version >= SSL3_VERSION)
1519 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1521 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1526 if (ret < 0) ret=-ret;
1530 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1533 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1534 return ret < 0 ? -1 : ret;
1537 int ssl3_send_server_hello(SSL *s)
1540 unsigned char *p,*d;
1545 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1547 buf=(unsigned char *)s->init_buf->data;
1548 #ifdef OPENSSL_NO_TLSEXT
1549 p=s->s3->server_random;
1550 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1553 /* Do the message type and length last */
1554 d=p= ssl_handshake_start(s);
1556 *(p++)=s->version>>8;
1557 *(p++)=s->version&0xff;
1560 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1561 p+=SSL3_RANDOM_SIZE;
1564 * There are several cases for the session ID to send
1565 * back in the server hello:
1566 * - For session reuse from the session cache,
1567 * we send back the old session ID.
1568 * - If stateless session reuse (using a session ticket)
1569 * is successful, we send back the client's "session ID"
1570 * (which doesn't actually identify the session).
1571 * - If it is a new session, we send back the new
1573 * - However, if we want the new session to be single-use,
1574 * we send back a 0-length session ID.
1575 * s->hit is non-zero in either case of session reuse,
1576 * so the following won't overwrite an ID that we're supposed
1579 if (s->session->not_resumable ||
1580 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1582 s->session->session_id_length=0;
1584 sl=s->session->session_id_length;
1585 if (sl > (int)sizeof(s->session->session_id))
1587 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1591 memcpy(p,s->session->session_id,sl);
1594 /* put the cipher */
1595 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1598 /* put the compression method */
1599 #ifdef OPENSSL_NO_COMP
1602 if (s->s3->tmp.new_compression == NULL)
1605 *(p++)=s->s3->tmp.new_compression->id;
1607 #ifndef OPENSSL_NO_TLSEXT
1608 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1610 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1613 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
1615 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1616 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1622 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1623 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1626 /* SSL3_ST_SW_SRVR_HELLO_B */
1627 return ssl_do_write(s);
1630 int ssl3_send_server_done(SSL *s)
1633 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1635 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1636 s->state = SSL3_ST_SW_SRVR_DONE_B;
1639 /* SSL3_ST_SW_SRVR_DONE_B */
1640 return ssl_do_write(s);
1643 int ssl3_send_server_key_exchange(SSL *s)
1645 #ifndef OPENSSL_NO_RSA
1649 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1652 #ifndef OPENSSL_NO_DH
1655 #ifndef OPENSSL_NO_ECDH
1656 EC_KEY *ecdh=NULL, *ecdhp;
1657 unsigned char *encodedPoint = NULL;
1660 BN_CTX *bn_ctx = NULL;
1663 const EVP_MD *md = NULL;
1664 unsigned char *p,*d;
1674 EVP_MD_CTX_init(&md_ctx);
1675 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1677 type=s->s3->tmp.new_cipher->algorithm_mkey;
1682 r[0]=r[1]=r[2]=r[3]=NULL;
1684 #ifndef OPENSSL_NO_RSA
1685 if (type & SSL_kRSA)
1688 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1690 rsa=s->cert->rsa_tmp_cb(s,
1691 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1692 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1695 al=SSL_AD_HANDSHAKE_FAILURE;
1696 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1704 al=SSL_AD_HANDSHAKE_FAILURE;
1705 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1710 s->s3->tmp.use_rsa_tmp=1;
1714 #ifndef OPENSSL_NO_DH
1715 if (type & SSL_kDHE)
1717 if (s->cert->dh_tmp_auto)
1719 dhp = ssl_get_auto_dh(s);
1722 al=SSL_AD_INTERNAL_ERROR;
1723 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1729 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1730 dhp=s->cert->dh_tmp_cb(s,
1731 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1732 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1735 al=SSL_AD_HANDSHAKE_FAILURE;
1736 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1739 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1740 DH_security_bits(dhp), 0, dhp))
1742 al=SSL_AD_HANDSHAKE_FAILURE;
1743 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
1746 if (s->s3->tmp.dh != NULL)
1748 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1752 if (s->cert->dh_tmp_auto)
1754 else if ((dh=DHparams_dup(dhp)) == NULL)
1756 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1761 if ((dhp->pub_key == NULL ||
1762 dhp->priv_key == NULL ||
1763 (s->options & SSL_OP_SINGLE_DH_USE)))
1765 if(!DH_generate_key(dh))
1767 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1774 dh->pub_key=BN_dup(dhp->pub_key);
1775 dh->priv_key=BN_dup(dhp->priv_key);
1776 if ((dh->pub_key == NULL) ||
1777 (dh->priv_key == NULL))
1779 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1789 #ifndef OPENSSL_NO_ECDH
1790 if (type & SSL_kECDHE)
1792 const EC_GROUP *group;
1794 ecdhp=cert->ecdh_tmp;
1795 if (s->cert->ecdh_tmp_auto)
1797 /* Get NID of appropriate shared curve */
1798 int nid = tls1_shared_curve(s, -2);
1799 if (nid != NID_undef)
1800 ecdhp = EC_KEY_new_by_curve_name(nid);
1802 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1804 ecdhp=s->cert->ecdh_tmp_cb(s,
1805 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1806 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1810 al=SSL_AD_HANDSHAKE_FAILURE;
1811 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1815 if (s->s3->tmp.ecdh != NULL)
1817 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1821 /* Duplicate the ECDH structure. */
1824 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1827 if (s->cert->ecdh_tmp_auto)
1829 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1831 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1835 s->s3->tmp.ecdh=ecdh;
1836 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1837 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1838 (s->options & SSL_OP_SINGLE_ECDH_USE))
1840 if(!EC_KEY_generate_key(ecdh))
1842 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1847 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1848 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1849 (EC_KEY_get0_private_key(ecdh) == NULL))
1851 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1855 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1856 (EC_GROUP_get_degree(group) > 163))
1858 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1862 /* XXX: For now, we only support ephemeral ECDH
1863 * keys over named (not generic) curves. For
1864 * supported named curves, curve_id is non-zero.
1867 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1870 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1874 /* Encode the public key.
1875 * First check the size of encoding and
1876 * allocate memory accordingly.
1878 encodedlen = EC_POINT_point2oct(group,
1879 EC_KEY_get0_public_key(ecdh),
1880 POINT_CONVERSION_UNCOMPRESSED,
1883 encodedPoint = (unsigned char *)
1884 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1885 bn_ctx = BN_CTX_new();
1886 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1888 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1893 encodedlen = EC_POINT_point2oct(group,
1894 EC_KEY_get0_public_key(ecdh),
1895 POINT_CONVERSION_UNCOMPRESSED,
1896 encodedPoint, encodedlen, bn_ctx);
1898 if (encodedlen == 0)
1900 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1904 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1906 /* XXX: For now, we only support named (not
1907 * generic) curves in ECDH ephemeral key exchanges.
1908 * In this situation, we need four additional bytes
1909 * to encode the entire ServerECDHParams
1914 /* We'll generate the serverKeyExchange message
1915 * explicitly so we can set these to NULLs
1923 #endif /* !OPENSSL_NO_ECDH */
1924 #ifndef OPENSSL_NO_PSK
1925 if (type & SSL_kPSK)
1927 /* reserve size for record length and PSK identity hint*/
1928 n+=2+strlen(s->ctx->psk_identity_hint);
1931 #endif /* !OPENSSL_NO_PSK */
1932 #ifndef OPENSSL_NO_SRP
1933 if (type & SSL_kSRP)
1935 if ((s->srp_ctx.N == NULL) ||
1936 (s->srp_ctx.g == NULL) ||
1937 (s->srp_ctx.s == NULL) ||
1938 (s->srp_ctx.B == NULL))
1940 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1951 al=SSL_AD_HANDSHAKE_FAILURE;
1952 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1955 for (i=0; i < 4 && r[i] != NULL; i++)
1957 nr[i]=BN_num_bytes(r[i]);
1958 #ifndef OPENSSL_NO_SRP
1959 if ((i == 2) && (type & SSL_kSRP))
1966 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1967 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1969 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1972 al=SSL_AD_DECODE_ERROR;
1975 kn=EVP_PKEY_size(pkey);
1983 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1985 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1988 d = p = ssl_handshake_start(s);
1990 for (i=0; i < 4 && r[i] != NULL; i++)
1992 #ifndef OPENSSL_NO_SRP
1993 if ((i == 2) && (type & SSL_kSRP))
2005 #ifndef OPENSSL_NO_ECDH
2006 if (type & SSL_kECDHE)
2008 /* XXX: For now, we only support named (not generic) curves.
2009 * In this situation, the serverKeyExchange message has:
2010 * [1 byte CurveType], [2 byte CurveName]
2011 * [1 byte length of encoded point], followed by
2012 * the actual encoded point itself
2014 *p = NAMED_CURVE_TYPE;
2022 memcpy((unsigned char*)p,
2023 (unsigned char *)encodedPoint,
2025 OPENSSL_free(encodedPoint);
2026 encodedPoint = NULL;
2031 #ifndef OPENSSL_NO_PSK
2032 if (type & SSL_kPSK)
2034 /* copy PSK identity hint */
2035 s2n(strlen(s->ctx->psk_identity_hint), p);
2036 strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
2037 p+=strlen(s->ctx->psk_identity_hint);
2044 /* n is the length of the params, they start at &(d[4])
2045 * and p points to the space at the end. */
2046 #ifndef OPENSSL_NO_RSA
2047 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
2051 for (num=2; num > 0; num--)
2053 EVP_MD_CTX_set_flags(&md_ctx,
2054 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2055 EVP_DigestInit_ex(&md_ctx,(num == 2)
2056 ?s->ctx->md5:s->ctx->sha1, NULL);
2057 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2058 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2059 EVP_DigestUpdate(&md_ctx,d,n);
2060 EVP_DigestFinal_ex(&md_ctx,q,
2061 (unsigned int *)&i);
2065 if (RSA_sign(NID_md5_sha1, md_buf, j,
2066 &(p[2]), &u, pkey->pkey.rsa) <= 0)
2068 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2078 /* send signature algorithm */
2079 if (SSL_USE_SIGALGS(s))
2081 if (!tls12_get_sigandhash(p, pkey, md))
2083 /* Should never happen */
2084 al=SSL_AD_INTERNAL_ERROR;
2085 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2091 fprintf(stderr, "Using hash %s\n",
2094 EVP_SignInit_ex(&md_ctx, md, NULL);
2095 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2096 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2097 EVP_SignUpdate(&md_ctx,d,n);
2098 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2099 (unsigned int *)&i,pkey))
2101 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2106 if (SSL_USE_SIGALGS(s))
2111 /* Is this error check actually needed? */
2112 al=SSL_AD_HANDSHAKE_FAILURE;
2113 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2118 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2121 s->state = SSL3_ST_SW_KEY_EXCH_B;
2122 EVP_MD_CTX_cleanup(&md_ctx);
2123 return ssl_do_write(s);
2125 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2127 #ifndef OPENSSL_NO_ECDH
2128 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2129 BN_CTX_free(bn_ctx);
2131 EVP_MD_CTX_cleanup(&md_ctx);
2135 int ssl3_send_certificate_request(SSL *s)
2137 unsigned char *p,*d;
2139 STACK_OF(X509_NAME) *sk=NULL;
2143 if (s->state == SSL3_ST_SW_CERT_REQ_A)
2147 d=p=ssl_handshake_start(s);
2149 /* get the list of acceptable cert types */
2151 n=ssl3_get_req_cert_type(s,p);
2156 if (SSL_USE_SIGALGS(s))
2158 const unsigned char *psigs;
2159 unsigned char *etmp = p;
2160 nl = tls12_get_psigalgs(s, &psigs);
2161 /* Skip over length for now */
2163 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2164 /* Now fill in length */
2174 sk=SSL_get_client_CA_list(s);
2178 for (i=0; i<sk_X509_NAME_num(sk); i++)
2180 name=sk_X509_NAME_value(sk,i);
2181 j=i2d_X509_NAME(name,NULL);
2182 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
2184 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2187 p = ssl_handshake_start(s) + n;
2188 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2191 i2d_X509_NAME(name,&p);
2198 i2d_X509_NAME(name,&p);
2199 j-=2; s2n(j,d); j+=2;
2205 /* else no CA names */
2206 p = ssl_handshake_start(s) + off;
2209 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2211 #ifdef NETSCAPE_HANG_BUG
2212 if (!SSL_IS_DTLS(s))
2214 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2216 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2219 p=(unsigned char *)s->init_buf->data + s->init_num;
2221 *(p++)=SSL3_MT_SERVER_DONE;
2229 s->state = SSL3_ST_SW_CERT_REQ_B;
2232 /* SSL3_ST_SW_CERT_REQ_B */
2233 return ssl_do_write(s);
2238 int ssl3_get_client_key_exchange(SSL *s)
2242 unsigned long alg_k;
2244 #ifndef OPENSSL_NO_RSA
2246 EVP_PKEY *pkey=NULL;
2248 #ifndef OPENSSL_NO_DH
2250 DH *dh_srvr, *dh_clnt = NULL;
2252 #ifndef OPENSSL_NO_KRB5
2254 #endif /* OPENSSL_NO_KRB5 */
2256 #ifndef OPENSSL_NO_ECDH
2257 EC_KEY *srvr_ecdh = NULL;
2258 EVP_PKEY *clnt_pub_pkey = NULL;
2259 EC_POINT *clnt_ecpoint = NULL;
2260 BN_CTX *bn_ctx = NULL;
2263 n=s->method->ssl_get_message(s,
2264 SSL3_ST_SR_KEY_EXCH_A,
2265 SSL3_ST_SR_KEY_EXCH_B,
2266 SSL3_MT_CLIENT_KEY_EXCHANGE,
2270 if (!ok) return((int)n);
2271 p=(unsigned char *)s->init_msg;
2273 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2275 #ifndef OPENSSL_NO_RSA
2276 if (alg_k & SSL_kRSA)
2278 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2280 unsigned char decrypt_good, version_good;
2283 /* FIX THIS UP EAY EAY EAY EAY */
2284 if (s->s3->tmp.use_rsa_tmp)
2286 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2287 rsa=s->cert->rsa_tmp;
2288 /* Don't do a callback because rsa_tmp should
2289 * be sent already */
2292 al=SSL_AD_HANDSHAKE_FAILURE;
2293 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2300 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2301 if ( (pkey == NULL) ||
2302 (pkey->type != EVP_PKEY_RSA) ||
2303 (pkey->pkey.rsa == NULL))
2305 al=SSL_AD_HANDSHAKE_FAILURE;
2306 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2312 /* TLS and [incidentally] DTLS{0xFEFF} */
2313 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2318 if (!(s->options & SSL_OP_TLS_D5_BUG))
2320 al = SSL_AD_DECODE_ERROR;
2321 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2332 * Reject overly short RSA ciphertext because we want to be sure
2333 * that the buffer size makes it safe to iterate over the entire
2334 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2335 * actual expected size is larger due to RSA padding, but the
2336 * bound is sufficient to be safe.
2338 if (n < SSL_MAX_MASTER_KEY_LENGTH)
2340 al = SSL_AD_DECRYPT_ERROR;
2341 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2345 /* We must not leak whether a decryption failure occurs because
2346 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2347 * RFC 2246, section 7.4.7.1). The code follows that advice of
2348 * the TLS RFC and generates a random premaster secret for the
2349 * case that the decrypt fails. See
2350 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2352 /* should be RAND_bytes, but we cannot work around a failure. */
2353 if (RAND_pseudo_bytes(rand_premaster_secret,
2354 sizeof(rand_premaster_secret)) <= 0)
2356 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2359 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2360 * decrypt_good will be 0xff if so and zero otherwise. */
2361 decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2363 /* If the version in the decrypted pre-master secret is correct
2364 * then version_good will be 0xff, otherwise it'll be zero.
2365 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2366 * (http://eprint.iacr.org/2003/052/) exploits the version
2367 * number check as a "bad version oracle". Thus version checks
2368 * are done in constant time and are treated like any other
2369 * decryption error. */
2370 version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2371 version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2373 /* The premaster secret must contain the same version number as
2374 * the ClientHello to detect version rollback attacks
2375 * (strangely, the protocol does not offer such protection for
2376 * DH ciphersuites). However, buggy clients exist that send the
2377 * negotiated protocol version instead if the server does not
2378 * support the requested protocol version. If
2379 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2380 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2382 unsigned char workaround_good;
2383 workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2384 workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2385 version_good |= workaround_good;
2388 /* Both decryption and version must be good for decrypt_good
2389 * to remain non-zero (0xff). */
2390 decrypt_good &= version_good;
2393 * Now copy rand_premaster_secret over from p using
2394 * decrypt_good_mask. If decryption failed, then p does not
2395 * contain valid plaintext, however, a check above guarantees
2396 * it is still sufficiently large to read from.
2398 for (j = 0; j < sizeof(rand_premaster_secret); j++)
2400 p[j] = constant_time_select_8(decrypt_good, p[j],
2401 rand_premaster_secret[j]);
2404 s->session->master_key_length=
2405 s->method->ssl3_enc->generate_master_secret(s,
2406 s->session->master_key,
2407 p,sizeof(rand_premaster_secret));
2408 OPENSSL_cleanse(p,sizeof(rand_premaster_secret));
2412 #ifndef OPENSSL_NO_DH
2413 if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
2416 EVP_PKEY *skey = NULL;
2423 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2425 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2434 if (alg_k & SSL_kDHr)
2435 idx = SSL_PKEY_DH_RSA;
2436 else if (alg_k & SSL_kDHd)
2437 idx = SSL_PKEY_DH_DSA;
2440 skey = s->cert->pkeys[idx].privatekey;
2441 if ((skey == NULL) ||
2442 (skey->type != EVP_PKEY_DH) ||
2443 (skey->pkey.dh == NULL))
2445 al=SSL_AD_HANDSHAKE_FAILURE;
2446 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2449 dh_srvr = skey->pkey.dh;
2451 else if (s->s3->tmp.dh == NULL)
2453 al=SSL_AD_HANDSHAKE_FAILURE;
2454 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2458 dh_srvr=s->s3->tmp.dh;
2462 /* Get pubkey from cert */
2463 EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2466 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2467 dh_clnt = EVP_PKEY_get1_DH(clkey);
2469 if (dh_clnt == NULL)
2471 al=SSL_AD_HANDSHAKE_FAILURE;
2472 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2475 EVP_PKEY_free(clkey);
2476 pub = dh_clnt->pub_key;
2479 pub=BN_bin2bn(p,i,NULL);
2482 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2486 i=DH_compute_key(p,pub,dh_srvr);
2490 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2495 DH_free(s->s3->tmp.dh);
2502 s->session->master_key_length=
2503 s->method->ssl3_enc->generate_master_secret(s,
2504 s->session->master_key,p,i);
2505 OPENSSL_cleanse(p,i);
2511 #ifndef OPENSSL_NO_KRB5
2512 if (alg_k & SSL_kKRB5)
2514 krb5_error_code krb5rc;
2515 krb5_data enc_ticket;
2516 krb5_data authenticator;
2518 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2519 EVP_CIPHER_CTX ciph_ctx;
2520 const EVP_CIPHER *enc = NULL;
2521 unsigned char iv[EVP_MAX_IV_LENGTH];
2522 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH
2523 + EVP_MAX_BLOCK_LENGTH];
2525 krb5_timestamp authtime = 0;
2526 krb5_ticket_times ttimes;
2528 EVP_CIPHER_CTX_init(&ciph_ctx);
2530 if (!kssl_ctx) kssl_ctx = kssl_ctx_new();
2533 enc_ticket.length = i;
2535 if (n < (long)(enc_ticket.length + 6))
2537 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2538 SSL_R_DATA_LENGTH_TOO_LONG);
2542 enc_ticket.data = (char *)p;
2543 p+=enc_ticket.length;
2546 authenticator.length = i;
2548 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2550 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2551 SSL_R_DATA_LENGTH_TOO_LONG);
2555 authenticator.data = (char *)p;
2556 p+=authenticator.length;
2560 enc_pms.data = (char *)p;
2563 /* Note that the length is checked again below,
2566 if(enc_pms.length > sizeof pms)
2568 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2569 SSL_R_DATA_LENGTH_TOO_LONG);
2573 if (n != (long)(enc_ticket.length + authenticator.length +
2574 enc_pms.length + 6))
2576 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2577 SSL_R_DATA_LENGTH_TOO_LONG);
2581 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2585 fprintf(stderr,"kssl_sget_tkt rtn %d [%d]\n",
2586 krb5rc, kssl_err.reason);
2588 fprintf(stderr,"kssl_err text= %s\n", kssl_err.text);
2589 #endif /* KSSL_DEBUG */
2590 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2595 /* Note: no authenticator is not considered an error,
2596 ** but will return authtime == 0.
2598 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2599 &authtime, &kssl_err)) != 0)
2602 fprintf(stderr,"kssl_check_authent rtn %d [%d]\n",
2603 krb5rc, kssl_err.reason);
2605 fprintf(stderr,"kssl_err text= %s\n", kssl_err.text);
2606 #endif /* KSSL_DEBUG */
2607 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2612 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2614 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2619 kssl_ctx_show(kssl_ctx);
2620 #endif /* KSSL_DEBUG */
2622 enc = kssl_map_enc(kssl_ctx->enctype);
2626 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2628 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2630 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2631 SSL_R_DECRYPTION_FAILED);
2634 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2635 (unsigned char *)enc_pms.data, enc_pms.length))
2637 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2638 SSL_R_DECRYPTION_FAILED);
2641 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2643 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2644 SSL_R_DATA_LENGTH_TOO_LONG);
2647 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2649 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2650 SSL_R_DECRYPTION_FAILED);
2654 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2656 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2657 SSL_R_DATA_LENGTH_TOO_LONG);
2660 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2662 /* The premaster secret must contain the same version number as the
2663 * ClientHello to detect version rollback attacks (strangely, the
2664 * protocol does not offer such protection for DH ciphersuites).
2665 * However, buggy clients exist that send random bytes instead of
2666 * the protocol version.
2667 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2668 * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2670 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2672 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2673 SSL_AD_DECODE_ERROR);
2678 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2680 s->session->master_key_length=
2681 s->method->ssl3_enc->generate_master_secret(s,
2682 s->session->master_key, pms, outl);
2684 if (kssl_ctx->client_princ)
2686 size_t len = strlen(kssl_ctx->client_princ);
2687 if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH )
2689 s->session->krb5_client_princ_len = len;
2690 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2695 /*- Was doing kssl_ctx_free() here,
2696 * but it caused problems for apache.
2697 * kssl_ctx = kssl_ctx_free(kssl_ctx);
2698 * if (s->kssl_ctx) s->kssl_ctx = NULL;
2702 #endif /* OPENSSL_NO_KRB5 */
2704 #ifndef OPENSSL_NO_ECDH
2705 if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
2710 const EC_GROUP *group;
2711 const BIGNUM *priv_key;
2713 /* initialize structures for server's ECDH key pair */
2714 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2716 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2717 ERR_R_MALLOC_FAILURE);
2721 /* Let's get server private key and group information */
2722 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2724 /* use the certificate */
2725 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2729 /* use the ephermeral values we saved when
2730 * generating the ServerKeyExchange msg.
2732 tkey = s->s3->tmp.ecdh;
2735 group = EC_KEY_get0_group(tkey);
2736 priv_key = EC_KEY_get0_private_key(tkey);
2738 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2739 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2741 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2746 /* Let's get client's public key */
2747 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2749 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2750 ERR_R_MALLOC_FAILURE);
2756 /* Client Publickey was in Client Certificate */
2758 if (alg_k & SSL_kECDHE)
2760 al=SSL_AD_HANDSHAKE_FAILURE;
2761 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2764 if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2766 (clnt_pub_pkey->type != EVP_PKEY_EC))
2768 /* XXX: For now, we do not support client
2769 * authentication using ECDH certificates
2770 * so this branch (n == 0L) of the code is
2771 * never executed. When that support is
2772 * added, we ought to ensure the key
2773 * received in the certificate is
2774 * authorized for key agreement.
2775 * ECDH_compute_key implicitly checks that
2776 * the two ECDH shares are for the same
2779 al=SSL_AD_HANDSHAKE_FAILURE;
2780 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2781 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2785 if (EC_POINT_copy(clnt_ecpoint,
2786 EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2788 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2792 ret = 2; /* Skip certificate verify processing */
2796 /* Get client's public key from encoded point
2797 * in the ClientKeyExchange message.
2799 if ((bn_ctx = BN_CTX_new()) == NULL)
2801 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2802 ERR_R_MALLOC_FAILURE);
2806 /* Get encoded point length */
2811 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2815 if (EC_POINT_oct2point(group,
2816 clnt_ecpoint, p, i, bn_ctx) == 0)
2818 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2822 /* p is pointing to somewhere in the buffer
2823 * currently, so set it to the start
2825 p=(unsigned char *)s->init_buf->data;
2828 /* Compute the shared pre-master secret */
2829 field_size = EC_GROUP_get_degree(group);
2830 if (field_size <= 0)
2832 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2836 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2839 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2844 EVP_PKEY_free(clnt_pub_pkey);
2845 EC_POINT_free(clnt_ecpoint);
2846 EC_KEY_free(srvr_ecdh);
2847 BN_CTX_free(bn_ctx);
2848 EC_KEY_free(s->s3->tmp.ecdh);
2849 s->s3->tmp.ecdh = NULL;
2851 /* Compute the master secret */
2852 s->session->master_key_length = s->method->ssl3_enc-> \
2853 generate_master_secret(s, s->session->master_key, p, i);
2855 OPENSSL_cleanse(p, i);
2860 #ifndef OPENSSL_NO_PSK
2861 if (alg_k & SSL_kPSK)
2863 unsigned char *t = NULL;
2864 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2865 unsigned int pre_ms_len = 0, psk_len = 0;
2867 char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2869 al=SSL_AD_HANDSHAKE_FAILURE;
2874 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2875 SSL_R_LENGTH_MISMATCH);
2878 if (i > PSK_MAX_IDENTITY_LEN)
2880 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2881 SSL_R_DATA_LENGTH_TOO_LONG);
2884 if (s->psk_server_callback == NULL)
2886 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2887 SSL_R_PSK_NO_SERVER_CB);
2891 /* Create guaranteed NULL-terminated identity
2892 * string for the callback */
2893 memcpy(tmp_id, p, i);
2894 memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2895 psk_len = s->psk_server_callback(s, tmp_id,
2896 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2897 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2899 if (psk_len > PSK_MAX_PSK_LEN)
2901 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2902 ERR_R_INTERNAL_ERROR);
2905 else if (psk_len == 0)
2907 /* PSK related to the given identity not found */
2908 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2909 SSL_R_PSK_IDENTITY_NOT_FOUND);
2910 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2914 /* create PSK pre_master_secret */
2915 pre_ms_len=2+psk_len+2+psk_len;
2917 memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2919 memset(t, 0, psk_len);
2923 if (s->session->psk_identity != NULL)
2924 OPENSSL_free(s->session->psk_identity);
2925 s->session->psk_identity = BUF_strdup((char *)p);
2926 if (s->session->psk_identity == NULL)
2928 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2929 ERR_R_MALLOC_FAILURE);
2933 if (s->session->psk_identity_hint != NULL)
2934 OPENSSL_free(s->session->psk_identity_hint);
2935 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2936 if (s->ctx->psk_identity_hint != NULL &&
2937 s->session->psk_identity_hint == NULL)
2939 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2940 ERR_R_MALLOC_FAILURE);
2944 s->session->master_key_length=
2945 s->method->ssl3_enc->generate_master_secret(s,
2946 s->session->master_key, psk_or_pre_ms, pre_ms_len);
2949 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2955 #ifndef OPENSSL_NO_SRP
2956 if (alg_k & SSL_kSRP)
2964 al=SSL_AD_DECODE_ERROR;
2965 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2968 if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2970 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2973 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2974 || BN_is_zero(s->srp_ctx.A))
2976 al=SSL_AD_ILLEGAL_PARAMETER;
2977 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
2980 if (s->session->srp_username != NULL)
2981 OPENSSL_free(s->session->srp_username);
2982 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2983 if (s->session->srp_username == NULL)
2985 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2986 ERR_R_MALLOC_FAILURE);
2990 if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2992 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2999 #endif /* OPENSSL_NO_SRP */
3000 if (alg_k & SSL_kGOST)
3003 EVP_PKEY_CTX *pkey_ctx;
3004 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3005 unsigned char premaster_secret[32], *start;
3006 size_t outlen=32, inlen;
3007 unsigned long alg_a;
3011 /* Get our certificate private key*/
3012 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3013 if (alg_a & SSL_aGOST94)
3014 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
3015 else if (alg_a & SSL_aGOST01)
3016 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3018 pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
3019 EVP_PKEY_decrypt_init(pkey_ctx);
3020 /* If client certificate is present and is of the same type, maybe
3021 * use it for key exchange. Don't mind errors from
3022 * EVP_PKEY_derive_set_peer, because it is completely valid to use
3023 * a client certificate for authorization only. */
3024 client_pub_pkey = X509_get_pubkey(s->session->peer);
3025 if (client_pub_pkey)
3027 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3030 /* Decrypt session key */
3031 if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED ||
3032 Ttag != V_ASN1_SEQUENCE ||
3033 Tclass != V_ASN1_UNIVERSAL)
3035 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
3040 if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0)
3043 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
3046 /* Generate master secret */
3047 s->session->master_key_length=
3048 s->method->ssl3_enc->generate_master_secret(s,
3049 s->session->master_key,premaster_secret,32);
3050 /* Check if pubkey from client certificate was used */
3051 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3056 EVP_PKEY_free(client_pub_pkey);
3057 EVP_PKEY_CTX_free(pkey_ctx);
3065 al=SSL_AD_HANDSHAKE_FAILURE;
3066 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
3067 SSL_R_UNKNOWN_CIPHER_TYPE);
3073 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3074 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3077 #ifndef OPENSSL_NO_ECDH
3078 EVP_PKEY_free(clnt_pub_pkey);
3079 EC_POINT_free(clnt_ecpoint);
3080 if (srvr_ecdh != NULL)
3081 EC_KEY_free(srvr_ecdh);
3082 BN_CTX_free(bn_ctx);
3087 int ssl3_get_cert_verify(SSL *s)
3089 EVP_PKEY *pkey=NULL;
3095 const EVP_MD *md = NULL;
3097 EVP_MD_CTX_init(&mctx);
3099 n=s->method->ssl_get_message(s,
3100 SSL3_ST_SR_CERT_VRFY_A,
3101 SSL3_ST_SR_CERT_VRFY_B,
3103 SSL3_RT_MAX_PLAIN_LENGTH,
3106 if (!ok) return((int)n);
3108 if (s->session->peer != NULL)
3110 peer=s->session->peer;
3111 pkey=X509_get_pubkey(peer);
3112 type=X509_certificate_type(peer,pkey);
3120 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3122 s->s3->tmp.reuse_message=1;
3123 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3125 al=SSL_AD_UNEXPECTED_MESSAGE;
3126 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3135 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3136 al=SSL_AD_UNEXPECTED_MESSAGE;
3140 if (!(type & EVP_PKT_SIGN))
3142 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3143 al=SSL_AD_ILLEGAL_PARAMETER;
3147 if (s->s3->change_cipher_spec)
3149 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3150 al=SSL_AD_UNEXPECTED_MESSAGE;
3154 /* we now have a signature that we need to verify */
3155 p=(unsigned char *)s->init_msg;
3156 /* Check for broken implementations of GOST ciphersuites */
3157 /* If key is GOST and n is exactly 64, it is bare
3158 * signature without length field */
3159 if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3160 pkey->type == NID_id_GostR3410_2001) )
3166 if (SSL_USE_SIGALGS(s))
3168 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3171 al = SSL_AD_INTERNAL_ERROR;
3176 al = SSL_AD_DECODE_ERROR;
3180 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3189 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3190 al=SSL_AD_DECODE_ERROR;
3194 j=EVP_PKEY_size(pkey);
3195 if ((i > j) || (n > j) || (n <= 0))
3197 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3198 al=SSL_AD_DECODE_ERROR;
3202 if (SSL_USE_SIGALGS(s))
3206 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3209 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3210 al=SSL_AD_INTERNAL_ERROR;
3214 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3217 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3218 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3220 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3221 al=SSL_AD_INTERNAL_ERROR;
3225 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3227 al=SSL_AD_DECRYPT_ERROR;
3228 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3233 #ifndef OPENSSL_NO_RSA
3234 if (pkey->type == EVP_PKEY_RSA)
3236 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3237 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
3241 al=SSL_AD_DECRYPT_ERROR;
3242 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3247 al=SSL_AD_DECRYPT_ERROR;
3248 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3254 #ifndef OPENSSL_NO_DSA
3255 if (pkey->type == EVP_PKEY_DSA)
3257 j=DSA_verify(pkey->save_type,
3258 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3259 SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3263 al=SSL_AD_DECRYPT_ERROR;
3264 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3270 #ifndef OPENSSL_NO_ECDSA
3271 if (pkey->type == EVP_PKEY_EC)
3273 j=ECDSA_verify(pkey->save_type,
3274 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3275 SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3279 al=SSL_AD_DECRYPT_ERROR;
3280 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3281 SSL_R_BAD_ECDSA_SIGNATURE);
3287 if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3288 { unsigned char signature[64];
3290 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3291 EVP_PKEY_verify_init(pctx);
3293 fprintf(stderr,"GOST signature length is %d",i);
3295 for (idx=0;idx<64;idx++) {
3296 signature[63-idx]=p[idx];
3298 j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3299 EVP_PKEY_CTX_free(pctx);
3302 al=SSL_AD_DECRYPT_ERROR;
3303 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3304 SSL_R_BAD_ECDSA_SIGNATURE);
3310 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3311 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3320 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3323 if (s->s3->handshake_buffer)
3325 BIO_free(s->s3->handshake_buffer);
3326 s->s3->handshake_buffer = NULL;
3327 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3329 EVP_MD_CTX_cleanup(&mctx);
3330 EVP_PKEY_free(pkey);
3334 int ssl3_get_client_certificate(SSL *s)
3336 int i,ok,al,ret= -1;
3338 unsigned long l,nc,llen,n;
3339 const unsigned char *p,*q;
3341 STACK_OF(X509) *sk=NULL;
3343 n=s->method->ssl_get_message(s,
3350 if (!ok) return((int)n);
3352 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3354 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
3355 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3357 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3358 al=SSL_AD_HANDSHAKE_FAILURE;
3361 /* If tls asked for a client cert, the client must return a 0 list */
3362 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3364 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3365 al=SSL_AD_UNEXPECTED_MESSAGE;
3368 s->s3->tmp.reuse_message=1;
3372 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3374 al=SSL_AD_UNEXPECTED_MESSAGE;
3375 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3378 p=d=(unsigned char *)s->init_msg;
3380 if ((sk=sk_X509_new_null()) == NULL)
3382 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3389 al=SSL_AD_DECODE_ERROR;
3390 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3393 for (nc=0; nc<llen; )
3396 if ((l+nc+3) > llen)
3398 al=SSL_AD_DECODE_ERROR;
3399 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3404 x=d2i_X509(NULL,&p,l);
3407 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3412 al=SSL_AD_DECODE_ERROR;
3413 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3416 if (!sk_X509_push(sk,x))
3418 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3425 if (sk_X509_num(sk) <= 0)
3427 /* TLS does not mind 0 certs returned */
3428 if (s->version == SSL3_VERSION)
3430 al=SSL_AD_HANDSHAKE_FAILURE;
3431 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3434 /* Fail for TLS only if we required a certificate */
3435 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3436 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3438 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3439 al=SSL_AD_HANDSHAKE_FAILURE;
3442 /* No client certificate so digest cached records */
3443 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3445 al=SSL_AD_INTERNAL_ERROR;
3452 i=ssl_verify_cert_chain(s,sk);
3455 al=ssl_verify_alarm_type(s->verify_result);
3456 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3461 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3462 al = SSL_AD_HANDSHAKE_FAILURE;
3465 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3468 al=SSL3_AD_HANDSHAKE_FAILURE;
3469 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3470 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3473 EVP_PKEY_free(pkey);
3476 if (s->session->peer != NULL) /* This should not be needed */
3477 X509_free(s->session->peer);
3478 s->session->peer=sk_X509_shift(sk);
3479 s->session->verify_result = s->verify_result;
3481 /* With the current implementation, sess_cert will always be NULL
3482 * when we arrive here. */
3483 if (s->session->sess_cert == NULL)
3485 s->session->sess_cert = ssl_sess_cert_new();
3486 if (s->session->sess_cert == NULL)
3488 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3492 if (s->session->sess_cert->cert_chain != NULL)
3493 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3494 s->session->sess_cert->cert_chain=sk;
3495 /* Inconsistency alert: cert_chain does *not* include the
3496 * peer's own certificate, while we do include it in s3_clnt.c */
3504 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3507 if (x != NULL) X509_free(x);
3508 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3512 int ssl3_send_server_certificate(SSL *s)
3516 if (s->state == SSL3_ST_SW_CERT_A)
3518 cpk=ssl_get_server_send_pkey(s);
3521 /* VRS: allow null cert if auth == KRB5 */
3522 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3523 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3525 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3530 if (!ssl3_output_cert_chain(s,cpk))
3532 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3535 s->state=SSL3_ST_SW_CERT_B;
3538 /* SSL3_ST_SW_CERT_B */
3539 return ssl_do_write(s);
3542 #ifndef OPENSSL_NO_TLSEXT
3543 /* send a new session ticket (not necessarily for a new session) */
3544 int ssl3_send_newsession_ticket(SSL *s)
3546 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3548 unsigned char *p, *senc, *macstart;
3549 const unsigned char *const_p;
3550 int len, slen_full, slen;
3555 SSL_CTX *tctx = s->initial_ctx;
3556 unsigned char iv[EVP_MAX_IV_LENGTH];
3557 unsigned char key_name[16];
3559 /* get session encoding length */
3560 slen_full = i2d_SSL_SESSION(s->session, NULL);
3561 /* Some length values are 16 bits, so forget it if session is
3564 if (slen_full > 0xFF00)
3566 senc = OPENSSL_malloc(slen_full);
3570 i2d_SSL_SESSION(s->session, &p);
3572 /* create a fresh copy (not shared with other threads) to clean up */
3574 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3580 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3582 slen = i2d_SSL_SESSION(sess, NULL);
3583 if (slen > slen_full) /* shouldn't ever happen */
3589 i2d_SSL_SESSION(sess, &p);
3590 SSL_SESSION_free(sess);
3593 * Grow buffer if need be: the length calculation is as
3594 * follows handshake_header_length +
3595 * 4 (ticket lifetime hint) + 2 (ticket length) +
3596 * 16 (key name) + max_iv_len (iv length) +
3597 * session_length + max_enc_block_size (max encrypted session
3598 * length) + max_md_size (HMAC).
3600 if (!BUF_MEM_grow(s->init_buf,
3601 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3602 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3604 p = ssl_handshake_start(s);
3605 EVP_CIPHER_CTX_init(&ctx);
3606 HMAC_CTX_init(&hctx);
3607 /* Initialize HMAC and cipher contexts. If callback present
3608 * it does all the work otherwise use generated values
3611 if (tctx->tlsext_ticket_key_cb)
3613 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3622 RAND_pseudo_bytes(iv, 16);
3623 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3624 tctx->tlsext_tick_aes_key, iv);
3625 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3626 tlsext_tick_md(), NULL);
3627 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3630 /* Ticket lifetime hint (advisory only):
3631 * We leave this unspecified for resumed session (for simplicity),
3632 * and guess that tickets for new sessions will live as long
3633 * as their sessions. */
3634 l2n(s->hit ? 0 : s->session->timeout, p);
3636 /* Skip ticket length for now */
3638 /* Output key name */
3640 memcpy(p, key_name, 16);
3643 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3644 p += EVP_CIPHER_CTX_iv_length(&ctx);
3645 /* Encrypt session data */
3646 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3648 EVP_EncryptFinal(&ctx, p, &len);
3650 EVP_CIPHER_CTX_cleanup(&ctx);
3652 HMAC_Update(&hctx, macstart, p - macstart);
3653 HMAC_Final(&hctx, p, &hlen);
3654 HMAC_CTX_cleanup(&hctx);
3657 /* Now write out lengths: p points to end of data written */
3659 len = p - ssl_handshake_start(s);
3660 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3661 /* Skip ticket lifetime hint */
3662 p = ssl_handshake_start(s) + 4;
3664 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3668 /* SSL3_ST_SW_SESSION_TICKET_B */
3669 return ssl_do_write(s);
3672 int ssl3_send_cert_status(SSL *s)
3674 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3678 * Grow buffer if need be: the length calculation is as
3679 * follows 1 (message type) + 3 (message length) +
3680 * 1 (ocsp response type) + 3 (ocsp response length)
3683 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3686 p=(unsigned char *)s->init_buf->data;
3689 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3690 /* message length */
3691 l2n3(s->tlsext_ocsp_resplen + 4, p);
3693 *(p++)= s->tlsext_status_type;
3694 /* length of OCSP response */
3695 l2n3(s->tlsext_ocsp_resplen, p);
3696 /* actual response */
3697 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3698 /* number of bytes to write */
3699 s->init_num = 8 + s->tlsext_ocsp_resplen;
3700 s->state=SSL3_ST_SW_CERT_STATUS_B;
3704 /* SSL3_ST_SW_CERT_STATUS_B */
3705 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3708 # ifndef OPENSSL_NO_NEXTPROTONEG
3709 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3710 * sets the next_proto member in s if found */
3711 int ssl3_get_next_proto(SSL *s)
3714 int proto_len, padding_len;
3716 const unsigned char *p;
3718 /* Clients cannot send a NextProtocol message if we didn't see the
3719 * extension in their ClientHello */
3720 if (!s->s3->next_proto_neg_seen)
3722 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3726 n=s->method->ssl_get_message(s,
3727 SSL3_ST_SR_NEXT_PROTO_A,
3728 SSL3_ST_SR_NEXT_PROTO_B,
3730 514, /* See the payload format below */
3736 /* s->state doesn't reflect whether ChangeCipherSpec has been received
3737 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3738 * by ssl3_get_finished). */
3739 if (!s->s3->change_cipher_spec)
3741 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3746 return 0; /* The body must be > 1 bytes long */
3748 p=(unsigned char *)s->init_msg;
3751 * The payload looks like:
3753 * uint8 proto[proto_len];
3754 * uint8 padding_len;
3755 * uint8 padding[padding_len];
3758 if (proto_len + 2 > s->init_num)
3760 padding_len = p[proto_len + 1];
3761 if (proto_len + padding_len + 2 != s->init_num)
3764 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3765 if (!s->next_proto_negotiated)
3767 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3770 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3771 s->next_proto_negotiated_len = proto_len;