Allocate extra space when NETSCAPE_HANG_BUG defined.
[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                         if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2188                                 {
2189                                 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2190                                 goto err;
2191                                 }
2192                         p=(unsigned char *)s->init_buf->data + s->init_num;
2193                         /* do the header */
2194                         *(p++)=SSL3_MT_SERVER_DONE;
2195                         *(p++)=0;
2196                         *(p++)=0;
2197                         *(p++)=0;
2198                         s->init_num += 4;
2199                         }
2200 #endif
2201
2202                 s->state = SSL3_ST_SW_CERT_REQ_B;
2203                 }
2204
2205         /* SSL3_ST_SW_CERT_REQ_B */
2206         return ssl_do_write(s);
2207 err:
2208         return(-1);
2209         }
2210
2211 int ssl3_get_client_key_exchange(SSL *s)
2212         {
2213         int i,al,ok;
2214         long n;
2215         unsigned long alg_k;
2216         unsigned char *p;
2217 #ifndef OPENSSL_NO_RSA
2218         RSA *rsa=NULL;
2219         EVP_PKEY *pkey=NULL;
2220 #endif
2221 #ifndef OPENSSL_NO_DH
2222         BIGNUM *pub=NULL;
2223         DH *dh_srvr, *dh_clnt = NULL;
2224 #endif
2225 #ifndef OPENSSL_NO_KRB5
2226         KSSL_ERR kssl_err;
2227 #endif /* OPENSSL_NO_KRB5 */
2228
2229 #ifndef OPENSSL_NO_ECDH
2230         EC_KEY *srvr_ecdh = NULL;
2231         EVP_PKEY *clnt_pub_pkey = NULL;
2232         EC_POINT *clnt_ecpoint = NULL;
2233         BN_CTX *bn_ctx = NULL; 
2234 #endif
2235
2236         n=s->method->ssl_get_message(s,
2237                 SSL3_ST_SR_KEY_EXCH_A,
2238                 SSL3_ST_SR_KEY_EXCH_B,
2239                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2240                 2048, /* ??? */
2241                 &ok);
2242
2243         if (!ok) return((int)n);
2244         p=(unsigned char *)s->init_msg;
2245
2246         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2247
2248 #ifndef OPENSSL_NO_RSA
2249         if (alg_k & SSL_kRSA)
2250                 {
2251                 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2252                 int decrypt_len, decrypt_good_mask;
2253                 unsigned char version_good;
2254
2255                 /* FIX THIS UP EAY EAY EAY EAY */
2256                 if (s->s3->tmp.use_rsa_tmp)
2257                         {
2258                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2259                                 rsa=s->cert->rsa_tmp;
2260                         /* Don't do a callback because rsa_tmp should
2261                          * be sent already */
2262                         if (rsa == NULL)
2263                                 {
2264                                 al=SSL_AD_HANDSHAKE_FAILURE;
2265                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2266                                 goto f_err;
2267
2268                                 }
2269                         }
2270                 else
2271                         {
2272                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2273                         if (    (pkey == NULL) ||
2274                                 (pkey->type != EVP_PKEY_RSA) ||
2275                                 (pkey->pkey.rsa == NULL))
2276                                 {
2277                                 al=SSL_AD_HANDSHAKE_FAILURE;
2278                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2279                                 goto f_err;
2280                                 }
2281                         rsa=pkey->pkey.rsa;
2282                         }
2283
2284                 /* TLS and [incidentally] DTLS{0xFEFF} */
2285                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2286                         {
2287                         n2s(p,i);
2288                         if (n != i+2)
2289                                 {
2290                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2291                                         {
2292                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2293                                         goto err;
2294                                         }
2295                                 else
2296                                         p-=2;
2297                                 }
2298                         else
2299                                 n=i;
2300                         }
2301
2302                 /* We must not leak whether a decryption failure occurs because
2303                  * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2304                  * RFC 2246, section 7.4.7.1). The code follows that advice of
2305                  * the TLS RFC and generates a random premaster secret for the
2306                  * case that the decrypt fails. See
2307                  * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2308
2309                 /* should be RAND_bytes, but we cannot work around a failure. */
2310                 if (RAND_pseudo_bytes(rand_premaster_secret,
2311                                       sizeof(rand_premaster_secret)) <= 0)
2312                         goto err;
2313                 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2314                 ERR_clear_error();
2315
2316                 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2317                  * decrypt_good_mask will be zero if so and non-zero otherwise. */
2318                 decrypt_good_mask = decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
2319
2320                 /* If the version in the decrypted pre-master secret is correct
2321                  * then version_good will be zero. The Klima-Pokorny-Rosa
2322                  * extension of Bleichenbacher's attack
2323                  * (http://eprint.iacr.org/2003/052/) exploits the version
2324                  * number check as a "bad version oracle". Thus version checks
2325                  * are done in constant time and are treated like any other
2326                  * decryption error. */
2327                 version_good = p[0] ^ (s->client_version>>8);
2328                 version_good |= p[1] ^ (s->client_version&0xff);
2329
2330                 /* The premaster secret must contain the same version number as
2331                  * the ClientHello to detect version rollback attacks
2332                  * (strangely, the protocol does not offer such protection for
2333                  * DH ciphersuites). However, buggy clients exist that send the
2334                  * negotiated protocol version instead if the server does not
2335                  * support the requested protocol version. If
2336                  * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2337                 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2338                         {
2339                         unsigned char workaround_mask = version_good;
2340                         unsigned char workaround;
2341
2342                         /* workaround_mask will be 0xff if version_good is
2343                          * non-zero (i.e. the version match failed). Otherwise
2344                          * it'll be 0x00. */
2345                         workaround_mask |= workaround_mask >> 4;
2346                         workaround_mask |= workaround_mask >> 2;
2347                         workaround_mask |= workaround_mask >> 1;
2348                         workaround_mask = ~((workaround_mask & 1) - 1);
2349
2350                         workaround = p[0] ^ (s->version>>8);
2351                         workaround |= p[1] ^ (s->version&0xff);
2352
2353                         /* If workaround_mask is 0xff (i.e. there was a version
2354                          * mismatch) then we copy the value of workaround over
2355                          * version_good. */
2356                         version_good = (workaround & workaround_mask) |
2357                                        (version_good & ~workaround_mask);
2358                         }
2359
2360                 /* If any bits in version_good are set then they'll poision
2361                  * decrypt_good_mask and cause rand_premaster_secret to be
2362                  * used. */
2363                 decrypt_good_mask |= version_good;
2364
2365                 /* decrypt_good_mask will be zero iff decrypt_len ==
2366                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
2367                  * fold the bottom 32 bits of it with an OR so that the LSB
2368                  * will be zero iff everything is good. This assumes that we'll
2369                  * never decrypt a value > 2**31 bytes, which seems safe. */
2370                 decrypt_good_mask |= decrypt_good_mask >> 16;
2371                 decrypt_good_mask |= decrypt_good_mask >> 8;
2372                 decrypt_good_mask |= decrypt_good_mask >> 4;
2373                 decrypt_good_mask |= decrypt_good_mask >> 2;
2374                 decrypt_good_mask |= decrypt_good_mask >> 1;
2375                 /* Now select only the LSB and subtract one. If decrypt_len ==
2376                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
2377                  * decrypt_good_mask will be all ones. Otherwise it'll be all
2378                  * zeros. */
2379                 decrypt_good_mask &= 1;
2380                 decrypt_good_mask--;
2381
2382                 /* Now copy rand_premaster_secret over p using
2383                  * decrypt_good_mask. */
2384                 for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2385                         {
2386                         p[i] = (p[i] & decrypt_good_mask) |
2387                                (rand_premaster_secret[i] & ~decrypt_good_mask);
2388                         }
2389
2390                 s->session->master_key_length=
2391                         s->method->ssl3_enc->generate_master_secret(s,
2392                                 s->session->master_key,
2393                                 p,i);
2394                 OPENSSL_cleanse(p,i);
2395                 }
2396         else
2397 #endif
2398 #ifndef OPENSSL_NO_DH
2399                 if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
2400                 {
2401                 int idx = -1;
2402                 EVP_PKEY *skey = NULL;
2403                 if (n)
2404                         n2s(p,i);
2405                 else
2406                         i = 0;
2407                 if (n && n != i+2)
2408                         {
2409                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2410                                 {
2411                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2412                                 goto err;
2413                                 }
2414                         else
2415                                 {
2416                                 p-=2;
2417                                 i=(int)n;
2418                                 }
2419                         }
2420                 if (alg_k & SSL_kDHr)
2421                         idx = SSL_PKEY_DH_RSA;
2422                 else if (alg_k & SSL_kDHd)
2423                         idx = SSL_PKEY_DH_DSA;
2424                 if (idx >= 0)
2425                         {
2426                         skey = s->cert->pkeys[idx].privatekey;
2427                         if ((skey == NULL) ||
2428                                 (skey->type != EVP_PKEY_DH) ||
2429                                 (skey->pkey.dh == NULL))
2430                                 {
2431                                 al=SSL_AD_HANDSHAKE_FAILURE;
2432                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2433                                 goto f_err;
2434                                 }
2435                         dh_srvr = skey->pkey.dh;
2436                         }
2437                 else if (s->s3->tmp.dh == NULL)
2438                         {
2439                         al=SSL_AD_HANDSHAKE_FAILURE;
2440                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2441                         goto f_err;
2442                         }
2443                 else
2444                         dh_srvr=s->s3->tmp.dh;
2445
2446                 if (n == 0L)
2447                         {
2448                         /* Get pubkey from cert */
2449                         EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2450                         if (clkey)
2451                                 {
2452                                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2453                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2454                                 }
2455                         if (dh_clnt == NULL)
2456                                 {
2457                                 al=SSL_AD_HANDSHAKE_FAILURE;
2458                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2459                                 goto f_err;
2460                                 }
2461                         EVP_PKEY_free(clkey);
2462                         pub = dh_clnt->pub_key;
2463                         }
2464                 else
2465                         pub=BN_bin2bn(p,i,NULL);
2466                 if (pub == NULL)
2467                         {
2468                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2469                         goto err;
2470                         }
2471
2472                 i=DH_compute_key(p,pub,dh_srvr);
2473
2474                 if (i <= 0)
2475                         {
2476                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2477                         BN_clear_free(pub);
2478                         goto err;
2479                         }
2480
2481                 DH_free(s->s3->tmp.dh);
2482                 s->s3->tmp.dh=NULL;
2483                 if (dh_clnt)
2484                         DH_free(dh_clnt);
2485                 else
2486                         BN_clear_free(pub);
2487                 pub=NULL;
2488                 s->session->master_key_length=
2489                         s->method->ssl3_enc->generate_master_secret(s,
2490                                 s->session->master_key,p,i);
2491                 OPENSSL_cleanse(p,i);
2492                 if (dh_clnt)
2493                         return 2;
2494                 }
2495         else
2496 #endif
2497 #ifndef OPENSSL_NO_KRB5
2498         if (alg_k & SSL_kKRB5)
2499                 {
2500                 krb5_error_code         krb5rc;
2501                 krb5_data               enc_ticket;
2502                 krb5_data               authenticator;
2503                 krb5_data               enc_pms;
2504                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
2505                 EVP_CIPHER_CTX          ciph_ctx;
2506                 const EVP_CIPHER        *enc = NULL;
2507                 unsigned char           iv[EVP_MAX_IV_LENGTH];
2508                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
2509                                                + EVP_MAX_BLOCK_LENGTH];
2510                 int                  padl, outl;
2511                 krb5_timestamp          authtime = 0;
2512                 krb5_ticket_times       ttimes;
2513
2514                 EVP_CIPHER_CTX_init(&ciph_ctx);
2515
2516                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2517
2518                 n2s(p,i);
2519                 enc_ticket.length = i;
2520
2521                 if (n < (long)(enc_ticket.length + 6))
2522                         {
2523                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2524                                 SSL_R_DATA_LENGTH_TOO_LONG);
2525                         goto err;
2526                         }
2527
2528                 enc_ticket.data = (char *)p;
2529                 p+=enc_ticket.length;
2530
2531                 n2s(p,i);
2532                 authenticator.length = i;
2533
2534                 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2535                         {
2536                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2537                                 SSL_R_DATA_LENGTH_TOO_LONG);
2538                         goto err;
2539                         }
2540
2541                 authenticator.data = (char *)p;
2542                 p+=authenticator.length;
2543
2544                 n2s(p,i);
2545                 enc_pms.length = i;
2546                 enc_pms.data = (char *)p;
2547                 p+=enc_pms.length;
2548
2549                 /* Note that the length is checked again below,
2550                 ** after decryption
2551                 */
2552                 if(enc_pms.length > sizeof pms)
2553                         {
2554                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2555                                SSL_R_DATA_LENGTH_TOO_LONG);
2556                         goto err;
2557                         }
2558
2559                 if (n != (long)(enc_ticket.length + authenticator.length +
2560                                                 enc_pms.length + 6))
2561                         {
2562                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2563                                 SSL_R_DATA_LENGTH_TOO_LONG);
2564                         goto err;
2565                         }
2566
2567                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2568                                         &kssl_err)) != 0)
2569                         {
2570 #ifdef KSSL_DEBUG
2571                         printf("kssl_sget_tkt rtn %d [%d]\n",
2572                                 krb5rc, kssl_err.reason);
2573                         if (kssl_err.text)
2574                                 printf("kssl_err text= %s\n", kssl_err.text);
2575 #endif  /* KSSL_DEBUG */
2576                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2577                                 kssl_err.reason);
2578                         goto err;
2579                         }
2580
2581                 /*  Note: no authenticator is not considered an error,
2582                 **  but will return authtime == 0.
2583                 */
2584                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2585                                         &authtime, &kssl_err)) != 0)
2586                         {
2587 #ifdef KSSL_DEBUG
2588                         printf("kssl_check_authent rtn %d [%d]\n",
2589                                 krb5rc, kssl_err.reason);
2590                         if (kssl_err.text)
2591                                 printf("kssl_err text= %s\n", kssl_err.text);
2592 #endif  /* KSSL_DEBUG */
2593                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2594                                 kssl_err.reason);
2595                         goto err;
2596                         }
2597
2598                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2599                         {
2600                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2601                         goto err;
2602                         }
2603
2604 #ifdef KSSL_DEBUG
2605                 kssl_ctx_show(kssl_ctx);
2606 #endif  /* KSSL_DEBUG */
2607
2608                 enc = kssl_map_enc(kssl_ctx->enctype);
2609                 if (enc == NULL)
2610                     goto err;
2611
2612                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2613
2614                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2615                         {
2616                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2617                                 SSL_R_DECRYPTION_FAILED);
2618                         goto err;
2619                         }
2620                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2621                                         (unsigned char *)enc_pms.data, enc_pms.length))
2622                         {
2623                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2624                                 SSL_R_DECRYPTION_FAILED);
2625                         goto err;
2626                         }
2627                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2628                         {
2629                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2630                                 SSL_R_DATA_LENGTH_TOO_LONG);
2631                         goto err;
2632                         }
2633                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2634                         {
2635                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2636                                 SSL_R_DECRYPTION_FAILED);
2637                         goto err;
2638                         }
2639                 outl += padl;
2640                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2641                         {
2642                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2643                                 SSL_R_DATA_LENGTH_TOO_LONG);
2644                         goto err;
2645                         }
2646                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2647                     {
2648                     /* The premaster secret must contain the same version number as the
2649                      * ClientHello to detect version rollback attacks (strangely, the
2650                      * protocol does not offer such protection for DH ciphersuites).
2651                      * However, buggy clients exist that send random bytes instead of
2652                      * the protocol version.
2653                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2654                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2655                      */
2656                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2657                         {
2658                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2659                                SSL_AD_DECODE_ERROR);
2660                         goto err;
2661                         }
2662                     }
2663
2664                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2665
2666                 s->session->master_key_length=
2667                         s->method->ssl3_enc->generate_master_secret(s,
2668                                 s->session->master_key, pms, outl);
2669
2670                 if (kssl_ctx->client_princ)
2671                         {
2672                         size_t len = strlen(kssl_ctx->client_princ);
2673                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2674                                 {
2675                                 s->session->krb5_client_princ_len = len;
2676                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2677                                 }
2678                         }
2679
2680
2681                 /*  Was doing kssl_ctx_free() here,
2682                 **  but it caused problems for apache.
2683                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2684                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2685                 */
2686                 }
2687         else
2688 #endif  /* OPENSSL_NO_KRB5 */
2689
2690 #ifndef OPENSSL_NO_ECDH
2691                 if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
2692                 {
2693                 int ret = 1;
2694                 int field_size = 0;
2695                 const EC_KEY   *tkey;
2696                 const EC_GROUP *group;
2697                 const BIGNUM *priv_key;
2698
2699                 /* initialize structures for server's ECDH key pair */
2700                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2701                         {
2702                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2703                             ERR_R_MALLOC_FAILURE);
2704                         goto err;
2705                         }
2706
2707                 /* Let's get server private key and group information */
2708                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2709                         { 
2710                         /* use the certificate */
2711                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2712                         }
2713                 else
2714                         {
2715                         /* use the ephermeral values we saved when
2716                          * generating the ServerKeyExchange msg.
2717                          */
2718                         tkey = s->s3->tmp.ecdh;
2719                         }
2720
2721                 group    = EC_KEY_get0_group(tkey);
2722                 priv_key = EC_KEY_get0_private_key(tkey);
2723
2724                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2725                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2726                         {
2727                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2728                                ERR_R_EC_LIB);
2729                         goto err;
2730                         }
2731
2732                 /* Let's get client's public key */
2733                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2734                         {
2735                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2736                             ERR_R_MALLOC_FAILURE);
2737                         goto err;
2738                         }
2739
2740                 if (n == 0L) 
2741                         {
2742                         /* Client Publickey was in Client Certificate */
2743
2744                          if (alg_k & SSL_kECDHE)
2745                                  {
2746                                  al=SSL_AD_HANDSHAKE_FAILURE;
2747                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2748                                  goto f_err;
2749                                  }
2750                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2751                             == NULL) || 
2752                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2753                                 {
2754                                 /* XXX: For now, we do not support client
2755                                  * authentication using ECDH certificates
2756                                  * so this branch (n == 0L) of the code is
2757                                  * never executed. When that support is
2758                                  * added, we ought to ensure the key 
2759                                  * received in the certificate is 
2760                                  * authorized for key agreement.
2761                                  * ECDH_compute_key implicitly checks that
2762                                  * the two ECDH shares are for the same
2763                                  * group.
2764                                  */
2765                                 al=SSL_AD_HANDSHAKE_FAILURE;
2766                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2767                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2768                                 goto f_err;
2769                                 }
2770
2771                         if (EC_POINT_copy(clnt_ecpoint,
2772                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2773                                 {
2774                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2775                                         ERR_R_EC_LIB);
2776                                 goto err;
2777                                 }
2778                         ret = 2; /* Skip certificate verify processing */
2779                         }
2780                 else
2781                         {
2782                         /* Get client's public key from encoded point
2783                          * in the ClientKeyExchange message.
2784                          */
2785                         if ((bn_ctx = BN_CTX_new()) == NULL)
2786                                 {
2787                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2788                                     ERR_R_MALLOC_FAILURE);
2789                                 goto err;
2790                                 }
2791
2792                         /* Get encoded point length */
2793                         i = *p; 
2794                         p += 1;
2795                         if (n != 1 + i)
2796                                 {
2797                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2798                                     ERR_R_EC_LIB);
2799                                 goto err;
2800                                 }
2801                         if (EC_POINT_oct2point(group, 
2802                             clnt_ecpoint, p, i, bn_ctx) == 0)
2803                                 {
2804                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2805                                     ERR_R_EC_LIB);
2806                                 goto err;
2807                                 }
2808                         /* p is pointing to somewhere in the buffer
2809                          * currently, so set it to the start 
2810                          */ 
2811                         p=(unsigned char *)s->init_buf->data;
2812                         }
2813
2814                 /* Compute the shared pre-master secret */
2815                 field_size = EC_GROUP_get_degree(group);
2816                 if (field_size <= 0)
2817                         {
2818                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2819                                ERR_R_ECDH_LIB);
2820                         goto err;
2821                         }
2822                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2823                 if (i <= 0)
2824                         {
2825                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2826                             ERR_R_ECDH_LIB);
2827                         goto err;
2828                         }
2829
2830                 EVP_PKEY_free(clnt_pub_pkey);
2831                 EC_POINT_free(clnt_ecpoint);
2832                 EC_KEY_free(srvr_ecdh);
2833                 BN_CTX_free(bn_ctx);
2834                 EC_KEY_free(s->s3->tmp.ecdh);
2835                 s->s3->tmp.ecdh = NULL; 
2836
2837                 /* Compute the master secret */
2838                 s->session->master_key_length = s->method->ssl3_enc-> \
2839                     generate_master_secret(s, s->session->master_key, p, i);
2840                 
2841                 OPENSSL_cleanse(p, i);
2842                 return (ret);
2843                 }
2844         else
2845 #endif
2846 #ifndef OPENSSL_NO_PSK
2847                 if (alg_k & SSL_kPSK)
2848                         {
2849                         unsigned char *t = NULL;
2850                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2851                         unsigned int pre_ms_len = 0, psk_len = 0;
2852                         int psk_err = 1;
2853                         char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2854
2855                         al=SSL_AD_HANDSHAKE_FAILURE;
2856
2857                         n2s(p,i);
2858                         if (n != i+2)
2859                                 {
2860                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2861                                         SSL_R_LENGTH_MISMATCH);
2862                                 goto psk_err;
2863                                 }
2864                         if (i > PSK_MAX_IDENTITY_LEN)
2865                                 {
2866                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2867                                         SSL_R_DATA_LENGTH_TOO_LONG);
2868                                 goto psk_err;
2869                                 }
2870                         if (s->psk_server_callback == NULL)
2871                                 {
2872                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2873                                        SSL_R_PSK_NO_SERVER_CB);
2874                                 goto psk_err;
2875                                 }
2876
2877                         /* Create guaranteed NULL-terminated identity
2878                          * string for the callback */
2879                         memcpy(tmp_id, p, i);
2880                         memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2881                         psk_len = s->psk_server_callback(s, tmp_id,
2882                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2883                         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2884
2885                         if (psk_len > PSK_MAX_PSK_LEN)
2886                                 {
2887                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2888                                         ERR_R_INTERNAL_ERROR);
2889                                 goto psk_err;
2890                                 }
2891                         else if (psk_len == 0)
2892                                 {
2893                                 /* PSK related to the given identity not found */
2894                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2895                                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2896                                 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2897                                 goto psk_err;
2898                                 }
2899
2900                         /* create PSK pre_master_secret */
2901                         pre_ms_len=2+psk_len+2+psk_len;
2902                         t = psk_or_pre_ms;
2903                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2904                         s2n(psk_len, t);
2905                         memset(t, 0, psk_len);
2906                         t+=psk_len;
2907                         s2n(psk_len, t);
2908
2909                         if (s->session->psk_identity != NULL)
2910                                 OPENSSL_free(s->session->psk_identity);
2911                         s->session->psk_identity = BUF_strdup((char *)p);
2912                         if (s->session->psk_identity == NULL)
2913                                 {
2914                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2915                                         ERR_R_MALLOC_FAILURE);
2916                                 goto psk_err;
2917                                 }
2918
2919                         if (s->session->psk_identity_hint != NULL)
2920                                 OPENSSL_free(s->session->psk_identity_hint);
2921                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2922                         if (s->ctx->psk_identity_hint != NULL &&
2923                                 s->session->psk_identity_hint == NULL)
2924                                 {
2925                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2926                                         ERR_R_MALLOC_FAILURE);
2927                                 goto psk_err;
2928                                 }
2929
2930                         s->session->master_key_length=
2931                                 s->method->ssl3_enc->generate_master_secret(s,
2932                                         s->session->master_key, psk_or_pre_ms, pre_ms_len);
2933                         psk_err = 0;
2934                 psk_err:
2935                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2936                         if (psk_err != 0)
2937                                 goto f_err;
2938                         }
2939                 else
2940 #endif
2941 #ifndef OPENSSL_NO_SRP
2942                 if (alg_k & SSL_kSRP)
2943                         {
2944                         int param_len;
2945
2946                         n2s(p,i);
2947                         param_len=i+2;
2948                         if (param_len > n)
2949                                 {
2950                                 al=SSL_AD_DECODE_ERROR;
2951                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2952                                 goto f_err;
2953                                 }
2954                         if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2955                                 {
2956                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2957                                 goto err;
2958                                 }
2959                         if (s->session->srp_username != NULL)
2960                                 OPENSSL_free(s->session->srp_username);
2961                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2962                         if (s->session->srp_username == NULL)
2963                                 {
2964                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2965                                         ERR_R_MALLOC_FAILURE);
2966                                 goto err;
2967                                 }
2968
2969                         if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2970                                 {
2971                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2972                                 goto err;
2973                                 }
2974
2975                         p+=i;
2976                         }
2977                 else
2978 #endif  /* OPENSSL_NO_SRP */
2979                 if (alg_k & SSL_kGOST) 
2980                         {
2981                         int ret = 0;
2982                         EVP_PKEY_CTX *pkey_ctx;
2983                         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2984                         unsigned char premaster_secret[32], *start;
2985                         size_t outlen=32, inlen;
2986                         unsigned long alg_a;
2987                         int Ttag, Tclass;
2988                         long Tlen;
2989
2990                         /* Get our certificate private key*/
2991                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2992                         if (alg_a & SSL_aGOST94)
2993                                 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2994                         else if (alg_a & SSL_aGOST01)
2995                                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2996
2997                         pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2998                         EVP_PKEY_decrypt_init(pkey_ctx);
2999                         /* If client certificate is present and is of the same type, maybe
3000                          * use it for key exchange.  Don't mind errors from
3001                          * EVP_PKEY_derive_set_peer, because it is completely valid to use
3002                          * a client certificate for authorization only. */
3003                         client_pub_pkey = X509_get_pubkey(s->session->peer);
3004                         if (client_pub_pkey)
3005                                 {
3006                                 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3007                                         ERR_clear_error();
3008                                 }
3009                         /* Decrypt session key */
3010                         if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || 
3011                                 Ttag != V_ASN1_SEQUENCE ||
3012                                 Tclass != V_ASN1_UNIVERSAL) 
3013                                 {
3014                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
3015                                 goto gerr;
3016                                 }
3017                         start = p;
3018                         inlen = Tlen;
3019                         if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
3020
3021                                 {
3022                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
3023                                 goto gerr;
3024                                 }
3025                         /* Generate master secret */
3026                         s->session->master_key_length=
3027                                 s->method->ssl3_enc->generate_master_secret(s,
3028                                         s->session->master_key,premaster_secret,32);
3029                         /* Check if pubkey from client certificate was used */
3030                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3031                                 ret = 2;
3032                         else
3033                                 ret = 1;
3034                 gerr:
3035                         EVP_PKEY_free(client_pub_pkey);
3036                         EVP_PKEY_CTX_free(pkey_ctx);
3037                         if (ret)
3038                                 return ret;
3039                         else
3040                                 goto err;
3041                         }
3042                 else
3043                 {
3044                 al=SSL_AD_HANDSHAKE_FAILURE;
3045                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
3046                                 SSL_R_UNKNOWN_CIPHER_TYPE);
3047                 goto f_err;
3048                 }
3049
3050         return(1);
3051 f_err:
3052         ssl3_send_alert(s,SSL3_AL_FATAL,al);
3053 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3054 err:
3055 #endif
3056 #ifndef OPENSSL_NO_ECDH
3057         EVP_PKEY_free(clnt_pub_pkey);
3058         EC_POINT_free(clnt_ecpoint);
3059         if (srvr_ecdh != NULL) 
3060                 EC_KEY_free(srvr_ecdh);
3061         BN_CTX_free(bn_ctx);
3062 #endif
3063         return(-1);
3064         }
3065
3066 int ssl3_get_cert_verify(SSL *s)
3067         {
3068         EVP_PKEY *pkey=NULL;
3069         unsigned char *p;
3070         int al,ok,ret=0;
3071         long n;
3072         int type=0,i,j;
3073         X509 *peer;
3074         const EVP_MD *md = NULL;
3075         EVP_MD_CTX mctx;
3076         EVP_MD_CTX_init(&mctx);
3077
3078         n=s->method->ssl_get_message(s,
3079                 SSL3_ST_SR_CERT_VRFY_A,
3080                 SSL3_ST_SR_CERT_VRFY_B,
3081                 -1,
3082                 516, /* Enough for 4096 bit RSA key with TLS v1.2 */
3083                 &ok);
3084
3085         if (!ok) return((int)n);
3086
3087         if (s->session->peer != NULL)
3088                 {
3089                 peer=s->session->peer;
3090                 pkey=X509_get_pubkey(peer);
3091                 type=X509_certificate_type(peer,pkey);
3092                 }
3093         else
3094                 {
3095                 peer=NULL;
3096                 pkey=NULL;
3097                 }
3098
3099         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3100                 {
3101                 s->s3->tmp.reuse_message=1;
3102                 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3103                         {
3104                         al=SSL_AD_UNEXPECTED_MESSAGE;
3105                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3106                         goto f_err;
3107                         }
3108                 ret=1;
3109                 goto end;
3110                 }
3111
3112         if (peer == NULL)
3113                 {
3114                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3115                 al=SSL_AD_UNEXPECTED_MESSAGE;
3116                 goto f_err;
3117                 }
3118
3119         if (!(type & EVP_PKT_SIGN))
3120                 {
3121                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3122                 al=SSL_AD_ILLEGAL_PARAMETER;
3123                 goto f_err;
3124                 }
3125
3126         if (s->s3->change_cipher_spec)
3127                 {
3128                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3129                 al=SSL_AD_UNEXPECTED_MESSAGE;
3130                 goto f_err;
3131                 }
3132
3133         /* we now have a signature that we need to verify */
3134         p=(unsigned char *)s->init_msg;
3135         /* Check for broken implementations of GOST ciphersuites */
3136         /* If key is GOST and n is exactly 64, it is bare
3137          * signature without length field */
3138         if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3139                 pkey->type == NID_id_GostR3410_2001) )
3140                 {
3141                 i=64;
3142                 } 
3143         else 
3144                 {       
3145                 if (SSL_USE_SIGALGS(s))
3146                         {
3147                         int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3148                         if (rv == -1)
3149                                 {
3150                                 al = SSL_AD_INTERNAL_ERROR;
3151                                 goto f_err;
3152                                 }
3153                         else if (rv == 0)
3154                                 {
3155                                 al = SSL_AD_DECODE_ERROR;
3156                                 goto f_err;
3157                                 }
3158 #ifdef SSL_DEBUG
3159 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3160 #endif
3161                         p += 2;
3162                         n -= 2;
3163                         }
3164                 n2s(p,i);
3165                 n-=2;
3166                 if (i > n)
3167                         {
3168                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3169                         al=SSL_AD_DECODE_ERROR;
3170                         goto f_err;
3171                         }
3172         }
3173         j=EVP_PKEY_size(pkey);
3174         if ((i > j) || (n > j) || (n <= 0))
3175                 {
3176                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3177                 al=SSL_AD_DECODE_ERROR;
3178                 goto f_err;
3179                 }
3180
3181         if (SSL_USE_SIGALGS(s))
3182                 {
3183                 long hdatalen = 0;
3184                 void *hdata;
3185                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3186                 if (hdatalen <= 0)
3187                         {
3188                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3189                         al=SSL_AD_INTERNAL_ERROR;
3190                         goto f_err;
3191                         }
3192 #ifdef SSL_DEBUG
3193                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3194                                                         EVP_MD_name(md));
3195 #endif
3196                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3197                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3198                         {
3199                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3200                         al=SSL_AD_INTERNAL_ERROR;
3201                         goto f_err;
3202                         }
3203
3204                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3205                         {
3206                         al=SSL_AD_DECRYPT_ERROR;
3207                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3208                         goto f_err;
3209                         }
3210                 }
3211         else
3212 #ifndef OPENSSL_NO_RSA 
3213         if (pkey->type == EVP_PKEY_RSA)
3214                 {
3215                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3216                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3217                                                         pkey->pkey.rsa);
3218                 if (i < 0)
3219                         {
3220                         al=SSL_AD_DECRYPT_ERROR;
3221                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3222                         goto f_err;
3223                         }
3224                 if (i == 0)
3225                         {
3226                         al=SSL_AD_DECRYPT_ERROR;
3227                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3228                         goto f_err;
3229                         }
3230                 }
3231         else
3232 #endif
3233 #ifndef OPENSSL_NO_DSA
3234                 if (pkey->type == EVP_PKEY_DSA)
3235                 {
3236                 j=DSA_verify(pkey->save_type,
3237                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3238                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3239                 if (j <= 0)
3240                         {
3241                         /* bad signature */
3242                         al=SSL_AD_DECRYPT_ERROR;
3243                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3244                         goto f_err;
3245                         }
3246                 }
3247         else
3248 #endif
3249 #ifndef OPENSSL_NO_ECDSA
3250                 if (pkey->type == EVP_PKEY_EC)
3251                 {
3252                 j=ECDSA_verify(pkey->save_type,
3253                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3254                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3255                 if (j <= 0)
3256                         {
3257                         /* bad signature */
3258                         al=SSL_AD_DECRYPT_ERROR;
3259                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3260                             SSL_R_BAD_ECDSA_SIGNATURE);
3261                         goto f_err;
3262                         }
3263                 }
3264         else
3265 #endif
3266         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3267                 {   unsigned char signature[64];
3268                         int idx;
3269                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3270                         EVP_PKEY_verify_init(pctx);
3271                         if (i!=64) {
3272                                 fprintf(stderr,"GOST signature length is %d",i);
3273                         }       
3274                         for (idx=0;idx<64;idx++) {
3275                                 signature[63-idx]=p[idx];
3276                         }       
3277                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3278                         EVP_PKEY_CTX_free(pctx);
3279                         if (j<=0) 
3280                                 {
3281                                 al=SSL_AD_DECRYPT_ERROR;
3282                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3283                                         SSL_R_BAD_ECDSA_SIGNATURE);
3284                                 goto f_err;
3285                                 }       
3286                 }
3287         else    
3288                 {
3289                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3290                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3291                 goto f_err;
3292                 }
3293
3294
3295         ret=1;
3296         if (0)
3297                 {
3298 f_err:
3299                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3300                 }
3301 end:
3302         if (s->s3->handshake_buffer)
3303                 {
3304                 BIO_free(s->s3->handshake_buffer);
3305                 s->s3->handshake_buffer = NULL;
3306                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3307                 }
3308         EVP_MD_CTX_cleanup(&mctx);
3309         EVP_PKEY_free(pkey);
3310         return(ret);
3311         }
3312
3313 int ssl3_get_client_certificate(SSL *s)
3314         {
3315         int i,ok,al,ret= -1;
3316         X509 *x=NULL;
3317         unsigned long l,nc,llen,n;
3318         const unsigned char *p,*q;
3319         unsigned char *d;
3320         STACK_OF(X509) *sk=NULL;
3321
3322         n=s->method->ssl_get_message(s,
3323                 SSL3_ST_SR_CERT_A,
3324                 SSL3_ST_SR_CERT_B,
3325                 -1,
3326                 s->max_cert_list,
3327                 &ok);
3328
3329         if (!ok) return((int)n);
3330
3331         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3332                 {
3333                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3334                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3335                         {
3336                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3337                         al=SSL_AD_HANDSHAKE_FAILURE;
3338                         goto f_err;
3339                         }
3340                 /* If tls asked for a client cert, the client must return a 0 list */
3341                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3342                         {
3343                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3344                         al=SSL_AD_UNEXPECTED_MESSAGE;
3345                         goto f_err;
3346                         }
3347                 s->s3->tmp.reuse_message=1;
3348                 return(1);
3349                 }
3350
3351         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3352                 {
3353                 al=SSL_AD_UNEXPECTED_MESSAGE;
3354                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3355                 goto f_err;
3356                 }
3357         p=d=(unsigned char *)s->init_msg;
3358
3359         if ((sk=sk_X509_new_null()) == NULL)
3360                 {
3361                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3362                 goto err;
3363                 }
3364
3365         n2l3(p,llen);
3366         if (llen+3 != n)
3367                 {
3368                 al=SSL_AD_DECODE_ERROR;
3369                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3370                 goto f_err;
3371                 }
3372         for (nc=0; nc<llen; )
3373                 {
3374                 n2l3(p,l);
3375                 if ((l+nc+3) > llen)
3376                         {
3377                         al=SSL_AD_DECODE_ERROR;
3378                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3379                         goto f_err;
3380                         }
3381
3382                 q=p;
3383                 x=d2i_X509(NULL,&p,l);
3384                 if (x == NULL)
3385                         {
3386                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3387                         goto err;
3388                         }
3389                 if (p != (q+l))
3390                         {
3391                         al=SSL_AD_DECODE_ERROR;
3392                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3393                         goto f_err;
3394                         }
3395                 if (!sk_X509_push(sk,x))
3396                         {
3397                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3398                         goto err;
3399                         }
3400                 x=NULL;
3401                 nc+=l+3;
3402                 }
3403
3404         if (sk_X509_num(sk) <= 0)
3405                 {
3406                 /* TLS does not mind 0 certs returned */
3407                 if (s->version == SSL3_VERSION)
3408                         {
3409                         al=SSL_AD_HANDSHAKE_FAILURE;
3410                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3411                         goto f_err;
3412                         }
3413                 /* Fail for TLS only if we required a certificate */
3414                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3415                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3416                         {
3417                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3418                         al=SSL_AD_HANDSHAKE_FAILURE;
3419                         goto f_err;
3420                         }
3421                 /* No client certificate so digest cached records */
3422                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3423                         {
3424                         al=SSL_AD_INTERNAL_ERROR;
3425                         goto f_err;
3426                         }
3427                 }
3428         else
3429                 {
3430                 EVP_PKEY *pkey;
3431                 i=ssl_verify_cert_chain(s,sk);
3432                 if (i <= 0)
3433                         {
3434                         al=ssl_verify_alarm_type(s->verify_result);
3435                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3436                         goto f_err;
3437                         }
3438                 if (i > 1)
3439                         {
3440                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3441                         al = SSL_AD_HANDSHAKE_FAILURE;
3442                         goto f_err;
3443                         }
3444                 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3445                 if (pkey == NULL)
3446                         {
3447                         al=SSL3_AD_HANDSHAKE_FAILURE;
3448                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3449                                                 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3450                         goto f_err;
3451                         }
3452                 EVP_PKEY_free(pkey);
3453                 }
3454
3455         if (s->session->peer != NULL) /* This should not be needed */
3456                 X509_free(s->session->peer);
3457         s->session->peer=sk_X509_shift(sk);
3458         s->session->verify_result = s->verify_result;
3459
3460         /* With the current implementation, sess_cert will always be NULL
3461          * when we arrive here. */
3462         if (s->session->sess_cert == NULL)
3463                 {
3464                 s->session->sess_cert = ssl_sess_cert_new();
3465                 if (s->session->sess_cert == NULL)
3466                         {
3467                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3468                         goto err;
3469                         }
3470                 }
3471         if (s->session->sess_cert->cert_chain != NULL)
3472                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3473         s->session->sess_cert->cert_chain=sk;
3474         /* Inconsistency alert: cert_chain does *not* include the
3475          * peer's own certificate, while we do include it in s3_clnt.c */
3476
3477         sk=NULL;
3478
3479         ret=1;
3480         if (0)
3481                 {
3482 f_err:
3483                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3484                 }
3485 err:
3486         if (x != NULL) X509_free(x);
3487         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3488         return(ret);
3489         }
3490
3491 int ssl3_send_server_certificate(SSL *s)
3492         {
3493         CERT_PKEY *cpk;
3494
3495         if (s->state == SSL3_ST_SW_CERT_A)
3496                 {
3497                 cpk=ssl_get_server_send_pkey(s);
3498                 if (cpk == NULL)
3499                         {
3500                         /* VRS: allow null cert if auth == KRB5 */
3501                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3502                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3503                                 {
3504                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3505                                 return(0);
3506                                 }
3507                         }
3508
3509                 if (!ssl3_output_cert_chain(s,cpk))
3510                         {
3511                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3512                         return(0);
3513                         }
3514                 s->state=SSL3_ST_SW_CERT_B;
3515                 }
3516
3517         /* SSL3_ST_SW_CERT_B */
3518         return ssl_do_write(s);
3519         }
3520
3521 #ifndef OPENSSL_NO_TLSEXT
3522 /* send a new session ticket (not necessarily for a new session) */
3523 int ssl3_send_newsession_ticket(SSL *s)
3524         {
3525         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3526                 {
3527                 unsigned char *p, *senc, *macstart;
3528                 const unsigned char *const_p;
3529                 int len, slen_full, slen;
3530                 SSL_SESSION *sess;
3531                 unsigned int hlen;
3532                 EVP_CIPHER_CTX ctx;
3533                 HMAC_CTX hctx;
3534                 SSL_CTX *tctx = s->initial_ctx;
3535                 unsigned char iv[EVP_MAX_IV_LENGTH];
3536                 unsigned char key_name[16];
3537
3538                 /* get session encoding length */
3539                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3540                 /* Some length values are 16 bits, so forget it if session is
3541                  * too long
3542                  */
3543                 if (slen_full > 0xFF00)
3544                         return -1;
3545                 senc = OPENSSL_malloc(slen_full);
3546                 if (!senc)
3547                         return -1;
3548                 p = senc;
3549                 i2d_SSL_SESSION(s->session, &p);
3550
3551                 /* create a fresh copy (not shared with other threads) to clean up */
3552                 const_p = senc;
3553                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3554                 if (sess == NULL)
3555                         {
3556                         OPENSSL_free(senc);
3557                         return -1;
3558                         }
3559                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3560
3561                 slen = i2d_SSL_SESSION(sess, NULL);
3562                 if (slen > slen_full) /* shouldn't ever happen */
3563                         {
3564                         OPENSSL_free(senc);
3565                         return -1;
3566                         }
3567                 p = senc;
3568                 i2d_SSL_SESSION(sess, &p);
3569                 SSL_SESSION_free(sess);
3570
3571                 /* Grow buffer if need be: the length calculation is as
3572                  * follows handshake_header_length +
3573                  * 4 (ticket lifetime hint) + 2 (ticket length) +
3574                  * 16 (key name) + max_iv_len (iv length) +
3575                  * session_length + max_enc_block_size (max encrypted session
3576                  * length) + max_md_size (HMAC).
3577                  */
3578                 if (!BUF_MEM_grow(s->init_buf,
3579                         SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3580                         EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3581                         return -1;
3582                 p = ssl_handshake_start(s);
3583                 EVP_CIPHER_CTX_init(&ctx);
3584                 HMAC_CTX_init(&hctx);
3585                 /* Initialize HMAC and cipher contexts. If callback present
3586                  * it does all the work otherwise use generated values
3587                  * from parent ctx.
3588                  */
3589                 if (tctx->tlsext_ticket_key_cb)
3590                         {
3591                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3592                                                          &hctx, 1) < 0)
3593                                 {
3594                                 OPENSSL_free(senc);
3595                                 return -1;
3596                                 }
3597                         }
3598                 else
3599                         {
3600                         RAND_pseudo_bytes(iv, 16);
3601                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3602                                         tctx->tlsext_tick_aes_key, iv);
3603                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3604                                         tlsext_tick_md(), NULL);
3605                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3606                         }
3607
3608                 /* Ticket lifetime hint (advisory only):
3609                  * We leave this unspecified for resumed session (for simplicity),
3610                  * and guess that tickets for new sessions will live as long
3611                  * as their sessions. */
3612                 l2n(s->hit ? 0 : s->session->timeout, p);
3613
3614                 /* Skip ticket length for now */
3615                 p += 2;
3616                 /* Output key name */
3617                 macstart = p;
3618                 memcpy(p, key_name, 16);
3619                 p += 16;
3620                 /* output IV */
3621                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3622                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3623                 /* Encrypt session data */
3624                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3625                 p += len;
3626                 EVP_EncryptFinal(&ctx, p, &len);
3627                 p += len;
3628                 EVP_CIPHER_CTX_cleanup(&ctx);
3629
3630                 HMAC_Update(&hctx, macstart, p - macstart);
3631                 HMAC_Final(&hctx, p, &hlen);
3632                 HMAC_CTX_cleanup(&hctx);
3633
3634                 p += hlen;
3635                 /* Now write out lengths: p points to end of data written */
3636                 /* Total length */
3637                 len = p - ssl_handshake_start(s);
3638                 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3639                 /* Skip ticket lifetime hint */
3640                 p = ssl_handshake_start(s) + 4;
3641                 s2n(len - 6, p);
3642                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3643                 OPENSSL_free(senc);
3644                 }
3645
3646         /* SSL3_ST_SW_SESSION_TICKET_B */
3647         return ssl_do_write(s);
3648         }
3649
3650 int ssl3_send_cert_status(SSL *s)
3651         {
3652         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3653                 {
3654                 unsigned char *p;
3655                 /* Grow buffer if need be: the length calculation is as
3656                  * follows 1 (message type) + 3 (message length) +
3657                  * 1 (ocsp response type) + 3 (ocsp response length)
3658                  * + (ocsp response)
3659                  */
3660                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3661                         return -1;
3662
3663                 p=(unsigned char *)s->init_buf->data;
3664
3665                 /* do the header */
3666                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3667                 /* message length */
3668                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3669                 /* status type */
3670                 *(p++)= s->tlsext_status_type;
3671                 /* length of OCSP response */
3672                 l2n3(s->tlsext_ocsp_resplen, p);
3673                 /* actual response */
3674                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3675                 /* number of bytes to write */
3676                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3677                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3678                 s->init_off = 0;
3679                 }
3680
3681         /* SSL3_ST_SW_CERT_STATUS_B */
3682         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3683         }
3684
3685 # ifndef OPENSSL_NO_NEXTPROTONEG
3686 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3687  * sets the next_proto member in s if found */
3688 int ssl3_get_next_proto(SSL *s)
3689         {
3690         int ok;
3691         int proto_len, padding_len;
3692         long n;
3693         const unsigned char *p;
3694
3695         /* Clients cannot send a NextProtocol message if we didn't see the
3696          * extension in their ClientHello */
3697         if (!s->s3->next_proto_neg_seen)
3698                 {
3699                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3700                 return -1;
3701                 }
3702
3703         n=s->method->ssl_get_message(s,
3704                 SSL3_ST_SR_NEXT_PROTO_A,
3705                 SSL3_ST_SR_NEXT_PROTO_B,
3706                 SSL3_MT_NEXT_PROTO,
3707                 514,  /* See the payload format below */
3708                 &ok);
3709
3710         if (!ok)
3711                 return((int)n);
3712
3713         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3714          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3715          * by ssl3_get_finished). */
3716         if (!s->s3->change_cipher_spec)
3717                 {
3718                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3719                 return -1;
3720                 }
3721
3722         if (n < 2)
3723                 return 0;  /* The body must be > 1 bytes long */
3724
3725         p=(unsigned char *)s->init_msg;
3726
3727         /* The payload looks like:
3728          *   uint8 proto_len;
3729          *   uint8 proto[proto_len];
3730          *   uint8 padding_len;
3731          *   uint8 padding[padding_len];
3732          */
3733         proto_len = p[0];
3734         if (proto_len + 2 > s->init_num)
3735                 return 0;
3736         padding_len = p[proto_len + 1];
3737         if (proto_len + padding_len + 2 != s->init_num)
3738                 return 0;
3739
3740         s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3741         if (!s->next_proto_negotiated)
3742                 {
3743                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3744                 return 0;
3745                 }
3746         memcpy(s->next_proto_negotiated, p + 1, proto_len);
3747         s->next_proto_negotiated_len = proto_len;
3748
3749         return 1;
3750         }
3751 # endif
3752
3753 int tls1_send_server_supplemental_data(SSL *s, int *skip)
3754         {
3755         int al = 0;
3756         if (s->ctx->srv_supp_data_records_count)
3757                 {
3758                 unsigned char *p = NULL;
3759                 unsigned char *size_loc = NULL;
3760                 srv_supp_data_record *record = NULL;
3761                 size_t length = 0;
3762                 size_t i = 0;
3763
3764                 for (i = 0; i < s->ctx->srv_supp_data_records_count; i++)
3765                         {
3766                         const unsigned char *out = NULL;
3767                         unsigned short outlen = 0;
3768                         int cb_retval = 0;
3769                         record = &s->ctx->srv_supp_data_records[i];
3770
3771                         /* NULL callback or -1 omits supp data entry */
3772                         if (!record->fn1)
3773                                 continue;
3774                         cb_retval = record->fn1(s, record->supp_data_type,
3775                                                 &out, &outlen, &al, record->arg);
3776                         if (cb_retval == -1)
3777                                 continue; /* skip this supp data entry */
3778                         if (cb_retval == 0)
3779                                 {
3780                                 SSLerr(SSL_F_TLS1_SEND_SERVER_SUPPLEMENTAL_DATA,ERR_R_BUF_LIB);
3781                                 goto f_err;
3782                                 }
3783                         if (outlen == 0 || TLSEXT_MAXLEN_supplemental_data < outlen + 4 + length)
3784                                 {
3785                                 SSLerr(SSL_F_TLS1_SEND_SERVER_SUPPLEMENTAL_DATA,ERR_R_BUF_LIB);
3786                                 return 0;
3787                                 }
3788                         /* write supp data entry...
3789                          * if first entry, write handshake message type
3790                          * jump back to write length at end */
3791                         if (length == 0)
3792                                 {
3793                                 /* 1 byte message type + 3 bytes for
3794                                  * message length */
3795                                 if (!BUF_MEM_grow_clean(s->init_buf, 4))
3796                                         {
3797                                         SSLerr(SSL_F_TLS1_SEND_SERVER_SUPPLEMENTAL_DATA,ERR_R_BUF_LIB);
3798                                         return 0;
3799                                         }
3800                                 p = (unsigned char *)s->init_buf->data;
3801                                 *(p++) = SSL3_MT_SUPPLEMENTAL_DATA;
3802                                 /* hold on to length field to update later */
3803                                 size_loc = p;
3804                                 /* skip over handshake length field (3
3805                                  * bytes) and supp_data length field
3806                                  * (3 bytes) */
3807                                 p += 3 + 3;
3808                                 length += 1 +3 +3;
3809                                 }
3810                         /* 2 byte supp data type + 2 byte length + outlen */
3811                         if (!BUF_MEM_grow(s->init_buf, outlen + 4))
3812                                 {
3813                                 SSLerr(SSL_F_TLS1_SEND_SERVER_SUPPLEMENTAL_DATA,ERR_R_BUF_LIB);
3814                                 return 0;
3815                                 }
3816                         s2n(record->supp_data_type, p);
3817                         s2n(outlen, p);
3818                         memcpy(p, out, outlen);
3819                         /* update length to supp data type (2 bytes) +
3820                          * supp data length (2 bytes) + supp data */
3821                         length += (outlen + 4);
3822                         p += outlen;
3823                         }
3824                 if (length > 0)
3825                         {
3826                         /* write handshake length */
3827                         l2n3(length - 4, size_loc);
3828                         /* supp_data length */
3829                         l2n3(length - 7, size_loc);
3830                         s->state = SSL3_ST_SW_SUPPLEMENTAL_DATA_B;
3831                         s->init_num = length;
3832                         s->init_off = 0;
3833
3834                         return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3835                         }
3836                 }
3837
3838         /* no supp data message sent */
3839         *skip = 1;
3840         s->init_num = 0;
3841         s->init_off = 0;
3842         return 1;
3843 f_err:
3844         ssl3_send_alert(s,SSL3_AL_FATAL,al);
3845         return 0;
3846         }
3847
3848 int tls1_get_client_supplemental_data(SSL *s)
3849         {
3850         int al = 0;
3851         int cb_retval = 0;
3852         int ok;
3853         long n;
3854         const unsigned char *p, *d;
3855         unsigned short supp_data_entry_type = 0;
3856         unsigned short supp_data_entry_len = 0;
3857         unsigned long supp_data_len = 0;
3858         size_t i = 0;
3859
3860         n=s->method->ssl_get_message(s,
3861                                      SSL3_ST_SR_SUPPLEMENTAL_DATA_A,
3862                                      SSL3_ST_SR_SUPPLEMENTAL_DATA_B,
3863                                      SSL3_MT_SUPPLEMENTAL_DATA,
3864                                      /* use default limit */
3865                                      TLSEXT_MAXLEN_supplemental_data,
3866                                      &ok);
3867
3868         if (!ok) return((int)n);
3869
3870         p = (unsigned char *)s->init_msg;
3871         d = p;
3872
3873         /* The message cannot be empty */
3874         if (n < 3)
3875                 {
3876                 al = SSL_AD_DECODE_ERROR;
3877                 SSLerr(SSL_F_TLS1_GET_CLIENT_SUPPLEMENTAL_DATA,SSL_R_LENGTH_MISMATCH);
3878                 goto f_err;
3879                 }
3880         n2l3(p, supp_data_len);
3881         while (p<d+supp_data_len)
3882                 {
3883                 n2s(p, supp_data_entry_type);
3884                 n2s(p, supp_data_entry_len);
3885                 /* if there is a callback for this supp data type, send it */
3886                 for (i=0; i < s->ctx->srv_supp_data_records_count; i++)
3887                         {
3888                         if (s->ctx->srv_supp_data_records[i].supp_data_type == supp_data_entry_type && s->ctx->srv_supp_data_records[i].fn2)
3889                                 {
3890                                 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);
3891                                 if (cb_retval == 0)
3892                                         {
3893                                         SSLerr(SSL_F_TLS1_GET_CLIENT_SUPPLEMENTAL_DATA, ERR_R_SSL_LIB);
3894                                         goto f_err;
3895                                         }
3896                                 }
3897                         }
3898                 p+=supp_data_entry_len;
3899                 }
3900         return 1;
3901 f_err:
3902         ssl3_send_alert(s,SSL3_AL_FATAL,al);
3903         return -1;
3904         }
3905 #endif