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