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);
278 s->type=SSL_ST_ACCEPT;
280 if (s->init_buf == NULL)
282 if ((buf=BUF_MEM_new()) == NULL)
287 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
295 if (!ssl3_setup_buffers(s))
302 s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
303 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
304 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
305 /* Should have been reset by ssl3_get_finished, too. */
306 s->s3->change_cipher_spec = 0;
308 if (s->state != SSL_ST_RENEGOTIATE)
310 /* Ok, we now need to push on a buffering BIO so that
311 * the output is sent in a way that TCP likes :-)
313 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
315 ssl3_init_finished_mac(s);
316 s->state=SSL3_ST_SR_CLNT_HELLO_A;
317 s->ctx->stats.sess_accept++;
319 else if (!s->s3->send_connection_binding &&
320 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
322 /* Server attempting to renegotiate with
323 * client that doesn't support secure
326 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
327 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
333 /* s->state == SSL_ST_RENEGOTIATE,
334 * we will just send a HelloRequest */
335 s->ctx->stats.sess_accept_renegotiate++;
336 s->state=SSL3_ST_SW_HELLO_REQ_A;
340 case SSL3_ST_SW_HELLO_REQ_A:
341 case SSL3_ST_SW_HELLO_REQ_B:
344 ret=ssl3_send_hello_request(s);
345 if (ret <= 0) goto end;
346 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
347 s->state=SSL3_ST_SW_FLUSH;
350 ssl3_init_finished_mac(s);
353 case SSL3_ST_SW_HELLO_REQ_C:
357 case SSL3_ST_SR_CLNT_HELLO_A:
358 case SSL3_ST_SR_CLNT_HELLO_B:
359 case SSL3_ST_SR_CLNT_HELLO_C:
362 ret=ssl3_get_client_hello(s);
363 if (ret <= 0) goto end;
364 #ifndef OPENSSL_NO_SRP
365 s->state = SSL3_ST_SR_CLNT_HELLO_D;
366 case SSL3_ST_SR_CLNT_HELLO_D:
369 if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
371 /* callback indicates firther work to be done */
372 s->rwstate=SSL_X509_LOOKUP;
375 if (ret != SSL_ERROR_NONE)
377 ssl3_send_alert(s,SSL3_AL_FATAL,al);
378 /* This is not really an error but the only means to
379 for a client to detect whether srp is supported. */
380 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
381 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
382 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
390 s->state=SSL3_ST_SW_SRVR_HELLO_A;
394 case SSL3_ST_SW_SRVR_HELLO_A:
395 case SSL3_ST_SW_SRVR_HELLO_B:
396 ret=ssl3_send_server_hello(s);
397 if (ret <= 0) goto end;
398 #ifndef OPENSSL_NO_TLSEXT
401 if (s->tlsext_ticket_expected)
402 s->state=SSL3_ST_SW_SESSION_TICKET_A;
404 s->state=SSL3_ST_SW_CHANGE_A;
408 s->state=SSL3_ST_SW_CHANGE_A;
411 s->state = SSL3_ST_SW_CERT_A;
415 case SSL3_ST_SW_CERT_A:
416 case SSL3_ST_SW_CERT_B:
417 /* Check if it is anon DH or anon ECDH, */
418 /* normal PSK or KRB5 or SRP */
419 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
420 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
422 ret=ssl3_send_server_certificate(s);
423 if (ret <= 0) goto end;
424 #ifndef OPENSSL_NO_TLSEXT
425 if (s->tlsext_status_expected)
426 s->state=SSL3_ST_SW_CERT_STATUS_A;
428 s->state=SSL3_ST_SW_KEY_EXCH_A;
433 s->state=SSL3_ST_SW_KEY_EXCH_A;
440 s->state=SSL3_ST_SW_KEY_EXCH_A;
445 case SSL3_ST_SW_KEY_EXCH_A:
446 case SSL3_ST_SW_KEY_EXCH_B:
447 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
449 /* clear this, it may get reset by
450 * send_server_key_exchange */
451 if ((s->options & SSL_OP_EPHEMERAL_RSA)
452 #ifndef OPENSSL_NO_KRB5
453 && !(alg_k & SSL_kKRB5)
454 #endif /* OPENSSL_NO_KRB5 */
456 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
457 * even when forbidden by protocol specs
458 * (handshake may fail as clients are not required to
459 * be able to handle this) */
460 s->s3->tmp.use_rsa_tmp=1;
462 s->s3->tmp.use_rsa_tmp=0;
465 /* only send if a DH key exchange, fortezza or
466 * RSA but we have a sign only certificate
468 * PSK: may send PSK identity hints
470 * For ECC ciphersuites, we send a serverKeyExchange
471 * message only if the cipher suite is either
472 * ECDH-anon or ECDHE. In other cases, the
473 * server certificate contains the server's
474 * public key for key exchange.
476 if (s->s3->tmp.use_rsa_tmp
477 /* PSK: send ServerKeyExchange if PSK identity
478 * hint if provided */
479 #ifndef OPENSSL_NO_PSK
480 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
482 #ifndef OPENSSL_NO_SRP
483 /* SRP: send ServerKeyExchange */
484 || (alg_k & SSL_kSRP)
486 || (alg_k & SSL_kEDH)
487 || (alg_k & SSL_kEECDH)
488 || ((alg_k & SSL_kRSA)
489 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
490 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
491 && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
497 ret=ssl3_send_server_key_exchange(s);
498 if (ret <= 0) goto end;
503 s->state=SSL3_ST_SW_CERT_REQ_A;
507 case SSL3_ST_SW_CERT_REQ_A:
508 case SSL3_ST_SW_CERT_REQ_B:
509 if (/* don't request cert unless asked for it: */
510 !(s->verify_mode & SSL_VERIFY_PEER) ||
511 /* if SSL_VERIFY_CLIENT_ONCE is set,
512 * don't request cert during re-negotiation: */
513 ((s->session->peer != NULL) &&
514 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
515 /* never request cert in anonymous ciphersuites
516 * (see section "Certificate request" in SSL 3 drafts
517 * and in RFC 2246): */
518 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
519 /* ... except when the application insists on verification
520 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
521 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
522 /* never request cert in Kerberos ciphersuites */
523 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
524 /* don't request certificate for SRP auth */
525 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
526 /* With normal PSK Certificates and
527 * Certificate Requests are omitted */
528 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
530 /* no cert request */
532 s->s3->tmp.cert_request=0;
533 s->state=SSL3_ST_SW_SRVR_DONE_A;
534 if (s->s3->handshake_buffer)
535 if (!ssl3_digest_cached_records(s))
540 s->s3->tmp.cert_request=1;
541 ret=ssl3_send_certificate_request(s);
542 if (ret <= 0) goto end;
543 #ifndef NETSCAPE_HANG_BUG
544 s->state=SSL3_ST_SW_SRVR_DONE_A;
546 s->state=SSL3_ST_SW_FLUSH;
547 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
553 case SSL3_ST_SW_SRVR_DONE_A:
554 case SSL3_ST_SW_SRVR_DONE_B:
555 ret=ssl3_send_server_done(s);
556 if (ret <= 0) goto end;
557 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
558 s->state=SSL3_ST_SW_FLUSH;
562 case SSL3_ST_SW_FLUSH:
564 /* This code originally checked to see if
565 * any data was pending using BIO_CTRL_INFO
566 * and then flushed. This caused problems
567 * as documented in PR#1939. The proposed
568 * fix doesn't completely resolve this issue
569 * as buggy implementations of BIO_CTRL_PENDING
570 * still exist. So instead we just flush
574 s->rwstate=SSL_WRITING;
575 if (BIO_flush(s->wbio) <= 0)
580 s->rwstate=SSL_NOTHING;
582 s->state=s->s3->tmp.next_state;
585 case SSL3_ST_SR_CERT_A:
586 case SSL3_ST_SR_CERT_B:
587 /* Check for second client hello (MS SGC) */
588 ret = ssl3_check_client_hello(s);
592 s->state = SSL3_ST_SR_CLNT_HELLO_C;
594 if (s->s3->tmp.cert_request)
596 ret=ssl3_get_client_certificate(s);
597 if (ret <= 0) goto end;
600 s->state=SSL3_ST_SR_KEY_EXCH_A;
604 case SSL3_ST_SR_KEY_EXCH_A:
605 case SSL3_ST_SR_KEY_EXCH_B:
606 ret=ssl3_get_client_key_exchange(s);
611 /* For the ECDH ciphersuites when
612 * the client sends its ECDH pub key in
613 * a certificate, the CertificateVerify
614 * message is not sent.
615 * Also for GOST ciphersuites when
616 * the client uses its key from the certificate
619 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
620 s->state=SSL3_ST_SR_FINISHED_A;
622 if (s->s3->next_proto_neg_seen)
623 s->state=SSL3_ST_SR_NEXT_PROTO_A;
625 s->state=SSL3_ST_SR_FINISHED_A;
629 else if (SSL_USE_SIGALGS(s))
631 s->state=SSL3_ST_SR_CERT_VRFY_A;
633 if (!s->session->peer)
635 /* For sigalgs freeze the handshake buffer
636 * at this point and digest cached records.
638 if (!s->s3->handshake_buffer)
640 SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
643 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
644 if (!ssl3_digest_cached_records(s))
652 s->state=SSL3_ST_SR_CERT_VRFY_A;
655 /* We need to get hashes here so if there is
656 * a client cert, it can be verified
657 * FIXME - digest processing for CertificateVerify
658 * should be generalized. But it is next step
660 if (s->s3->handshake_buffer)
661 if (!ssl3_digest_cached_records(s))
663 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
664 if (s->s3->handshake_dgst[dgst_num])
668 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]));
669 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
680 case SSL3_ST_SR_CERT_VRFY_A:
681 case SSL3_ST_SR_CERT_VRFY_B:
683 * This *should* be the first time we enable CCS, but be
684 * extra careful about surrounding code changes. We need
685 * to set this here because we don't know if we're
686 * expecting a CertificateVerify or not.
688 if (!s->s3->change_cipher_spec)
689 s->s3->flags |= SSL3_FLAGS_CCS_OK;
690 /* we should decide if we expected this one */
691 ret=ssl3_get_cert_verify(s);
692 if (ret <= 0) goto end;
694 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
695 s->state=SSL3_ST_SR_FINISHED_A;
697 if (s->s3->next_proto_neg_seen)
698 s->state=SSL3_ST_SR_NEXT_PROTO_A;
700 s->state=SSL3_ST_SR_FINISHED_A;
705 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
706 case SSL3_ST_SR_NEXT_PROTO_A:
707 case SSL3_ST_SR_NEXT_PROTO_B:
709 * Enable CCS for resumed handshakes with NPN.
710 * In a full handshake with NPN, we end up here through
711 * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
712 * already set. Receiving a CCS clears the flag, so make
713 * sure not to re-enable it to ban duplicates.
714 * s->s3->change_cipher_spec is set when a CCS is
715 * processed in s3_pkt.c, and remains set until
716 * the client's Finished message is read.
718 if (!s->s3->change_cipher_spec)
719 s->s3->flags |= SSL3_FLAGS_CCS_OK;
721 ret=ssl3_get_next_proto(s);
722 if (ret <= 0) goto end;
724 s->state=SSL3_ST_SR_FINISHED_A;
728 case SSL3_ST_SR_FINISHED_A:
729 case SSL3_ST_SR_FINISHED_B:
731 * Enable CCS for resumed handshakes without NPN.
732 * In a full handshake, we end up here through
733 * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
734 * already set. Receiving a CCS clears the flag, so make
735 * sure not to re-enable it to ban duplicates.
736 * s->s3->change_cipher_spec is set when a CCS is
737 * processed in s3_pkt.c, and remains set until
738 * the client's Finished message is read.
740 if (!s->s3->change_cipher_spec)
741 s->s3->flags |= SSL3_FLAGS_CCS_OK;
742 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
743 SSL3_ST_SR_FINISHED_B);
744 if (ret <= 0) goto end;
747 #ifndef OPENSSL_NO_TLSEXT
748 else if (s->tlsext_ticket_expected)
749 s->state=SSL3_ST_SW_SESSION_TICKET_A;
752 s->state=SSL3_ST_SW_CHANGE_A;
756 #ifndef OPENSSL_NO_TLSEXT
757 case SSL3_ST_SW_SESSION_TICKET_A:
758 case SSL3_ST_SW_SESSION_TICKET_B:
759 ret=ssl3_send_newsession_ticket(s);
760 if (ret <= 0) goto end;
761 s->state=SSL3_ST_SW_CHANGE_A;
765 case SSL3_ST_SW_CERT_STATUS_A:
766 case SSL3_ST_SW_CERT_STATUS_B:
767 ret=ssl3_send_cert_status(s);
768 if (ret <= 0) goto end;
769 s->state=SSL3_ST_SW_KEY_EXCH_A;
775 case SSL3_ST_SW_CHANGE_A:
776 case SSL3_ST_SW_CHANGE_B:
778 s->session->cipher=s->s3->tmp.new_cipher;
779 if (!s->method->ssl3_enc->setup_key_block(s))
780 { ret= -1; goto end; }
782 ret=ssl3_send_change_cipher_spec(s,
783 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
785 if (ret <= 0) goto end;
786 s->state=SSL3_ST_SW_FINISHED_A;
789 if (!s->method->ssl3_enc->change_cipher_state(s,
790 SSL3_CHANGE_CIPHER_SERVER_WRITE))
798 case SSL3_ST_SW_FINISHED_A:
799 case SSL3_ST_SW_FINISHED_B:
800 ret=ssl3_send_finished(s,
801 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
802 s->method->ssl3_enc->server_finished_label,
803 s->method->ssl3_enc->server_finished_label_len);
804 if (ret <= 0) goto end;
805 s->state=SSL3_ST_SW_FLUSH;
808 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
809 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
811 if (s->s3->next_proto_neg_seen)
813 s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
816 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
820 s->s3->tmp.next_state=SSL_ST_OK;
825 /* clean a few things up */
826 ssl3_cleanup_key_block(s);
828 BUF_MEM_free(s->init_buf);
831 /* remove buffering on output */
832 ssl_free_wbio_buffer(s);
836 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
841 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
843 s->ctx->stats.sess_accept_good++;
845 s->handshake_func=ssl3_accept;
847 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
855 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
861 if (!s->s3->tmp.reuse_message && !skip)
865 if ((ret=BIO_flush(s->wbio)) <= 0)
870 if ((cb != NULL) && (s->state != state))
874 cb(s,SSL_CB_ACCEPT_LOOP,1);
881 /* BIO_flush(s->wbio); */
885 cb(s,SSL_CB_ACCEPT_EXIT,ret);
889 int ssl3_send_hello_request(SSL *s)
892 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
894 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
895 s->state=SSL3_ST_SW_HELLO_REQ_B;
898 /* SSL3_ST_SW_HELLO_REQ_B */
899 return ssl_do_write(s);
902 int ssl3_check_client_hello(SSL *s)
907 /* this function is called when we really expect a Certificate message,
908 * so permit appropriate message length */
909 n=s->method->ssl_get_message(s,
915 if (!ok) return((int)n);
916 s->s3->tmp.reuse_message = 1;
917 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
919 /* We only allow the client to restart the handshake once per
921 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
923 SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
926 /* Throw away what we have done so far in the current handshake,
927 * which will now be aborted. (A full SSL_clear would be too much.) */
928 #ifndef OPENSSL_NO_DH
929 if (s->s3->tmp.dh != NULL)
931 DH_free(s->s3->tmp.dh);
932 s->s3->tmp.dh = NULL;
935 #ifndef OPENSSL_NO_ECDH
936 if (s->s3->tmp.ecdh != NULL)
938 EC_KEY_free(s->s3->tmp.ecdh);
939 s->s3->tmp.ecdh = NULL;
942 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
948 int ssl3_get_client_hello(SSL *s)
950 int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
951 unsigned int cookie_len;
956 #ifndef OPENSSL_NO_COMP
960 STACK_OF(SSL_CIPHER) *ciphers=NULL;
962 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
965 /* We do this so that we will respond with our native type.
966 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
967 * This down switching should be handled by a different method.
968 * If we are SSLv3, we will respond with SSLv3, even if prompted with
971 if (s->state == SSL3_ST_SR_CLNT_HELLO_A
974 s->state=SSL3_ST_SR_CLNT_HELLO_B;
977 n=s->method->ssl_get_message(s,
978 SSL3_ST_SR_CLNT_HELLO_B,
979 SSL3_ST_SR_CLNT_HELLO_C,
980 SSL3_MT_CLIENT_HELLO,
981 SSL3_RT_MAX_PLAIN_LENGTH,
984 if (!ok) return((int)n);
986 d=p=(unsigned char *)s->init_msg;
988 /* use version from inside client hello, not from record header
989 * (may differ: see RFC 2246, Appendix E, second paragraph) */
990 s->client_version=(((int)p[0])<<8)|(int)p[1];
993 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
994 s->method->version != DTLS_ANY_VERSION)
995 : (s->client_version < s->version))
997 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
998 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
999 !s->enc_write_ctx && !s->write_hash)
1001 /* similar to ssl3_get_record, send alert using remote version number */
1002 s->version = s->client_version;
1004 al = SSL_AD_PROTOCOL_VERSION;
1008 /* If we require cookies and this ClientHello doesn't
1009 * contain one, just return since we do not want to
1010 * allocate any memory yet. So check cookie length...
1012 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1014 unsigned int session_length, cookie_length;
1016 session_length = *(p + SSL3_RANDOM_SIZE);
1017 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1019 if (cookie_length == 0)
1023 /* load the client random */
1024 memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1025 p+=SSL3_RANDOM_SIZE;
1027 /* get the session-id */
1031 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1032 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1033 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1034 * than a change to default behavior so that applications relying on this for security
1035 * won't even compile against older library versions).
1037 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1038 * renegotiation but not a new session (s->new_session remains unset): for servers,
1039 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1040 * setting will be ignored.
1042 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1044 if (!ssl_get_new_session(s,1))
1049 i=ssl_get_prev_session(s, p, j, d + n);
1051 { /* previous session */
1058 if (!ssl_get_new_session(s,1))
1068 cookie_len = *(p++);
1071 * The ClientHello may contain a cookie even if the
1072 * HelloVerify message has not been sent--make sure that it
1073 * does not cause an overflow.
1075 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1078 al = SSL_AD_DECODE_ERROR;
1079 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1083 /* verify the cookie if appropriate option is set. */
1084 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1087 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1089 if ( s->ctx->app_verify_cookie_cb != NULL)
1091 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1094 al=SSL_AD_HANDSHAKE_FAILURE;
1095 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1096 SSL_R_COOKIE_MISMATCH);
1099 /* else cookie verification succeeded */
1101 else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1102 s->d1->cookie_len) != 0) /* default verification */
1104 al=SSL_AD_HANDSHAKE_FAILURE;
1105 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1106 SSL_R_COOKIE_MISMATCH);
1109 /* Set to -2 so if successful we return 2 */
1114 if (s->method->version == DTLS_ANY_VERSION)
1116 /* Select version to use */
1117 if (s->client_version <= DTLS1_2_VERSION &&
1118 !(s->options & SSL_OP_NO_DTLSv1_2))
1120 s->version = DTLS1_2_VERSION;
1121 s->method = DTLSv1_2_server_method();
1123 else if (tls1_suiteb(s))
1125 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1126 s->version = s->client_version;
1127 al = SSL_AD_PROTOCOL_VERSION;
1130 else if (s->client_version <= DTLS1_VERSION &&
1131 !(s->options & SSL_OP_NO_DTLSv1))
1133 s->version = DTLS1_VERSION;
1134 s->method = DTLSv1_server_method();
1138 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1139 s->version = s->client_version;
1140 al = SSL_AD_PROTOCOL_VERSION;
1143 s->session->ssl_version = s->version;
1148 if ((i == 0) && (j != 0))
1150 /* we need a cipher if we are not resuming a session */
1151 al=SSL_AD_ILLEGAL_PARAMETER;
1152 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1157 /* not enough data */
1158 al=SSL_AD_DECODE_ERROR;
1159 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1162 if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1169 /* If it is a hit, check that the cipher is in the list */
1170 if ((s->hit) && (i > 0))
1173 id=s->session->cipher->id;
1176 printf("client sent %d ciphers\n",sk_num(ciphers));
1178 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1180 c=sk_SSL_CIPHER_value(ciphers,i);
1182 printf("client [%2d of %2d]:%s\n",
1183 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1191 /* Disabled because it can be used in a ciphersuite downgrade
1192 * attack: CVE-2010-4180.
1195 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1197 /* Special case as client bug workaround: the previously used cipher may
1198 * not be in the current list, the client instead might be trying to
1199 * continue using a cipher that before wasn't chosen due to server
1200 * preferences. We'll have to reject the connection if the cipher is not
1201 * enabled, though. */
1202 c = sk_SSL_CIPHER_value(ciphers, 0);
1203 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1205 s->session->cipher = c;
1212 /* we need to have the cipher in the cipher
1213 * list if we are asked to reuse it */
1214 al=SSL_AD_ILLEGAL_PARAMETER;
1215 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1224 /* not enough data */
1225 al=SSL_AD_DECODE_ERROR;
1226 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1229 #ifndef OPENSSL_NO_COMP
1234 if (p[j] == 0) break;
1241 al=SSL_AD_DECODE_ERROR;
1242 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1246 #ifndef OPENSSL_NO_TLSEXT
1248 if (s->version >= SSL3_VERSION)
1250 if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
1252 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1257 /* Check if we want to use external pre-shared secret for this
1258 * handshake for not reused session only. We need to generate
1259 * server_random before calling tls_session_secret_cb in order to allow
1260 * SessionTicket processing to use it in key derivation. */
1263 pos=s->s3->server_random;
1264 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1270 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1272 SSL_CIPHER *pref_cipher=NULL;
1274 s->session->master_key_length=sizeof(s->session->master_key);
1275 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1276 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1279 s->session->ciphers=ciphers;
1280 s->session->verify_result=X509_V_OK;
1284 /* check if some cipher was preferred by call back */
1285 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1286 if (pref_cipher == NULL)
1288 al=SSL_AD_HANDSHAKE_FAILURE;
1289 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1293 s->session->cipher=pref_cipher;
1296 sk_SSL_CIPHER_free(s->cipher_list);
1298 if (s->cipher_list_by_id)
1299 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1301 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1302 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1307 /* Worst case, we will use the NULL compression, but if we have other
1308 * options, we will now look for them. We have i-1 compression
1309 * algorithms from the client, starting at q. */
1310 s->s3->tmp.new_compression=NULL;
1311 #ifndef OPENSSL_NO_COMP
1312 /* This only happens if we have a cache hit */
1313 if (s->session->compress_meth != 0)
1315 int m, comp_id = s->session->compress_meth;
1316 /* Perform sanity checks on resumed compression algorithm */
1317 /* Can't disable compression */
1318 if (s->options & SSL_OP_NO_COMPRESSION)
1320 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1323 /* Look for resumed compression method */
1324 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1326 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1327 if (comp_id == comp->id)
1329 s->s3->tmp.new_compression=comp;
1333 if (s->s3->tmp.new_compression == NULL)
1335 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1338 /* Look for resumed method in compression list */
1339 for (m = 0; m < i; m++)
1341 if (q[m] == comp_id)
1346 al=SSL_AD_ILLEGAL_PARAMETER;
1347 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1353 else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1354 { /* See if we have a match */
1355 int m,nn,o,v,done=0;
1357 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1358 for (m=0; m<nn; m++)
1360 comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1373 s->s3->tmp.new_compression=comp;
1378 /* If compression is disabled we'd better not try to resume a session
1379 * using compression.
1381 if (s->session->compress_meth != 0)
1383 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1388 /* Given s->session->ciphers and SSL_get_ciphers, we must
1393 #ifdef OPENSSL_NO_COMP
1394 s->session->compress_meth=0;
1396 s->session->compress_meth=(comp == NULL)?0:comp->id;
1398 if (s->session->ciphers != NULL)
1399 sk_SSL_CIPHER_free(s->session->ciphers);
1400 s->session->ciphers=ciphers;
1401 if (ciphers == NULL)
1403 al=SSL_AD_ILLEGAL_PARAMETER;
1404 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1408 if (!tls1_set_server_sigalgs(s))
1410 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1413 /* Let cert callback update server certificates if required */
1415 if (s->cert->cert_cb)
1417 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1420 al=SSL_AD_INTERNAL_ERROR;
1421 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
1426 s->rwstate=SSL_X509_LOOKUP;
1429 s->rwstate = SSL_NOTHING;
1431 c=ssl3_choose_cipher(s,s->session->ciphers,
1432 SSL_get_ciphers(s));
1436 al=SSL_AD_HANDSHAKE_FAILURE;
1437 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1440 s->s3->tmp.new_cipher=c;
1444 /* Session-id reuse */
1445 #ifdef REUSE_CIPHER_BUG
1446 STACK_OF(SSL_CIPHER) *sk;
1447 SSL_CIPHER *nc=NULL;
1448 SSL_CIPHER *ec=NULL;
1450 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1452 sk=s->session->ciphers;
1453 for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1455 c=sk_SSL_CIPHER_value(sk,i);
1456 if (c->algorithm_enc & SSL_eNULL)
1458 if (SSL_C_IS_EXPORT(c))
1462 s->s3->tmp.new_cipher=nc;
1463 else if (ec != NULL)
1464 s->s3->tmp.new_cipher=ec;
1466 s->s3->tmp.new_cipher=s->session->cipher;
1470 s->s3->tmp.new_cipher=s->session->cipher;
1473 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1475 if (!ssl3_digest_cached_records(s))
1479 /* we now have the following setup.
1481 * cipher_list - our prefered list of ciphers
1482 * ciphers - the clients prefered list of ciphers
1483 * compression - basically ignored right now
1484 * ssl version is set - sslv3
1485 * s->session - The ssl session has been setup.
1486 * s->hit - session reuse flag
1487 * s->tmp.new_cipher - the new cipher to use.
1490 /* Handles TLS extensions that we couldn't check earlier */
1491 if (s->version >= SSL3_VERSION)
1493 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1495 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1500 if (ret < 0) ret=-ret;
1504 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1507 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1508 return ret < 0 ? -1 : ret;
1511 int ssl3_send_server_hello(SSL *s)
1514 unsigned char *p,*d;
1519 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1521 buf=(unsigned char *)s->init_buf->data;
1522 #ifdef OPENSSL_NO_TLSEXT
1523 p=s->s3->server_random;
1524 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1527 /* Do the message type and length last */
1528 d=p= ssl_handshake_start(s);
1530 *(p++)=s->version>>8;
1531 *(p++)=s->version&0xff;
1534 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1535 p+=SSL3_RANDOM_SIZE;
1537 /* There are several cases for the session ID to send
1538 * back in the server hello:
1539 * - For session reuse from the session cache,
1540 * we send back the old session ID.
1541 * - If stateless session reuse (using a session ticket)
1542 * is successful, we send back the client's "session ID"
1543 * (which doesn't actually identify the session).
1544 * - If it is a new session, we send back the new
1546 * - However, if we want the new session to be single-use,
1547 * we send back a 0-length session ID.
1548 * s->hit is non-zero in either case of session reuse,
1549 * so the following won't overwrite an ID that we're supposed
1552 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1554 s->session->session_id_length=0;
1556 sl=s->session->session_id_length;
1557 if (sl > (int)sizeof(s->session->session_id))
1559 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1563 memcpy(p,s->session->session_id,sl);
1566 /* put the cipher */
1567 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1570 /* put the compression method */
1571 #ifdef OPENSSL_NO_COMP
1574 if (s->s3->tmp.new_compression == NULL)
1577 *(p++)=s->s3->tmp.new_compression->id;
1579 #ifndef OPENSSL_NO_TLSEXT
1580 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1582 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1585 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
1587 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1588 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1594 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1595 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1598 /* SSL3_ST_SW_SRVR_HELLO_B */
1599 return ssl_do_write(s);
1602 int ssl3_send_server_done(SSL *s)
1605 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1607 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1608 s->state = SSL3_ST_SW_SRVR_DONE_B;
1611 /* SSL3_ST_SW_SRVR_DONE_B */
1612 return ssl_do_write(s);
1615 int ssl3_send_server_key_exchange(SSL *s)
1617 #ifndef OPENSSL_NO_RSA
1621 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1624 #ifndef OPENSSL_NO_DH
1627 #ifndef OPENSSL_NO_ECDH
1628 EC_KEY *ecdh=NULL, *ecdhp;
1629 unsigned char *encodedPoint = NULL;
1632 BN_CTX *bn_ctx = NULL;
1635 const EVP_MD *md = NULL;
1636 unsigned char *p,*d;
1646 EVP_MD_CTX_init(&md_ctx);
1647 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1649 type=s->s3->tmp.new_cipher->algorithm_mkey;
1654 r[0]=r[1]=r[2]=r[3]=NULL;
1656 #ifndef OPENSSL_NO_RSA
1657 if (type & SSL_kRSA)
1660 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1662 rsa=s->cert->rsa_tmp_cb(s,
1663 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1664 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1667 al=SSL_AD_HANDSHAKE_FAILURE;
1668 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1676 al=SSL_AD_HANDSHAKE_FAILURE;
1677 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1682 s->s3->tmp.use_rsa_tmp=1;
1686 #ifndef OPENSSL_NO_DH
1687 if (type & SSL_kEDH)
1690 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1691 dhp=s->cert->dh_tmp_cb(s,
1692 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1693 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1696 al=SSL_AD_HANDSHAKE_FAILURE;
1697 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1701 if (s->s3->tmp.dh != NULL)
1703 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1707 if ((dh=DHparams_dup(dhp)) == NULL)
1709 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1714 if ((dhp->pub_key == NULL ||
1715 dhp->priv_key == NULL ||
1716 (s->options & SSL_OP_SINGLE_DH_USE)))
1718 if(!DH_generate_key(dh))
1720 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1727 dh->pub_key=BN_dup(dhp->pub_key);
1728 dh->priv_key=BN_dup(dhp->priv_key);
1729 if ((dh->pub_key == NULL) ||
1730 (dh->priv_key == NULL))
1732 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1742 #ifndef OPENSSL_NO_ECDH
1743 if (type & SSL_kEECDH)
1745 const EC_GROUP *group;
1747 ecdhp=cert->ecdh_tmp;
1748 if (s->cert->ecdh_tmp_auto)
1750 /* Get NID of appropriate shared curve */
1751 int nid = tls1_shared_curve(s, -2);
1752 if (nid != NID_undef)
1753 ecdhp = EC_KEY_new_by_curve_name(nid);
1755 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1757 ecdhp=s->cert->ecdh_tmp_cb(s,
1758 SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1759 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1763 al=SSL_AD_HANDSHAKE_FAILURE;
1764 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1768 if (s->s3->tmp.ecdh != NULL)
1770 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1774 /* Duplicate the ECDH structure. */
1777 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1780 if (s->cert->ecdh_tmp_auto)
1782 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1784 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1788 s->s3->tmp.ecdh=ecdh;
1789 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1790 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1791 (s->options & SSL_OP_SINGLE_ECDH_USE))
1793 if(!EC_KEY_generate_key(ecdh))
1795 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1800 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1801 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1802 (EC_KEY_get0_private_key(ecdh) == NULL))
1804 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1808 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1809 (EC_GROUP_get_degree(group) > 163))
1811 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1815 /* XXX: For now, we only support ephemeral ECDH
1816 * keys over named (not generic) curves. For
1817 * supported named curves, curve_id is non-zero.
1820 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1823 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1827 /* Encode the public key.
1828 * First check the size of encoding and
1829 * allocate memory accordingly.
1831 encodedlen = EC_POINT_point2oct(group,
1832 EC_KEY_get0_public_key(ecdh),
1833 POINT_CONVERSION_UNCOMPRESSED,
1836 encodedPoint = (unsigned char *)
1837 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1838 bn_ctx = BN_CTX_new();
1839 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1841 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1846 encodedlen = EC_POINT_point2oct(group,
1847 EC_KEY_get0_public_key(ecdh),
1848 POINT_CONVERSION_UNCOMPRESSED,
1849 encodedPoint, encodedlen, bn_ctx);
1851 if (encodedlen == 0)
1853 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1857 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1859 /* XXX: For now, we only support named (not
1860 * generic) curves in ECDH ephemeral key exchanges.
1861 * In this situation, we need four additional bytes
1862 * to encode the entire ServerECDHParams
1867 /* We'll generate the serverKeyExchange message
1868 * explicitly so we can set these to NULLs
1876 #endif /* !OPENSSL_NO_ECDH */
1877 #ifndef OPENSSL_NO_PSK
1878 if (type & SSL_kPSK)
1880 /* reserve size for record length and PSK identity hint*/
1881 n+=2+strlen(s->ctx->psk_identity_hint);
1884 #endif /* !OPENSSL_NO_PSK */
1885 #ifndef OPENSSL_NO_SRP
1886 if (type & SSL_kSRP)
1888 if ((s->srp_ctx.N == NULL) ||
1889 (s->srp_ctx.g == NULL) ||
1890 (s->srp_ctx.s == NULL) ||
1891 (s->srp_ctx.B == NULL))
1893 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1904 al=SSL_AD_HANDSHAKE_FAILURE;
1905 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1908 for (i=0; i < 4 && r[i] != NULL; i++)
1910 nr[i]=BN_num_bytes(r[i]);
1911 #ifndef OPENSSL_NO_SRP
1912 if ((i == 2) && (type & SSL_kSRP))
1919 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1920 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1922 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1925 al=SSL_AD_DECODE_ERROR;
1928 kn=EVP_PKEY_size(pkey);
1936 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1938 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1941 d = p = ssl_handshake_start(s);
1943 for (i=0; i < 4 && r[i] != NULL; i++)
1945 #ifndef OPENSSL_NO_SRP
1946 if ((i == 2) && (type & SSL_kSRP))
1958 #ifndef OPENSSL_NO_ECDH
1959 if (type & SSL_kEECDH)
1961 /* XXX: For now, we only support named (not generic) curves.
1962 * In this situation, the serverKeyExchange message has:
1963 * [1 byte CurveType], [2 byte CurveName]
1964 * [1 byte length of encoded point], followed by
1965 * the actual encoded point itself
1967 *p = NAMED_CURVE_TYPE;
1975 memcpy((unsigned char*)p,
1976 (unsigned char *)encodedPoint,
1978 OPENSSL_free(encodedPoint);
1979 encodedPoint = NULL;
1984 #ifndef OPENSSL_NO_PSK
1985 if (type & SSL_kPSK)
1987 /* copy PSK identity hint */
1988 s2n(strlen(s->ctx->psk_identity_hint), p);
1989 strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1990 p+=strlen(s->ctx->psk_identity_hint);
1997 /* n is the length of the params, they start at &(d[4])
1998 * and p points to the space at the end. */
1999 #ifndef OPENSSL_NO_RSA
2000 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
2004 for (num=2; num > 0; num--)
2006 EVP_MD_CTX_set_flags(&md_ctx,
2007 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2008 EVP_DigestInit_ex(&md_ctx,(num == 2)
2009 ?s->ctx->md5:s->ctx->sha1, NULL);
2010 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2011 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2012 EVP_DigestUpdate(&md_ctx,d,n);
2013 EVP_DigestFinal_ex(&md_ctx,q,
2014 (unsigned int *)&i);
2018 if (RSA_sign(NID_md5_sha1, md_buf, j,
2019 &(p[2]), &u, pkey->pkey.rsa) <= 0)
2021 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2031 /* send signature algorithm */
2032 if (SSL_USE_SIGALGS(s))
2034 if (!tls12_get_sigandhash(p, pkey, md))
2036 /* Should never happen */
2037 al=SSL_AD_INTERNAL_ERROR;
2038 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2044 fprintf(stderr, "Using hash %s\n",
2047 EVP_SignInit_ex(&md_ctx, md, NULL);
2048 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2049 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2050 EVP_SignUpdate(&md_ctx,d,n);
2051 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2052 (unsigned int *)&i,pkey))
2054 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2059 if (SSL_USE_SIGALGS(s))
2064 /* Is this error check actually needed? */
2065 al=SSL_AD_HANDSHAKE_FAILURE;
2066 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2071 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2074 s->state = SSL3_ST_SW_KEY_EXCH_B;
2075 EVP_MD_CTX_cleanup(&md_ctx);
2076 return ssl_do_write(s);
2078 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2080 #ifndef OPENSSL_NO_ECDH
2081 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2082 BN_CTX_free(bn_ctx);
2084 EVP_MD_CTX_cleanup(&md_ctx);
2088 int ssl3_send_certificate_request(SSL *s)
2090 unsigned char *p,*d;
2092 STACK_OF(X509_NAME) *sk=NULL;
2096 if (s->state == SSL3_ST_SW_CERT_REQ_A)
2100 d=p=ssl_handshake_start(s);
2102 /* get the list of acceptable cert types */
2104 n=ssl3_get_req_cert_type(s,p);
2109 if (SSL_USE_SIGALGS(s))
2111 const unsigned char *psigs;
2112 nl = tls12_get_psigalgs(s, &psigs);
2114 memcpy(p, psigs, nl);
2123 sk=SSL_get_client_CA_list(s);
2127 for (i=0; i<sk_X509_NAME_num(sk); i++)
2129 name=sk_X509_NAME_value(sk,i);
2130 j=i2d_X509_NAME(name,NULL);
2131 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
2133 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2136 p = ssl_handshake_start(s) + n;
2137 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2140 i2d_X509_NAME(name,&p);
2147 i2d_X509_NAME(name,&p);
2148 j-=2; s2n(j,d); j+=2;
2154 /* else no CA names */
2155 p = ssl_handshake_start(s) + off;
2158 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2160 #ifdef NETSCAPE_HANG_BUG
2161 if (!SSL_IS_DTLS(s))
2163 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2165 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2168 p=(unsigned char *)s->init_buf->data + s->init_num;
2170 *(p++)=SSL3_MT_SERVER_DONE;
2178 s->state = SSL3_ST_SW_CERT_REQ_B;
2181 /* SSL3_ST_SW_CERT_REQ_B */
2182 return ssl_do_write(s);
2187 int ssl3_get_client_key_exchange(SSL *s)
2191 unsigned long alg_k;
2193 #ifndef OPENSSL_NO_RSA
2195 EVP_PKEY *pkey=NULL;
2197 #ifndef OPENSSL_NO_DH
2199 DH *dh_srvr, *dh_clnt = NULL;
2201 #ifndef OPENSSL_NO_KRB5
2203 #endif /* OPENSSL_NO_KRB5 */
2205 #ifndef OPENSSL_NO_ECDH
2206 EC_KEY *srvr_ecdh = NULL;
2207 EVP_PKEY *clnt_pub_pkey = NULL;
2208 EC_POINT *clnt_ecpoint = NULL;
2209 BN_CTX *bn_ctx = NULL;
2212 n=s->method->ssl_get_message(s,
2213 SSL3_ST_SR_KEY_EXCH_A,
2214 SSL3_ST_SR_KEY_EXCH_B,
2215 SSL3_MT_CLIENT_KEY_EXCHANGE,
2219 if (!ok) return((int)n);
2220 p=(unsigned char *)s->init_msg;
2222 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2224 #ifndef OPENSSL_NO_RSA
2225 if (alg_k & SSL_kRSA)
2227 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2229 unsigned char decrypt_good, version_good;
2231 /* FIX THIS UP EAY EAY EAY EAY */
2232 if (s->s3->tmp.use_rsa_tmp)
2234 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2235 rsa=s->cert->rsa_tmp;
2236 /* Don't do a callback because rsa_tmp should
2237 * be sent already */
2240 al=SSL_AD_HANDSHAKE_FAILURE;
2241 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2248 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2249 if ( (pkey == NULL) ||
2250 (pkey->type != EVP_PKEY_RSA) ||
2251 (pkey->pkey.rsa == NULL))
2253 al=SSL_AD_HANDSHAKE_FAILURE;
2254 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2260 /* TLS and [incidentally] DTLS{0xFEFF} */
2261 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2266 if (!(s->options & SSL_OP_TLS_D5_BUG))
2268 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2278 /* We must not leak whether a decryption failure occurs because
2279 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2280 * RFC 2246, section 7.4.7.1). The code follows that advice of
2281 * the TLS RFC and generates a random premaster secret for the
2282 * case that the decrypt fails. See
2283 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2285 /* should be RAND_bytes, but we cannot work around a failure. */
2286 if (RAND_pseudo_bytes(rand_premaster_secret,
2287 sizeof(rand_premaster_secret)) <= 0)
2289 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2292 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2293 * decrypt_good will be 0xff if so and zero otherwise. */
2294 decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2296 /* If the version in the decrypted pre-master secret is correct
2297 * then version_good will be 0xff, otherwise it'll be zero.
2298 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2299 * (http://eprint.iacr.org/2003/052/) exploits the version
2300 * number check as a "bad version oracle". Thus version checks
2301 * are done in constant time and are treated like any other
2302 * decryption error. */
2303 version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2304 version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2306 /* The premaster secret must contain the same version number as
2307 * the ClientHello to detect version rollback attacks
2308 * (strangely, the protocol does not offer such protection for
2309 * DH ciphersuites). However, buggy clients exist that send the
2310 * negotiated protocol version instead if the server does not
2311 * support the requested protocol version. If
2312 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2313 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2315 unsigned char workaround_good;
2316 workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2317 workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2318 version_good |= workaround_good;
2321 /* Both decryption and version must be good for decrypt_good
2322 * to remain non-zero (0xff). */
2323 decrypt_good &= version_good;
2325 /* Now copy rand_premaster_secret over p using
2326 * decrypt_good_mask. */
2327 for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2329 p[i] = constant_time_select_8(decrypt_good, p[i],
2330 rand_premaster_secret[i]);
2333 s->session->master_key_length=
2334 s->method->ssl3_enc->generate_master_secret(s,
2335 s->session->master_key,
2337 OPENSSL_cleanse(p,i);
2341 #ifndef OPENSSL_NO_DH
2342 if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2345 EVP_PKEY *skey = NULL;
2352 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2354 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2363 if (alg_k & SSL_kDHr)
2364 idx = SSL_PKEY_DH_RSA;
2365 else if (alg_k & SSL_kDHd)
2366 idx = SSL_PKEY_DH_DSA;
2369 skey = s->cert->pkeys[idx].privatekey;
2370 if ((skey == NULL) ||
2371 (skey->type != EVP_PKEY_DH) ||
2372 (skey->pkey.dh == NULL))
2374 al=SSL_AD_HANDSHAKE_FAILURE;
2375 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2378 dh_srvr = skey->pkey.dh;
2380 else if (s->s3->tmp.dh == NULL)
2382 al=SSL_AD_HANDSHAKE_FAILURE;
2383 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2387 dh_srvr=s->s3->tmp.dh;
2391 /* Get pubkey from cert */
2392 EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2395 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2396 dh_clnt = EVP_PKEY_get1_DH(clkey);
2398 if (dh_clnt == NULL)
2400 al=SSL_AD_HANDSHAKE_FAILURE;
2401 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2404 EVP_PKEY_free(clkey);
2405 pub = dh_clnt->pub_key;
2408 pub=BN_bin2bn(p,i,NULL);
2411 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2415 i=DH_compute_key(p,pub,dh_srvr);
2419 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2424 DH_free(s->s3->tmp.dh);
2431 s->session->master_key_length=
2432 s->method->ssl3_enc->generate_master_secret(s,
2433 s->session->master_key,p,i);
2434 OPENSSL_cleanse(p,i);
2440 #ifndef OPENSSL_NO_KRB5
2441 if (alg_k & SSL_kKRB5)
2443 krb5_error_code krb5rc;
2444 krb5_data enc_ticket;
2445 krb5_data authenticator;
2447 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2448 EVP_CIPHER_CTX ciph_ctx;
2449 const EVP_CIPHER *enc = NULL;
2450 unsigned char iv[EVP_MAX_IV_LENGTH];
2451 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH
2452 + EVP_MAX_BLOCK_LENGTH];
2454 krb5_timestamp authtime = 0;
2455 krb5_ticket_times ttimes;
2457 EVP_CIPHER_CTX_init(&ciph_ctx);
2459 if (!kssl_ctx) kssl_ctx = kssl_ctx_new();
2462 enc_ticket.length = i;
2464 if (n < (long)(enc_ticket.length + 6))
2466 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2467 SSL_R_DATA_LENGTH_TOO_LONG);
2471 enc_ticket.data = (char *)p;
2472 p+=enc_ticket.length;
2475 authenticator.length = i;
2477 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2479 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2480 SSL_R_DATA_LENGTH_TOO_LONG);
2484 authenticator.data = (char *)p;
2485 p+=authenticator.length;
2489 enc_pms.data = (char *)p;
2492 /* Note that the length is checked again below,
2495 if(enc_pms.length > sizeof pms)
2497 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2498 SSL_R_DATA_LENGTH_TOO_LONG);
2502 if (n != (long)(enc_ticket.length + authenticator.length +
2503 enc_pms.length + 6))
2505 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2506 SSL_R_DATA_LENGTH_TOO_LONG);
2510 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2514 printf("kssl_sget_tkt rtn %d [%d]\n",
2515 krb5rc, kssl_err.reason);
2517 printf("kssl_err text= %s\n", kssl_err.text);
2518 #endif /* KSSL_DEBUG */
2519 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2524 /* Note: no authenticator is not considered an error,
2525 ** but will return authtime == 0.
2527 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2528 &authtime, &kssl_err)) != 0)
2531 printf("kssl_check_authent rtn %d [%d]\n",
2532 krb5rc, kssl_err.reason);
2534 printf("kssl_err text= %s\n", kssl_err.text);
2535 #endif /* KSSL_DEBUG */
2536 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2541 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2543 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2548 kssl_ctx_show(kssl_ctx);
2549 #endif /* KSSL_DEBUG */
2551 enc = kssl_map_enc(kssl_ctx->enctype);
2555 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2557 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2559 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2560 SSL_R_DECRYPTION_FAILED);
2563 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2564 (unsigned char *)enc_pms.data, enc_pms.length))
2566 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2567 SSL_R_DECRYPTION_FAILED);
2570 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2572 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2573 SSL_R_DATA_LENGTH_TOO_LONG);
2576 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2578 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2579 SSL_R_DECRYPTION_FAILED);
2583 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2585 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2586 SSL_R_DATA_LENGTH_TOO_LONG);
2589 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2591 /* The premaster secret must contain the same version number as the
2592 * ClientHello to detect version rollback attacks (strangely, the
2593 * protocol does not offer such protection for DH ciphersuites).
2594 * However, buggy clients exist that send random bytes instead of
2595 * the protocol version.
2596 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2597 * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2599 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2601 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2602 SSL_AD_DECODE_ERROR);
2607 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2609 s->session->master_key_length=
2610 s->method->ssl3_enc->generate_master_secret(s,
2611 s->session->master_key, pms, outl);
2613 if (kssl_ctx->client_princ)
2615 size_t len = strlen(kssl_ctx->client_princ);
2616 if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH )
2618 s->session->krb5_client_princ_len = len;
2619 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2624 /* Was doing kssl_ctx_free() here,
2625 ** but it caused problems for apache.
2626 ** kssl_ctx = kssl_ctx_free(kssl_ctx);
2627 ** if (s->kssl_ctx) s->kssl_ctx = NULL;
2631 #endif /* OPENSSL_NO_KRB5 */
2633 #ifndef OPENSSL_NO_ECDH
2634 if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2639 const EC_GROUP *group;
2640 const BIGNUM *priv_key;
2642 /* initialize structures for server's ECDH key pair */
2643 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2645 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2646 ERR_R_MALLOC_FAILURE);
2650 /* Let's get server private key and group information */
2651 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2653 /* use the certificate */
2654 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2658 /* use the ephermeral values we saved when
2659 * generating the ServerKeyExchange msg.
2661 tkey = s->s3->tmp.ecdh;
2664 group = EC_KEY_get0_group(tkey);
2665 priv_key = EC_KEY_get0_private_key(tkey);
2667 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2668 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2670 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2675 /* Let's get client's public key */
2676 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2678 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2679 ERR_R_MALLOC_FAILURE);
2685 /* Client Publickey was in Client Certificate */
2687 if (alg_k & SSL_kEECDH)
2689 al=SSL_AD_HANDSHAKE_FAILURE;
2690 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2693 if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2695 (clnt_pub_pkey->type != EVP_PKEY_EC))
2697 /* XXX: For now, we do not support client
2698 * authentication using ECDH certificates
2699 * so this branch (n == 0L) of the code is
2700 * never executed. When that support is
2701 * added, we ought to ensure the key
2702 * received in the certificate is
2703 * authorized for key agreement.
2704 * ECDH_compute_key implicitly checks that
2705 * the two ECDH shares are for the same
2708 al=SSL_AD_HANDSHAKE_FAILURE;
2709 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2710 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2714 if (EC_POINT_copy(clnt_ecpoint,
2715 EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2717 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2721 ret = 2; /* Skip certificate verify processing */
2725 /* Get client's public key from encoded point
2726 * in the ClientKeyExchange message.
2728 if ((bn_ctx = BN_CTX_new()) == NULL)
2730 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2731 ERR_R_MALLOC_FAILURE);
2735 /* Get encoded point length */
2740 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2744 if (EC_POINT_oct2point(group,
2745 clnt_ecpoint, p, i, bn_ctx) == 0)
2747 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2751 /* p is pointing to somewhere in the buffer
2752 * currently, so set it to the start
2754 p=(unsigned char *)s->init_buf->data;
2757 /* Compute the shared pre-master secret */
2758 field_size = EC_GROUP_get_degree(group);
2759 if (field_size <= 0)
2761 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2765 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2768 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2773 EVP_PKEY_free(clnt_pub_pkey);
2774 EC_POINT_free(clnt_ecpoint);
2775 EC_KEY_free(srvr_ecdh);
2776 BN_CTX_free(bn_ctx);
2777 EC_KEY_free(s->s3->tmp.ecdh);
2778 s->s3->tmp.ecdh = NULL;
2780 /* Compute the master secret */
2781 s->session->master_key_length = s->method->ssl3_enc-> \
2782 generate_master_secret(s, s->session->master_key, p, i);
2784 OPENSSL_cleanse(p, i);
2789 #ifndef OPENSSL_NO_PSK
2790 if (alg_k & SSL_kPSK)
2792 unsigned char *t = NULL;
2793 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2794 unsigned int pre_ms_len = 0, psk_len = 0;
2796 char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2798 al=SSL_AD_HANDSHAKE_FAILURE;
2803 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2804 SSL_R_LENGTH_MISMATCH);
2807 if (i > PSK_MAX_IDENTITY_LEN)
2809 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2810 SSL_R_DATA_LENGTH_TOO_LONG);
2813 if (s->psk_server_callback == NULL)
2815 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2816 SSL_R_PSK_NO_SERVER_CB);
2820 /* Create guaranteed NULL-terminated identity
2821 * string for the callback */
2822 memcpy(tmp_id, p, i);
2823 memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2824 psk_len = s->psk_server_callback(s, tmp_id,
2825 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2826 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2828 if (psk_len > PSK_MAX_PSK_LEN)
2830 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2831 ERR_R_INTERNAL_ERROR);
2834 else if (psk_len == 0)
2836 /* PSK related to the given identity not found */
2837 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2838 SSL_R_PSK_IDENTITY_NOT_FOUND);
2839 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2843 /* create PSK pre_master_secret */
2844 pre_ms_len=2+psk_len+2+psk_len;
2846 memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2848 memset(t, 0, psk_len);
2852 if (s->session->psk_identity != NULL)
2853 OPENSSL_free(s->session->psk_identity);
2854 s->session->psk_identity = BUF_strdup((char *)p);
2855 if (s->session->psk_identity == NULL)
2857 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2858 ERR_R_MALLOC_FAILURE);
2862 if (s->session->psk_identity_hint != NULL)
2863 OPENSSL_free(s->session->psk_identity_hint);
2864 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2865 if (s->ctx->psk_identity_hint != NULL &&
2866 s->session->psk_identity_hint == NULL)
2868 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2869 ERR_R_MALLOC_FAILURE);
2873 s->session->master_key_length=
2874 s->method->ssl3_enc->generate_master_secret(s,
2875 s->session->master_key, psk_or_pre_ms, pre_ms_len);
2878 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2884 #ifndef OPENSSL_NO_SRP
2885 if (alg_k & SSL_kSRP)
2893 al=SSL_AD_DECODE_ERROR;
2894 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2897 if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2899 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2902 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2903 || BN_is_zero(s->srp_ctx.A))
2905 al=SSL_AD_ILLEGAL_PARAMETER;
2906 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
2909 if (s->session->srp_username != NULL)
2910 OPENSSL_free(s->session->srp_username);
2911 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2912 if (s->session->srp_username == NULL)
2914 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2915 ERR_R_MALLOC_FAILURE);
2919 if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2921 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2928 #endif /* OPENSSL_NO_SRP */
2929 if (alg_k & SSL_kGOST)
2932 EVP_PKEY_CTX *pkey_ctx;
2933 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2934 unsigned char premaster_secret[32], *start;
2935 size_t outlen=32, inlen;
2936 unsigned long alg_a;
2940 /* Get our certificate private key*/
2941 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2942 if (alg_a & SSL_aGOST94)
2943 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2944 else if (alg_a & SSL_aGOST01)
2945 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2947 pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2948 EVP_PKEY_decrypt_init(pkey_ctx);
2949 /* If client certificate is present and is of the same type, maybe
2950 * use it for key exchange. Don't mind errors from
2951 * EVP_PKEY_derive_set_peer, because it is completely valid to use
2952 * a client certificate for authorization only. */
2953 client_pub_pkey = X509_get_pubkey(s->session->peer);
2954 if (client_pub_pkey)
2956 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2959 /* Decrypt session key */
2960 if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED ||
2961 Ttag != V_ASN1_SEQUENCE ||
2962 Tclass != V_ASN1_UNIVERSAL)
2964 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2969 if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0)
2972 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2975 /* Generate master secret */
2976 s->session->master_key_length=
2977 s->method->ssl3_enc->generate_master_secret(s,
2978 s->session->master_key,premaster_secret,32);
2979 /* Check if pubkey from client certificate was used */
2980 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2985 EVP_PKEY_free(client_pub_pkey);
2986 EVP_PKEY_CTX_free(pkey_ctx);
2994 al=SSL_AD_HANDSHAKE_FAILURE;
2995 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2996 SSL_R_UNKNOWN_CIPHER_TYPE);
3002 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3003 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3006 #ifndef OPENSSL_NO_ECDH
3007 EVP_PKEY_free(clnt_pub_pkey);
3008 EC_POINT_free(clnt_ecpoint);
3009 if (srvr_ecdh != NULL)
3010 EC_KEY_free(srvr_ecdh);
3011 BN_CTX_free(bn_ctx);
3016 int ssl3_get_cert_verify(SSL *s)
3018 EVP_PKEY *pkey=NULL;
3024 const EVP_MD *md = NULL;
3026 EVP_MD_CTX_init(&mctx);
3028 n=s->method->ssl_get_message(s,
3029 SSL3_ST_SR_CERT_VRFY_A,
3030 SSL3_ST_SR_CERT_VRFY_B,
3032 SSL3_RT_MAX_PLAIN_LENGTH,
3035 if (!ok) return((int)n);
3037 if (s->session->peer != NULL)
3039 peer=s->session->peer;
3040 pkey=X509_get_pubkey(peer);
3041 type=X509_certificate_type(peer,pkey);
3049 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3051 s->s3->tmp.reuse_message=1;
3052 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3054 al=SSL_AD_UNEXPECTED_MESSAGE;
3055 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3064 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3065 al=SSL_AD_UNEXPECTED_MESSAGE;
3069 if (!(type & EVP_PKT_SIGN))
3071 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3072 al=SSL_AD_ILLEGAL_PARAMETER;
3076 if (s->s3->change_cipher_spec)
3078 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3079 al=SSL_AD_UNEXPECTED_MESSAGE;
3083 /* we now have a signature that we need to verify */
3084 p=(unsigned char *)s->init_msg;
3085 /* Check for broken implementations of GOST ciphersuites */
3086 /* If key is GOST and n is exactly 64, it is bare
3087 * signature without length field */
3088 if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3089 pkey->type == NID_id_GostR3410_2001) )
3095 if (SSL_USE_SIGALGS(s))
3097 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3100 al = SSL_AD_INTERNAL_ERROR;
3105 al = SSL_AD_DECODE_ERROR;
3109 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3118 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3119 al=SSL_AD_DECODE_ERROR;
3123 j=EVP_PKEY_size(pkey);
3124 if ((i > j) || (n > j) || (n <= 0))
3126 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3127 al=SSL_AD_DECODE_ERROR;
3131 if (SSL_USE_SIGALGS(s))
3135 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3138 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3139 al=SSL_AD_INTERNAL_ERROR;
3143 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3146 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3147 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3149 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3150 al=SSL_AD_INTERNAL_ERROR;
3154 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3156 al=SSL_AD_DECRYPT_ERROR;
3157 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3162 #ifndef OPENSSL_NO_RSA
3163 if (pkey->type == EVP_PKEY_RSA)
3165 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3166 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
3170 al=SSL_AD_DECRYPT_ERROR;
3171 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3176 al=SSL_AD_DECRYPT_ERROR;
3177 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3183 #ifndef OPENSSL_NO_DSA
3184 if (pkey->type == EVP_PKEY_DSA)
3186 j=DSA_verify(pkey->save_type,
3187 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3188 SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3192 al=SSL_AD_DECRYPT_ERROR;
3193 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3199 #ifndef OPENSSL_NO_ECDSA
3200 if (pkey->type == EVP_PKEY_EC)
3202 j=ECDSA_verify(pkey->save_type,
3203 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3204 SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3208 al=SSL_AD_DECRYPT_ERROR;
3209 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3210 SSL_R_BAD_ECDSA_SIGNATURE);
3216 if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3217 { unsigned char signature[64];
3219 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3220 EVP_PKEY_verify_init(pctx);
3222 fprintf(stderr,"GOST signature length is %d",i);
3224 for (idx=0;idx<64;idx++) {
3225 signature[63-idx]=p[idx];
3227 j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3228 EVP_PKEY_CTX_free(pctx);
3231 al=SSL_AD_DECRYPT_ERROR;
3232 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3233 SSL_R_BAD_ECDSA_SIGNATURE);
3239 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3240 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3249 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3252 if (s->s3->handshake_buffer)
3254 BIO_free(s->s3->handshake_buffer);
3255 s->s3->handshake_buffer = NULL;
3256 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3258 EVP_MD_CTX_cleanup(&mctx);
3259 EVP_PKEY_free(pkey);
3263 int ssl3_get_client_certificate(SSL *s)
3265 int i,ok,al,ret= -1;
3267 unsigned long l,nc,llen,n;
3268 const unsigned char *p,*q;
3270 STACK_OF(X509) *sk=NULL;
3272 n=s->method->ssl_get_message(s,
3279 if (!ok) return((int)n);
3281 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3283 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
3284 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3286 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3287 al=SSL_AD_HANDSHAKE_FAILURE;
3290 /* If tls asked for a client cert, the client must return a 0 list */
3291 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3293 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3294 al=SSL_AD_UNEXPECTED_MESSAGE;
3297 s->s3->tmp.reuse_message=1;
3301 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3303 al=SSL_AD_UNEXPECTED_MESSAGE;
3304 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3307 p=d=(unsigned char *)s->init_msg;
3309 if ((sk=sk_X509_new_null()) == NULL)
3311 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3318 al=SSL_AD_DECODE_ERROR;
3319 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3322 for (nc=0; nc<llen; )
3325 if ((l+nc+3) > llen)
3327 al=SSL_AD_DECODE_ERROR;
3328 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3333 x=d2i_X509(NULL,&p,l);
3336 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3341 al=SSL_AD_DECODE_ERROR;
3342 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3345 if (!sk_X509_push(sk,x))
3347 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3354 if (sk_X509_num(sk) <= 0)
3356 /* TLS does not mind 0 certs returned */
3357 if (s->version == SSL3_VERSION)
3359 al=SSL_AD_HANDSHAKE_FAILURE;
3360 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3363 /* Fail for TLS only if we required a certificate */
3364 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3365 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3367 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3368 al=SSL_AD_HANDSHAKE_FAILURE;
3371 /* No client certificate so digest cached records */
3372 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3374 al=SSL_AD_INTERNAL_ERROR;
3380 i=ssl_verify_cert_chain(s,sk);
3383 al=ssl_verify_alarm_type(s->verify_result);
3384 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3389 if (s->session->peer != NULL) /* This should not be needed */
3390 X509_free(s->session->peer);
3391 s->session->peer=sk_X509_shift(sk);
3392 s->session->verify_result = s->verify_result;
3394 /* With the current implementation, sess_cert will always be NULL
3395 * when we arrive here. */
3396 if (s->session->sess_cert == NULL)
3398 s->session->sess_cert = ssl_sess_cert_new();
3399 if (s->session->sess_cert == NULL)
3401 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3405 if (s->session->sess_cert->cert_chain != NULL)
3406 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3407 s->session->sess_cert->cert_chain=sk;
3408 /* Inconsistency alert: cert_chain does *not* include the
3409 * peer's own certificate, while we do include it in s3_clnt.c */
3417 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3420 if (x != NULL) X509_free(x);
3421 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3425 int ssl3_send_server_certificate(SSL *s)
3429 if (s->state == SSL3_ST_SW_CERT_A)
3431 cpk=ssl_get_server_send_pkey(s);
3434 /* VRS: allow null cert if auth == KRB5 */
3435 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3436 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3438 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3443 ssl3_output_cert_chain(s,cpk);
3444 s->state=SSL3_ST_SW_CERT_B;
3447 /* SSL3_ST_SW_CERT_B */
3448 return ssl_do_write(s);
3451 #ifndef OPENSSL_NO_TLSEXT
3452 /* send a new session ticket (not necessarily for a new session) */
3453 int ssl3_send_newsession_ticket(SSL *s)
3455 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3457 unsigned char *p, *senc, *macstart;
3458 const unsigned char *const_p;
3459 int len, slen_full, slen;
3464 SSL_CTX *tctx = s->initial_ctx;
3465 unsigned char iv[EVP_MAX_IV_LENGTH];
3466 unsigned char key_name[16];
3468 /* get session encoding length */
3469 slen_full = i2d_SSL_SESSION(s->session, NULL);
3470 /* Some length values are 16 bits, so forget it if session is
3473 if (slen_full > 0xFF00)
3475 senc = OPENSSL_malloc(slen_full);
3479 i2d_SSL_SESSION(s->session, &p);
3481 /* create a fresh copy (not shared with other threads) to clean up */
3483 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3489 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3491 slen = i2d_SSL_SESSION(sess, NULL);
3492 if (slen > slen_full) /* shouldn't ever happen */
3498 i2d_SSL_SESSION(sess, &p);
3499 SSL_SESSION_free(sess);
3501 /* Grow buffer if need be: the length calculation is as
3502 * follows handshake_header_length +
3503 * 4 (ticket lifetime hint) + 2 (ticket length) +
3504 * 16 (key name) + max_iv_len (iv length) +
3505 * session_length + max_enc_block_size (max encrypted session
3506 * length) + max_md_size (HMAC).
3508 if (!BUF_MEM_grow(s->init_buf,
3509 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3510 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3512 p = ssl_handshake_start(s);
3513 EVP_CIPHER_CTX_init(&ctx);
3514 HMAC_CTX_init(&hctx);
3515 /* Initialize HMAC and cipher contexts. If callback present
3516 * it does all the work otherwise use generated values
3519 if (tctx->tlsext_ticket_key_cb)
3521 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3530 RAND_pseudo_bytes(iv, 16);
3531 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3532 tctx->tlsext_tick_aes_key, iv);
3533 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3534 tlsext_tick_md(), NULL);
3535 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3538 /* Ticket lifetime hint (advisory only):
3539 * We leave this unspecified for resumed session (for simplicity),
3540 * and guess that tickets for new sessions will live as long
3541 * as their sessions. */
3542 l2n(s->hit ? 0 : s->session->timeout, p);
3544 /* Skip ticket length for now */
3546 /* Output key name */
3548 memcpy(p, key_name, 16);
3551 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3552 p += EVP_CIPHER_CTX_iv_length(&ctx);
3553 /* Encrypt session data */
3554 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3556 EVP_EncryptFinal(&ctx, p, &len);
3558 EVP_CIPHER_CTX_cleanup(&ctx);
3560 HMAC_Update(&hctx, macstart, p - macstart);
3561 HMAC_Final(&hctx, p, &hlen);
3562 HMAC_CTX_cleanup(&hctx);
3565 /* Now write out lengths: p points to end of data written */
3567 len = p - ssl_handshake_start(s);
3568 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3569 /* Skip ticket lifetime hint */
3570 p = ssl_handshake_start(s) + 4;
3572 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3576 /* SSL3_ST_SW_SESSION_TICKET_B */
3577 return ssl_do_write(s);
3580 int ssl3_send_cert_status(SSL *s)
3582 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3585 /* Grow buffer if need be: the length calculation is as
3586 * follows 1 (message type) + 3 (message length) +
3587 * 1 (ocsp response type) + 3 (ocsp response length)
3590 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3593 p=(unsigned char *)s->init_buf->data;
3596 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3597 /* message length */
3598 l2n3(s->tlsext_ocsp_resplen + 4, p);
3600 *(p++)= s->tlsext_status_type;
3601 /* length of OCSP response */
3602 l2n3(s->tlsext_ocsp_resplen, p);
3603 /* actual response */
3604 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3605 /* number of bytes to write */
3606 s->init_num = 8 + s->tlsext_ocsp_resplen;
3607 s->state=SSL3_ST_SW_CERT_STATUS_B;
3611 /* SSL3_ST_SW_CERT_STATUS_B */
3612 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3615 # ifndef OPENSSL_NO_NEXTPROTONEG
3616 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3617 * sets the next_proto member in s if found */
3618 int ssl3_get_next_proto(SSL *s)
3621 int proto_len, padding_len;
3623 const unsigned char *p;
3625 /* Clients cannot send a NextProtocol message if we didn't see the
3626 * extension in their ClientHello */
3627 if (!s->s3->next_proto_neg_seen)
3629 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3633 n=s->method->ssl_get_message(s,
3634 SSL3_ST_SR_NEXT_PROTO_A,
3635 SSL3_ST_SR_NEXT_PROTO_B,
3637 514, /* See the payload format below */
3643 /* s->state doesn't reflect whether ChangeCipherSpec has been received
3644 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3645 * by ssl3_get_finished). */
3646 if (!s->s3->change_cipher_spec)
3648 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3653 return 0; /* The body must be > 1 bytes long */
3655 p=(unsigned char *)s->init_msg;
3657 /* The payload looks like:
3659 * uint8 proto[proto_len];
3660 * uint8 padding_len;
3661 * uint8 padding[padding_len];
3664 if (proto_len + 2 > s->init_num)
3666 padding_len = p[proto_len + 1];
3667 if (proto_len + padding_len + 2 != s->init_num)
3670 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3671 if (!s->next_proto_negotiated)
3673 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3676 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3677 s->next_proto_negotiated_len = proto_len;