440fc13e4fe75765005d8a12e8d9ea103a5822b0
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
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.
8  * 
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).
15  * 
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.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
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)"
40  * 
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
51  * SUCH DAMAGE.
52  * 
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.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
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
71  *    distribution.
72  *
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/)"
77  *
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.
82  *
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.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
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  * ====================================================================
105  *
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).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by 
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
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.
134  *
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.
138  *
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.
143  *
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
148  * OTHERWISE.
149  */
150
151 #define REUSE_CIPHER_BUG
152 #define NETSCAPE_HANG_BUG
153
154 #include <stdio.h>
155 #include "ssl_locl.h"
156 #include "kssl_lcl.h"
157 #include <openssl/buffer.h>
158 #include <openssl/rand.h>
159 #include <openssl/objects.h>
160 #include <openssl/evp.h>
161 #include <openssl/hmac.h>
162 #include <openssl/x509.h>
163 #ifndef OPENSSL_NO_DH
164 #include <openssl/dh.h>
165 #endif
166 #include <openssl/bn.h>
167 #ifndef OPENSSL_NO_KRB5
168 #include <openssl/krb5_asn.h>
169 #endif
170 #include <openssl/md5.h>
171
172 static const SSL_METHOD *ssl3_get_server_method(int ver);
173
174 static const SSL_METHOD *ssl3_get_server_method(int ver)
175         {
176         if (ver == SSL3_VERSION)
177                 return(SSLv3_server_method());
178         else
179                 return(NULL);
180         }
181
182 #ifndef OPENSSL_NO_SRP
183 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
184         {
185         int ret = SSL_ERROR_NONE;
186
187         *al = SSL_AD_UNRECOGNIZED_NAME;
188
189         if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
190             (s->srp_ctx.TLS_ext_srp_username_callback != NULL))
191                 {
192                 if(s->srp_ctx.login == NULL)
193                         {
194                         /* RFC 5054 says SHOULD reject, 
195                            we do so if There is no srp login name */
196                         ret = SSL3_AL_FATAL;
197                         *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
198                         }
199                 else
200                         {
201                         ret = SSL_srp_server_param_with_username(s,al);
202                         }
203                 }
204         return ret;
205         }
206 #endif
207
208 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
209                         ssl3_accept,
210                         ssl_undefined_function,
211                         ssl3_get_server_method)
212
213 int ssl3_accept(SSL *s)
214         {
215         BUF_MEM *buf;
216         unsigned long alg_k,Time=(unsigned long)time(NULL);
217         void (*cb)(const SSL *ssl,int type,int val)=NULL;
218         int ret= -1;
219         int new_state,state,skip=0;
220
221         RAND_add(&Time,sizeof(Time),0);
222         ERR_clear_error();
223         clear_sys_error();
224
225         if (s->info_callback != NULL)
226                 cb=s->info_callback;
227         else if (s->ctx->info_callback != NULL)
228                 cb=s->ctx->info_callback;
229
230         /* init things to blank */
231         s->in_handshake++;
232         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
233
234         if (s->cert == NULL)
235                 {
236                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
237                 return(-1);
238                 }
239
240 #ifndef OPENSSL_NO_HEARTBEATS
241         /* If we're awaiting a HeartbeatResponse, pretend we
242          * already got and don't await it anymore, because
243          * Heartbeats don't make sense during handshakes anyway.
244          */
245         if (s->tlsext_hb_pending)
246                 {
247                 s->tlsext_hb_pending = 0;
248                 s->tlsext_hb_seq++;
249                 }
250 #endif
251
252         for (;;)
253                 {
254                 state=s->state;
255
256                 switch (s->state)
257                         {
258                 case SSL_ST_RENEGOTIATE:
259                         s->renegotiate=1;
260                         /* s->state=SSL_ST_ACCEPT; */
261
262                 case SSL_ST_BEFORE:
263                 case SSL_ST_ACCEPT:
264                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
265                 case SSL_ST_OK|SSL_ST_ACCEPT:
266
267                         s->server=1;
268                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
269
270                         if ((s->version>>8) != 3)
271                                 {
272                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
273                                 return -1;
274                                 }
275
276                         if (!ssl_security(s, SSL_SECOP_VERSION, 0,
277                                                         s->version, NULL))
278                                 {
279                                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
280                                 return -1;
281                                 }
282
283                         s->type=SSL_ST_ACCEPT;
284
285                         if (s->init_buf == NULL)
286                                 {
287                                 if ((buf=BUF_MEM_new()) == NULL)
288                                         {
289                                         ret= -1;
290                                         goto end;
291                                         }
292                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
293                                         {
294                                         ret= -1;
295                                         goto end;
296                                         }
297                                 s->init_buf=buf;
298                                 }
299
300                         if (!ssl3_setup_buffers(s))
301                                 {
302                                 ret= -1;
303                                 goto end;
304                                 }
305
306                         s->init_num=0;
307                         s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
308                         s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
309
310                         if (s->state != SSL_ST_RENEGOTIATE)
311                                 {
312                                 /* Ok, we now need to push on a buffering BIO so that
313                                  * the output is sent in a way that TCP likes :-)
314                                  */
315                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
316                                 
317                                 ssl3_init_finished_mac(s);
318                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
319                                 s->ctx->stats.sess_accept++;
320                                 }
321                         else if (!s->s3->send_connection_binding &&
322                                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
323                                 {
324                                 /* Server attempting to renegotiate with
325                                  * client that doesn't support secure
326                                  * renegotiation.
327                                  */
328                                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
329                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
330                                 ret = -1;
331                                 goto end;
332                                 }
333                         else
334                                 {
335                                 /* s->state == SSL_ST_RENEGOTIATE,
336                                  * we will just send a HelloRequest */
337                                 s->ctx->stats.sess_accept_renegotiate++;
338                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
339                                 }
340                         break;
341
342                 case SSL3_ST_SW_HELLO_REQ_A:
343                 case SSL3_ST_SW_HELLO_REQ_B:
344
345                         s->shutdown=0;
346                         ret=ssl3_send_hello_request(s);
347                         if (ret <= 0) goto end;
348                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
349                         s->state=SSL3_ST_SW_FLUSH;
350                         s->init_num=0;
351
352                         ssl3_init_finished_mac(s);
353                         break;
354
355                 case SSL3_ST_SW_HELLO_REQ_C:
356                         s->state=SSL_ST_OK;
357                         break;
358
359                 case SSL3_ST_SR_CLNT_HELLO_A:
360                 case SSL3_ST_SR_CLNT_HELLO_B:
361                 case SSL3_ST_SR_CLNT_HELLO_C:
362
363                         ret=ssl3_get_client_hello(s);
364                         if (ret <= 0) goto end;
365 #ifndef OPENSSL_NO_SRP
366                         s->state = SSL3_ST_SR_CLNT_HELLO_D;
367                 case SSL3_ST_SR_CLNT_HELLO_D:
368                         {
369                         int al;
370                         if ((ret = ssl_check_srp_ext_ClientHello(s,&al))  < 0)
371                                         {
372                                         /* callback indicates firther work to be done */
373                                         s->rwstate=SSL_X509_LOOKUP;
374                                         goto end;
375                                         }
376                         if (ret != SSL_ERROR_NONE)
377                                 {
378                                 ssl3_send_alert(s,SSL3_AL_FATAL,al);    
379                                 /* This is not really an error but the only means to
380                                    for a client to detect whether srp is supported. */
381                                    if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)      
382                                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);                     
383                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;                       
384                                 ret= -1;
385                                 goto end;       
386                                 }
387                         }
388 #endif          
389                         
390                         s->renegotiate = 2;
391                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
392                         s->init_num=0;
393                         break;
394
395                 case SSL3_ST_SW_SRVR_HELLO_A:
396                 case SSL3_ST_SW_SRVR_HELLO_B:
397                         ret=ssl3_send_server_hello(s);
398                         if (ret <= 0) goto end;
399 #ifndef OPENSSL_NO_TLSEXT
400                         if (s->hit)
401                                 {
402                                 if (s->tlsext_ticket_expected)
403                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
404                                 else
405                                         s->state=SSL3_ST_SW_CHANGE_A;
406                                 }
407 #else
408                         if (s->hit)
409                                         s->state=SSL3_ST_SW_CHANGE_A;
410 #endif
411                         else
412                                         s->state = SSL3_ST_SW_CERT_A;
413                         s->init_num = 0;
414                         break;
415
416                 case SSL3_ST_SW_CERT_A:
417                 case SSL3_ST_SW_CERT_B:
418                         /* Check if it is anon DH or anon ECDH, */
419                         /* normal PSK or KRB5 or SRP */
420                         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
421                                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
422                                 {
423                                 ret=ssl3_send_server_certificate(s);
424                                 if (ret <= 0) goto end;
425 #ifndef OPENSSL_NO_TLSEXT
426                                 if (s->tlsext_status_expected)
427                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
428                                 else
429                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
430                                 }
431                         else
432                                 {
433                                 skip = 1;
434                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
435                                 }
436 #else
437                                 }
438                         else
439                                 skip=1;
440
441                         s->state=SSL3_ST_SW_KEY_EXCH_A;
442 #endif
443                         s->init_num=0;
444                         break;
445
446                 case SSL3_ST_SW_KEY_EXCH_A:
447                 case SSL3_ST_SW_KEY_EXCH_B:
448                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
449
450                         /* clear this, it may get reset by
451                          * send_server_key_exchange */
452                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
453 #ifndef OPENSSL_NO_KRB5
454                                 && !(alg_k & SSL_kKRB5)
455 #endif /* OPENSSL_NO_KRB5 */
456                                 )
457                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
458                                  * even when forbidden by protocol specs
459                                  * (handshake may fail as clients are not required to
460                                  * be able to handle this) */
461                                 s->s3->tmp.use_rsa_tmp=1;
462                         else
463                                 s->s3->tmp.use_rsa_tmp=0;
464
465
466                         /* only send if a DH key exchange, fortezza or
467                          * RSA but we have a sign only certificate
468                          *
469                          * PSK: may send PSK identity hints
470                          *
471                          * For ECC ciphersuites, we send a serverKeyExchange
472                          * message only if the cipher suite is either
473                          * ECDH-anon or ECDHE. In other cases, the
474                          * server certificate contains the server's
475                          * public key for key exchange.
476                          */
477                         if (s->s3->tmp.use_rsa_tmp
478                         /* PSK: send ServerKeyExchange if PSK identity
479                          * hint if provided */
480 #ifndef OPENSSL_NO_PSK
481                             || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
482 #endif
483 #ifndef OPENSSL_NO_SRP
484                             /* SRP: send ServerKeyExchange */
485                             || (alg_k & SSL_kSRP)
486 #endif
487                             || (alg_k & SSL_kDHE)
488                             || (alg_k & SSL_kECDHE)
489                             || ((alg_k & SSL_kRSA)
490                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
491                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
492                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
493                                         )
494                                     )
495                                 )
496                             )
497                                 {
498                                 ret=ssl3_send_server_key_exchange(s);
499                                 if (ret <= 0) goto end;
500                                 }
501                         else
502                                 skip=1;
503
504                         s->state=SSL3_ST_SW_CERT_REQ_A;
505                         s->init_num=0;
506                         break;
507
508                 case SSL3_ST_SW_CERT_REQ_A:
509                 case SSL3_ST_SW_CERT_REQ_B:
510                         if (/* don't request cert unless asked for it: */
511                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
512                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
513                                  * don't request cert during re-negotiation: */
514                                 ((s->session->peer != NULL) &&
515                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
516                                 /* never request cert in anonymous ciphersuites
517                                  * (see section "Certificate request" in SSL 3 drafts
518                                  * and in RFC 2246): */
519                                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
520                                  /* ... except when the application insists on verification
521                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
522                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
523                                  /* never request cert in Kerberos ciphersuites */
524                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
525                                 /* don't request certificate for SRP auth */
526                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
527                                 /* With normal PSK Certificates and
528                                  * Certificate Requests are omitted */
529                                 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
530                                 {
531                                 /* no cert request */
532                                 skip=1;
533                                 s->s3->tmp.cert_request=0;
534                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
535                                 if (s->s3->handshake_buffer)
536                                         if (!ssl3_digest_cached_records(s))
537                                                 return -1;
538                                 }
539                         else
540                                 {
541                                 s->s3->tmp.cert_request=1;
542                                 ret=ssl3_send_certificate_request(s);
543                                 if (ret <= 0) goto end;
544 #ifndef NETSCAPE_HANG_BUG
545                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
546 #else
547                                 s->state=SSL3_ST_SW_FLUSH;
548                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
549 #endif
550                                 s->init_num=0;
551                                 }
552                         break;
553
554                 case SSL3_ST_SW_SRVR_DONE_A:
555                 case SSL3_ST_SW_SRVR_DONE_B:
556                         ret=ssl3_send_server_done(s);
557                         if (ret <= 0) goto end;
558                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
559                         s->state=SSL3_ST_SW_FLUSH;
560                         s->init_num=0;
561                         break;
562                 
563                 case SSL3_ST_SW_FLUSH:
564
565                         /* This code originally checked to see if
566                          * any data was pending using BIO_CTRL_INFO
567                          * and then flushed. This caused problems
568                          * as documented in PR#1939. The proposed
569                          * fix doesn't completely resolve this issue
570                          * as buggy implementations of BIO_CTRL_PENDING
571                          * still exist. So instead we just flush
572                          * unconditionally.
573                          */
574
575                         s->rwstate=SSL_WRITING;
576                         if (BIO_flush(s->wbio) <= 0)
577                                 {
578                                 ret= -1;
579                                 goto end;
580                                 }
581                         s->rwstate=SSL_NOTHING;
582
583                         s->state=s->s3->tmp.next_state;
584                         break;
585
586                 case SSL3_ST_SR_CERT_A:
587                 case SSL3_ST_SR_CERT_B:
588                         /* Check for second client hello (MS SGC) */
589                         ret = ssl3_check_client_hello(s);
590                         if (ret <= 0)
591                                 goto end;
592                         if (ret == 2)
593                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
594                         else {
595                                 if (s->s3->tmp.cert_request)
596                                         {
597                                         ret=ssl3_get_client_certificate(s);
598                                         if (ret <= 0) goto end;
599                                         }
600                                 s->init_num=0;
601                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
602                         }
603                         break;
604
605                 case SSL3_ST_SR_KEY_EXCH_A:
606                 case SSL3_ST_SR_KEY_EXCH_B:
607                         ret=ssl3_get_client_key_exchange(s);
608                         if (ret <= 0)
609                                 goto end;
610                         if (ret == 2)
611                                 {
612                                 /* For the ECDH ciphersuites when
613                                  * the client sends its ECDH pub key in
614                                  * a certificate, the CertificateVerify
615                                  * message is not sent.
616                                  * Also for GOST ciphersuites when
617                                  * the client uses its key from the certificate
618                                  * for key exchange.
619                                  */
620 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
621                                 s->state=SSL3_ST_SR_FINISHED_A;
622 #else
623                                 if (s->s3->next_proto_neg_seen)
624                                         s->state=SSL3_ST_SR_NEXT_PROTO_A;
625                                 else
626                                         s->state=SSL3_ST_SR_FINISHED_A;
627 #endif
628                                 s->init_num = 0;
629                                 }
630                         else if (SSL_USE_SIGALGS(s))
631                                 {
632                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
633                                 s->init_num=0;
634                                 if (!s->session->peer)
635                                         break;
636                                 /* For sigalgs freeze the handshake buffer
637                                  * at this point and digest cached records.
638                                  */
639                                 if (!s->s3->handshake_buffer)
640                                         {
641                                         SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
642                                         return -1;
643                                         }
644                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
645                                 if (!ssl3_digest_cached_records(s))
646                                         return -1;
647                                 }
648                         else
649                                 {
650                                 int offset=0;
651                                 int dgst_num;
652
653                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
654                                 s->init_num=0;
655
656                                 /* We need to get hashes here so if there is
657                                  * a client cert, it can be verified
658                                  * FIXME - digest processing for CertificateVerify
659                                  * should be generalized. But it is next step
660                                  */
661                                 if (s->s3->handshake_buffer)
662                                         if (!ssl3_digest_cached_records(s))
663                                                 return -1;
664                                 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
665                                         if (s->s3->handshake_dgst[dgst_num]) 
666                                                 {
667                                                 int dgst_size;
668
669                                                 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]));
670                                                 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
671                                                 if (dgst_size < 0)
672                                                         {
673                                                         ret = -1;
674                                                         goto end;
675                                                         }
676                                                 offset+=dgst_size;
677                                                 }               
678                                 }
679                         break;
680
681                 case SSL3_ST_SR_CERT_VRFY_A:
682                 case SSL3_ST_SR_CERT_VRFY_B:
683
684                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
685                         /* we should decide if we expected this one */
686                         ret=ssl3_get_cert_verify(s);
687                         if (ret <= 0) goto end;
688
689 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
690                         s->state=SSL3_ST_SR_FINISHED_A;
691 #else
692                         if (s->s3->next_proto_neg_seen)
693                                 s->state=SSL3_ST_SR_NEXT_PROTO_A;
694                         else
695                                 s->state=SSL3_ST_SR_FINISHED_A;
696 #endif
697                         s->init_num=0;
698                         break;
699
700 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
701                 case SSL3_ST_SR_NEXT_PROTO_A:
702                 case SSL3_ST_SR_NEXT_PROTO_B:
703                         ret=ssl3_get_next_proto(s);
704                         if (ret <= 0) goto end;
705                         s->init_num = 0;
706                         s->state=SSL3_ST_SR_FINISHED_A;
707                         break;
708 #endif
709
710                 case SSL3_ST_SR_FINISHED_A:
711                 case SSL3_ST_SR_FINISHED_B:
712                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
713                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
714                                 SSL3_ST_SR_FINISHED_B);
715                         if (ret <= 0) goto end;
716                         if (s->hit)
717                                 s->state=SSL_ST_OK;
718 #ifndef OPENSSL_NO_TLSEXT
719                         else if (s->tlsext_ticket_expected)
720                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
721 #endif
722                         else
723                                 s->state=SSL3_ST_SW_CHANGE_A;
724                         s->init_num=0;
725                         break;
726
727 #ifndef OPENSSL_NO_TLSEXT
728                 case SSL3_ST_SW_SESSION_TICKET_A:
729                 case SSL3_ST_SW_SESSION_TICKET_B:
730                         ret=ssl3_send_newsession_ticket(s);
731                         if (ret <= 0) goto end;
732                         s->state=SSL3_ST_SW_CHANGE_A;
733                         s->init_num=0;
734                         break;
735
736                 case SSL3_ST_SW_CERT_STATUS_A:
737                 case SSL3_ST_SW_CERT_STATUS_B:
738                         ret=ssl3_send_cert_status(s);
739                         if (ret <= 0) goto end;
740                         s->state=SSL3_ST_SW_KEY_EXCH_A;
741                         s->init_num=0;
742                         break;
743
744 #endif
745
746                 case SSL3_ST_SW_CHANGE_A:
747                 case SSL3_ST_SW_CHANGE_B:
748
749                         s->session->cipher=s->s3->tmp.new_cipher;
750                         if (!s->method->ssl3_enc->setup_key_block(s))
751                                 { ret= -1; goto end; }
752
753                         ret=ssl3_send_change_cipher_spec(s,
754                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
755
756                         if (ret <= 0) goto end;
757                         s->state=SSL3_ST_SW_FINISHED_A;
758                         s->init_num=0;
759
760                         if (!s->method->ssl3_enc->change_cipher_state(s,
761                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
762                                 {
763                                 ret= -1;
764                                 goto end;
765                                 }
766
767                         break;
768
769                 case SSL3_ST_SW_FINISHED_A:
770                 case SSL3_ST_SW_FINISHED_B:
771                         ret=ssl3_send_finished(s,
772                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
773                                 s->method->ssl3_enc->server_finished_label,
774                                 s->method->ssl3_enc->server_finished_label_len);
775                         if (ret <= 0) goto end;
776                         s->state=SSL3_ST_SW_FLUSH;
777                         if (s->hit)
778                                 {
779 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
780                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
781 #else
782                                 if (s->s3->next_proto_neg_seen)
783                                         {
784                                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
785                                         s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
786                                         }
787                                 else
788                                         s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
789 #endif
790                                 }
791                         else
792                                 s->s3->tmp.next_state=SSL_ST_OK;
793                         s->init_num=0;
794                         break;
795
796                 case SSL_ST_OK:
797                         /* clean a few things up */
798                         ssl3_cleanup_key_block(s);
799
800                         BUF_MEM_free(s->init_buf);
801                         s->init_buf=NULL;
802
803                         /* remove buffering on output */
804                         ssl_free_wbio_buffer(s);
805
806                         s->init_num=0;
807
808                         if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
809                                 {
810                                 s->renegotiate=0;
811                                 s->new_session=0;
812                                 
813                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
814                                 
815                                 s->ctx->stats.sess_accept_good++;
816                                 /* s->server=1; */
817                                 s->handshake_func=ssl3_accept;
818
819                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
820                                 }
821                         
822                         ret = 1;
823                         goto end;
824                         /* break; */
825
826                 default:
827                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
828                         ret= -1;
829                         goto end;
830                         /* break; */
831                         }
832                 
833                 if (!s->s3->tmp.reuse_message && !skip)
834                         {
835                         if (s->debug)
836                                 {
837                                 if ((ret=BIO_flush(s->wbio)) <= 0)
838                                         goto end;
839                                 }
840
841
842                         if ((cb != NULL) && (s->state != state))
843                                 {
844                                 new_state=s->state;
845                                 s->state=state;
846                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
847                                 s->state=new_state;
848                                 }
849                         }
850                 skip=0;
851                 }
852 end:
853         /* BIO_flush(s->wbio); */
854
855         s->in_handshake--;
856         if (cb != NULL)
857                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
858         return(ret);
859         }
860
861 int ssl3_send_hello_request(SSL *s)
862         {
863
864         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
865                 {
866                 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
867                 s->state=SSL3_ST_SW_HELLO_REQ_B;
868                 }
869
870         /* SSL3_ST_SW_HELLO_REQ_B */
871         return ssl_do_write(s);
872         }
873
874 int ssl3_check_client_hello(SSL *s)
875         {
876         int ok;
877         long n;
878
879         /* this function is called when we really expect a Certificate message,
880          * so permit appropriate message length */
881         n=s->method->ssl_get_message(s,
882                 SSL3_ST_SR_CERT_A,
883                 SSL3_ST_SR_CERT_B,
884                 -1,
885                 s->max_cert_list,
886                 &ok);
887         if (!ok) return((int)n);
888         s->s3->tmp.reuse_message = 1;
889         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
890                 {
891                 /* We only allow the client to restart the handshake once per
892                  * negotiation. */
893                 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
894                         {
895                         SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
896                         return -1;
897                         }
898                 /* Throw away what we have done so far in the current handshake,
899                  * which will now be aborted. (A full SSL_clear would be too much.) */
900 #ifndef OPENSSL_NO_DH
901                 if (s->s3->tmp.dh != NULL)
902                         {
903                         DH_free(s->s3->tmp.dh);
904                         s->s3->tmp.dh = NULL;
905                         }
906 #endif
907 #ifndef OPENSSL_NO_ECDH
908                 if (s->s3->tmp.ecdh != NULL)
909                         {
910                         EC_KEY_free(s->s3->tmp.ecdh);
911                         s->s3->tmp.ecdh = NULL;
912                         }
913 #endif
914                 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
915                 return 2;
916                 }
917         return 1;
918 }
919
920 int ssl3_get_client_hello(SSL *s)
921         {
922         int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
923         unsigned int cookie_len;
924         long n;
925         unsigned long id;
926         unsigned char *p,*d;
927         SSL_CIPHER *c;
928 #ifndef OPENSSL_NO_COMP
929         unsigned char *q;
930         SSL_COMP *comp=NULL;
931 #endif
932         STACK_OF(SSL_CIPHER) *ciphers=NULL;
933
934         if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
935                 goto retry_cert;
936
937         /* We do this so that we will respond with our native type.
938          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
939          * This down switching should be handled by a different method.
940          * If we are SSLv3, we will respond with SSLv3, even if prompted with
941          * TLSv1.
942          */
943         if (s->state == SSL3_ST_SR_CLNT_HELLO_A
944                 )
945                 {
946                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
947                 }
948         s->first_packet=1;
949         n=s->method->ssl_get_message(s,
950                 SSL3_ST_SR_CLNT_HELLO_B,
951                 SSL3_ST_SR_CLNT_HELLO_C,
952                 SSL3_MT_CLIENT_HELLO,
953                 SSL3_RT_MAX_PLAIN_LENGTH,
954                 &ok);
955
956         if (!ok) return((int)n);
957         s->first_packet=0;
958         d=p=(unsigned char *)s->init_msg;
959
960         /* use version from inside client hello, not from record header
961          * (may differ: see RFC 2246, Appendix E, second paragraph) */
962         s->client_version=(((int)p[0])<<8)|(int)p[1];
963         p+=2;
964
965         if (SSL_IS_DTLS(s)  ?   (s->client_version > s->version &&
966                                  s->method->version != DTLS_ANY_VERSION)
967                             :   (s->client_version < s->version))
968                 {
969                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
970                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
971                         !s->enc_write_ctx && !s->write_hash)
972                         {
973                         /* similar to ssl3_get_record, send alert using remote version number */
974                         s->version = s->client_version;
975                         }
976                 al = SSL_AD_PROTOCOL_VERSION;
977                 goto f_err;
978                 }
979
980         /* If we require cookies and this ClientHello doesn't
981          * contain one, just return since we do not want to
982          * allocate any memory yet. So check cookie length...
983          */
984         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
985                 {
986                 unsigned int session_length, cookie_length;
987                 
988                 session_length = *(p + SSL3_RANDOM_SIZE);
989                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
990
991                 if (cookie_length == 0)
992                         return 1;
993                 }
994
995         /* load the client random */
996         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
997         p+=SSL3_RANDOM_SIZE;
998
999         /* get the session-id */
1000         j= *(p++);
1001
1002         s->hit=0;
1003         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1004          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1005          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1006          * than a change to default behavior so that applications relying on this for security
1007          * won't even compile against older library versions).
1008          *
1009          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1010          * renegotiation but not a new session (s->new_session remains unset): for servers,
1011          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1012          * setting will be ignored.
1013          */
1014         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1015                 {
1016                 if (!ssl_get_new_session(s,1))
1017                         goto err;
1018                 }
1019         else
1020                 {
1021                 i=ssl_get_prev_session(s, p, j, d + n);
1022                 if (i == 1)
1023                         { /* previous session */
1024                         s->hit=1;
1025                         }
1026                 else if (i == -1)
1027                         goto err;
1028                 else /* i == 0 */
1029                         {
1030                         if (!ssl_get_new_session(s,1))
1031                                 goto err;
1032                         }
1033                 }
1034
1035         p+=j;
1036
1037         if (SSL_IS_DTLS(s))
1038                 {
1039                 /* cookie stuff */
1040                 cookie_len = *(p++);
1041
1042                 /* 
1043                  * The ClientHello may contain a cookie even if the
1044                  * HelloVerify message has not been sent--make sure that it
1045                  * does not cause an overflow.
1046                  */
1047                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1048                         {
1049                         /* too much data */
1050                         al = SSL_AD_DECODE_ERROR;
1051                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1052                         goto f_err;
1053                         }
1054
1055                 /* verify the cookie if appropriate option is set. */
1056                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1057                         cookie_len > 0)
1058                         {
1059                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
1060
1061                         if ( s->ctx->app_verify_cookie_cb != NULL)
1062                                 {
1063                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1064                                         cookie_len) == 0)
1065                                         {
1066                                         al=SSL_AD_HANDSHAKE_FAILURE;
1067                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1068                                                 SSL_R_COOKIE_MISMATCH);
1069                                         goto f_err;
1070                                         }
1071                                 /* else cookie verification succeeded */
1072                                 }
1073                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
1074                                                   s->d1->cookie_len) != 0) /* default verification */
1075                                 {
1076                                         al=SSL_AD_HANDSHAKE_FAILURE;
1077                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1078                                                 SSL_R_COOKIE_MISMATCH);
1079                                         goto f_err;
1080                                 }
1081                         /* Set to -2 so if successful we return 2 */
1082                         ret = -2;
1083                         }
1084
1085                 p += cookie_len;
1086                 if (s->method->version == DTLS_ANY_VERSION)
1087                         {
1088                         /* Select version to use */
1089                         if (s->client_version <= DTLS1_2_VERSION &&
1090                                 !(s->options & SSL_OP_NO_DTLSv1_2))
1091                                 {
1092                                 s->version = DTLS1_2_VERSION;
1093                                 s->method = DTLSv1_2_server_method();
1094                                 }
1095                         else if (tls1_suiteb(s))
1096                                 {
1097                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1098                                 s->version = s->client_version;
1099                                 al = SSL_AD_PROTOCOL_VERSION;
1100                                 goto f_err;
1101                                 }
1102                         else if (s->client_version <= DTLS1_VERSION &&
1103                                 !(s->options & SSL_OP_NO_DTLSv1))
1104                                 {
1105                                 s->version = DTLS1_VERSION;
1106                                 s->method = DTLSv1_server_method();
1107                                 }
1108                         else
1109                                 {
1110                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1111                                 s->version = s->client_version;
1112                                 al = SSL_AD_PROTOCOL_VERSION;
1113                                 goto f_err;
1114                                 }
1115                         s->session->ssl_version = s->version;
1116                         }
1117                 }
1118
1119         n2s(p,i);
1120         if ((i == 0) && (j != 0))
1121                 {
1122                 /* we need a cipher if we are not resuming a session */
1123                 al=SSL_AD_ILLEGAL_PARAMETER;
1124                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1125                 goto f_err;
1126                 }
1127         if ((p+i) >= (d+n))
1128                 {
1129                 /* not enough data */
1130                 al=SSL_AD_DECODE_ERROR;
1131                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1132                 goto f_err;
1133                 }
1134         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1135                 == NULL))
1136                 {
1137                 goto err;
1138                 }
1139         p+=i;
1140
1141         /* If it is a hit, check that the cipher is in the list */
1142         if ((s->hit) && (i > 0))
1143                 {
1144                 j=0;
1145                 id=s->session->cipher->id;
1146
1147 #ifdef CIPHER_DEBUG
1148                 printf("client sent %d ciphers\n",sk_num(ciphers));
1149 #endif
1150                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1151                         {
1152                         c=sk_SSL_CIPHER_value(ciphers,i);
1153 #ifdef CIPHER_DEBUG
1154                         printf("client [%2d of %2d]:%s\n",
1155                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1156 #endif
1157                         if (c->id == id)
1158                                 {
1159                                 j=1;
1160                                 break;
1161                                 }
1162                         }
1163 /* Disabled because it can be used in a ciphersuite downgrade
1164  * attack: CVE-2010-4180.
1165  */
1166 #if 0
1167                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1168                         {
1169                         /* Special case as client bug workaround: the previously used cipher may
1170                          * not be in the current list, the client instead might be trying to
1171                          * continue using a cipher that before wasn't chosen due to server
1172                          * preferences.  We'll have to reject the connection if the cipher is not
1173                          * enabled, though. */
1174                         c = sk_SSL_CIPHER_value(ciphers, 0);
1175                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1176                                 {
1177                                 s->session->cipher = c;
1178                                 j = 1;
1179                                 }
1180                         }
1181 #endif
1182                 if (j == 0)
1183                         {
1184                         /* we need to have the cipher in the cipher
1185                          * list if we are asked to reuse it */
1186                         al=SSL_AD_ILLEGAL_PARAMETER;
1187                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1188                         goto f_err;
1189                         }
1190                 }
1191
1192         /* compression */
1193         i= *(p++);
1194         if ((p+i) > (d+n))
1195                 {
1196                 /* not enough data */
1197                 al=SSL_AD_DECODE_ERROR;
1198                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1199                 goto f_err;
1200                 }
1201 #ifndef OPENSSL_NO_COMP
1202         q=p;
1203 #endif
1204         for (j=0; j<i; j++)
1205                 {
1206                 if (p[j] == 0) break;
1207                 }
1208
1209         p+=i;
1210         if (j >= i)
1211                 {
1212                 /* no compress */
1213                 al=SSL_AD_DECODE_ERROR;
1214                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1215                 goto f_err;
1216                 }
1217
1218 #ifndef OPENSSL_NO_TLSEXT
1219         /* TLS extensions*/
1220         if (s->version >= SSL3_VERSION)
1221                 {
1222                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
1223                         {
1224                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1225                         goto err;
1226                         }
1227                 }
1228
1229         /* Check if we want to use external pre-shared secret for this
1230          * handshake for not reused session only. We need to generate
1231          * server_random before calling tls_session_secret_cb in order to allow
1232          * SessionTicket processing to use it in key derivation. */
1233         {
1234                 unsigned char *pos;
1235                 pos=s->s3->server_random;
1236                 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1237                         {
1238                         goto f_err;
1239                         }
1240         }
1241
1242         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1243                 {
1244                 SSL_CIPHER *pref_cipher=NULL;
1245
1246                 s->session->master_key_length=sizeof(s->session->master_key);
1247                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1248                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1249                         {
1250                         s->hit=1;
1251                         s->session->ciphers=ciphers;
1252                         s->session->verify_result=X509_V_OK;
1253
1254                         ciphers=NULL;
1255
1256                         /* check if some cipher was preferred by call back */
1257                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1258                         if (pref_cipher == NULL)
1259                                 {
1260                                 al=SSL_AD_HANDSHAKE_FAILURE;
1261                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1262                                 goto f_err;
1263                                 }
1264
1265                         s->session->cipher=pref_cipher;
1266
1267                         if (s->cipher_list)
1268                                 sk_SSL_CIPHER_free(s->cipher_list);
1269
1270                         if (s->cipher_list_by_id)
1271                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1272
1273                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1274                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1275                         }
1276                 }
1277 #endif
1278
1279         /* Worst case, we will use the NULL compression, but if we have other
1280          * options, we will now look for them.  We have i-1 compression
1281          * algorithms from the client, starting at q. */
1282         s->s3->tmp.new_compression=NULL;
1283 #ifndef OPENSSL_NO_COMP
1284         /* This only happens if we have a cache hit */
1285         if (s->session->compress_meth != 0)
1286                 {
1287                 int m, comp_id = s->session->compress_meth;
1288                 /* Perform sanity checks on resumed compression algorithm */
1289                 /* Can't disable compression */
1290                 if (!ssl_allow_compression(s))
1291                         {
1292                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1293                         goto f_err;
1294                         }
1295                 /* Look for resumed compression method */
1296                 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1297                         {
1298                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1299                         if (comp_id == comp->id)
1300                                 {
1301                                 s->s3->tmp.new_compression=comp;
1302                                 break;
1303                                 }
1304                         }
1305                 if (s->s3->tmp.new_compression == NULL)
1306                         {
1307                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1308                         goto f_err;
1309                         }
1310                 /* Look for resumed method in compression list */
1311                 for (m = 0; m < i; m++)
1312                         {
1313                         if (q[m] == comp_id)
1314                                 break;
1315                         }
1316                 if (m >= i)
1317                         {
1318                         al=SSL_AD_ILLEGAL_PARAMETER;
1319                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1320                         goto f_err;
1321                         }
1322                 }
1323         else if (s->hit)
1324                 comp = NULL;
1325         else if (ssl_allow_compression(s) && s->ctx->comp_methods)
1326                 { /* See if we have a match */
1327                 int m,nn,o,v,done=0;
1328
1329                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1330                 for (m=0; m<nn; m++)
1331                         {
1332                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1333                         v=comp->id;
1334                         for (o=0; o<i; o++)
1335                                 {
1336                                 if (v == q[o])
1337                                         {
1338                                         done=1;
1339                                         break;
1340                                         }
1341                                 }
1342                         if (done) break;
1343                         }
1344                 if (done)
1345                         s->s3->tmp.new_compression=comp;
1346                 else
1347                         comp=NULL;
1348                 }
1349 #else
1350         /* If compression is disabled we'd better not try to resume a session
1351          * using compression.
1352          */
1353         if (s->session->compress_meth != 0)
1354                 {
1355                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1356                 goto f_err;
1357                 }
1358 #endif
1359
1360         /* Given s->session->ciphers and SSL_get_ciphers, we must
1361          * pick a cipher */
1362
1363         if (!s->hit)
1364                 {
1365 #ifdef OPENSSL_NO_COMP
1366                 s->session->compress_meth=0;
1367 #else
1368                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1369 #endif
1370                 if (s->session->ciphers != NULL)
1371                         sk_SSL_CIPHER_free(s->session->ciphers);
1372                 s->session->ciphers=ciphers;
1373                 if (ciphers == NULL)
1374                         {
1375                         al=SSL_AD_ILLEGAL_PARAMETER;
1376                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1377                         goto f_err;
1378                         }
1379                 ciphers=NULL;
1380                 /* Let cert callback update server certificates if required */
1381                 retry_cert:             
1382                 if (s->cert->cert_cb)
1383                         {
1384                         int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1385                         if (rv == 0)
1386                                 {
1387                                 al=SSL_AD_INTERNAL_ERROR;
1388                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
1389                                 goto f_err;
1390                                 }
1391                         if (rv < 0)
1392                                 {
1393                                 s->rwstate=SSL_X509_LOOKUP;
1394                                 return -1;
1395                                 }
1396                         s->rwstate = SSL_NOTHING;
1397                         }
1398                 c=ssl3_choose_cipher(s,s->session->ciphers,
1399                                      SSL_get_ciphers(s));
1400
1401                 if (c == NULL)
1402                         {
1403                         al=SSL_AD_HANDSHAKE_FAILURE;
1404                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1405                         goto f_err;
1406                         }
1407                 s->s3->tmp.new_cipher=c;
1408                 /* check whether we should disable session resumption */
1409                 if (s->not_resumable_session_cb != NULL)
1410                         s->session->not_resumable=s->not_resumable_session_cb(s,
1411                                 ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1412                 if (s->session->not_resumable)
1413                         /* do not send a session ticket */
1414                         s->tlsext_ticket_expected = 0;
1415                 }
1416         else
1417                 {
1418                 /* Session-id reuse */
1419 #ifdef REUSE_CIPHER_BUG
1420                 STACK_OF(SSL_CIPHER) *sk;
1421                 SSL_CIPHER *nc=NULL;
1422                 SSL_CIPHER *ec=NULL;
1423
1424                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1425                         {
1426                         sk=s->session->ciphers;
1427                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1428                                 {
1429                                 c=sk_SSL_CIPHER_value(sk,i);
1430                                 if (c->algorithm_enc & SSL_eNULL)
1431                                         nc=c;
1432                                 if (SSL_C_IS_EXPORT(c))
1433                                         ec=c;
1434                                 }
1435                         if (nc != NULL)
1436                                 s->s3->tmp.new_cipher=nc;
1437                         else if (ec != NULL)
1438                                 s->s3->tmp.new_cipher=ec;
1439                         else
1440                                 s->s3->tmp.new_cipher=s->session->cipher;
1441                         }
1442                 else
1443 #endif
1444                 s->s3->tmp.new_cipher=s->session->cipher;
1445                 }
1446
1447         if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1448                 {
1449                 if (!ssl3_digest_cached_records(s))
1450                         goto f_err;
1451                 }
1452         
1453         /* we now have the following setup. 
1454          * client_random
1455          * cipher_list          - our prefered list of ciphers
1456          * ciphers              - the clients prefered list of ciphers
1457          * compression          - basically ignored right now
1458          * ssl version is set   - sslv3
1459          * s->session           - The ssl session has been setup.
1460          * s->hit               - session reuse flag
1461          * s->s3->tmp.new_cipher- the new cipher to use.
1462          */
1463
1464         /* Handles TLS extensions that we couldn't check earlier */
1465         if (s->version >= SSL3_VERSION)
1466                 {
1467                 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1468                         {
1469                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1470                         goto err;
1471                         }
1472                 }
1473
1474         if (ret < 0) ret=-ret;
1475         if (0)
1476                 {
1477 f_err:
1478                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1479                 }
1480 err:
1481         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1482         return ret < 0 ? -1 : ret;
1483         }
1484
1485 int ssl3_send_server_hello(SSL *s)
1486         {
1487         unsigned char *buf;
1488         unsigned char *p,*d;
1489         int i,sl;
1490         int al = 0;
1491         unsigned long l;
1492
1493         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1494                 {
1495                 buf=(unsigned char *)s->init_buf->data;
1496 #ifdef OPENSSL_NO_TLSEXT
1497                 p=s->s3->server_random;
1498                 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1499                         return -1;
1500 #endif
1501                 /* Do the message type and length last */
1502                 d=p= ssl_handshake_start(s);
1503
1504                 *(p++)=s->version>>8;
1505                 *(p++)=s->version&0xff;
1506
1507                 /* Random stuff */
1508                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1509                 p+=SSL3_RANDOM_SIZE;
1510
1511                 /* There are several cases for the session ID to send
1512                  * back in the server hello:
1513                  * - For session reuse from the session cache,
1514                  *   we send back the old session ID.
1515                  * - If stateless session reuse (using a session ticket)
1516                  *   is successful, we send back the client's "session ID"
1517                  *   (which doesn't actually identify the session).
1518                  * - If it is a new session, we send back the new
1519                  *   session ID.
1520                  * - However, if we want the new session to be single-use,
1521                  *   we send back a 0-length session ID.
1522                  * s->hit is non-zero in either case of session reuse,
1523                  * so the following won't overwrite an ID that we're supposed
1524                  * to send back.
1525                  */
1526                 if (s->session->not_resumable ||
1527                         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1528                                 && !s->hit))
1529                         s->session->session_id_length=0;
1530
1531                 sl=s->session->session_id_length;
1532                 if (sl > (int)sizeof(s->session->session_id))
1533                         {
1534                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1535                         return -1;
1536                         }
1537                 *(p++)=sl;
1538                 memcpy(p,s->session->session_id,sl);
1539                 p+=sl;
1540
1541                 /* put the cipher */
1542                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1543                 p+=i;
1544
1545                 /* put the compression method */
1546 #ifdef OPENSSL_NO_COMP
1547                         *(p++)=0;
1548 #else
1549                 if (s->s3->tmp.new_compression == NULL)
1550                         *(p++)=0;
1551                 else
1552                         *(p++)=s->s3->tmp.new_compression->id;
1553 #endif
1554 #ifndef OPENSSL_NO_TLSEXT
1555                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1556                         {
1557                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1558                         return -1;
1559                         }
1560                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
1561                         {
1562                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1563                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1564                         return -1;
1565                         }
1566 #endif
1567                 /* do the header */
1568                 l=(p-d);
1569                 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1570                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1571                 }
1572
1573         /* SSL3_ST_SW_SRVR_HELLO_B */
1574         return ssl_do_write(s);
1575         }
1576
1577 int ssl3_send_server_done(SSL *s)
1578         {
1579
1580         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1581                 {
1582                 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1583                 s->state = SSL3_ST_SW_SRVR_DONE_B;
1584                 }
1585
1586         /* SSL3_ST_SW_SRVR_DONE_B */
1587         return ssl_do_write(s);
1588         }
1589
1590 int ssl3_send_server_key_exchange(SSL *s)
1591         {
1592 #ifndef OPENSSL_NO_RSA
1593         unsigned char *q;
1594         int j,num;
1595         RSA *rsa;
1596         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1597         unsigned int u;
1598 #endif
1599 #ifndef OPENSSL_NO_DH
1600         DH *dh=NULL,*dhp;
1601 #endif
1602 #ifndef OPENSSL_NO_ECDH
1603         EC_KEY *ecdh=NULL, *ecdhp;
1604         unsigned char *encodedPoint = NULL;
1605         int encodedlen = 0;
1606         int curve_id = 0;
1607         BN_CTX *bn_ctx = NULL; 
1608 #endif
1609         EVP_PKEY *pkey;
1610         const EVP_MD *md = NULL;
1611         unsigned char *p,*d;
1612         int al,i;
1613         unsigned long type;
1614         int n;
1615         CERT *cert;
1616         BIGNUM *r[4];
1617         int nr[4],kn;
1618         BUF_MEM *buf;
1619         EVP_MD_CTX md_ctx;
1620
1621         EVP_MD_CTX_init(&md_ctx);
1622         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1623                 {
1624                 type=s->s3->tmp.new_cipher->algorithm_mkey;
1625                 cert=s->cert;
1626
1627                 buf=s->init_buf;
1628
1629                 r[0]=r[1]=r[2]=r[3]=NULL;
1630                 n=0;
1631 #ifndef OPENSSL_NO_RSA
1632                 if (type & SSL_kRSA)
1633                         {
1634                         rsa=cert->rsa_tmp;
1635                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1636                                 {
1637                                 rsa=s->cert->rsa_tmp_cb(s,
1638                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1639                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1640                                 if(rsa == NULL)
1641                                 {
1642                                         al=SSL_AD_HANDSHAKE_FAILURE;
1643                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1644                                         goto f_err;
1645                                 }
1646                                 RSA_up_ref(rsa);
1647                                 cert->rsa_tmp=rsa;
1648                                 }
1649                         if (rsa == NULL)
1650                                 {
1651                                 al=SSL_AD_HANDSHAKE_FAILURE;
1652                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1653                                 goto f_err;
1654                                 }
1655                         r[0]=rsa->n;
1656                         r[1]=rsa->e;
1657                         s->s3->tmp.use_rsa_tmp=1;
1658                         }
1659                 else
1660 #endif
1661 #ifndef OPENSSL_NO_DH
1662                         if (type & SSL_kDHE)
1663                         {
1664                         if (s->cert->dh_tmp_auto)
1665                                 {
1666                                 dhp = ssl_get_auto_dh(s);
1667                                 if (dhp == NULL)
1668                                         {
1669                                         al=SSL_AD_INTERNAL_ERROR;
1670                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1671                                         goto f_err;
1672                                         }
1673                                 }
1674                         else
1675                                 dhp=cert->dh_tmp;
1676                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1677                                 dhp=s->cert->dh_tmp_cb(s,
1678                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1679                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1680                         if (dhp == NULL)
1681                                 {
1682                                 al=SSL_AD_HANDSHAKE_FAILURE;
1683                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1684                                 goto f_err;
1685                                 }
1686                         if (!ssl_security(s, SSL_SECOP_TMP_DH,
1687                                                 DH_security_bits(dhp), 0, dhp))
1688                                 {
1689                                 al=SSL_AD_HANDSHAKE_FAILURE;
1690                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
1691                                 goto f_err;
1692                                 }
1693                         if (s->s3->tmp.dh != NULL)
1694                                 {
1695                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1696                                 goto err;
1697                                 }
1698
1699                         if (s->cert->dh_tmp_auto)
1700                                 dh = dhp;
1701                         else if ((dh=DHparams_dup(dhp)) == NULL)
1702                                 {
1703                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1704                                 goto err;
1705                                 }
1706
1707                         s->s3->tmp.dh=dh;
1708                         if ((dhp->pub_key == NULL ||
1709                              dhp->priv_key == NULL ||
1710                              (s->options & SSL_OP_SINGLE_DH_USE)))
1711                                 {
1712                                 if(!DH_generate_key(dh))
1713                                     {
1714                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1715                                            ERR_R_DH_LIB);
1716                                     goto err;
1717                                     }
1718                                 }
1719                         else
1720                                 {
1721                                 dh->pub_key=BN_dup(dhp->pub_key);
1722                                 dh->priv_key=BN_dup(dhp->priv_key);
1723                                 if ((dh->pub_key == NULL) ||
1724                                         (dh->priv_key == NULL))
1725                                         {
1726                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1727                                         goto err;
1728                                         }
1729                                 }
1730                         r[0]=dh->p;
1731                         r[1]=dh->g;
1732                         r[2]=dh->pub_key;
1733                         }
1734                 else 
1735 #endif
1736 #ifndef OPENSSL_NO_ECDH
1737                         if (type & SSL_kECDHE)
1738                         {
1739                         const EC_GROUP *group;
1740
1741                         ecdhp=cert->ecdh_tmp;
1742                         if (s->cert->ecdh_tmp_auto)
1743                                 {
1744                                 /* Get NID of appropriate shared curve */
1745                                 int nid = tls1_shared_curve(s, -2);
1746                                 if (nid != NID_undef)
1747                                         ecdhp = EC_KEY_new_by_curve_name(nid);
1748                                 }
1749                         else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1750                                 {
1751                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1752                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1753                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1754                                 }
1755                         if (ecdhp == NULL)
1756                                 {
1757                                 al=SSL_AD_HANDSHAKE_FAILURE;
1758                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1759                                 goto f_err;
1760                                 }
1761
1762                         if (s->s3->tmp.ecdh != NULL)
1763                                 {
1764                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1765                                 goto err;
1766                                 }
1767
1768                         /* Duplicate the ECDH structure. */
1769                         if (ecdhp == NULL)
1770                                 {
1771                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1772                                 goto err;
1773                                 }
1774                         if (s->cert->ecdh_tmp_auto)
1775                                 ecdh = ecdhp;
1776                         else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1777                                 {
1778                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1779                                 goto err;
1780                                 }
1781
1782                         s->s3->tmp.ecdh=ecdh;
1783                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1784                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1785                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1786                                 {
1787                                 if(!EC_KEY_generate_key(ecdh))
1788                                     {
1789                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1790                                     goto err;
1791                                     }
1792                                 }
1793
1794                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1795                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1796                             (EC_KEY_get0_private_key(ecdh) == NULL))
1797                                 {
1798                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1799                                 goto err;
1800                                 }
1801
1802                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1803                             (EC_GROUP_get_degree(group) > 163)) 
1804                                 {
1805                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1806                                 goto err;
1807                                 }
1808
1809                         /* XXX: For now, we only support ephemeral ECDH
1810                          * keys over named (not generic) curves. For 
1811                          * supported named curves, curve_id is non-zero.
1812                          */
1813                         if ((curve_id = 
1814                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1815                             == 0)
1816                                 {
1817                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1818                                 goto err;
1819                                 }
1820
1821                         /* Encode the public key.
1822                          * First check the size of encoding and
1823                          * allocate memory accordingly.
1824                          */
1825                         encodedlen = EC_POINT_point2oct(group, 
1826                             EC_KEY_get0_public_key(ecdh),
1827                             POINT_CONVERSION_UNCOMPRESSED, 
1828                             NULL, 0, NULL);
1829
1830                         encodedPoint = (unsigned char *) 
1831                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1832                         bn_ctx = BN_CTX_new();
1833                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1834                                 {
1835                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1836                                 goto err;
1837                                 }
1838
1839
1840                         encodedlen = EC_POINT_point2oct(group, 
1841                             EC_KEY_get0_public_key(ecdh), 
1842                             POINT_CONVERSION_UNCOMPRESSED, 
1843                             encodedPoint, encodedlen, bn_ctx);
1844
1845                         if (encodedlen == 0) 
1846                                 {
1847                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1848                                 goto err;
1849                                 }
1850
1851                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1852
1853                         /* XXX: For now, we only support named (not 
1854                          * generic) curves in ECDH ephemeral key exchanges.
1855                          * In this situation, we need four additional bytes
1856                          * to encode the entire ServerECDHParams
1857                          * structure. 
1858                          */
1859                         n = 4 + encodedlen;
1860
1861                         /* We'll generate the serverKeyExchange message
1862                          * explicitly so we can set these to NULLs
1863                          */
1864                         r[0]=NULL;
1865                         r[1]=NULL;
1866                         r[2]=NULL;
1867                         r[3]=NULL;
1868                         }
1869                 else 
1870 #endif /* !OPENSSL_NO_ECDH */
1871 #ifndef OPENSSL_NO_PSK
1872                         if (type & SSL_kPSK)
1873                                 {
1874                                 /* reserve size for record length and PSK identity hint*/
1875                                 n+=2+strlen(s->ctx->psk_identity_hint);
1876                                 }
1877                         else
1878 #endif /* !OPENSSL_NO_PSK */
1879 #ifndef OPENSSL_NO_SRP
1880                 if (type & SSL_kSRP)
1881                         {
1882                         if ((s->srp_ctx.N == NULL) ||
1883                                 (s->srp_ctx.g == NULL) ||
1884                                 (s->srp_ctx.s == NULL) ||
1885                                 (s->srp_ctx.B == NULL))
1886                                 {
1887                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1888                                 goto err;
1889                                 }
1890                         r[0]=s->srp_ctx.N;
1891                         r[1]=s->srp_ctx.g;
1892                         r[2]=s->srp_ctx.s;
1893                         r[3]=s->srp_ctx.B;
1894                         }
1895                 else 
1896 #endif
1897                         {
1898                         al=SSL_AD_HANDSHAKE_FAILURE;
1899                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1900                         goto f_err;
1901                         }
1902                 for (i=0; i < 4 && r[i] != NULL; i++)
1903                         {
1904                         nr[i]=BN_num_bytes(r[i]);
1905 #ifndef OPENSSL_NO_SRP
1906                         if ((i == 2) && (type & SSL_kSRP))
1907                                 n+=1+nr[i];
1908                         else
1909 #endif
1910                         n+=2+nr[i];
1911                         }
1912
1913                 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1914                         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1915                         {
1916                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1917                                 == NULL)
1918                                 {
1919                                 al=SSL_AD_DECODE_ERROR;
1920                                 goto f_err;
1921                                 }
1922                         kn=EVP_PKEY_size(pkey);
1923                         }
1924                 else
1925                         {
1926                         pkey=NULL;
1927                         kn=0;
1928                         }
1929
1930                 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1931                         {
1932                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1933                         goto err;
1934                         }
1935                 d = p = ssl_handshake_start(s);
1936
1937                 for (i=0; i < 4 && r[i] != NULL; i++)
1938                         {
1939 #ifndef OPENSSL_NO_SRP
1940                         if ((i == 2) && (type & SSL_kSRP))
1941                                 {
1942                                 *p = nr[i];
1943                                 p++;
1944                                 }
1945                         else
1946 #endif
1947                         s2n(nr[i],p);
1948                         BN_bn2bin(r[i],p);
1949                         p+=nr[i];
1950                         }
1951
1952 #ifndef OPENSSL_NO_ECDH
1953                 if (type & SSL_kECDHE) 
1954                         {
1955                         /* XXX: For now, we only support named (not generic) curves.
1956                          * In this situation, the serverKeyExchange message has:
1957                          * [1 byte CurveType], [2 byte CurveName]
1958                          * [1 byte length of encoded point], followed by
1959                          * the actual encoded point itself
1960                          */
1961                         *p = NAMED_CURVE_TYPE;
1962                         p += 1;
1963                         *p = 0;
1964                         p += 1;
1965                         *p = curve_id;
1966                         p += 1;
1967                         *p = encodedlen;
1968                         p += 1;
1969                         memcpy((unsigned char*)p, 
1970                             (unsigned char *)encodedPoint, 
1971                             encodedlen);
1972                         OPENSSL_free(encodedPoint);
1973                         encodedPoint = NULL;
1974                         p += encodedlen;
1975                         }
1976 #endif
1977
1978 #ifndef OPENSSL_NO_PSK
1979                 if (type & SSL_kPSK)
1980                         {
1981                         /* copy PSK identity hint */
1982                         s2n(strlen(s->ctx->psk_identity_hint), p); 
1983                         strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1984                         p+=strlen(s->ctx->psk_identity_hint);
1985                         }
1986 #endif
1987
1988                 /* not anonymous */
1989                 if (pkey != NULL)
1990                         {
1991                         /* n is the length of the params, they start at &(d[4])
1992                          * and p points to the space at the end. */
1993 #ifndef OPENSSL_NO_RSA
1994                         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1995                                 {
1996                                 q=md_buf;
1997                                 j=0;
1998                                 for (num=2; num > 0; num--)
1999                                         {
2000                                         EVP_MD_CTX_set_flags(&md_ctx,
2001                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2002                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
2003                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
2004                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2005                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2006                                         EVP_DigestUpdate(&md_ctx,d,n);
2007                                         EVP_DigestFinal_ex(&md_ctx,q,
2008                                                 (unsigned int *)&i);
2009                                         q+=i;
2010                                         j+=i;
2011                                         }
2012                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
2013                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
2014                                         {
2015                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2016                                         goto err;
2017                                         }
2018                                 s2n(u,p);
2019                                 n+=u+2;
2020                                 }
2021                         else
2022 #endif
2023                         if (md)
2024                                 {
2025                                 /* send signature algorithm */
2026                                 if (SSL_USE_SIGALGS(s))
2027                                         {
2028                                         if (!tls12_get_sigandhash(p, pkey, md))
2029                                                 {
2030                                                 /* Should never happen */
2031                                                 al=SSL_AD_INTERNAL_ERROR;
2032                                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2033                                                 goto f_err;
2034                                                 }
2035                                         p+=2;
2036                                         }
2037 #ifdef SSL_DEBUG
2038                                 fprintf(stderr, "Using hash %s\n",
2039                                                         EVP_MD_name(md));
2040 #endif
2041                                 EVP_SignInit_ex(&md_ctx, md, NULL);
2042                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2043                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2044                                 EVP_SignUpdate(&md_ctx,d,n);
2045                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2046                                         (unsigned int *)&i,pkey))
2047                                         {
2048                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2049                                         goto err;
2050                                         }
2051                                 s2n(i,p);
2052                                 n+=i+2;
2053                                 if (SSL_USE_SIGALGS(s))
2054                                         n+= 2;
2055                                 }
2056                         else
2057                                 {
2058                                 /* Is this error check actually needed? */
2059                                 al=SSL_AD_HANDSHAKE_FAILURE;
2060                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2061                                 goto f_err;
2062                                 }
2063                         }
2064
2065                 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2066                 }
2067
2068         s->state = SSL3_ST_SW_KEY_EXCH_B;
2069         EVP_MD_CTX_cleanup(&md_ctx);
2070         return ssl_do_write(s);
2071 f_err:
2072         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2073 err:
2074 #ifndef OPENSSL_NO_ECDH
2075         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2076         BN_CTX_free(bn_ctx);
2077 #endif
2078         EVP_MD_CTX_cleanup(&md_ctx);
2079         return(-1);
2080         }
2081
2082 int ssl3_send_certificate_request(SSL *s)
2083         {
2084         unsigned char *p,*d;
2085         int i,j,nl,off,n;
2086         STACK_OF(X509_NAME) *sk=NULL;
2087         X509_NAME *name;
2088         BUF_MEM *buf;
2089
2090         if (s->state == SSL3_ST_SW_CERT_REQ_A)
2091                 {
2092                 buf=s->init_buf;
2093
2094                 d=p=ssl_handshake_start(s);
2095
2096                 /* get the list of acceptable cert types */
2097                 p++;
2098                 n=ssl3_get_req_cert_type(s,p);
2099                 d[0]=n;
2100                 p+=n;
2101                 n++;
2102
2103                 if (SSL_USE_SIGALGS(s))
2104                         {
2105                         const unsigned char *psigs;
2106                         unsigned char *etmp = p;
2107                         nl = tls12_get_psigalgs(s, &psigs);
2108                         /* Skip over length for now */
2109                         p += 2;
2110                         nl = tls12_copy_sigalgs(s, p, psigs, nl);
2111                         /* Now fill in length */
2112                         s2n(nl, etmp);
2113                         p += nl;
2114                         n += nl + 2;
2115                         }
2116
2117                 off=n;
2118                 p+=2;
2119                 n+=2;
2120
2121                 sk=SSL_get_client_CA_list(s);
2122                 nl=0;
2123                 if (sk != NULL)
2124                         {
2125                         for (i=0; i<sk_X509_NAME_num(sk); i++)
2126                                 {
2127                                 name=sk_X509_NAME_value(sk,i);
2128                                 j=i2d_X509_NAME(name,NULL);
2129                                 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
2130                                         {
2131                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2132                                         goto err;
2133                                         }
2134                                 p = ssl_handshake_start(s) + n;
2135                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2136                                         {
2137                                         s2n(j,p);
2138                                         i2d_X509_NAME(name,&p);
2139                                         n+=2+j;
2140                                         nl+=2+j;
2141                                         }
2142                                 else
2143                                         {
2144                                         d=p;
2145                                         i2d_X509_NAME(name,&p);
2146                                         j-=2; s2n(j,d); j+=2;
2147                                         n+=j;
2148                                         nl+=j;
2149                                         }
2150                                 }
2151                         }
2152                 /* else no CA names */
2153                 p = ssl_handshake_start(s) + off;
2154                 s2n(nl,p);
2155
2156                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2157
2158 #ifdef NETSCAPE_HANG_BUG
2159                 if (!SSL_IS_DTLS(s))
2160                         {
2161                         if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2162                                 {
2163                                 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2164                                 goto err;
2165                                 }
2166                         p=(unsigned char *)s->init_buf->data + s->init_num;
2167                         /* do the header */
2168                         *(p++)=SSL3_MT_SERVER_DONE;
2169                         *(p++)=0;
2170                         *(p++)=0;
2171                         *(p++)=0;
2172                         s->init_num += 4;
2173                         }
2174 #endif
2175
2176                 s->state = SSL3_ST_SW_CERT_REQ_B;
2177                 }
2178
2179         /* SSL3_ST_SW_CERT_REQ_B */
2180         return ssl_do_write(s);
2181 err:
2182         return(-1);
2183         }
2184
2185 int ssl3_get_client_key_exchange(SSL *s)
2186         {
2187         int i,al,ok;
2188         long n;
2189         unsigned long alg_k;
2190         unsigned char *p;
2191 #ifndef OPENSSL_NO_RSA
2192         RSA *rsa=NULL;
2193         EVP_PKEY *pkey=NULL;
2194 #endif
2195 #ifndef OPENSSL_NO_DH
2196         BIGNUM *pub=NULL;
2197         DH *dh_srvr, *dh_clnt = NULL;
2198 #endif
2199 #ifndef OPENSSL_NO_KRB5
2200         KSSL_ERR kssl_err;
2201 #endif /* OPENSSL_NO_KRB5 */
2202
2203 #ifndef OPENSSL_NO_ECDH
2204         EC_KEY *srvr_ecdh = NULL;
2205         EVP_PKEY *clnt_pub_pkey = NULL;
2206         EC_POINT *clnt_ecpoint = NULL;
2207         BN_CTX *bn_ctx = NULL; 
2208 #endif
2209
2210         n=s->method->ssl_get_message(s,
2211                 SSL3_ST_SR_KEY_EXCH_A,
2212                 SSL3_ST_SR_KEY_EXCH_B,
2213                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2214                 2048, /* ??? */
2215                 &ok);
2216
2217         if (!ok) return((int)n);
2218         p=(unsigned char *)s->init_msg;
2219
2220         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2221
2222 #ifndef OPENSSL_NO_RSA
2223         if (alg_k & SSL_kRSA)
2224                 {
2225                 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2226                 int decrypt_len, decrypt_good_mask;
2227                 unsigned char version_good;
2228
2229                 /* FIX THIS UP EAY EAY EAY EAY */
2230                 if (s->s3->tmp.use_rsa_tmp)
2231                         {
2232                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2233                                 rsa=s->cert->rsa_tmp;
2234                         /* Don't do a callback because rsa_tmp should
2235                          * be sent already */
2236                         if (rsa == NULL)
2237                                 {
2238                                 al=SSL_AD_HANDSHAKE_FAILURE;
2239                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2240                                 goto f_err;
2241
2242                                 }
2243                         }
2244                 else
2245                         {
2246                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2247                         if (    (pkey == NULL) ||
2248                                 (pkey->type != EVP_PKEY_RSA) ||
2249                                 (pkey->pkey.rsa == NULL))
2250                                 {
2251                                 al=SSL_AD_HANDSHAKE_FAILURE;
2252                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2253                                 goto f_err;
2254                                 }
2255                         rsa=pkey->pkey.rsa;
2256                         }
2257
2258                 /* TLS and [incidentally] DTLS{0xFEFF} */
2259                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2260                         {
2261                         n2s(p,i);
2262                         if (n != i+2)
2263                                 {
2264                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2265                                         {
2266                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2267                                         goto err;
2268                                         }
2269                                 else
2270                                         p-=2;
2271                                 }
2272                         else
2273                                 n=i;
2274                         }
2275
2276                 /* We must not leak whether a decryption failure occurs because
2277                  * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2278                  * RFC 2246, section 7.4.7.1). The code follows that advice of
2279                  * the TLS RFC and generates a random premaster secret for the
2280                  * case that the decrypt fails. See
2281                  * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2282
2283                 /* should be RAND_bytes, but we cannot work around a failure. */
2284                 if (RAND_pseudo_bytes(rand_premaster_secret,
2285                                       sizeof(rand_premaster_secret)) <= 0)
2286                         goto err;
2287                 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2288                 ERR_clear_error();
2289
2290                 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2291                  * decrypt_good_mask will be zero if so and non-zero otherwise. */
2292                 decrypt_good_mask = decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
2293
2294                 /* If the version in the decrypted pre-master secret is correct
2295                  * then version_good will be zero. The Klima-Pokorny-Rosa
2296                  * extension of Bleichenbacher's attack
2297                  * (http://eprint.iacr.org/2003/052/) exploits the version
2298                  * number check as a "bad version oracle". Thus version checks
2299                  * are done in constant time and are treated like any other
2300                  * decryption error. */
2301                 version_good = p[0] ^ (s->client_version>>8);
2302                 version_good |= p[1] ^ (s->client_version&0xff);
2303
2304                 /* The premaster secret must contain the same version number as
2305                  * the ClientHello to detect version rollback attacks
2306                  * (strangely, the protocol does not offer such protection for
2307                  * DH ciphersuites). However, buggy clients exist that send the
2308                  * negotiated protocol version instead if the server does not
2309                  * support the requested protocol version. If
2310                  * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2311                 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2312                         {
2313                         unsigned char workaround_mask = version_good;
2314                         unsigned char workaround;
2315
2316                         /* workaround_mask will be 0xff if version_good is
2317                          * non-zero (i.e. the version match failed). Otherwise
2318                          * it'll be 0x00. */
2319                         workaround_mask |= workaround_mask >> 4;
2320                         workaround_mask |= workaround_mask >> 2;
2321                         workaround_mask |= workaround_mask >> 1;
2322                         workaround_mask = ~((workaround_mask & 1) - 1);
2323
2324                         workaround = p[0] ^ (s->version>>8);
2325                         workaround |= p[1] ^ (s->version&0xff);
2326
2327                         /* If workaround_mask is 0xff (i.e. there was a version
2328                          * mismatch) then we copy the value of workaround over
2329                          * version_good. */
2330                         version_good = (workaround & workaround_mask) |
2331                                        (version_good & ~workaround_mask);
2332                         }
2333
2334                 /* If any bits in version_good are set then they'll poision
2335                  * decrypt_good_mask and cause rand_premaster_secret to be
2336                  * used. */
2337                 decrypt_good_mask |= version_good;
2338
2339                 /* decrypt_good_mask will be zero iff decrypt_len ==
2340                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
2341                  * fold the bottom 32 bits of it with an OR so that the LSB
2342                  * will be zero iff everything is good. This assumes that we'll
2343                  * never decrypt a value > 2**31 bytes, which seems safe. */
2344                 decrypt_good_mask |= decrypt_good_mask >> 16;
2345                 decrypt_good_mask |= decrypt_good_mask >> 8;
2346                 decrypt_good_mask |= decrypt_good_mask >> 4;
2347                 decrypt_good_mask |= decrypt_good_mask >> 2;
2348                 decrypt_good_mask |= decrypt_good_mask >> 1;
2349                 /* Now select only the LSB and subtract one. If decrypt_len ==
2350                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
2351                  * decrypt_good_mask will be all ones. Otherwise it'll be all
2352                  * zeros. */
2353                 decrypt_good_mask &= 1;
2354                 decrypt_good_mask--;
2355
2356                 /* Now copy rand_premaster_secret over p using
2357                  * decrypt_good_mask. */
2358                 for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2359                         {
2360                         p[i] = (p[i] & decrypt_good_mask) |
2361                                (rand_premaster_secret[i] & ~decrypt_good_mask);
2362                         }
2363
2364                 s->session->master_key_length=
2365                         s->method->ssl3_enc->generate_master_secret(s,
2366                                 s->session->master_key,
2367                                 p,i);
2368                 OPENSSL_cleanse(p,i);
2369                 }
2370         else
2371 #endif
2372 #ifndef OPENSSL_NO_DH
2373                 if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
2374                 {
2375                 int idx = -1;
2376                 EVP_PKEY *skey = NULL;
2377                 if (n)
2378                         n2s(p,i);
2379                 else
2380                         i = 0;
2381                 if (n && n != i+2)
2382                         {
2383                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2384                                 {
2385                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2386                                 goto err;
2387                                 }
2388                         else
2389                                 {
2390                                 p-=2;
2391                                 i=(int)n;
2392                                 }
2393                         }
2394                 if (alg_k & SSL_kDHr)
2395                         idx = SSL_PKEY_DH_RSA;
2396                 else if (alg_k & SSL_kDHd)
2397                         idx = SSL_PKEY_DH_DSA;
2398                 if (idx >= 0)
2399                         {
2400                         skey = s->cert->pkeys[idx].privatekey;
2401                         if ((skey == NULL) ||
2402                                 (skey->type != EVP_PKEY_DH) ||
2403                                 (skey->pkey.dh == NULL))
2404                                 {
2405                                 al=SSL_AD_HANDSHAKE_FAILURE;
2406                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2407                                 goto f_err;
2408                                 }
2409                         dh_srvr = skey->pkey.dh;
2410                         }
2411                 else if (s->s3->tmp.dh == NULL)
2412                         {
2413                         al=SSL_AD_HANDSHAKE_FAILURE;
2414                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2415                         goto f_err;
2416                         }
2417                 else
2418                         dh_srvr=s->s3->tmp.dh;
2419
2420                 if (n == 0L)
2421                         {
2422                         /* Get pubkey from cert */
2423                         EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2424                         if (clkey)
2425                                 {
2426                                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2427                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2428                                 }
2429                         if (dh_clnt == NULL)
2430                                 {
2431                                 al=SSL_AD_HANDSHAKE_FAILURE;
2432                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2433                                 goto f_err;
2434                                 }
2435                         EVP_PKEY_free(clkey);
2436                         pub = dh_clnt->pub_key;
2437                         }
2438                 else
2439                         pub=BN_bin2bn(p,i,NULL);
2440                 if (pub == NULL)
2441                         {
2442                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2443                         goto err;
2444                         }
2445
2446                 i=DH_compute_key(p,pub,dh_srvr);
2447
2448                 if (i <= 0)
2449                         {
2450                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2451                         BN_clear_free(pub);
2452                         goto err;
2453                         }
2454
2455                 DH_free(s->s3->tmp.dh);
2456                 s->s3->tmp.dh=NULL;
2457                 if (dh_clnt)
2458                         DH_free(dh_clnt);
2459                 else
2460                         BN_clear_free(pub);
2461                 pub=NULL;
2462                 s->session->master_key_length=
2463                         s->method->ssl3_enc->generate_master_secret(s,
2464                                 s->session->master_key,p,i);
2465                 OPENSSL_cleanse(p,i);
2466                 if (dh_clnt)
2467                         return 2;
2468                 }
2469         else
2470 #endif
2471 #ifndef OPENSSL_NO_KRB5
2472         if (alg_k & SSL_kKRB5)
2473                 {
2474                 krb5_error_code         krb5rc;
2475                 krb5_data               enc_ticket;
2476                 krb5_data               authenticator;
2477                 krb5_data               enc_pms;
2478                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
2479                 EVP_CIPHER_CTX          ciph_ctx;
2480                 const EVP_CIPHER        *enc = NULL;
2481                 unsigned char           iv[EVP_MAX_IV_LENGTH];
2482                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
2483                                                + EVP_MAX_BLOCK_LENGTH];
2484                 int                  padl, outl;
2485                 krb5_timestamp          authtime = 0;
2486                 krb5_ticket_times       ttimes;
2487
2488                 EVP_CIPHER_CTX_init(&ciph_ctx);
2489
2490                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2491
2492                 n2s(p,i);
2493                 enc_ticket.length = i;
2494
2495                 if (n < (long)(enc_ticket.length + 6))
2496                         {
2497                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2498                                 SSL_R_DATA_LENGTH_TOO_LONG);
2499                         goto err;
2500                         }
2501
2502                 enc_ticket.data = (char *)p;
2503                 p+=enc_ticket.length;
2504
2505                 n2s(p,i);
2506                 authenticator.length = i;
2507
2508                 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2509                         {
2510                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2511                                 SSL_R_DATA_LENGTH_TOO_LONG);
2512                         goto err;
2513                         }
2514
2515                 authenticator.data = (char *)p;
2516                 p+=authenticator.length;
2517
2518                 n2s(p,i);
2519                 enc_pms.length = i;
2520                 enc_pms.data = (char *)p;
2521                 p+=enc_pms.length;
2522
2523                 /* Note that the length is checked again below,
2524                 ** after decryption
2525                 */
2526                 if(enc_pms.length > sizeof pms)
2527                         {
2528                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2529                                SSL_R_DATA_LENGTH_TOO_LONG);
2530                         goto err;
2531                         }
2532
2533                 if (n != (long)(enc_ticket.length + authenticator.length +
2534                                                 enc_pms.length + 6))
2535                         {
2536                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2537                                 SSL_R_DATA_LENGTH_TOO_LONG);
2538                         goto err;
2539                         }
2540
2541                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2542                                         &kssl_err)) != 0)
2543                         {
2544 #ifdef KSSL_DEBUG
2545                         printf("kssl_sget_tkt rtn %d [%d]\n",
2546                                 krb5rc, kssl_err.reason);
2547                         if (kssl_err.text)
2548                                 printf("kssl_err text= %s\n", kssl_err.text);
2549 #endif  /* KSSL_DEBUG */
2550                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2551                                 kssl_err.reason);
2552                         goto err;
2553                         }
2554
2555                 /*  Note: no authenticator is not considered an error,
2556                 **  but will return authtime == 0.
2557                 */
2558                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2559                                         &authtime, &kssl_err)) != 0)
2560                         {
2561 #ifdef KSSL_DEBUG
2562                         printf("kssl_check_authent rtn %d [%d]\n",
2563                                 krb5rc, kssl_err.reason);
2564                         if (kssl_err.text)
2565                                 printf("kssl_err text= %s\n", kssl_err.text);
2566 #endif  /* KSSL_DEBUG */
2567                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2568                                 kssl_err.reason);
2569                         goto err;
2570                         }
2571
2572                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2573                         {
2574                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2575                         goto err;
2576                         }
2577
2578 #ifdef KSSL_DEBUG
2579                 kssl_ctx_show(kssl_ctx);
2580 #endif  /* KSSL_DEBUG */
2581
2582                 enc = kssl_map_enc(kssl_ctx->enctype);
2583                 if (enc == NULL)
2584                     goto err;
2585
2586                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2587
2588                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2589                         {
2590                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2591                                 SSL_R_DECRYPTION_FAILED);
2592                         goto err;
2593                         }
2594                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2595                                         (unsigned char *)enc_pms.data, enc_pms.length))
2596                         {
2597                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2598                                 SSL_R_DECRYPTION_FAILED);
2599                         goto err;
2600                         }
2601                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2602                         {
2603                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2604                                 SSL_R_DATA_LENGTH_TOO_LONG);
2605                         goto err;
2606                         }
2607                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2608                         {
2609                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2610                                 SSL_R_DECRYPTION_FAILED);
2611                         goto err;
2612                         }
2613                 outl += padl;
2614                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2615                         {
2616                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2617                                 SSL_R_DATA_LENGTH_TOO_LONG);
2618                         goto err;
2619                         }
2620                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2621                     {
2622                     /* The premaster secret must contain the same version number as the
2623                      * ClientHello to detect version rollback attacks (strangely, the
2624                      * protocol does not offer such protection for DH ciphersuites).
2625                      * However, buggy clients exist that send random bytes instead of
2626                      * the protocol version.
2627                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2628                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2629                      */
2630                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2631                         {
2632                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2633                                SSL_AD_DECODE_ERROR);
2634                         goto err;
2635                         }
2636                     }
2637
2638                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2639
2640                 s->session->master_key_length=
2641                         s->method->ssl3_enc->generate_master_secret(s,
2642                                 s->session->master_key, pms, outl);
2643
2644                 if (kssl_ctx->client_princ)
2645                         {
2646                         size_t len = strlen(kssl_ctx->client_princ);
2647                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2648                                 {
2649                                 s->session->krb5_client_princ_len = len;
2650                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2651                                 }
2652                         }
2653
2654
2655                 /*  Was doing kssl_ctx_free() here,
2656                 **  but it caused problems for apache.
2657                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2658                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2659                 */
2660                 }
2661         else
2662 #endif  /* OPENSSL_NO_KRB5 */
2663
2664 #ifndef OPENSSL_NO_ECDH
2665                 if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
2666                 {
2667                 int ret = 1;
2668                 int field_size = 0;
2669                 const EC_KEY   *tkey;
2670                 const EC_GROUP *group;
2671                 const BIGNUM *priv_key;
2672
2673                 /* initialize structures for server's ECDH key pair */
2674                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2675                         {
2676                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2677                             ERR_R_MALLOC_FAILURE);
2678                         goto err;
2679                         }
2680
2681                 /* Let's get server private key and group information */
2682                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2683                         { 
2684                         /* use the certificate */
2685                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2686                         }
2687                 else
2688                         {
2689                         /* use the ephermeral values we saved when
2690                          * generating the ServerKeyExchange msg.
2691                          */
2692                         tkey = s->s3->tmp.ecdh;
2693                         }
2694
2695                 group    = EC_KEY_get0_group(tkey);
2696                 priv_key = EC_KEY_get0_private_key(tkey);
2697
2698                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2699                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2700                         {
2701                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2702                                ERR_R_EC_LIB);
2703                         goto err;
2704                         }
2705
2706                 /* Let's get client's public key */
2707                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2708                         {
2709                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2710                             ERR_R_MALLOC_FAILURE);
2711                         goto err;
2712                         }
2713
2714                 if (n == 0L) 
2715                         {
2716                         /* Client Publickey was in Client Certificate */
2717
2718                          if (alg_k & SSL_kECDHE)
2719                                  {
2720                                  al=SSL_AD_HANDSHAKE_FAILURE;
2721                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2722                                  goto f_err;
2723                                  }
2724                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2725                             == NULL) || 
2726                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2727                                 {
2728                                 /* XXX: For now, we do not support client
2729                                  * authentication using ECDH certificates
2730                                  * so this branch (n == 0L) of the code is
2731                                  * never executed. When that support is
2732                                  * added, we ought to ensure the key 
2733                                  * received in the certificate is 
2734                                  * authorized for key agreement.
2735                                  * ECDH_compute_key implicitly checks that
2736                                  * the two ECDH shares are for the same
2737                                  * group.
2738                                  */
2739                                 al=SSL_AD_HANDSHAKE_FAILURE;
2740                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2741                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2742                                 goto f_err;
2743                                 }
2744
2745                         if (EC_POINT_copy(clnt_ecpoint,
2746                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2747                                 {
2748                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2749                                         ERR_R_EC_LIB);
2750                                 goto err;
2751                                 }
2752                         ret = 2; /* Skip certificate verify processing */
2753                         }
2754                 else
2755                         {
2756                         /* Get client's public key from encoded point
2757                          * in the ClientKeyExchange message.
2758                          */
2759                         if ((bn_ctx = BN_CTX_new()) == NULL)
2760                                 {
2761                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2762                                     ERR_R_MALLOC_FAILURE);
2763                                 goto err;
2764                                 }
2765
2766                         /* Get encoded point length */
2767                         i = *p; 
2768                         p += 1;
2769                         if (n != 1 + i)
2770                                 {
2771                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2772                                     ERR_R_EC_LIB);
2773                                 goto err;
2774                                 }
2775                         if (EC_POINT_oct2point(group, 
2776                             clnt_ecpoint, p, i, bn_ctx) == 0)
2777                                 {
2778                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2779                                     ERR_R_EC_LIB);
2780                                 goto err;
2781                                 }
2782                         /* p is pointing to somewhere in the buffer
2783                          * currently, so set it to the start 
2784                          */ 
2785                         p=(unsigned char *)s->init_buf->data;
2786                         }
2787
2788                 /* Compute the shared pre-master secret */
2789                 field_size = EC_GROUP_get_degree(group);
2790                 if (field_size <= 0)
2791                         {
2792                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2793                                ERR_R_ECDH_LIB);
2794                         goto err;
2795                         }
2796                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2797                 if (i <= 0)
2798                         {
2799                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2800                             ERR_R_ECDH_LIB);
2801                         goto err;
2802                         }
2803
2804                 EVP_PKEY_free(clnt_pub_pkey);
2805                 EC_POINT_free(clnt_ecpoint);
2806                 EC_KEY_free(srvr_ecdh);
2807                 BN_CTX_free(bn_ctx);
2808                 EC_KEY_free(s->s3->tmp.ecdh);
2809                 s->s3->tmp.ecdh = NULL; 
2810
2811                 /* Compute the master secret */
2812                 s->session->master_key_length = s->method->ssl3_enc-> \
2813                     generate_master_secret(s, s->session->master_key, p, i);
2814                 
2815                 OPENSSL_cleanse(p, i);
2816                 return (ret);
2817                 }
2818         else
2819 #endif
2820 #ifndef OPENSSL_NO_PSK
2821                 if (alg_k & SSL_kPSK)
2822                         {
2823                         unsigned char *t = NULL;
2824                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2825                         unsigned int pre_ms_len = 0, psk_len = 0;
2826                         int psk_err = 1;
2827                         char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2828
2829                         al=SSL_AD_HANDSHAKE_FAILURE;
2830
2831                         n2s(p,i);
2832                         if (n != i+2)
2833                                 {
2834                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2835                                         SSL_R_LENGTH_MISMATCH);
2836                                 goto psk_err;
2837                                 }
2838                         if (i > PSK_MAX_IDENTITY_LEN)
2839                                 {
2840                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2841                                         SSL_R_DATA_LENGTH_TOO_LONG);
2842                                 goto psk_err;
2843                                 }
2844                         if (s->psk_server_callback == NULL)
2845                                 {
2846                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2847                                        SSL_R_PSK_NO_SERVER_CB);
2848                                 goto psk_err;
2849                                 }
2850
2851                         /* Create guaranteed NULL-terminated identity
2852                          * string for the callback */
2853                         memcpy(tmp_id, p, i);
2854                         memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2855                         psk_len = s->psk_server_callback(s, tmp_id,
2856                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2857                         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2858
2859                         if (psk_len > PSK_MAX_PSK_LEN)
2860                                 {
2861                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2862                                         ERR_R_INTERNAL_ERROR);
2863                                 goto psk_err;
2864                                 }
2865                         else if (psk_len == 0)
2866                                 {
2867                                 /* PSK related to the given identity not found */
2868                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2869                                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2870                                 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2871                                 goto psk_err;
2872                                 }
2873
2874                         /* create PSK pre_master_secret */
2875                         pre_ms_len=2+psk_len+2+psk_len;
2876                         t = psk_or_pre_ms;
2877                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2878                         s2n(psk_len, t);
2879                         memset(t, 0, psk_len);
2880                         t+=psk_len;
2881                         s2n(psk_len, t);
2882
2883                         if (s->session->psk_identity != NULL)
2884                                 OPENSSL_free(s->session->psk_identity);
2885                         s->session->psk_identity = BUF_strdup((char *)p);
2886                         if (s->session->psk_identity == NULL)
2887                                 {
2888                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2889                                         ERR_R_MALLOC_FAILURE);
2890                                 goto psk_err;
2891                                 }
2892
2893                         if (s->session->psk_identity_hint != NULL)
2894                                 OPENSSL_free(s->session->psk_identity_hint);
2895                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2896                         if (s->ctx->psk_identity_hint != NULL &&
2897                                 s->session->psk_identity_hint == NULL)
2898                                 {
2899                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2900                                         ERR_R_MALLOC_FAILURE);
2901                                 goto psk_err;
2902                                 }
2903
2904                         s->session->master_key_length=
2905                                 s->method->ssl3_enc->generate_master_secret(s,
2906                                         s->session->master_key, psk_or_pre_ms, pre_ms_len);
2907                         psk_err = 0;
2908                 psk_err:
2909                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2910                         if (psk_err != 0)
2911                                 goto f_err;
2912                         }
2913                 else
2914 #endif
2915 #ifndef OPENSSL_NO_SRP
2916                 if (alg_k & SSL_kSRP)
2917                         {
2918                         int param_len;
2919
2920                         n2s(p,i);
2921                         param_len=i+2;
2922                         if (param_len > n)
2923                                 {
2924                                 al=SSL_AD_DECODE_ERROR;
2925                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2926                                 goto f_err;
2927                                 }
2928                         if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2929                                 {
2930                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2931                                 goto err;
2932                                 }
2933                         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2934                                 || BN_is_zero(s->srp_ctx.A))
2935                                 {
2936                                 al=SSL_AD_ILLEGAL_PARAMETER;
2937                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
2938                                 goto f_err;
2939                                 }
2940                         if (s->session->srp_username != NULL)
2941                                 OPENSSL_free(s->session->srp_username);
2942                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2943                         if (s->session->srp_username == NULL)
2944                                 {
2945                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2946                                         ERR_R_MALLOC_FAILURE);
2947                                 goto err;
2948                                 }
2949
2950                         if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2951                                 {
2952                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2953                                 goto err;
2954                                 }
2955
2956                         p+=i;
2957                         }
2958                 else
2959 #endif  /* OPENSSL_NO_SRP */
2960                 if (alg_k & SSL_kGOST) 
2961                         {
2962                         int ret = 0;
2963                         EVP_PKEY_CTX *pkey_ctx;
2964                         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2965                         unsigned char premaster_secret[32], *start;
2966                         size_t outlen=32, inlen;
2967                         unsigned long alg_a;
2968                         int Ttag, Tclass;
2969                         long Tlen;
2970
2971                         /* Get our certificate private key*/
2972                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2973                         if (alg_a & SSL_aGOST94)
2974                                 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2975                         else if (alg_a & SSL_aGOST01)
2976                                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2977
2978                         pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2979                         EVP_PKEY_decrypt_init(pkey_ctx);
2980                         /* If client certificate is present and is of the same type, maybe
2981                          * use it for key exchange.  Don't mind errors from
2982                          * EVP_PKEY_derive_set_peer, because it is completely valid to use
2983                          * a client certificate for authorization only. */
2984                         client_pub_pkey = X509_get_pubkey(s->session->peer);
2985                         if (client_pub_pkey)
2986                                 {
2987                                 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2988                                         ERR_clear_error();
2989                                 }
2990                         /* Decrypt session key */
2991                         if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || 
2992                                 Ttag != V_ASN1_SEQUENCE ||
2993                                 Tclass != V_ASN1_UNIVERSAL) 
2994                                 {
2995                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2996                                 goto gerr;
2997                                 }
2998                         start = p;
2999                         inlen = Tlen;
3000                         if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
3001
3002                                 {
3003                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
3004                                 goto gerr;
3005                                 }
3006                         /* Generate master secret */
3007                         s->session->master_key_length=
3008                                 s->method->ssl3_enc->generate_master_secret(s,
3009                                         s->session->master_key,premaster_secret,32);
3010                         /* Check if pubkey from client certificate was used */
3011                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3012                                 ret = 2;
3013                         else
3014                                 ret = 1;
3015                 gerr:
3016                         EVP_PKEY_free(client_pub_pkey);
3017                         EVP_PKEY_CTX_free(pkey_ctx);
3018                         if (ret)
3019                                 return ret;
3020                         else
3021                                 goto err;
3022                         }
3023                 else
3024                 {
3025                 al=SSL_AD_HANDSHAKE_FAILURE;
3026                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
3027                                 SSL_R_UNKNOWN_CIPHER_TYPE);
3028                 goto f_err;
3029                 }
3030
3031         return(1);
3032 f_err:
3033         ssl3_send_alert(s,SSL3_AL_FATAL,al);
3034 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3035 err:
3036 #endif
3037 #ifndef OPENSSL_NO_ECDH
3038         EVP_PKEY_free(clnt_pub_pkey);
3039         EC_POINT_free(clnt_ecpoint);
3040         if (srvr_ecdh != NULL) 
3041                 EC_KEY_free(srvr_ecdh);
3042         BN_CTX_free(bn_ctx);
3043 #endif
3044         return(-1);
3045         }
3046
3047 int ssl3_get_cert_verify(SSL *s)
3048         {
3049         EVP_PKEY *pkey=NULL;
3050         unsigned char *p;
3051         int al,ok,ret=0;
3052         long n;
3053         int type=0,i,j;
3054         X509 *peer;
3055         const EVP_MD *md = NULL;
3056         EVP_MD_CTX mctx;
3057         EVP_MD_CTX_init(&mctx);
3058
3059         n=s->method->ssl_get_message(s,
3060                 SSL3_ST_SR_CERT_VRFY_A,
3061                 SSL3_ST_SR_CERT_VRFY_B,
3062                 -1,
3063                 SSL3_RT_MAX_PLAIN_LENGTH,
3064                 &ok);
3065
3066         if (!ok) return((int)n);
3067
3068         if (s->session->peer != NULL)
3069                 {
3070                 peer=s->session->peer;
3071                 pkey=X509_get_pubkey(peer);
3072                 type=X509_certificate_type(peer,pkey);
3073                 }
3074         else
3075                 {
3076                 peer=NULL;
3077                 pkey=NULL;
3078                 }
3079
3080         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3081                 {
3082                 s->s3->tmp.reuse_message=1;
3083                 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3084                         {
3085                         al=SSL_AD_UNEXPECTED_MESSAGE;
3086                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3087                         goto f_err;
3088                         }
3089                 ret=1;
3090                 goto end;
3091                 }
3092
3093         if (peer == NULL)
3094                 {
3095                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3096                 al=SSL_AD_UNEXPECTED_MESSAGE;
3097                 goto f_err;
3098                 }
3099
3100         if (!(type & EVP_PKT_SIGN))
3101                 {
3102                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3103                 al=SSL_AD_ILLEGAL_PARAMETER;
3104                 goto f_err;
3105                 }
3106
3107         if (s->s3->change_cipher_spec)
3108                 {
3109                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3110                 al=SSL_AD_UNEXPECTED_MESSAGE;
3111                 goto f_err;
3112                 }
3113
3114         /* we now have a signature that we need to verify */
3115         p=(unsigned char *)s->init_msg;
3116         /* Check for broken implementations of GOST ciphersuites */
3117         /* If key is GOST and n is exactly 64, it is bare
3118          * signature without length field */
3119         if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3120                 pkey->type == NID_id_GostR3410_2001) )
3121                 {
3122                 i=64;
3123                 } 
3124         else 
3125                 {       
3126                 if (SSL_USE_SIGALGS(s))
3127                         {
3128                         int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3129                         if (rv == -1)
3130                                 {
3131                                 al = SSL_AD_INTERNAL_ERROR;
3132                                 goto f_err;
3133                                 }
3134                         else if (rv == 0)
3135                                 {
3136                                 al = SSL_AD_DECODE_ERROR;
3137                                 goto f_err;
3138                                 }
3139 #ifdef SSL_DEBUG
3140 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3141 #endif
3142                         p += 2;
3143                         n -= 2;
3144                         }
3145                 n2s(p,i);
3146                 n-=2;
3147                 if (i > n)
3148                         {
3149                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3150                         al=SSL_AD_DECODE_ERROR;
3151                         goto f_err;
3152                         }
3153         }
3154         j=EVP_PKEY_size(pkey);
3155         if ((i > j) || (n > j) || (n <= 0))
3156                 {
3157                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3158                 al=SSL_AD_DECODE_ERROR;
3159                 goto f_err;
3160                 }
3161
3162         if (SSL_USE_SIGALGS(s))
3163                 {
3164                 long hdatalen = 0;
3165                 void *hdata;
3166                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3167                 if (hdatalen <= 0)
3168                         {
3169                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3170                         al=SSL_AD_INTERNAL_ERROR;
3171                         goto f_err;
3172                         }
3173 #ifdef SSL_DEBUG
3174                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3175                                                         EVP_MD_name(md));
3176 #endif
3177                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3178                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3179                         {
3180                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3181                         al=SSL_AD_INTERNAL_ERROR;
3182                         goto f_err;
3183                         }
3184
3185                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3186                         {
3187                         al=SSL_AD_DECRYPT_ERROR;
3188                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3189                         goto f_err;
3190                         }
3191                 }
3192         else
3193 #ifndef OPENSSL_NO_RSA 
3194         if (pkey->type == EVP_PKEY_RSA)
3195                 {
3196                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3197                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3198                                                         pkey->pkey.rsa);
3199                 if (i < 0)
3200                         {
3201                         al=SSL_AD_DECRYPT_ERROR;
3202                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3203                         goto f_err;
3204                         }
3205                 if (i == 0)
3206                         {
3207                         al=SSL_AD_DECRYPT_ERROR;
3208                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3209                         goto f_err;
3210                         }
3211                 }
3212         else
3213 #endif
3214 #ifndef OPENSSL_NO_DSA
3215                 if (pkey->type == EVP_PKEY_DSA)
3216                 {
3217                 j=DSA_verify(pkey->save_type,
3218                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3219                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3220                 if (j <= 0)
3221                         {
3222                         /* bad signature */
3223                         al=SSL_AD_DECRYPT_ERROR;
3224                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3225                         goto f_err;
3226                         }
3227                 }
3228         else
3229 #endif
3230 #ifndef OPENSSL_NO_ECDSA
3231                 if (pkey->type == EVP_PKEY_EC)
3232                 {
3233                 j=ECDSA_verify(pkey->save_type,
3234                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3235                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3236                 if (j <= 0)
3237                         {
3238                         /* bad signature */
3239                         al=SSL_AD_DECRYPT_ERROR;
3240                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3241                             SSL_R_BAD_ECDSA_SIGNATURE);
3242                         goto f_err;
3243                         }
3244                 }
3245         else
3246 #endif
3247         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3248                 {   unsigned char signature[64];
3249                         int idx;
3250                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3251                         EVP_PKEY_verify_init(pctx);
3252                         if (i!=64) {
3253                                 fprintf(stderr,"GOST signature length is %d",i);
3254                         }       
3255                         for (idx=0;idx<64;idx++) {
3256                                 signature[63-idx]=p[idx];
3257                         }       
3258                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3259                         EVP_PKEY_CTX_free(pctx);
3260                         if (j<=0) 
3261                                 {
3262                                 al=SSL_AD_DECRYPT_ERROR;
3263                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3264                                         SSL_R_BAD_ECDSA_SIGNATURE);
3265                                 goto f_err;
3266                                 }       
3267                 }
3268         else    
3269                 {
3270                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3271                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3272                 goto f_err;
3273                 }
3274
3275
3276         ret=1;
3277         if (0)
3278                 {
3279 f_err:
3280                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3281                 }
3282 end:
3283         if (s->s3->handshake_buffer)
3284                 {
3285                 BIO_free(s->s3->handshake_buffer);
3286                 s->s3->handshake_buffer = NULL;
3287                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3288                 }
3289         EVP_MD_CTX_cleanup(&mctx);
3290         EVP_PKEY_free(pkey);
3291         return(ret);
3292         }
3293
3294 int ssl3_get_client_certificate(SSL *s)
3295         {
3296         int i,ok,al,ret= -1;
3297         X509 *x=NULL;
3298         unsigned long l,nc,llen,n;
3299         const unsigned char *p,*q;
3300         unsigned char *d;
3301         STACK_OF(X509) *sk=NULL;
3302
3303         n=s->method->ssl_get_message(s,
3304                 SSL3_ST_SR_CERT_A,
3305                 SSL3_ST_SR_CERT_B,
3306                 -1,
3307                 s->max_cert_list,
3308                 &ok);
3309
3310         if (!ok) return((int)n);
3311
3312         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3313                 {
3314                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3315                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3316                         {
3317                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3318                         al=SSL_AD_HANDSHAKE_FAILURE;
3319                         goto f_err;
3320                         }
3321                 /* If tls asked for a client cert, the client must return a 0 list */
3322                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3323                         {
3324                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3325                         al=SSL_AD_UNEXPECTED_MESSAGE;
3326                         goto f_err;
3327                         }
3328                 s->s3->tmp.reuse_message=1;
3329                 return(1);
3330                 }
3331
3332         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3333                 {
3334                 al=SSL_AD_UNEXPECTED_MESSAGE;
3335                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3336                 goto f_err;
3337                 }
3338         p=d=(unsigned char *)s->init_msg;
3339
3340         if ((sk=sk_X509_new_null()) == NULL)
3341                 {
3342                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3343                 goto err;
3344                 }
3345
3346         n2l3(p,llen);
3347         if (llen+3 != n)
3348                 {
3349                 al=SSL_AD_DECODE_ERROR;
3350                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3351                 goto f_err;
3352                 }
3353         for (nc=0; nc<llen; )
3354                 {
3355                 n2l3(p,l);
3356                 if ((l+nc+3) > llen)
3357                         {
3358                         al=SSL_AD_DECODE_ERROR;
3359                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3360                         goto f_err;
3361                         }
3362
3363                 q=p;
3364                 x=d2i_X509(NULL,&p,l);
3365                 if (x == NULL)
3366                         {
3367                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3368                         goto err;
3369                         }
3370                 if (p != (q+l))
3371                         {
3372                         al=SSL_AD_DECODE_ERROR;
3373                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3374                         goto f_err;
3375                         }
3376                 if (!sk_X509_push(sk,x))
3377                         {
3378                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3379                         goto err;
3380                         }
3381                 x=NULL;
3382                 nc+=l+3;
3383                 }
3384
3385         if (sk_X509_num(sk) <= 0)
3386                 {
3387                 /* TLS does not mind 0 certs returned */
3388                 if (s->version == SSL3_VERSION)
3389                         {
3390                         al=SSL_AD_HANDSHAKE_FAILURE;
3391                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3392                         goto f_err;
3393                         }
3394                 /* Fail for TLS only if we required a certificate */
3395                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3396                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3397                         {
3398                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3399                         al=SSL_AD_HANDSHAKE_FAILURE;
3400                         goto f_err;
3401                         }
3402                 /* No client certificate so digest cached records */
3403                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3404                         {
3405                         al=SSL_AD_INTERNAL_ERROR;
3406                         goto f_err;
3407                         }
3408                 }
3409         else
3410                 {
3411                 EVP_PKEY *pkey;
3412                 i=ssl_verify_cert_chain(s,sk);
3413                 if (i <= 0)
3414                         {
3415                         al=ssl_verify_alarm_type(s->verify_result);
3416                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3417                         goto f_err;
3418                         }
3419                 if (i > 1)
3420                         {
3421                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3422                         al = SSL_AD_HANDSHAKE_FAILURE;
3423                         goto f_err;
3424                         }
3425                 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3426                 if (pkey == NULL)
3427                         {
3428                         al=SSL3_AD_HANDSHAKE_FAILURE;
3429                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3430                                                 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3431                         goto f_err;
3432                         }
3433                 EVP_PKEY_free(pkey);
3434                 }
3435
3436         if (s->session->peer != NULL) /* This should not be needed */
3437                 X509_free(s->session->peer);
3438         s->session->peer=sk_X509_shift(sk);
3439         s->session->verify_result = s->verify_result;
3440
3441         /* With the current implementation, sess_cert will always be NULL
3442          * when we arrive here. */
3443         if (s->session->sess_cert == NULL)
3444                 {
3445                 s->session->sess_cert = ssl_sess_cert_new();
3446                 if (s->session->sess_cert == NULL)
3447                         {
3448                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3449                         goto err;
3450                         }
3451                 }
3452         if (s->session->sess_cert->cert_chain != NULL)
3453                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3454         s->session->sess_cert->cert_chain=sk;
3455         /* Inconsistency alert: cert_chain does *not* include the
3456          * peer's own certificate, while we do include it in s3_clnt.c */
3457
3458         sk=NULL;
3459
3460         ret=1;
3461         if (0)
3462                 {
3463 f_err:
3464                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3465                 }
3466 err:
3467         if (x != NULL) X509_free(x);
3468         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3469         return(ret);
3470         }
3471
3472 int ssl3_send_server_certificate(SSL *s)
3473         {
3474         CERT_PKEY *cpk;
3475
3476         if (s->state == SSL3_ST_SW_CERT_A)
3477                 {
3478                 cpk=ssl_get_server_send_pkey(s);
3479                 if (cpk == NULL)
3480                         {
3481                         /* VRS: allow null cert if auth == KRB5 */
3482                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3483                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3484                                 {
3485                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3486                                 return(0);
3487                                 }
3488                         }
3489
3490                 if (!ssl3_output_cert_chain(s,cpk))
3491                         {
3492                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3493                         return(0);
3494                         }
3495                 s->state=SSL3_ST_SW_CERT_B;
3496                 }
3497
3498         /* SSL3_ST_SW_CERT_B */
3499         return ssl_do_write(s);
3500         }
3501
3502 #ifndef OPENSSL_NO_TLSEXT
3503 /* send a new session ticket (not necessarily for a new session) */
3504 int ssl3_send_newsession_ticket(SSL *s)
3505         {
3506         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3507                 {
3508                 unsigned char *p, *senc, *macstart;
3509                 const unsigned char *const_p;
3510                 int len, slen_full, slen;
3511                 SSL_SESSION *sess;
3512                 unsigned int hlen;
3513                 EVP_CIPHER_CTX ctx;
3514                 HMAC_CTX hctx;
3515                 SSL_CTX *tctx = s->initial_ctx;
3516                 unsigned char iv[EVP_MAX_IV_LENGTH];
3517                 unsigned char key_name[16];
3518
3519                 /* get session encoding length */
3520                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3521                 /* Some length values are 16 bits, so forget it if session is
3522                  * too long
3523                  */
3524                 if (slen_full > 0xFF00)
3525                         return -1;
3526                 senc = OPENSSL_malloc(slen_full);
3527                 if (!senc)
3528                         return -1;
3529                 p = senc;
3530                 i2d_SSL_SESSION(s->session, &p);
3531
3532                 /* create a fresh copy (not shared with other threads) to clean up */
3533                 const_p = senc;
3534                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3535                 if (sess == NULL)
3536                         {
3537                         OPENSSL_free(senc);
3538                         return -1;
3539                         }
3540                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3541
3542                 slen = i2d_SSL_SESSION(sess, NULL);
3543                 if (slen > slen_full) /* shouldn't ever happen */
3544                         {
3545                         OPENSSL_free(senc);
3546                         return -1;
3547                         }
3548                 p = senc;
3549                 i2d_SSL_SESSION(sess, &p);
3550                 SSL_SESSION_free(sess);
3551
3552                 /* Grow buffer if need be: the length calculation is as
3553                  * follows handshake_header_length +
3554                  * 4 (ticket lifetime hint) + 2 (ticket length) +
3555                  * 16 (key name) + max_iv_len (iv length) +
3556                  * session_length + max_enc_block_size (max encrypted session
3557                  * length) + max_md_size (HMAC).
3558                  */
3559                 if (!BUF_MEM_grow(s->init_buf,
3560                         SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3561                         EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3562                         return -1;
3563                 p = ssl_handshake_start(s);
3564                 EVP_CIPHER_CTX_init(&ctx);
3565                 HMAC_CTX_init(&hctx);
3566                 /* Initialize HMAC and cipher contexts. If callback present
3567                  * it does all the work otherwise use generated values
3568                  * from parent ctx.
3569                  */
3570                 if (tctx->tlsext_ticket_key_cb)
3571                         {
3572                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3573                                                          &hctx, 1) < 0)
3574                                 {
3575                                 OPENSSL_free(senc);
3576                                 return -1;
3577                                 }
3578                         }
3579                 else
3580                         {
3581                         RAND_pseudo_bytes(iv, 16);
3582                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3583                                         tctx->tlsext_tick_aes_key, iv);
3584                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3585                                         tlsext_tick_md(), NULL);
3586                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3587                         }
3588
3589                 /* Ticket lifetime hint (advisory only):
3590                  * We leave this unspecified for resumed session (for simplicity),
3591                  * and guess that tickets for new sessions will live as long
3592                  * as their sessions. */
3593                 l2n(s->hit ? 0 : s->session->timeout, p);
3594
3595                 /* Skip ticket length for now */
3596                 p += 2;
3597                 /* Output key name */
3598                 macstart = p;
3599                 memcpy(p, key_name, 16);
3600                 p += 16;
3601                 /* output IV */
3602                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3603                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3604                 /* Encrypt session data */
3605                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3606                 p += len;
3607                 EVP_EncryptFinal(&ctx, p, &len);
3608                 p += len;
3609                 EVP_CIPHER_CTX_cleanup(&ctx);
3610
3611                 HMAC_Update(&hctx, macstart, p - macstart);
3612                 HMAC_Final(&hctx, p, &hlen);
3613                 HMAC_CTX_cleanup(&hctx);
3614
3615                 p += hlen;
3616                 /* Now write out lengths: p points to end of data written */
3617                 /* Total length */
3618                 len = p - ssl_handshake_start(s);
3619                 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3620                 /* Skip ticket lifetime hint */
3621                 p = ssl_handshake_start(s) + 4;
3622                 s2n(len - 6, p);
3623                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3624                 OPENSSL_free(senc);
3625                 }
3626
3627         /* SSL3_ST_SW_SESSION_TICKET_B */
3628         return ssl_do_write(s);
3629         }
3630
3631 int ssl3_send_cert_status(SSL *s)
3632         {
3633         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3634                 {
3635                 unsigned char *p;
3636                 /* Grow buffer if need be: the length calculation is as
3637                  * follows 1 (message type) + 3 (message length) +
3638                  * 1 (ocsp response type) + 3 (ocsp response length)
3639                  * + (ocsp response)
3640                  */
3641                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3642                         return -1;
3643
3644                 p=(unsigned char *)s->init_buf->data;
3645
3646                 /* do the header */
3647                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3648                 /* message length */
3649                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3650                 /* status type */
3651                 *(p++)= s->tlsext_status_type;
3652                 /* length of OCSP response */
3653                 l2n3(s->tlsext_ocsp_resplen, p);
3654                 /* actual response */
3655                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3656                 /* number of bytes to write */
3657                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3658                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3659                 s->init_off = 0;
3660                 }
3661
3662         /* SSL3_ST_SW_CERT_STATUS_B */
3663         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3664         }
3665
3666 # ifndef OPENSSL_NO_NEXTPROTONEG
3667 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3668  * sets the next_proto member in s if found */
3669 int ssl3_get_next_proto(SSL *s)
3670         {
3671         int ok;
3672         int proto_len, padding_len;
3673         long n;
3674         const unsigned char *p;
3675
3676         /* Clients cannot send a NextProtocol message if we didn't see the
3677          * extension in their ClientHello */
3678         if (!s->s3->next_proto_neg_seen)
3679                 {
3680                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3681                 return -1;
3682                 }
3683
3684         n=s->method->ssl_get_message(s,
3685                 SSL3_ST_SR_NEXT_PROTO_A,
3686                 SSL3_ST_SR_NEXT_PROTO_B,
3687                 SSL3_MT_NEXT_PROTO,
3688                 514,  /* See the payload format below */
3689                 &ok);
3690
3691         if (!ok)
3692                 return((int)n);
3693
3694         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3695          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3696          * by ssl3_get_finished). */
3697         if (!s->s3->change_cipher_spec)
3698                 {
3699                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3700                 return -1;
3701                 }
3702
3703         if (n < 2)
3704                 return 0;  /* The body must be > 1 bytes long */
3705
3706         p=(unsigned char *)s->init_msg;
3707
3708         /* The payload looks like:
3709          *   uint8 proto_len;
3710          *   uint8 proto[proto_len];
3711          *   uint8 padding_len;
3712          *   uint8 padding[padding_len];
3713          */
3714         proto_len = p[0];
3715         if (proto_len + 2 > s->init_num)
3716                 return 0;
3717         padding_len = p[proto_len + 1];
3718         if (proto_len + padding_len + 2 != s->init_num)
3719                 return 0;
3720
3721         s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3722         if (!s->next_proto_negotiated)
3723                 {
3724                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3725                 return 0;
3726                 }
3727         memcpy(s->next_proto_negotiated, p + 1, proto_len);
3728         s->next_proto_negotiated_len = proto_len;
3729
3730         return 1;
3731         }
3732 # endif
3733
3734 #endif