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))
303 if (!ssl3_setup_buffers(s))
310 s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
311 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
313 if (s->state != SSL_ST_RENEGOTIATE)
315 /* Ok, we now need to push on a buffering BIO so that
316 * the output is sent in a way that TCP likes :-)
318 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
320 ssl3_init_finished_mac(s);
321 s->state=SSL3_ST_SR_CLNT_HELLO_A;
322 s->ctx->stats.sess_accept++;
324 else if (!s->s3->send_connection_binding &&
325 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
327 /* Server attempting to renegotiate with
328 * client that doesn't support secure
331 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
332 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
338 /* s->state == SSL_ST_RENEGOTIATE,
339 * we will just send a HelloRequest */
340 s->ctx->stats.sess_accept_renegotiate++;
341 s->state=SSL3_ST_SW_HELLO_REQ_A;
345 case SSL3_ST_SW_HELLO_REQ_A:
346 case SSL3_ST_SW_HELLO_REQ_B:
349 ret=ssl3_send_hello_request(s);
350 if (ret <= 0) goto end;
351 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
352 s->state=SSL3_ST_SW_FLUSH;
355 ssl3_init_finished_mac(s);
358 case SSL3_ST_SW_HELLO_REQ_C:
362 case SSL3_ST_SR_CLNT_HELLO_A:
363 case SSL3_ST_SR_CLNT_HELLO_B:
364 case SSL3_ST_SR_CLNT_HELLO_C:
366 ret=ssl3_get_client_hello(s);
367 if (ret <= 0) goto end;
368 #ifndef OPENSSL_NO_SRP
369 s->state = SSL3_ST_SR_CLNT_HELLO_D;
370 case SSL3_ST_SR_CLNT_HELLO_D:
373 if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
375 /* callback indicates firther work to be done */
376 s->rwstate=SSL_X509_LOOKUP;
379 if (ret != SSL_ERROR_NONE)
381 ssl3_send_alert(s,SSL3_AL_FATAL,al);
382 /* This is not really an error but the only means to
383 for a client to detect whether srp is supported. */
384 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
385 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
386 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
394 s->state=SSL3_ST_SW_SRVR_HELLO_A;
398 case SSL3_ST_SW_SRVR_HELLO_A:
399 case SSL3_ST_SW_SRVR_HELLO_B:
400 ret=ssl3_send_server_hello(s);
401 if (ret <= 0) goto end;
402 #ifndef OPENSSL_NO_TLSEXT
405 if (s->tlsext_ticket_expected)
406 s->state=SSL3_ST_SW_SESSION_TICKET_A;
408 s->state=SSL3_ST_SW_CHANGE_A;
412 s->state=SSL3_ST_SW_CHANGE_A;
415 s->state = SSL3_ST_SW_CERT_A;
419 case SSL3_ST_SW_CERT_A:
420 case SSL3_ST_SW_CERT_B:
421 /* Check if it is anon DH or anon ECDH, */
422 /* normal PSK or KRB5 or SRP */
423 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
424 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
426 ret=ssl3_send_server_certificate(s);
427 if (ret <= 0) goto end;
428 #ifndef OPENSSL_NO_TLSEXT
429 if (s->tlsext_status_expected)
430 s->state=SSL3_ST_SW_CERT_STATUS_A;
432 s->state=SSL3_ST_SW_KEY_EXCH_A;
437 s->state=SSL3_ST_SW_KEY_EXCH_A;
444 s->state=SSL3_ST_SW_KEY_EXCH_A;
449 case SSL3_ST_SW_KEY_EXCH_A:
450 case SSL3_ST_SW_KEY_EXCH_B:
451 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
453 /* clear this, it may get reset by
454 * send_server_key_exchange */
455 if ((s->options & SSL_OP_EPHEMERAL_RSA)
456 #ifndef OPENSSL_NO_KRB5
457 && !(alg_k & SSL_kKRB5)
458 #endif /* OPENSSL_NO_KRB5 */
460 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
461 * even when forbidden by protocol specs
462 * (handshake may fail as clients are not required to
463 * be able to handle this) */
464 s->s3->tmp.use_rsa_tmp=1;
466 s->s3->tmp.use_rsa_tmp=0;
469 /* only send if a DH key exchange, fortezza or
470 * RSA but we have a sign only certificate
472 * PSK: may send PSK identity hints
474 * For ECC ciphersuites, we send a serverKeyExchange
475 * message only if the cipher suite is either
476 * ECDH-anon or ECDHE. In other cases, the
477 * server certificate contains the server's
478 * public key for key exchange.
480 if (s->s3->tmp.use_rsa_tmp
481 /* PSK: send ServerKeyExchange if PSK identity
482 * hint if provided */
483 #ifndef OPENSSL_NO_PSK
484 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
486 #ifndef OPENSSL_NO_SRP
487 /* SRP: send ServerKeyExchange */
488 || (alg_k & SSL_kSRP)
490 || (alg_k & SSL_kDHE)
491 || (alg_k & SSL_kECDHE)
492 || ((alg_k & SSL_kRSA)
493 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
494 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
495 && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
501 ret=ssl3_send_server_key_exchange(s);
502 if (ret <= 0) goto end;
507 s->state=SSL3_ST_SW_CERT_REQ_A;
511 case SSL3_ST_SW_CERT_REQ_A:
512 case SSL3_ST_SW_CERT_REQ_B:
513 if (/* don't request cert unless asked for it: */
514 !(s->verify_mode & SSL_VERIFY_PEER) ||
515 /* if SSL_VERIFY_CLIENT_ONCE is set,
516 * don't request cert during re-negotiation: */
517 ((s->session->peer != NULL) &&
518 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
519 /* never request cert in anonymous ciphersuites
520 * (see section "Certificate request" in SSL 3 drafts
521 * and in RFC 2246): */
522 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
523 /* ... except when the application insists on verification
524 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
525 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
526 /* never request cert in Kerberos ciphersuites */
527 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
528 /* don't request certificate for SRP auth */
529 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
530 /* With normal PSK Certificates and
531 * Certificate Requests are omitted */
532 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
534 /* no cert request */
536 s->s3->tmp.cert_request=0;
537 s->state=SSL3_ST_SW_SRVR_DONE_A;
538 if (s->s3->handshake_buffer)
539 if (!ssl3_digest_cached_records(s))
544 s->s3->tmp.cert_request=1;
545 ret=ssl3_send_certificate_request(s);
546 if (ret <= 0) goto end;
547 #ifndef NETSCAPE_HANG_BUG
548 s->state=SSL3_ST_SW_SRVR_DONE_A;
550 s->state=SSL3_ST_SW_FLUSH;
551 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
557 case SSL3_ST_SW_SRVR_DONE_A:
558 case SSL3_ST_SW_SRVR_DONE_B:
559 ret=ssl3_send_server_done(s);
560 if (ret <= 0) goto end;
561 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
562 s->state=SSL3_ST_SW_FLUSH;
566 case SSL3_ST_SW_FLUSH:
568 /* This code originally checked to see if
569 * any data was pending using BIO_CTRL_INFO
570 * and then flushed. This caused problems
571 * as documented in PR#1939. The proposed
572 * fix doesn't completely resolve this issue
573 * as buggy implementations of BIO_CTRL_PENDING
574 * still exist. So instead we just flush
578 s->rwstate=SSL_WRITING;
579 if (BIO_flush(s->wbio) <= 0)
584 s->rwstate=SSL_NOTHING;
586 s->state=s->s3->tmp.next_state;
589 case SSL3_ST_SR_CERT_A:
590 case SSL3_ST_SR_CERT_B:
591 /* Check for second client hello (MS SGC) */
592 ret = ssl3_check_client_hello(s);
596 s->state = SSL3_ST_SR_CLNT_HELLO_C;
598 if (s->s3->tmp.cert_request)
600 ret=ssl3_get_client_certificate(s);
601 if (ret <= 0) goto end;
604 s->state=SSL3_ST_SR_KEY_EXCH_A;
608 case SSL3_ST_SR_KEY_EXCH_A:
609 case SSL3_ST_SR_KEY_EXCH_B:
610 ret=ssl3_get_client_key_exchange(s);
615 /* For the ECDH ciphersuites when
616 * the client sends its ECDH pub key in
617 * a certificate, the CertificateVerify
618 * message is not sent.
619 * Also for GOST ciphersuites when
620 * the client uses its key from the certificate
623 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
624 s->state=SSL3_ST_SR_FINISHED_A;
626 if (s->s3->next_proto_neg_seen)
627 s->state=SSL3_ST_SR_NEXT_PROTO_A;
629 s->state=SSL3_ST_SR_FINISHED_A;
633 else if (SSL_USE_SIGALGS(s))
635 s->state=SSL3_ST_SR_CERT_VRFY_A;
637 if (!s->session->peer)
639 /* For sigalgs freeze the handshake buffer
640 * at this point and digest cached records.
642 if (!s->s3->handshake_buffer)
644 SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
647 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
648 if (!ssl3_digest_cached_records(s))
656 s->state=SSL3_ST_SR_CERT_VRFY_A;
659 /* We need to get hashes here so if there is
660 * a client cert, it can be verified
661 * FIXME - digest processing for CertificateVerify
662 * should be generalized. But it is next step
664 if (s->s3->handshake_buffer)
665 if (!ssl3_digest_cached_records(s))
667 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
668 if (s->s3->handshake_dgst[dgst_num])
672 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]));
673 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
684 case SSL3_ST_SR_CERT_VRFY_A:
685 case SSL3_ST_SR_CERT_VRFY_B:
687 s->s3->flags |= SSL3_FLAGS_CCS_OK;
688 /* we should decide if we expected this one */
689 ret=ssl3_get_cert_verify(s);
690 if (ret <= 0) goto end;
692 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
693 s->state=SSL3_ST_SR_FINISHED_A;
695 if (s->s3->next_proto_neg_seen)
696 s->state=SSL3_ST_SR_NEXT_PROTO_A;
698 s->state=SSL3_ST_SR_FINISHED_A;
703 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
704 case SSL3_ST_SR_NEXT_PROTO_A:
705 case SSL3_ST_SR_NEXT_PROTO_B:
706 ret=ssl3_get_next_proto(s);
707 if (ret <= 0) goto end;
709 s->state=SSL3_ST_SR_FINISHED_A;
713 case SSL3_ST_SR_FINISHED_A:
714 case SSL3_ST_SR_FINISHED_B:
715 s->s3->flags |= SSL3_FLAGS_CCS_OK;
716 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
717 SSL3_ST_SR_FINISHED_B);
718 if (ret <= 0) goto end;
721 #ifndef OPENSSL_NO_TLSEXT
722 else if (s->tlsext_ticket_expected)
723 s->state=SSL3_ST_SW_SESSION_TICKET_A;
726 s->state=SSL3_ST_SW_CHANGE_A;
730 #ifndef OPENSSL_NO_TLSEXT
731 case SSL3_ST_SW_SESSION_TICKET_A:
732 case SSL3_ST_SW_SESSION_TICKET_B:
733 ret=ssl3_send_newsession_ticket(s);
734 if (ret <= 0) goto end;
735 s->state=SSL3_ST_SW_CHANGE_A;
739 case SSL3_ST_SW_CERT_STATUS_A:
740 case SSL3_ST_SW_CERT_STATUS_B:
741 ret=ssl3_send_cert_status(s);
742 if (ret <= 0) goto end;
743 s->state=SSL3_ST_SW_KEY_EXCH_A;
749 case SSL3_ST_SW_CHANGE_A:
750 case SSL3_ST_SW_CHANGE_B:
752 s->session->cipher=s->s3->tmp.new_cipher;
753 if (!s->method->ssl3_enc->setup_key_block(s))
754 { ret= -1; goto end; }
756 ret=ssl3_send_change_cipher_spec(s,
757 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
759 if (ret <= 0) goto end;
760 s->state=SSL3_ST_SW_FINISHED_A;
763 if (!s->method->ssl3_enc->change_cipher_state(s,
764 SSL3_CHANGE_CIPHER_SERVER_WRITE))
772 case SSL3_ST_SW_FINISHED_A:
773 case SSL3_ST_SW_FINISHED_B:
774 ret=ssl3_send_finished(s,
775 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
776 s->method->ssl3_enc->server_finished_label,
777 s->method->ssl3_enc->server_finished_label_len);
778 if (ret <= 0) goto end;
779 s->state=SSL3_ST_SW_FLUSH;
782 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
783 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
785 if (s->s3->next_proto_neg_seen)
787 s->s3->flags |= SSL3_FLAGS_CCS_OK;
788 s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
791 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
795 s->s3->tmp.next_state=SSL_ST_OK;
800 /* clean a few things up */
801 ssl3_cleanup_key_block(s);
803 BUF_MEM_free(s->init_buf);
806 /* remove buffering on output */
807 ssl_free_wbio_buffer(s);
811 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
816 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
818 s->ctx->stats.sess_accept_good++;
820 s->handshake_func=ssl3_accept;
822 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
830 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
836 if (!s->s3->tmp.reuse_message && !skip)
840 if ((ret=BIO_flush(s->wbio)) <= 0)
845 if ((cb != NULL) && (s->state != state))
849 cb(s,SSL_CB_ACCEPT_LOOP,1);
856 /* BIO_flush(s->wbio); */
860 cb(s,SSL_CB_ACCEPT_EXIT,ret);
864 int ssl3_send_hello_request(SSL *s)
867 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
869 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
870 s->state=SSL3_ST_SW_HELLO_REQ_B;
873 /* SSL3_ST_SW_HELLO_REQ_B */
874 return ssl_do_write(s);
877 int ssl3_check_client_hello(SSL *s)
882 /* this function is called when we really expect a Certificate message,
883 * so permit appropriate message length */
884 n=s->method->ssl_get_message(s,
890 if (!ok) return((int)n);
891 s->s3->tmp.reuse_message = 1;
892 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
894 /* We only allow the client to restart the handshake once per
896 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
898 SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
901 /* Throw away what we have done so far in the current handshake,
902 * which will now be aborted. (A full SSL_clear would be too much.) */
903 #ifndef OPENSSL_NO_DH
904 if (s->s3->tmp.dh != NULL)
906 DH_free(s->s3->tmp.dh);
907 s->s3->tmp.dh = NULL;
910 #ifndef OPENSSL_NO_ECDH
911 if (s->s3->tmp.ecdh != NULL)
913 EC_KEY_free(s->s3->tmp.ecdh);
914 s->s3->tmp.ecdh = NULL;
917 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
923 int ssl3_get_client_hello(SSL *s)
925 int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
926 unsigned int cookie_len;
931 #ifndef OPENSSL_NO_COMP
935 STACK_OF(SSL_CIPHER) *ciphers=NULL;
937 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
940 /* We do this so that we will respond with our native type.
941 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
942 * This down switching should be handled by a different method.
943 * If we are SSLv3, we will respond with SSLv3, even if prompted with
946 if (s->state == SSL3_ST_SR_CLNT_HELLO_A
949 s->state=SSL3_ST_SR_CLNT_HELLO_B;
952 n=s->method->ssl_get_message(s,
953 SSL3_ST_SR_CLNT_HELLO_B,
954 SSL3_ST_SR_CLNT_HELLO_C,
955 SSL3_MT_CLIENT_HELLO,
956 SSL3_RT_MAX_PLAIN_LENGTH,
959 if (!ok) return((int)n);
961 d=p=(unsigned char *)s->init_msg;
963 /* use version from inside client hello, not from record header
964 * (may differ: see RFC 2246, Appendix E, second paragraph) */
965 s->client_version=(((int)p[0])<<8)|(int)p[1];
968 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
969 s->method->version != DTLS_ANY_VERSION)
970 : (s->client_version < s->version))
972 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
973 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
974 !s->enc_write_ctx && !s->write_hash)
976 /* similar to ssl3_get_record, send alert using remote version number */
977 s->version = s->client_version;
979 al = SSL_AD_PROTOCOL_VERSION;
983 /* If we require cookies and this ClientHello doesn't
984 * contain one, just return since we do not want to
985 * allocate any memory yet. So check cookie length...
987 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
989 unsigned int session_length, cookie_length;
991 session_length = *(p + SSL3_RANDOM_SIZE);
992 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
994 if (cookie_length == 0)
998 /* load the client random */
999 memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1000 p+=SSL3_RANDOM_SIZE;
1002 /* get the session-id */
1006 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1007 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1008 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1009 * than a change to default behavior so that applications relying on this for security
1010 * won't even compile against older library versions).
1012 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1013 * renegotiation but not a new session (s->new_session remains unset): for servers,
1014 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1015 * setting will be ignored.
1017 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1019 if (!ssl_get_new_session(s,1))
1024 i=ssl_get_prev_session(s, p, j, d + n);
1026 { /* previous session */
1033 if (!ssl_get_new_session(s,1))
1043 cookie_len = *(p++);
1046 * The ClientHello may contain a cookie even if the
1047 * HelloVerify message has not been sent--make sure that it
1048 * does not cause an overflow.
1050 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1053 al = SSL_AD_DECODE_ERROR;
1054 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1058 /* verify the cookie if appropriate option is set. */
1059 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1062 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1064 if ( s->ctx->app_verify_cookie_cb != NULL)
1066 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1069 al=SSL_AD_HANDSHAKE_FAILURE;
1070 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1071 SSL_R_COOKIE_MISMATCH);
1074 /* else cookie verification succeeded */
1076 else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1077 s->d1->cookie_len) != 0) /* default verification */
1079 al=SSL_AD_HANDSHAKE_FAILURE;
1080 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1081 SSL_R_COOKIE_MISMATCH);
1084 /* Set to -2 so if successful we return 2 */
1089 if (s->method->version == DTLS_ANY_VERSION)
1091 /* Select version to use */
1092 if (s->client_version <= DTLS1_2_VERSION &&
1093 !(s->options & SSL_OP_NO_DTLSv1_2))
1095 s->version = DTLS1_2_VERSION;
1096 s->method = DTLSv1_2_server_method();
1098 else if (tls1_suiteb(s))
1100 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1101 s->version = s->client_version;
1102 al = SSL_AD_PROTOCOL_VERSION;
1105 else if (s->client_version <= DTLS1_VERSION &&
1106 !(s->options & SSL_OP_NO_DTLSv1))
1108 s->version = DTLS1_VERSION;
1109 s->method = DTLSv1_server_method();
1113 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1114 s->version = s->client_version;
1115 al = SSL_AD_PROTOCOL_VERSION;
1118 s->session->ssl_version = s->version;
1123 if ((i == 0) && (j != 0))
1125 /* we need a cipher if we are not resuming a session */
1126 al=SSL_AD_ILLEGAL_PARAMETER;
1127 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1132 /* not enough data */
1133 al=SSL_AD_DECODE_ERROR;
1134 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1137 if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1144 /* If it is a hit, check that the cipher is in the list */
1145 if ((s->hit) && (i > 0))
1148 id=s->session->cipher->id;
1151 printf("client sent %d ciphers\n",sk_num(ciphers));
1153 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1155 c=sk_SSL_CIPHER_value(ciphers,i);
1157 printf("client [%2d of %2d]:%s\n",
1158 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1166 /* Disabled because it can be used in a ciphersuite downgrade
1167 * attack: CVE-2010-4180.
1170 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1172 /* Special case as client bug workaround: the previously used cipher may
1173 * not be in the current list, the client instead might be trying to
1174 * continue using a cipher that before wasn't chosen due to server
1175 * preferences. We'll have to reject the connection if the cipher is not
1176 * enabled, though. */
1177 c = sk_SSL_CIPHER_value(ciphers, 0);
1178 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1180 s->session->cipher = c;
1187 /* we need to have the cipher in the cipher
1188 * list if we are asked to reuse it */
1189 al=SSL_AD_ILLEGAL_PARAMETER;
1190 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1199 /* not enough data */
1200 al=SSL_AD_DECODE_ERROR;
1201 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1204 #ifndef OPENSSL_NO_COMP
1209 if (p[j] == 0) break;
1216 al=SSL_AD_DECODE_ERROR;
1217 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1221 #ifndef OPENSSL_NO_TLSEXT
1223 if (s->version >= SSL3_VERSION)
1225 if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
1227 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1232 /* Check if we want to use external pre-shared secret for this
1233 * handshake for not reused session only. We need to generate
1234 * server_random before calling tls_session_secret_cb in order to allow
1235 * SessionTicket processing to use it in key derivation. */
1238 pos=s->s3->server_random;
1239 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1245 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1247 SSL_CIPHER *pref_cipher=NULL;
1249 s->session->master_key_length=sizeof(s->session->master_key);
1250 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1251 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1254 s->session->ciphers=ciphers;
1255 s->session->verify_result=X509_V_OK;
1259 /* check if some cipher was preferred by call back */
1260 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1261 if (pref_cipher == NULL)
1263 al=SSL_AD_HANDSHAKE_FAILURE;
1264 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1268 s->session->cipher=pref_cipher;
1271 sk_SSL_CIPHER_free(s->cipher_list);
1273 if (s->cipher_list_by_id)
1274 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1276 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1277 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1282 /* Worst case, we will use the NULL compression, but if we have other
1283 * options, we will now look for them. We have i-1 compression
1284 * algorithms from the client, starting at q. */
1285 s->s3->tmp.new_compression=NULL;
1286 #ifndef OPENSSL_NO_COMP
1287 /* This only happens if we have a cache hit */
1288 if (s->session->compress_meth != 0)
1290 int m, comp_id = s->session->compress_meth;
1291 /* Perform sanity checks on resumed compression algorithm */
1292 /* Can't disable compression */
1293 if (!ssl_allow_compression(s))
1295 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1298 /* Look for resumed compression method */
1299 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1301 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1302 if (comp_id == comp->id)
1304 s->s3->tmp.new_compression=comp;
1308 if (s->s3->tmp.new_compression == NULL)
1310 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1313 /* Look for resumed method in compression list */
1314 for (m = 0; m < i; m++)
1316 if (q[m] == comp_id)
1321 al=SSL_AD_ILLEGAL_PARAMETER;
1322 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1328 else if (ssl_allow_compression(s) && s->ctx->comp_methods)
1329 { /* See if we have a match */
1330 int m,nn,o,v,done=0;
1332 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1333 for (m=0; m<nn; m++)
1335 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1348 s->s3->tmp.new_compression=comp;
1353 /* If compression is disabled we'd better not try to resume a session
1354 * using compression.
1356 if (s->session->compress_meth != 0)
1358 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1363 /* Given s->session->ciphers and SSL_get_ciphers, we must
1368 #ifdef OPENSSL_NO_COMP
1369 s->session->compress_meth=0;
1371 s->session->compress_meth=(comp == NULL)?0:comp->id;
1373 if (s->session->ciphers != NULL)
1374 sk_SSL_CIPHER_free(s->session->ciphers);
1375 s->session->ciphers=ciphers;
1376 if (ciphers == NULL)
1378 al=SSL_AD_ILLEGAL_PARAMETER;
1379 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1383 if (!tls1_set_server_sigalgs(s))
1385 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1388 /* Let cert callback update server certificates if required */
1390 if (s->cert->cert_cb)
1392 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1395 al=SSL_AD_INTERNAL_ERROR;
1396 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
1401 s->rwstate=SSL_X509_LOOKUP;
1404 s->rwstate = SSL_NOTHING;
1406 c=ssl3_choose_cipher(s,s->session->ciphers,
1407 SSL_get_ciphers(s));
1411 al=SSL_AD_HANDSHAKE_FAILURE;
1412 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1415 s->s3->tmp.new_cipher=c;
1416 /* check whether we should disable session resumption */
1417 if (s->not_resumable_session_cb != NULL)
1418 s->session->not_resumable=s->not_resumable_session_cb(s,
1419 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1420 if (s->session->not_resumable)
1421 /* do not send a session ticket */
1422 s->tlsext_ticket_expected = 0;
1426 /* Session-id reuse */
1427 #ifdef REUSE_CIPHER_BUG
1428 STACK_OF(SSL_CIPHER) *sk;
1429 SSL_CIPHER *nc=NULL;
1430 SSL_CIPHER *ec=NULL;
1432 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1434 sk=s->session->ciphers;
1435 for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1437 c=sk_SSL_CIPHER_value(sk,i);
1438 if (c->algorithm_enc & SSL_eNULL)
1440 if (SSL_C_IS_EXPORT(c))
1444 s->s3->tmp.new_cipher=nc;
1445 else if (ec != NULL)
1446 s->s3->tmp.new_cipher=ec;
1448 s->s3->tmp.new_cipher=s->session->cipher;
1452 s->s3->tmp.new_cipher=s->session->cipher;
1455 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1457 if (!ssl3_digest_cached_records(s))
1461 /* we now have the following setup.
1463 * cipher_list - our prefered list of ciphers
1464 * ciphers - the clients prefered list of ciphers
1465 * compression - basically ignored right now
1466 * ssl version is set - sslv3
1467 * s->session - The ssl session has been setup.
1468 * s->hit - session reuse flag
1469 * s->s3->tmp.new_cipher- the new cipher to use.
1472 /* Handles TLS extensions that we couldn't check earlier */
1473 if (s->version >= SSL3_VERSION)
1475 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1477 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1482 if (ret < 0) ret=-ret;
1486 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1489 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1490 return ret < 0 ? -1 : ret;
1493 int ssl3_send_server_hello(SSL *s)
1496 unsigned char *p,*d;
1501 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1503 buf=(unsigned char *)s->init_buf->data;
1504 #ifdef OPENSSL_NO_TLSEXT
1505 p=s->s3->server_random;
1506 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1509 /* Do the message type and length last */
1510 d=p= ssl_handshake_start(s);
1512 *(p++)=s->version>>8;
1513 *(p++)=s->version&0xff;
1516 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1517 p+=SSL3_RANDOM_SIZE;
1519 /* There are several cases for the session ID to send
1520 * back in the server hello:
1521 * - For session reuse from the session cache,
1522 * we send back the old session ID.
1523 * - If stateless session reuse (using a session ticket)
1524 * is successful, we send back the client's "session ID"
1525 * (which doesn't actually identify the session).
1526 * - If it is a new session, we send back the new
1528 * - However, if we want the new session to be single-use,
1529 * we send back a 0-length session ID.
1530 * s->hit is non-zero in either case of session reuse,
1531 * so the following won't overwrite an ID that we're supposed
1534 if (s->session->not_resumable ||
1535 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1537 s->session->session_id_length=0;
1539 sl=s->session->session_id_length;
1540 if (sl > (int)sizeof(s->session->session_id))
1542 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1546 memcpy(p,s->session->session_id,sl);
1549 /* put the cipher */
1550 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1553 /* put the compression method */
1554 #ifdef OPENSSL_NO_COMP
1557 if (s->s3->tmp.new_compression == NULL)
1560 *(p++)=s->s3->tmp.new_compression->id;
1562 #ifndef OPENSSL_NO_TLSEXT
1563 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1565 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1568 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
1570 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1571 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1577 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1578 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1581 /* SSL3_ST_SW_SRVR_HELLO_B */
1582 return ssl_do_write(s);
1585 int ssl3_send_server_done(SSL *s)
1588 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1590 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1591 s->state = SSL3_ST_SW_SRVR_DONE_B;
1594 /* SSL3_ST_SW_SRVR_DONE_B */
1595 return ssl_do_write(s);
1598 int ssl3_send_server_key_exchange(SSL *s)
1600 #ifndef OPENSSL_NO_RSA
1604 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1607 #ifndef OPENSSL_NO_DH
1610 #ifndef OPENSSL_NO_ECDH
1611 EC_KEY *ecdh=NULL, *ecdhp;
1612 unsigned char *encodedPoint = NULL;
1615 BN_CTX *bn_ctx = NULL;
1618 const EVP_MD *md = NULL;
1619 unsigned char *p,*d;
1629 EVP_MD_CTX_init(&md_ctx);
1630 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1632 type=s->s3->tmp.new_cipher->algorithm_mkey;
1637 r[0]=r[1]=r[2]=r[3]=NULL;
1639 #ifndef OPENSSL_NO_RSA
1640 if (type & SSL_kRSA)
1643 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1645 rsa=s->cert->rsa_tmp_cb(s,
1646 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1647 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1650 al=SSL_AD_HANDSHAKE_FAILURE;
1651 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1659 al=SSL_AD_HANDSHAKE_FAILURE;
1660 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1665 s->s3->tmp.use_rsa_tmp=1;
1669 #ifndef OPENSSL_NO_DH
1670 if (type & SSL_kDHE)
1672 if (s->cert->dh_tmp_auto)
1674 dhp = ssl_get_auto_dh(s);
1677 al=SSL_AD_INTERNAL_ERROR;
1678 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1684 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1685 dhp=s->cert->dh_tmp_cb(s,
1686 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1687 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1690 al=SSL_AD_HANDSHAKE_FAILURE;
1691 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1694 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1695 DH_security_bits(dhp), 0, dhp))
1697 al=SSL_AD_HANDSHAKE_FAILURE;
1698 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
1701 if (s->s3->tmp.dh != NULL)
1703 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1707 if (s->cert->dh_tmp_auto)
1709 else if ((dh=DHparams_dup(dhp)) == NULL)
1711 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1716 if ((dhp->pub_key == NULL ||
1717 dhp->priv_key == NULL ||
1718 (s->options & SSL_OP_SINGLE_DH_USE)))
1720 if(!DH_generate_key(dh))
1722 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1729 dh->pub_key=BN_dup(dhp->pub_key);
1730 dh->priv_key=BN_dup(dhp->priv_key);
1731 if ((dh->pub_key == NULL) ||
1732 (dh->priv_key == NULL))
1734 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1744 #ifndef OPENSSL_NO_ECDH
1745 if (type & SSL_kECDHE)
1747 const EC_GROUP *group;
1749 ecdhp=cert->ecdh_tmp;
1750 if (s->cert->ecdh_tmp_auto)
1752 /* Get NID of appropriate shared curve */
1753 int nid = tls1_shared_curve(s, -2);
1754 if (nid != NID_undef)
1755 ecdhp = EC_KEY_new_by_curve_name(nid);
1757 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1759 ecdhp=s->cert->ecdh_tmp_cb(s,
1760 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1761 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1765 al=SSL_AD_HANDSHAKE_FAILURE;
1766 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1770 if (s->s3->tmp.ecdh != NULL)
1772 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1776 /* Duplicate the ECDH structure. */
1779 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1782 if (s->cert->ecdh_tmp_auto)
1784 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1786 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1790 s->s3->tmp.ecdh=ecdh;
1791 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1792 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1793 (s->options & SSL_OP_SINGLE_ECDH_USE))
1795 if(!EC_KEY_generate_key(ecdh))
1797 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1802 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1803 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1804 (EC_KEY_get0_private_key(ecdh) == NULL))
1806 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1810 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1811 (EC_GROUP_get_degree(group) > 163))
1813 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1817 /* XXX: For now, we only support ephemeral ECDH
1818 * keys over named (not generic) curves. For
1819 * supported named curves, curve_id is non-zero.
1822 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1825 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1829 /* Encode the public key.
1830 * First check the size of encoding and
1831 * allocate memory accordingly.
1833 encodedlen = EC_POINT_point2oct(group,
1834 EC_KEY_get0_public_key(ecdh),
1835 POINT_CONVERSION_UNCOMPRESSED,
1838 encodedPoint = (unsigned char *)
1839 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1840 bn_ctx = BN_CTX_new();
1841 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1843 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1848 encodedlen = EC_POINT_point2oct(group,
1849 EC_KEY_get0_public_key(ecdh),
1850 POINT_CONVERSION_UNCOMPRESSED,
1851 encodedPoint, encodedlen, bn_ctx);
1853 if (encodedlen == 0)
1855 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1859 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1861 /* XXX: For now, we only support named (not
1862 * generic) curves in ECDH ephemeral key exchanges.
1863 * In this situation, we need four additional bytes
1864 * to encode the entire ServerECDHParams
1869 /* We'll generate the serverKeyExchange message
1870 * explicitly so we can set these to NULLs
1878 #endif /* !OPENSSL_NO_ECDH */
1879 #ifndef OPENSSL_NO_PSK
1880 if (type & SSL_kPSK)
1882 /* reserve size for record length and PSK identity hint*/
1883 n+=2+strlen(s->ctx->psk_identity_hint);
1886 #endif /* !OPENSSL_NO_PSK */
1887 #ifndef OPENSSL_NO_SRP
1888 if (type & SSL_kSRP)
1890 if ((s->srp_ctx.N == NULL) ||
1891 (s->srp_ctx.g == NULL) ||
1892 (s->srp_ctx.s == NULL) ||
1893 (s->srp_ctx.B == NULL))
1895 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1906 al=SSL_AD_HANDSHAKE_FAILURE;
1907 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1910 for (i=0; i < 4 && r[i] != NULL; i++)
1912 nr[i]=BN_num_bytes(r[i]);
1913 #ifndef OPENSSL_NO_SRP
1914 if ((i == 2) && (type & SSL_kSRP))
1921 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1922 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1924 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1927 al=SSL_AD_DECODE_ERROR;
1930 kn=EVP_PKEY_size(pkey);
1938 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1940 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1943 d = p = ssl_handshake_start(s);
1945 for (i=0; i < 4 && r[i] != NULL; i++)
1947 #ifndef OPENSSL_NO_SRP
1948 if ((i == 2) && (type & SSL_kSRP))
1960 #ifndef OPENSSL_NO_ECDH
1961 if (type & SSL_kECDHE)
1963 /* XXX: For now, we only support named (not generic) curves.
1964 * In this situation, the serverKeyExchange message has:
1965 * [1 byte CurveType], [2 byte CurveName]
1966 * [1 byte length of encoded point], followed by
1967 * the actual encoded point itself
1969 *p = NAMED_CURVE_TYPE;
1977 memcpy((unsigned char*)p,
1978 (unsigned char *)encodedPoint,
1980 OPENSSL_free(encodedPoint);
1981 encodedPoint = NULL;
1986 #ifndef OPENSSL_NO_PSK
1987 if (type & SSL_kPSK)
1989 /* copy PSK identity hint */
1990 s2n(strlen(s->ctx->psk_identity_hint), p);
1991 strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1992 p+=strlen(s->ctx->psk_identity_hint);
1999 /* n is the length of the params, they start at &(d[4])
2000 * and p points to the space at the end. */
2001 #ifndef OPENSSL_NO_RSA
2002 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
2006 for (num=2; num > 0; num--)
2008 EVP_MD_CTX_set_flags(&md_ctx,
2009 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2010 EVP_DigestInit_ex(&md_ctx,(num == 2)
2011 ?s->ctx->md5:s->ctx->sha1, NULL);
2012 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2013 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2014 EVP_DigestUpdate(&md_ctx,d,n);
2015 EVP_DigestFinal_ex(&md_ctx,q,
2016 (unsigned int *)&i);
2020 if (RSA_sign(NID_md5_sha1, md_buf, j,
2021 &(p[2]), &u, pkey->pkey.rsa) <= 0)
2023 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2033 /* send signature algorithm */
2034 if (SSL_USE_SIGALGS(s))
2036 if (!tls12_get_sigandhash(p, pkey, md))
2038 /* Should never happen */
2039 al=SSL_AD_INTERNAL_ERROR;
2040 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2046 fprintf(stderr, "Using hash %s\n",
2049 EVP_SignInit_ex(&md_ctx, md, NULL);
2050 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2051 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2052 EVP_SignUpdate(&md_ctx,d,n);
2053 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2054 (unsigned int *)&i,pkey))
2056 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2061 if (SSL_USE_SIGALGS(s))
2066 /* Is this error check actually needed? */
2067 al=SSL_AD_HANDSHAKE_FAILURE;
2068 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2073 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2076 s->state = SSL3_ST_SW_KEY_EXCH_B;
2077 EVP_MD_CTX_cleanup(&md_ctx);
2078 return ssl_do_write(s);
2080 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2082 #ifndef OPENSSL_NO_ECDH
2083 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2084 BN_CTX_free(bn_ctx);
2086 EVP_MD_CTX_cleanup(&md_ctx);
2090 int ssl3_send_certificate_request(SSL *s)
2092 unsigned char *p,*d;
2094 STACK_OF(X509_NAME) *sk=NULL;
2098 if (s->state == SSL3_ST_SW_CERT_REQ_A)
2102 d=p=ssl_handshake_start(s);
2104 /* get the list of acceptable cert types */
2106 n=ssl3_get_req_cert_type(s,p);
2111 if (SSL_USE_SIGALGS(s))
2113 const unsigned char *psigs;
2114 unsigned char *etmp = p;
2115 nl = tls12_get_psigalgs(s, &psigs);
2116 /* Skip over length for now */
2118 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2119 /* Now fill in length */
2129 sk=SSL_get_client_CA_list(s);
2133 for (i=0; i<sk_X509_NAME_num(sk); i++)
2135 name=sk_X509_NAME_value(sk,i);
2136 j=i2d_X509_NAME(name,NULL);
2137 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
2139 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2142 p = ssl_handshake_start(s) + n;
2143 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2146 i2d_X509_NAME(name,&p);
2153 i2d_X509_NAME(name,&p);
2154 j-=2; s2n(j,d); j+=2;
2160 /* else no CA names */
2161 p = ssl_handshake_start(s) + off;
2164 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2166 #ifdef NETSCAPE_HANG_BUG
2167 if (!SSL_IS_DTLS(s))
2169 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2171 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2174 p=(unsigned char *)s->init_buf->data + s->init_num;
2176 *(p++)=SSL3_MT_SERVER_DONE;
2184 s->state = SSL3_ST_SW_CERT_REQ_B;
2187 /* SSL3_ST_SW_CERT_REQ_B */
2188 return ssl_do_write(s);
2193 int ssl3_get_client_key_exchange(SSL *s)
2197 unsigned long alg_k;
2199 #ifndef OPENSSL_NO_RSA
2201 EVP_PKEY *pkey=NULL;
2203 #ifndef OPENSSL_NO_DH
2205 DH *dh_srvr, *dh_clnt = NULL;
2207 #ifndef OPENSSL_NO_KRB5
2209 #endif /* OPENSSL_NO_KRB5 */
2211 #ifndef OPENSSL_NO_ECDH
2212 EC_KEY *srvr_ecdh = NULL;
2213 EVP_PKEY *clnt_pub_pkey = NULL;
2214 EC_POINT *clnt_ecpoint = NULL;
2215 BN_CTX *bn_ctx = NULL;
2218 n=s->method->ssl_get_message(s,
2219 SSL3_ST_SR_KEY_EXCH_A,
2220 SSL3_ST_SR_KEY_EXCH_B,
2221 SSL3_MT_CLIENT_KEY_EXCHANGE,
2225 if (!ok) return((int)n);
2226 p=(unsigned char *)s->init_msg;
2228 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2230 #ifndef OPENSSL_NO_RSA
2231 if (alg_k & SSL_kRSA)
2233 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2235 unsigned char decrypt_good, version_good;
2237 /* FIX THIS UP EAY EAY EAY EAY */
2238 if (s->s3->tmp.use_rsa_tmp)
2240 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2241 rsa=s->cert->rsa_tmp;
2242 /* Don't do a callback because rsa_tmp should
2243 * be sent already */
2246 al=SSL_AD_HANDSHAKE_FAILURE;
2247 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2254 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2255 if ( (pkey == NULL) ||
2256 (pkey->type != EVP_PKEY_RSA) ||
2257 (pkey->pkey.rsa == NULL))
2259 al=SSL_AD_HANDSHAKE_FAILURE;
2260 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2266 /* TLS and [incidentally] DTLS{0xFEFF} */
2267 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2272 if (!(s->options & SSL_OP_TLS_D5_BUG))
2274 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2284 /* We must not leak whether a decryption failure occurs because
2285 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2286 * RFC 2246, section 7.4.7.1). The code follows that advice of
2287 * the TLS RFC and generates a random premaster secret for the
2288 * case that the decrypt fails. See
2289 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2291 /* should be RAND_bytes, but we cannot work around a failure. */
2292 if (RAND_pseudo_bytes(rand_premaster_secret,
2293 sizeof(rand_premaster_secret)) <= 0)
2295 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2298 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2299 * decrypt_good will be 0xff if so and zero otherwise. */
2300 decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2302 /* If the version in the decrypted pre-master secret is correct
2303 * then version_good will be 0xff, otherwise it'll be zero.
2304 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2305 * (http://eprint.iacr.org/2003/052/) exploits the version
2306 * number check as a "bad version oracle". Thus version checks
2307 * are done in constant time and are treated like any other
2308 * decryption error. */
2309 version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2310 version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2312 /* The premaster secret must contain the same version number as
2313 * the ClientHello to detect version rollback attacks
2314 * (strangely, the protocol does not offer such protection for
2315 * DH ciphersuites). However, buggy clients exist that send the
2316 * negotiated protocol version instead if the server does not
2317 * support the requested protocol version. If
2318 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2319 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2321 unsigned char workaround_good;
2322 workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2323 workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2324 version_good |= workaround_good;
2327 /* Both decryption and version must be good for decrypt_good
2328 * to remain non-zero (0xff). */
2329 decrypt_good &= version_good;
2331 /* Now copy rand_premaster_secret over p using
2332 * decrypt_good_mask. */
2333 for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2335 p[i] = constant_time_select_8(decrypt_good, p[i],
2336 rand_premaster_secret[i]);
2339 s->session->master_key_length=
2340 s->method->ssl3_enc->generate_master_secret(s,
2341 s->session->master_key,
2343 OPENSSL_cleanse(p,i);
2347 #ifndef OPENSSL_NO_DH
2348 if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
2351 EVP_PKEY *skey = NULL;
2358 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2360 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2369 if (alg_k & SSL_kDHr)
2370 idx = SSL_PKEY_DH_RSA;
2371 else if (alg_k & SSL_kDHd)
2372 idx = SSL_PKEY_DH_DSA;
2375 skey = s->cert->pkeys[idx].privatekey;
2376 if ((skey == NULL) ||
2377 (skey->type != EVP_PKEY_DH) ||
2378 (skey->pkey.dh == NULL))
2380 al=SSL_AD_HANDSHAKE_FAILURE;
2381 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2384 dh_srvr = skey->pkey.dh;
2386 else if (s->s3->tmp.dh == NULL)
2388 al=SSL_AD_HANDSHAKE_FAILURE;
2389 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2393 dh_srvr=s->s3->tmp.dh;
2397 /* Get pubkey from cert */
2398 EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2401 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2402 dh_clnt = EVP_PKEY_get1_DH(clkey);
2404 if (dh_clnt == NULL)
2406 al=SSL_AD_HANDSHAKE_FAILURE;
2407 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2410 EVP_PKEY_free(clkey);
2411 pub = dh_clnt->pub_key;
2414 pub=BN_bin2bn(p,i,NULL);
2417 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2421 i=DH_compute_key(p,pub,dh_srvr);
2425 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2430 DH_free(s->s3->tmp.dh);
2437 s->session->master_key_length=
2438 s->method->ssl3_enc->generate_master_secret(s,
2439 s->session->master_key,p,i);
2440 OPENSSL_cleanse(p,i);
2446 #ifndef OPENSSL_NO_KRB5
2447 if (alg_k & SSL_kKRB5)
2449 krb5_error_code krb5rc;
2450 krb5_data enc_ticket;
2451 krb5_data authenticator;
2453 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2454 EVP_CIPHER_CTX ciph_ctx;
2455 const EVP_CIPHER *enc = NULL;
2456 unsigned char iv[EVP_MAX_IV_LENGTH];
2457 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH
2458 + EVP_MAX_BLOCK_LENGTH];
2460 krb5_timestamp authtime = 0;
2461 krb5_ticket_times ttimes;
2463 EVP_CIPHER_CTX_init(&ciph_ctx);
2465 if (!kssl_ctx) kssl_ctx = kssl_ctx_new();
2468 enc_ticket.length = i;
2470 if (n < (long)(enc_ticket.length + 6))
2472 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2473 SSL_R_DATA_LENGTH_TOO_LONG);
2477 enc_ticket.data = (char *)p;
2478 p+=enc_ticket.length;
2481 authenticator.length = i;
2483 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2485 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2486 SSL_R_DATA_LENGTH_TOO_LONG);
2490 authenticator.data = (char *)p;
2491 p+=authenticator.length;
2495 enc_pms.data = (char *)p;
2498 /* Note that the length is checked again below,
2501 if(enc_pms.length > sizeof pms)
2503 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2504 SSL_R_DATA_LENGTH_TOO_LONG);
2508 if (n != (long)(enc_ticket.length + authenticator.length +
2509 enc_pms.length + 6))
2511 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2512 SSL_R_DATA_LENGTH_TOO_LONG);
2516 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2520 printf("kssl_sget_tkt rtn %d [%d]\n",
2521 krb5rc, kssl_err.reason);
2523 printf("kssl_err text= %s\n", kssl_err.text);
2524 #endif /* KSSL_DEBUG */
2525 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2530 /* Note: no authenticator is not considered an error,
2531 ** but will return authtime == 0.
2533 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2534 &authtime, &kssl_err)) != 0)
2537 printf("kssl_check_authent rtn %d [%d]\n",
2538 krb5rc, kssl_err.reason);
2540 printf("kssl_err text= %s\n", kssl_err.text);
2541 #endif /* KSSL_DEBUG */
2542 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2547 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2549 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2554 kssl_ctx_show(kssl_ctx);
2555 #endif /* KSSL_DEBUG */
2557 enc = kssl_map_enc(kssl_ctx->enctype);
2561 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2563 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2565 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2566 SSL_R_DECRYPTION_FAILED);
2569 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2570 (unsigned char *)enc_pms.data, enc_pms.length))
2572 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2573 SSL_R_DECRYPTION_FAILED);
2576 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2578 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2579 SSL_R_DATA_LENGTH_TOO_LONG);
2582 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2584 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2585 SSL_R_DECRYPTION_FAILED);
2589 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2591 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2592 SSL_R_DATA_LENGTH_TOO_LONG);
2595 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2597 /* The premaster secret must contain the same version number as the
2598 * ClientHello to detect version rollback attacks (strangely, the
2599 * protocol does not offer such protection for DH ciphersuites).
2600 * However, buggy clients exist that send random bytes instead of
2601 * the protocol version.
2602 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2603 * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2605 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2607 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2608 SSL_AD_DECODE_ERROR);
2613 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2615 s->session->master_key_length=
2616 s->method->ssl3_enc->generate_master_secret(s,
2617 s->session->master_key, pms, outl);
2619 if (kssl_ctx->client_princ)
2621 size_t len = strlen(kssl_ctx->client_princ);
2622 if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH )
2624 s->session->krb5_client_princ_len = len;
2625 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2630 /* Was doing kssl_ctx_free() here,
2631 ** but it caused problems for apache.
2632 ** kssl_ctx = kssl_ctx_free(kssl_ctx);
2633 ** if (s->kssl_ctx) s->kssl_ctx = NULL;
2637 #endif /* OPENSSL_NO_KRB5 */
2639 #ifndef OPENSSL_NO_ECDH
2640 if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
2645 const EC_GROUP *group;
2646 const BIGNUM *priv_key;
2648 /* initialize structures for server's ECDH key pair */
2649 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2651 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2652 ERR_R_MALLOC_FAILURE);
2656 /* Let's get server private key and group information */
2657 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2659 /* use the certificate */
2660 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2664 /* use the ephermeral values we saved when
2665 * generating the ServerKeyExchange msg.
2667 tkey = s->s3->tmp.ecdh;
2670 group = EC_KEY_get0_group(tkey);
2671 priv_key = EC_KEY_get0_private_key(tkey);
2673 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2674 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2676 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2681 /* Let's get client's public key */
2682 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2684 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2685 ERR_R_MALLOC_FAILURE);
2691 /* Client Publickey was in Client Certificate */
2693 if (alg_k & SSL_kECDHE)
2695 al=SSL_AD_HANDSHAKE_FAILURE;
2696 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2699 if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2701 (clnt_pub_pkey->type != EVP_PKEY_EC))
2703 /* XXX: For now, we do not support client
2704 * authentication using ECDH certificates
2705 * so this branch (n == 0L) of the code is
2706 * never executed. When that support is
2707 * added, we ought to ensure the key
2708 * received in the certificate is
2709 * authorized for key agreement.
2710 * ECDH_compute_key implicitly checks that
2711 * the two ECDH shares are for the same
2714 al=SSL_AD_HANDSHAKE_FAILURE;
2715 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2716 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2720 if (EC_POINT_copy(clnt_ecpoint,
2721 EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2723 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2727 ret = 2; /* Skip certificate verify processing */
2731 /* Get client's public key from encoded point
2732 * in the ClientKeyExchange message.
2734 if ((bn_ctx = BN_CTX_new()) == NULL)
2736 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2737 ERR_R_MALLOC_FAILURE);
2741 /* Get encoded point length */
2746 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2750 if (EC_POINT_oct2point(group,
2751 clnt_ecpoint, p, i, bn_ctx) == 0)
2753 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2757 /* p is pointing to somewhere in the buffer
2758 * currently, so set it to the start
2760 p=(unsigned char *)s->init_buf->data;
2763 /* Compute the shared pre-master secret */
2764 field_size = EC_GROUP_get_degree(group);
2765 if (field_size <= 0)
2767 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2771 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2774 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2779 EVP_PKEY_free(clnt_pub_pkey);
2780 EC_POINT_free(clnt_ecpoint);
2781 EC_KEY_free(srvr_ecdh);
2782 BN_CTX_free(bn_ctx);
2783 EC_KEY_free(s->s3->tmp.ecdh);
2784 s->s3->tmp.ecdh = NULL;
2786 /* Compute the master secret */
2787 s->session->master_key_length = s->method->ssl3_enc-> \
2788 generate_master_secret(s, s->session->master_key, p, i);
2790 OPENSSL_cleanse(p, i);
2795 #ifndef OPENSSL_NO_PSK
2796 if (alg_k & SSL_kPSK)
2798 unsigned char *t = NULL;
2799 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2800 unsigned int pre_ms_len = 0, psk_len = 0;
2802 char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2804 al=SSL_AD_HANDSHAKE_FAILURE;
2809 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2810 SSL_R_LENGTH_MISMATCH);
2813 if (i > PSK_MAX_IDENTITY_LEN)
2815 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2816 SSL_R_DATA_LENGTH_TOO_LONG);
2819 if (s->psk_server_callback == NULL)
2821 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2822 SSL_R_PSK_NO_SERVER_CB);
2826 /* Create guaranteed NULL-terminated identity
2827 * string for the callback */
2828 memcpy(tmp_id, p, i);
2829 memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2830 psk_len = s->psk_server_callback(s, tmp_id,
2831 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2832 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2834 if (psk_len > PSK_MAX_PSK_LEN)
2836 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2837 ERR_R_INTERNAL_ERROR);
2840 else if (psk_len == 0)
2842 /* PSK related to the given identity not found */
2843 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2844 SSL_R_PSK_IDENTITY_NOT_FOUND);
2845 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2849 /* create PSK pre_master_secret */
2850 pre_ms_len=2+psk_len+2+psk_len;
2852 memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2854 memset(t, 0, psk_len);
2858 if (s->session->psk_identity != NULL)
2859 OPENSSL_free(s->session->psk_identity);
2860 s->session->psk_identity = BUF_strdup((char *)p);
2861 if (s->session->psk_identity == NULL)
2863 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2864 ERR_R_MALLOC_FAILURE);
2868 if (s->session->psk_identity_hint != NULL)
2869 OPENSSL_free(s->session->psk_identity_hint);
2870 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2871 if (s->ctx->psk_identity_hint != NULL &&
2872 s->session->psk_identity_hint == NULL)
2874 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2875 ERR_R_MALLOC_FAILURE);
2879 s->session->master_key_length=
2880 s->method->ssl3_enc->generate_master_secret(s,
2881 s->session->master_key, psk_or_pre_ms, pre_ms_len);
2884 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2890 #ifndef OPENSSL_NO_SRP
2891 if (alg_k & SSL_kSRP)
2899 al=SSL_AD_DECODE_ERROR;
2900 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2903 if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2905 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2908 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2909 || BN_is_zero(s->srp_ctx.A))
2911 al=SSL_AD_ILLEGAL_PARAMETER;
2912 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
2915 if (s->session->srp_username != NULL)
2916 OPENSSL_free(s->session->srp_username);
2917 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2918 if (s->session->srp_username == NULL)
2920 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2921 ERR_R_MALLOC_FAILURE);
2925 if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2927 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2934 #endif /* OPENSSL_NO_SRP */
2935 if (alg_k & SSL_kGOST)
2938 EVP_PKEY_CTX *pkey_ctx;
2939 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2940 unsigned char premaster_secret[32], *start;
2941 size_t outlen=32, inlen;
2942 unsigned long alg_a;
2946 /* Get our certificate private key*/
2947 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2948 if (alg_a & SSL_aGOST94)
2949 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2950 else if (alg_a & SSL_aGOST01)
2951 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2953 pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2954 EVP_PKEY_decrypt_init(pkey_ctx);
2955 /* If client certificate is present and is of the same type, maybe
2956 * use it for key exchange. Don't mind errors from
2957 * EVP_PKEY_derive_set_peer, because it is completely valid to use
2958 * a client certificate for authorization only. */
2959 client_pub_pkey = X509_get_pubkey(s->session->peer);
2960 if (client_pub_pkey)
2962 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2965 /* Decrypt session key */
2966 if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED ||
2967 Ttag != V_ASN1_SEQUENCE ||
2968 Tclass != V_ASN1_UNIVERSAL)
2970 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2975 if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0)
2978 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2981 /* Generate master secret */
2982 s->session->master_key_length=
2983 s->method->ssl3_enc->generate_master_secret(s,
2984 s->session->master_key,premaster_secret,32);
2985 /* Check if pubkey from client certificate was used */
2986 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2991 EVP_PKEY_free(client_pub_pkey);
2992 EVP_PKEY_CTX_free(pkey_ctx);
3000 al=SSL_AD_HANDSHAKE_FAILURE;
3001 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
3002 SSL_R_UNKNOWN_CIPHER_TYPE);
3008 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3009 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3012 #ifndef OPENSSL_NO_ECDH
3013 EVP_PKEY_free(clnt_pub_pkey);
3014 EC_POINT_free(clnt_ecpoint);
3015 if (srvr_ecdh != NULL)
3016 EC_KEY_free(srvr_ecdh);
3017 BN_CTX_free(bn_ctx);
3022 int ssl3_get_cert_verify(SSL *s)
3024 EVP_PKEY *pkey=NULL;
3030 const EVP_MD *md = NULL;
3032 EVP_MD_CTX_init(&mctx);
3034 n=s->method->ssl_get_message(s,
3035 SSL3_ST_SR_CERT_VRFY_A,
3036 SSL3_ST_SR_CERT_VRFY_B,
3038 SSL3_RT_MAX_PLAIN_LENGTH,
3041 if (!ok) return((int)n);
3043 if (s->session->peer != NULL)
3045 peer=s->session->peer;
3046 pkey=X509_get_pubkey(peer);
3047 type=X509_certificate_type(peer,pkey);
3055 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3057 s->s3->tmp.reuse_message=1;
3058 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3060 al=SSL_AD_UNEXPECTED_MESSAGE;
3061 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3070 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3071 al=SSL_AD_UNEXPECTED_MESSAGE;
3075 if (!(type & EVP_PKT_SIGN))
3077 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3078 al=SSL_AD_ILLEGAL_PARAMETER;
3082 if (s->s3->change_cipher_spec)
3084 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3085 al=SSL_AD_UNEXPECTED_MESSAGE;
3089 /* we now have a signature that we need to verify */
3090 p=(unsigned char *)s->init_msg;
3091 /* Check for broken implementations of GOST ciphersuites */
3092 /* If key is GOST and n is exactly 64, it is bare
3093 * signature without length field */
3094 if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3095 pkey->type == NID_id_GostR3410_2001) )
3101 if (SSL_USE_SIGALGS(s))
3103 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3106 al = SSL_AD_INTERNAL_ERROR;
3111 al = SSL_AD_DECODE_ERROR;
3115 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3124 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3125 al=SSL_AD_DECODE_ERROR;
3129 j=EVP_PKEY_size(pkey);
3130 if ((i > j) || (n > j) || (n <= 0))
3132 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3133 al=SSL_AD_DECODE_ERROR;
3137 if (SSL_USE_SIGALGS(s))
3141 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3144 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3145 al=SSL_AD_INTERNAL_ERROR;
3149 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3152 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3153 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3155 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3156 al=SSL_AD_INTERNAL_ERROR;
3160 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3162 al=SSL_AD_DECRYPT_ERROR;
3163 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3168 #ifndef OPENSSL_NO_RSA
3169 if (pkey->type == EVP_PKEY_RSA)
3171 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3172 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
3176 al=SSL_AD_DECRYPT_ERROR;
3177 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3182 al=SSL_AD_DECRYPT_ERROR;
3183 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3189 #ifndef OPENSSL_NO_DSA
3190 if (pkey->type == EVP_PKEY_DSA)
3192 j=DSA_verify(pkey->save_type,
3193 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3194 SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3198 al=SSL_AD_DECRYPT_ERROR;
3199 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3205 #ifndef OPENSSL_NO_ECDSA
3206 if (pkey->type == EVP_PKEY_EC)
3208 j=ECDSA_verify(pkey->save_type,
3209 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3210 SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3214 al=SSL_AD_DECRYPT_ERROR;
3215 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3216 SSL_R_BAD_ECDSA_SIGNATURE);
3222 if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3223 { unsigned char signature[64];
3225 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3226 EVP_PKEY_verify_init(pctx);
3228 fprintf(stderr,"GOST signature length is %d",i);
3230 for (idx=0;idx<64;idx++) {
3231 signature[63-idx]=p[idx];
3233 j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3234 EVP_PKEY_CTX_free(pctx);
3237 al=SSL_AD_DECRYPT_ERROR;
3238 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3239 SSL_R_BAD_ECDSA_SIGNATURE);
3245 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3246 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3255 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3258 if (s->s3->handshake_buffer)
3260 BIO_free(s->s3->handshake_buffer);
3261 s->s3->handshake_buffer = NULL;
3262 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3264 EVP_MD_CTX_cleanup(&mctx);
3265 EVP_PKEY_free(pkey);
3269 int ssl3_get_client_certificate(SSL *s)
3271 int i,ok,al,ret= -1;
3273 unsigned long l,nc,llen,n;
3274 const unsigned char *p,*q;
3276 STACK_OF(X509) *sk=NULL;
3278 n=s->method->ssl_get_message(s,
3285 if (!ok) return((int)n);
3287 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3289 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
3290 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3292 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3293 al=SSL_AD_HANDSHAKE_FAILURE;
3296 /* If tls asked for a client cert, the client must return a 0 list */
3297 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3299 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3300 al=SSL_AD_UNEXPECTED_MESSAGE;
3303 s->s3->tmp.reuse_message=1;
3307 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3309 al=SSL_AD_UNEXPECTED_MESSAGE;
3310 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3313 p=d=(unsigned char *)s->init_msg;
3315 if ((sk=sk_X509_new_null()) == NULL)
3317 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3324 al=SSL_AD_DECODE_ERROR;
3325 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3328 for (nc=0; nc<llen; )
3331 if ((l+nc+3) > llen)
3333 al=SSL_AD_DECODE_ERROR;
3334 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3339 x=d2i_X509(NULL,&p,l);
3342 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3347 al=SSL_AD_DECODE_ERROR;
3348 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3351 if (!sk_X509_push(sk,x))
3353 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3360 if (sk_X509_num(sk) <= 0)
3362 /* TLS does not mind 0 certs returned */
3363 if (s->version == SSL3_VERSION)
3365 al=SSL_AD_HANDSHAKE_FAILURE;
3366 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3369 /* Fail for TLS only if we required a certificate */
3370 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3371 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3373 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3374 al=SSL_AD_HANDSHAKE_FAILURE;
3377 /* No client certificate so digest cached records */
3378 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3380 al=SSL_AD_INTERNAL_ERROR;
3387 i=ssl_verify_cert_chain(s,sk);
3390 al=ssl_verify_alarm_type(s->verify_result);
3391 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3396 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3397 al = SSL_AD_HANDSHAKE_FAILURE;
3400 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3403 al=SSL3_AD_HANDSHAKE_FAILURE;
3404 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3405 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3408 EVP_PKEY_free(pkey);
3411 if (s->session->peer != NULL) /* This should not be needed */
3412 X509_free(s->session->peer);
3413 s->session->peer=sk_X509_shift(sk);
3414 s->session->verify_result = s->verify_result;
3416 /* With the current implementation, sess_cert will always be NULL
3417 * when we arrive here. */
3418 if (s->session->sess_cert == NULL)
3420 s->session->sess_cert = ssl_sess_cert_new();
3421 if (s->session->sess_cert == NULL)
3423 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3427 if (s->session->sess_cert->cert_chain != NULL)
3428 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3429 s->session->sess_cert->cert_chain=sk;
3430 /* Inconsistency alert: cert_chain does *not* include the
3431 * peer's own certificate, while we do include it in s3_clnt.c */
3439 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3442 if (x != NULL) X509_free(x);
3443 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3447 int ssl3_send_server_certificate(SSL *s)
3451 if (s->state == SSL3_ST_SW_CERT_A)
3453 cpk=ssl_get_server_send_pkey(s);
3456 /* VRS: allow null cert if auth == KRB5 */
3457 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3458 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3460 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3465 if (!ssl3_output_cert_chain(s,cpk))
3467 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3470 s->state=SSL3_ST_SW_CERT_B;
3473 /* SSL3_ST_SW_CERT_B */
3474 return ssl_do_write(s);
3477 #ifndef OPENSSL_NO_TLSEXT
3478 /* send a new session ticket (not necessarily for a new session) */
3479 int ssl3_send_newsession_ticket(SSL *s)
3481 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3483 unsigned char *p, *senc, *macstart;
3484 const unsigned char *const_p;
3485 int len, slen_full, slen;
3490 SSL_CTX *tctx = s->initial_ctx;
3491 unsigned char iv[EVP_MAX_IV_LENGTH];
3492 unsigned char key_name[16];
3494 /* get session encoding length */
3495 slen_full = i2d_SSL_SESSION(s->session, NULL);
3496 /* Some length values are 16 bits, so forget it if session is
3499 if (slen_full > 0xFF00)
3501 senc = OPENSSL_malloc(slen_full);
3505 i2d_SSL_SESSION(s->session, &p);
3507 /* create a fresh copy (not shared with other threads) to clean up */
3509 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3515 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3517 slen = i2d_SSL_SESSION(sess, NULL);
3518 if (slen > slen_full) /* shouldn't ever happen */
3524 i2d_SSL_SESSION(sess, &p);
3525 SSL_SESSION_free(sess);
3527 /* Grow buffer if need be: the length calculation is as
3528 * follows handshake_header_length +
3529 * 4 (ticket lifetime hint) + 2 (ticket length) +
3530 * 16 (key name) + max_iv_len (iv length) +
3531 * session_length + max_enc_block_size (max encrypted session
3532 * length) + max_md_size (HMAC).
3534 if (!BUF_MEM_grow(s->init_buf,
3535 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3536 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3538 p = ssl_handshake_start(s);
3539 EVP_CIPHER_CTX_init(&ctx);
3540 HMAC_CTX_init(&hctx);
3541 /* Initialize HMAC and cipher contexts. If callback present
3542 * it does all the work otherwise use generated values
3545 if (tctx->tlsext_ticket_key_cb)
3547 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3556 RAND_pseudo_bytes(iv, 16);
3557 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3558 tctx->tlsext_tick_aes_key, iv);
3559 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3560 tlsext_tick_md(), NULL);
3561 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3564 /* Ticket lifetime hint (advisory only):
3565 * We leave this unspecified for resumed session (for simplicity),
3566 * and guess that tickets for new sessions will live as long
3567 * as their sessions. */
3568 l2n(s->hit ? 0 : s->session->timeout, p);
3570 /* Skip ticket length for now */
3572 /* Output key name */
3574 memcpy(p, key_name, 16);
3577 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3578 p += EVP_CIPHER_CTX_iv_length(&ctx);
3579 /* Encrypt session data */
3580 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3582 EVP_EncryptFinal(&ctx, p, &len);
3584 EVP_CIPHER_CTX_cleanup(&ctx);
3586 HMAC_Update(&hctx, macstart, p - macstart);
3587 HMAC_Final(&hctx, p, &hlen);
3588 HMAC_CTX_cleanup(&hctx);
3591 /* Now write out lengths: p points to end of data written */
3593 len = p - ssl_handshake_start(s);
3594 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3595 /* Skip ticket lifetime hint */
3596 p = ssl_handshake_start(s) + 4;
3598 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3602 /* SSL3_ST_SW_SESSION_TICKET_B */
3603 return ssl_do_write(s);
3606 int ssl3_send_cert_status(SSL *s)
3608 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3611 /* Grow buffer if need be: the length calculation is as
3612 * follows 1 (message type) + 3 (message length) +
3613 * 1 (ocsp response type) + 3 (ocsp response length)
3616 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3619 p=(unsigned char *)s->init_buf->data;
3622 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3623 /* message length */
3624 l2n3(s->tlsext_ocsp_resplen + 4, p);
3626 *(p++)= s->tlsext_status_type;
3627 /* length of OCSP response */
3628 l2n3(s->tlsext_ocsp_resplen, p);
3629 /* actual response */
3630 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3631 /* number of bytes to write */
3632 s->init_num = 8 + s->tlsext_ocsp_resplen;
3633 s->state=SSL3_ST_SW_CERT_STATUS_B;
3637 /* SSL3_ST_SW_CERT_STATUS_B */
3638 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3641 # ifndef OPENSSL_NO_NEXTPROTONEG
3642 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3643 * sets the next_proto member in s if found */
3644 int ssl3_get_next_proto(SSL *s)
3647 int proto_len, padding_len;
3649 const unsigned char *p;
3651 /* Clients cannot send a NextProtocol message if we didn't see the
3652 * extension in their ClientHello */
3653 if (!s->s3->next_proto_neg_seen)
3655 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3659 n=s->method->ssl_get_message(s,
3660 SSL3_ST_SR_NEXT_PROTO_A,
3661 SSL3_ST_SR_NEXT_PROTO_B,
3663 514, /* See the payload format below */
3669 /* s->state doesn't reflect whether ChangeCipherSpec has been received
3670 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3671 * by ssl3_get_finished). */
3672 if (!s->s3->change_cipher_spec)
3674 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3679 return 0; /* The body must be > 1 bytes long */
3681 p=(unsigned char *)s->init_msg;
3683 /* The payload looks like:
3685 * uint8 proto[proto_len];
3686 * uint8 padding_len;
3687 * uint8 padding[padding_len];
3690 if (proto_len + 2 > s->init_num)
3692 padding_len = p[proto_len + 1];
3693 if (proto_len + padding_len + 2 != s->init_num)
3696 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3697 if (!s->next_proto_negotiated)
3699 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3702 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3703 s->next_proto_negotiated_len = proto_len;