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