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