mark all block comments that need format preserving so that
[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 &= ~SSL3_FLAGS_SGC_RESTART_DONE;
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                         if (s->rwstate != SSL_X509_LOOKUP)
363                         {
364                                 ret=ssl3_get_client_hello(s);
365                                 if (ret <= 0) goto end;
366                         }
367 #ifndef OPENSSL_NO_SRP
368                         {
369                         int al;
370                         if ((ret = ssl_check_srp_ext_ClientHello(s,&al))  < 0)
371                                         {
372                                         /* callback indicates firther work to be done */
373                                         s->rwstate=SSL_X509_LOOKUP;
374                                         goto end;
375                                         }
376                         if (ret != SSL_ERROR_NONE)
377                                 {
378                                 ssl3_send_alert(s,SSL3_AL_FATAL,al);    
379                                 /* This is not really an error but the only means to
380                                    for a client to detect whether srp is supported. */
381                                    if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)      
382                                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);                     
383                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;                       
384                                 ret= -1;
385                                 goto end;       
386                                 }
387                         }
388 #endif          
389                         
390                         s->renegotiate = 2;
391                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
392                         s->init_num=0;
393                         break;
394
395                 case SSL3_ST_SW_SRVR_HELLO_A:
396                 case SSL3_ST_SW_SRVR_HELLO_B:
397                         ret=ssl3_send_server_hello(s);
398                         if (ret <= 0) goto end;
399 #ifndef OPENSSL_NO_TLSEXT
400                         if (s->hit)
401                                 {
402                                 if (s->tlsext_ticket_expected)
403                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
404                                 else
405                                         s->state=SSL3_ST_SW_CHANGE_A;
406                                 }
407 #else
408                         if (s->hit)
409                                         s->state=SSL3_ST_SW_CHANGE_A;
410 #endif
411                         else
412                                 s->state=SSL3_ST_SW_CERT_A;
413                         s->init_num=0;
414                         break;
415
416                 case SSL3_ST_SW_CERT_A:
417                 case SSL3_ST_SW_CERT_B:
418                         /* Check if it is anon DH or anon ECDH, */
419                         /* normal PSK or KRB5 or SRP */
420                         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
421                                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
422                                 {
423                                 ret=ssl3_send_server_certificate(s);
424                                 if (ret <= 0) goto end;
425 #ifndef OPENSSL_NO_TLSEXT
426                                 if (s->tlsext_status_expected)
427                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
428                                 else
429                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
430                                 }
431                         else
432                                 {
433                                 skip = 1;
434                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
435                                 }
436 #else
437                                 }
438                         else
439                                 skip=1;
440
441                         s->state=SSL3_ST_SW_KEY_EXCH_A;
442 #endif
443                         s->init_num=0;
444                         break;
445
446                 case SSL3_ST_SW_KEY_EXCH_A:
447                 case SSL3_ST_SW_KEY_EXCH_B:
448                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
449
450                         /*
451                          * clear this, it may get reset by
452                          * send_server_key_exchange
453                          */
454                         s->s3->tmp.use_rsa_tmp=0;
455
456
457                         /* only send if a DH key exchange, fortezza or
458                          * RSA but we have a sign only certificate
459                          *
460                          * PSK: may send PSK identity hints
461                          *
462                          * For ECC ciphersuites, we send a serverKeyExchange
463                          * message only if the cipher suite is either
464                          * ECDH-anon or ECDHE. In other cases, the
465                          * server certificate contains the server's
466                          * public key for key exchange.
467                          */
468                         if (0
469                         /* PSK: send ServerKeyExchange if PSK identity
470                          * hint if provided */
471 #ifndef OPENSSL_NO_PSK
472                             || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
473 #endif
474 #ifndef OPENSSL_NO_SRP
475                             /* SRP: send ServerKeyExchange */
476                             || (alg_k & SSL_kSRP)
477 #endif
478                             || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
479                             || (alg_k & SSL_kEECDH)
480                             || ((alg_k & SSL_kRSA)
481                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
482                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
483                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
484                                         )
485                                     )
486                                 )
487                             )
488                                 {
489                                 ret=ssl3_send_server_key_exchange(s);
490                                 if (ret <= 0) goto end;
491                                 }
492                         else
493                                 skip=1;
494
495                         s->state=SSL3_ST_SW_CERT_REQ_A;
496                         s->init_num=0;
497                         break;
498
499                 case SSL3_ST_SW_CERT_REQ_A:
500                 case SSL3_ST_SW_CERT_REQ_B:
501                         if (/* don't request cert unless asked for it: */
502                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
503                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
504                                  * don't request cert during re-negotiation: */
505                                 ((s->session->peer != NULL) &&
506                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
507                                 /* never request cert in anonymous ciphersuites
508                                  * (see section "Certificate request" in SSL 3 drafts
509                                  * and in RFC 2246): */
510                                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
511                                  /* ... except when the application insists on verification
512                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
513                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
514                                  /* never request cert in Kerberos ciphersuites */
515                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
516                                 /* don't request certificate for SRP auth */
517                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
518                                 /* With normal PSK Certificates and
519                                  * Certificate Requests are omitted */
520                                 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
521                                 {
522                                 /* no cert request */
523                                 skip=1;
524                                 s->s3->tmp.cert_request=0;
525                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
526                                 if (s->s3->handshake_buffer)
527                                         if (!ssl3_digest_cached_records(s))
528                                                 return -1;
529                                 }
530                         else
531                                 {
532                                 s->s3->tmp.cert_request=1;
533                                 ret=ssl3_send_certificate_request(s);
534                                 if (ret <= 0) goto end;
535 #ifndef NETSCAPE_HANG_BUG
536                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
537 #else
538                                 s->state=SSL3_ST_SW_FLUSH;
539                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
540 #endif
541                                 s->init_num=0;
542                                 }
543                         break;
544
545                 case SSL3_ST_SW_SRVR_DONE_A:
546                 case SSL3_ST_SW_SRVR_DONE_B:
547                         ret=ssl3_send_server_done(s);
548                         if (ret <= 0) goto end;
549                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
550                         s->state=SSL3_ST_SW_FLUSH;
551                         s->init_num=0;
552                         break;
553                 
554                 case SSL3_ST_SW_FLUSH:
555
556                         /* This code originally checked to see if
557                          * any data was pending using BIO_CTRL_INFO
558                          * and then flushed. This caused problems
559                          * as documented in PR#1939. The proposed
560                          * fix doesn't completely resolve this issue
561                          * as buggy implementations of BIO_CTRL_PENDING
562                          * still exist. So instead we just flush
563                          * unconditionally.
564                          */
565
566                         s->rwstate=SSL_WRITING;
567                         if (BIO_flush(s->wbio) <= 0)
568                                 {
569                                 ret= -1;
570                                 goto end;
571                                 }
572                         s->rwstate=SSL_NOTHING;
573
574                         s->state=s->s3->tmp.next_state;
575                         break;
576
577                 case SSL3_ST_SR_CERT_A:
578                 case SSL3_ST_SR_CERT_B:
579                         /* Check for second client hello (MS SGC) */
580                         ret = ssl3_check_client_hello(s);
581                         if (ret <= 0)
582                                 goto end;
583                         if (ret == 2)
584                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
585                         else {
586                                 if (s->s3->tmp.cert_request)
587                                         {
588                                         ret=ssl3_get_client_certificate(s);
589                                         if (ret <= 0) goto end;
590                                         }
591                                 s->init_num=0;
592                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
593                         }
594                         break;
595
596                 case SSL3_ST_SR_KEY_EXCH_A:
597                 case SSL3_ST_SR_KEY_EXCH_B:
598                         ret=ssl3_get_client_key_exchange(s);
599                         if (ret <= 0)
600                                 goto end;
601                         if (ret == 2)
602                                 {
603                                 /* For the ECDH ciphersuites when
604                                  * the client sends its ECDH pub key in
605                                  * a certificate, the CertificateVerify
606                                  * message is not sent.
607                                  * Also for GOST ciphersuites when
608                                  * the client uses its key from the certificate
609                                  * for key exchange.
610                                  */
611 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
612                                 s->state=SSL3_ST_SR_FINISHED_A;
613 #else
614                                 if (s->s3->next_proto_neg_seen)
615                                         s->state=SSL3_ST_SR_NEXT_PROTO_A;
616                                 else
617                                         s->state=SSL3_ST_SR_FINISHED_A;
618 #endif
619                                 s->init_num = 0;
620                                 }
621                         else if (TLS1_get_version(s) >= TLS1_2_VERSION)
622                                 {
623                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
624                                 s->init_num=0;
625                                 if (!s->session->peer)
626                                         break;
627                                 /* For TLS v1.2 freeze the handshake buffer
628                                  * at this point and digest cached records.
629                                  */
630                                 if (!s->s3->handshake_buffer)
631                                         {
632                                         SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
633                                         return -1;
634                                         }
635                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
636                                 if (!ssl3_digest_cached_records(s))
637                                         return -1;
638                                 }
639                         else
640                                 {
641                                 int offset=0;
642                                 int dgst_num;
643
644                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
645                                 s->init_num=0;
646
647                                 /* We need to get hashes here so if there is
648                                  * a client cert, it can be verified
649                                  * FIXME - digest processing for CertificateVerify
650                                  * should be generalized. But it is next step
651                                  */
652                                 if (s->s3->handshake_buffer)
653                                         if (!ssl3_digest_cached_records(s))
654                                                 return -1;
655                                 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
656                                         if (s->s3->handshake_dgst[dgst_num]) 
657                                                 {
658                                                 int dgst_size;
659
660                                                 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]));
661                                                 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
662                                                 if (dgst_size < 0)
663                                                         {
664                                                         ret = -1;
665                                                         goto end;
666                                                         }
667                                                 offset+=dgst_size;
668                                                 }               
669                                 }
670                         break;
671
672                 case SSL3_ST_SR_CERT_VRFY_A:
673                 case SSL3_ST_SR_CERT_VRFY_B:
674                         /*
675                          * This *should* be the first time we enable CCS, but be
676                          * extra careful about surrounding code changes. We need
677                          * to set this here because we don't know if we're
678                          * expecting a CertificateVerify or not.
679                          */
680                         if (!s->s3->change_cipher_spec)
681                                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
682                         /* we should decide if we expected this one */
683                         ret=ssl3_get_cert_verify(s);
684                         if (ret <= 0) goto end;
685
686 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
687                         s->state=SSL3_ST_SR_FINISHED_A;
688 #else
689                         if (s->s3->next_proto_neg_seen)
690                                 s->state=SSL3_ST_SR_NEXT_PROTO_A;
691                         else
692                                 s->state=SSL3_ST_SR_FINISHED_A;
693 #endif
694                         s->init_num=0;
695                         break;
696
697 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
698                 case SSL3_ST_SR_NEXT_PROTO_A:
699                 case SSL3_ST_SR_NEXT_PROTO_B:
700                         /*
701                          * Enable CCS for resumed handshakes with NPN.
702                          * In a full handshake with NPN, we end up here through
703                          * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
704                          * already set. Receiving a CCS clears the flag, so make
705                          * sure not to re-enable it to ban duplicates.
706                          * s->s3->change_cipher_spec is set when a CCS is
707                          * processed in s3_pkt.c, and remains set until
708                          * the client's Finished message is read.
709                          */
710                         if (!s->s3->change_cipher_spec)
711                                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
712
713                         ret=ssl3_get_next_proto(s);
714                         if (ret <= 0) goto end;
715                         s->init_num = 0;
716                         s->state=SSL3_ST_SR_FINISHED_A;
717                         break;
718 #endif
719
720                 case SSL3_ST_SR_FINISHED_A:
721                 case SSL3_ST_SR_FINISHED_B:
722                         /*
723                          * Enable CCS for resumed handshakes without NPN.
724                          * In a full handshake, we end up here through
725                          * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
726                          * already set. Receiving a CCS clears the flag, so make
727                          * sure not to re-enable it to ban duplicates.
728                          * s->s3->change_cipher_spec is set when a CCS is
729                          * processed in s3_pkt.c, and remains set until
730                          * the client's Finished message is read.
731                          */
732                         if (!s->s3->change_cipher_spec)
733                                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
734                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
735                                 SSL3_ST_SR_FINISHED_B);
736                         if (ret <= 0) goto end;
737                         if (s->hit)
738                                 s->state=SSL_ST_OK;
739 #ifndef OPENSSL_NO_TLSEXT
740                         else if (s->tlsext_ticket_expected)
741                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
742 #endif
743                         else
744                                 s->state=SSL3_ST_SW_CHANGE_A;
745                         s->init_num=0;
746                         break;
747
748 #ifndef OPENSSL_NO_TLSEXT
749                 case SSL3_ST_SW_SESSION_TICKET_A:
750                 case SSL3_ST_SW_SESSION_TICKET_B:
751                         ret=ssl3_send_newsession_ticket(s);
752                         if (ret <= 0) goto end;
753                         s->state=SSL3_ST_SW_CHANGE_A;
754                         s->init_num=0;
755                         break;
756
757                 case SSL3_ST_SW_CERT_STATUS_A:
758                 case SSL3_ST_SW_CERT_STATUS_B:
759                         ret=ssl3_send_cert_status(s);
760                         if (ret <= 0) goto end;
761                         s->state=SSL3_ST_SW_KEY_EXCH_A;
762                         s->init_num=0;
763                         break;
764
765 #endif
766
767                 case SSL3_ST_SW_CHANGE_A:
768                 case SSL3_ST_SW_CHANGE_B:
769
770                         s->session->cipher=s->s3->tmp.new_cipher;
771                         if (!s->method->ssl3_enc->setup_key_block(s))
772                                 { ret= -1; goto end; }
773
774                         ret=ssl3_send_change_cipher_spec(s,
775                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
776
777                         if (ret <= 0) goto end;
778                         s->state=SSL3_ST_SW_FINISHED_A;
779                         s->init_num=0;
780
781                         if (!s->method->ssl3_enc->change_cipher_state(s,
782                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
783                                 {
784                                 ret= -1;
785                                 goto end;
786                                 }
787
788                         break;
789
790                 case SSL3_ST_SW_FINISHED_A:
791                 case SSL3_ST_SW_FINISHED_B:
792                         ret=ssl3_send_finished(s,
793                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
794                                 s->method->ssl3_enc->server_finished_label,
795                                 s->method->ssl3_enc->server_finished_label_len);
796                         if (ret <= 0) goto end;
797                         s->state=SSL3_ST_SW_FLUSH;
798                         if (s->hit)
799                                 {
800 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
801                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
802 #else
803                                 if (s->s3->next_proto_neg_seen)
804                                         {
805                                         s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
806                                         }
807                                 else
808                                         s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
809 #endif
810                                 }
811                         else
812                                 s->s3->tmp.next_state=SSL_ST_OK;
813                         s->init_num=0;
814                         break;
815
816                 case SSL_ST_OK:
817                         /* clean a few things up */
818                         ssl3_cleanup_key_block(s);
819
820                         BUF_MEM_free(s->init_buf);
821                         s->init_buf=NULL;
822
823                         /* remove buffering on output */
824                         ssl_free_wbio_buffer(s);
825
826                         s->init_num=0;
827
828                         if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
829                                 {
830                                 s->renegotiate=0;
831                                 s->new_session=0;
832                                 
833                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
834                                 
835                                 s->ctx->stats.sess_accept_good++;
836                                 /* s->server=1; */
837                                 s->handshake_func=ssl3_accept;
838
839                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
840                                 }
841                         
842                         ret = 1;
843                         goto end;
844                         /* break; */
845
846                 default:
847                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
848                         ret= -1;
849                         goto end;
850                         /* break; */
851                         }
852                 
853                 if (!s->s3->tmp.reuse_message && !skip)
854                         {
855                         if (s->debug)
856                                 {
857                                 if ((ret=BIO_flush(s->wbio)) <= 0)
858                                         goto end;
859                                 }
860
861
862                         if ((cb != NULL) && (s->state != state))
863                                 {
864                                 new_state=s->state;
865                                 s->state=state;
866                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
867                                 s->state=new_state;
868                                 }
869                         }
870                 skip=0;
871                 }
872 end:
873         /* BIO_flush(s->wbio); */
874
875         s->in_handshake--;
876         if (cb != NULL)
877                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
878         return(ret);
879         }
880
881 int ssl3_send_hello_request(SSL *s)
882         {
883         unsigned char *p;
884
885         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
886                 {
887                 p=(unsigned char *)s->init_buf->data;
888                 *(p++)=SSL3_MT_HELLO_REQUEST;
889                 *(p++)=0;
890                 *(p++)=0;
891                 *(p++)=0;
892
893                 s->state=SSL3_ST_SW_HELLO_REQ_B;
894                 /* number of bytes to write */
895                 s->init_num=4;
896                 s->init_off=0;
897                 }
898
899         /* SSL3_ST_SW_HELLO_REQ_B */
900         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
901         }
902
903 int ssl3_check_client_hello(SSL *s)
904         {
905         int ok;
906         long n;
907
908         /* this function is called when we really expect a Certificate message,
909          * so permit appropriate message length */
910         n=s->method->ssl_get_message(s,
911                 SSL3_ST_SR_CERT_A,
912                 SSL3_ST_SR_CERT_B,
913                 -1,
914                 s->max_cert_list,
915                 &ok);
916         if (!ok) return((int)n);
917         s->s3->tmp.reuse_message = 1;
918         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
919                 {
920                 /* We only allow the client to restart the handshake once per
921                  * negotiation. */
922                 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
923                         {
924                         SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
925                         return -1;
926                         }
927                 /* Throw away what we have done so far in the current handshake,
928                  * which will now be aborted. (A full SSL_clear would be too much.) */
929 #ifndef OPENSSL_NO_DH
930                 if (s->s3->tmp.dh != NULL)
931                         {
932                         DH_free(s->s3->tmp.dh);
933                         s->s3->tmp.dh = NULL;
934                         }
935 #endif
936 #ifndef OPENSSL_NO_ECDH
937                 if (s->s3->tmp.ecdh != NULL)
938                         {
939                         EC_KEY_free(s->s3->tmp.ecdh);
940                         s->s3->tmp.ecdh = NULL;
941                         }
942 #endif
943                 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
944                 return 2;
945                 }
946         return 1;
947 }
948
949 int ssl3_get_client_hello(SSL *s)
950         {
951         int i,j,ok,al,ret= -1;
952         unsigned int cookie_len;
953         long n;
954         unsigned long id;
955         unsigned char *p,*d,*q;
956         SSL_CIPHER *c;
957 #ifndef OPENSSL_NO_COMP
958         SSL_COMP *comp=NULL;
959 #endif
960         STACK_OF(SSL_CIPHER) *ciphers=NULL;
961
962         /* We do this so that we will respond with our native type.
963          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
964          * This down switching should be handled by a different method.
965          * If we are SSLv3, we will respond with SSLv3, even if prompted with
966          * TLSv1.
967          */
968         if (s->state == SSL3_ST_SR_CLNT_HELLO_A
969                 )
970                 {
971                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
972                 }
973         s->first_packet=1;
974         n=s->method->ssl_get_message(s,
975                 SSL3_ST_SR_CLNT_HELLO_B,
976                 SSL3_ST_SR_CLNT_HELLO_C,
977                 SSL3_MT_CLIENT_HELLO,
978                 SSL3_RT_MAX_PLAIN_LENGTH,
979                 &ok);
980
981         if (!ok) return((int)n);
982         s->first_packet=0;
983         d=p=(unsigned char *)s->init_msg;
984
985         /* use version from inside client hello, not from record header
986          * (may differ: see RFC 2246, Appendix E, second paragraph) */
987         s->client_version=(((int)p[0])<<8)|(int)p[1];
988         p+=2;
989
990         if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
991             (s->version != DTLS1_VERSION && s->client_version < s->version))
992                 {
993                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
994                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR && 
995                         !s->enc_write_ctx && !s->write_hash)
996                         {
997                         /* similar to ssl3_get_record, send alert using remote version number */
998                         s->version = s->client_version;
999                         }
1000                 al = SSL_AD_PROTOCOL_VERSION;
1001                 goto f_err;
1002                 }
1003
1004         /* If we require cookies and this ClientHello doesn't
1005          * contain one, just return since we do not want to
1006          * allocate any memory yet. So check cookie length...
1007          */
1008         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1009                 {
1010                 unsigned int session_length, cookie_length;
1011                 
1012                 session_length = *(p + SSL3_RANDOM_SIZE);
1013                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1014
1015                 if (cookie_length == 0)
1016                         return 1;
1017                 }
1018
1019         /* load the client random */
1020         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1021         p+=SSL3_RANDOM_SIZE;
1022
1023         /* get the session-id */
1024         j= *(p++);
1025
1026         s->hit=0;
1027         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1028          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1029          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1030          * than a change to default behavior so that applications relying on this for security
1031          * won't even compile against older library versions).
1032          *
1033          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1034          * renegotiation but not a new session (s->new_session remains unset): for servers,
1035          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1036          * setting will be ignored.
1037          */
1038         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1039                 {
1040                 if (!ssl_get_new_session(s,1))
1041                         goto err;
1042                 }
1043         else
1044                 {
1045                 i=ssl_get_prev_session(s, p, j, d + n);
1046                 /*
1047                  * Only resume if the session's version matches the negotiated
1048                  * version.
1049                  * RFC 5246 does not provide much useful advice on resumption
1050                  * with a different protocol version. It doesn't forbid it but
1051                  * the sanity of such behaviour would be questionable.
1052                  * In practice, clients do not accept a version mismatch and
1053                  * will abort the handshake with an error.
1054                  */
1055                 if (i == 1 && s->version == s->session->ssl_version)
1056                         { /* previous session */
1057                         s->hit=1;
1058                         }
1059                 else if (i == -1)
1060                         goto err;
1061                 else /* i == 0 */
1062                         {
1063                         if (!ssl_get_new_session(s,1))
1064                                 goto err;
1065                         }
1066                 }
1067
1068         p+=j;
1069
1070         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1071                 {
1072                 /* cookie stuff */
1073                 cookie_len = *(p++);
1074
1075                 /* 
1076                  * The ClientHello may contain a cookie even if the
1077                  * HelloVerify message has not been sent--make sure that it
1078                  * does not cause an overflow.
1079                  */
1080                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1081                         {
1082                         /* too much data */
1083                         al = SSL_AD_DECODE_ERROR;
1084                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1085                         goto f_err;
1086                         }
1087
1088                 /* verify the cookie if appropriate option is set. */
1089                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1090                         cookie_len > 0)
1091                         {
1092                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
1093
1094                         if ( s->ctx->app_verify_cookie_cb != NULL)
1095                                 {
1096                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1097                                         cookie_len) == 0)
1098                                         {
1099                                         al=SSL_AD_HANDSHAKE_FAILURE;
1100                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1101                                                 SSL_R_COOKIE_MISMATCH);
1102                                         goto f_err;
1103                                         }
1104                                 /* else cookie verification succeeded */
1105                                 }
1106                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
1107                                                   s->d1->cookie_len) != 0) /* default verification */
1108                                 {
1109                                         al=SSL_AD_HANDSHAKE_FAILURE;
1110                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1111                                                 SSL_R_COOKIE_MISMATCH);
1112                                         goto f_err;
1113                                 }
1114
1115                         ret = 2;
1116                         }
1117
1118                 p += cookie_len;
1119                 }
1120
1121         n2s(p,i);
1122         if ((i == 0) && (j != 0))
1123                 {
1124                 /* we need a cipher if we are not resuming a session */
1125                 al=SSL_AD_ILLEGAL_PARAMETER;
1126                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1127                 goto f_err;
1128                 }
1129         if ((p+i) >= (d+n))
1130                 {
1131                 /* not enough data */
1132                 al=SSL_AD_DECODE_ERROR;
1133                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1134                 goto f_err;
1135                 }
1136         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1137                 == NULL))
1138                 {
1139                 goto err;
1140                 }
1141         p+=i;
1142
1143         /* If it is a hit, check that the cipher is in the list */
1144         if ((s->hit) && (i > 0))
1145                 {
1146                 j=0;
1147                 id=s->session->cipher->id;
1148
1149 #ifdef CIPHER_DEBUG
1150                 fprintf(stderr,"client sent %d ciphers\n",sk_SSL_CIPHER_num(ciphers));
1151 #endif
1152                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1153                         {
1154                         c=sk_SSL_CIPHER_value(ciphers,i);
1155 #ifdef CIPHER_DEBUG
1156                         fprintf(stderr,"client [%2d of %2d]:%s\n",
1157                                 i,sk_SSL_CIPHER_num(ciphers),
1158                                 SSL_CIPHER_get_name(c));
1159 #endif
1160                         if (c->id == id)
1161                                 {
1162                                 j=1;
1163                                 break;
1164                                 }
1165                         }
1166 /* Disabled because it can be used in a ciphersuite downgrade
1167  * attack: CVE-2010-4180.
1168  */
1169 #if 0
1170                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1171                         {
1172                         /* Special case as client bug workaround: the previously used cipher may
1173                          * not be in the current list, the client instead might be trying to
1174                          * continue using a cipher that before wasn't chosen due to server
1175                          * preferences.  We'll have to reject the connection if the cipher is not
1176                          * enabled, though. */
1177                         c = sk_SSL_CIPHER_value(ciphers, 0);
1178                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1179                                 {
1180                                 s->session->cipher = c;
1181                                 j = 1;
1182                                 }
1183                         }
1184 #endif
1185                 if (j == 0)
1186                         {
1187                         /* we need to have the cipher in the cipher
1188                          * list if we are asked to reuse it */
1189                         al=SSL_AD_ILLEGAL_PARAMETER;
1190                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1191                         goto f_err;
1192                         }
1193                 }
1194
1195         /* compression */
1196         i= *(p++);
1197         if ((p+i) > (d+n))
1198                 {
1199                 /* not enough data */
1200                 al=SSL_AD_DECODE_ERROR;
1201                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1202                 goto f_err;
1203                 }
1204         q=p;
1205         for (j=0; j<i; j++)
1206                 {
1207                 if (p[j] == 0) break;
1208                 }
1209
1210         p+=i;
1211         if (j >= i)
1212                 {
1213                 /* no compress */
1214                 al=SSL_AD_DECODE_ERROR;
1215                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1216                 goto f_err;
1217                 }
1218
1219 #ifndef OPENSSL_NO_TLSEXT
1220         /* TLS extensions*/
1221         if (s->version >= SSL3_VERSION)
1222                 {
1223                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
1224                         {
1225                         /* 'al' set by ssl_parse_clienthello_tlsext */
1226                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1227                         goto f_err;
1228                         }
1229                 }
1230                 if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1231                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
1232                         goto err;
1233                 }
1234
1235         /* Check if we want to use external pre-shared secret for this
1236          * handshake for not reused session only. We need to generate
1237          * server_random before calling tls_session_secret_cb in order to allow
1238          * SessionTicket processing to use it in key derivation. */
1239         {
1240                 unsigned char *pos;
1241                 pos=s->s3->server_random;
1242                 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1243                         {
1244                         al=SSL_AD_INTERNAL_ERROR;
1245                         goto f_err;
1246                         }
1247         }
1248
1249         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1250                 {
1251                 SSL_CIPHER *pref_cipher=NULL;
1252
1253                 s->session->master_key_length=sizeof(s->session->master_key);
1254                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1255                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1256                         {
1257                         s->hit=1;
1258                         s->session->ciphers=ciphers;
1259                         s->session->verify_result=X509_V_OK;
1260
1261                         ciphers=NULL;
1262
1263                         /* check if some cipher was preferred by call back */
1264                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1265                         if (pref_cipher == NULL)
1266                                 {
1267                                 al=SSL_AD_HANDSHAKE_FAILURE;
1268                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1269                                 goto f_err;
1270                                 }
1271
1272                         s->session->cipher=pref_cipher;
1273
1274                         if (s->cipher_list)
1275                                 sk_SSL_CIPHER_free(s->cipher_list);
1276
1277                         if (s->cipher_list_by_id)
1278                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1279
1280                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1281                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1282                         }
1283                 }
1284 #endif
1285
1286         /* Worst case, we will use the NULL compression, but if we have other
1287          * options, we will now look for them.  We have i-1 compression
1288          * algorithms from the client, starting at q. */
1289         s->s3->tmp.new_compression=NULL;
1290 #ifndef OPENSSL_NO_COMP
1291         /* This only happens if we have a cache hit */
1292         if (s->session->compress_meth != 0)
1293                 {
1294                 int m, comp_id = s->session->compress_meth;
1295                 /* Perform sanity checks on resumed compression algorithm */
1296                 /* Can't disable compression */
1297                 if (s->options & SSL_OP_NO_COMPRESSION)
1298                         {
1299                         al=SSL_AD_INTERNAL_ERROR;
1300                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1301                         goto f_err;
1302                         }
1303                 /* Look for resumed compression method */
1304                 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1305                         {
1306                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1307                         if (comp_id == comp->id)
1308                                 {
1309                                 s->s3->tmp.new_compression=comp;
1310                                 break;
1311                                 }
1312                         }
1313                 if (s->s3->tmp.new_compression == NULL)
1314                         {
1315                         al=SSL_AD_INTERNAL_ERROR;
1316                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1317                         goto f_err;
1318                         }
1319                 /* Look for resumed method in compression list */
1320                 for (m = 0; m < i; m++)
1321                         {
1322                         if (q[m] == comp_id)
1323                                 break;
1324                         }
1325                 if (m >= i)
1326                         {
1327                         al=SSL_AD_ILLEGAL_PARAMETER;
1328                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1329                         goto f_err;
1330                         }
1331                 }
1332         else if (s->hit)
1333                 comp = NULL;
1334         else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1335                 { /* See if we have a match */
1336                 int m,nn,o,v,done=0;
1337
1338                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1339                 for (m=0; m<nn; m++)
1340                         {
1341                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1342                         v=comp->id;
1343                         for (o=0; o<i; o++)
1344                                 {
1345                                 if (v == q[o])
1346                                         {
1347                                         done=1;
1348                                         break;
1349                                         }
1350                                 }
1351                         if (done) break;
1352                         }
1353                 if (done)
1354                         s->s3->tmp.new_compression=comp;
1355                 else
1356                         comp=NULL;
1357                 }
1358 #else
1359         /* If compression is disabled we'd better not try to resume a session
1360          * using compression.
1361          */
1362         if (s->session->compress_meth != 0)
1363                 {
1364                 al=SSL_AD_INTERNAL_ERROR;
1365                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1366                 goto f_err;
1367                 }
1368 #endif
1369
1370         /* Given s->session->ciphers and SSL_get_ciphers, we must
1371          * pick a cipher */
1372
1373         if (!s->hit)
1374                 {
1375 #ifdef OPENSSL_NO_COMP
1376                 s->session->compress_meth=0;
1377 #else
1378                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1379 #endif
1380                 if (s->session->ciphers != NULL)
1381                         sk_SSL_CIPHER_free(s->session->ciphers);
1382                 s->session->ciphers=ciphers;
1383                 if (ciphers == NULL)
1384                         {
1385                         al=SSL_AD_ILLEGAL_PARAMETER;
1386                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1387                         goto f_err;
1388                         }
1389                 ciphers=NULL;
1390                 c=ssl3_choose_cipher(s,s->session->ciphers,
1391                                      SSL_get_ciphers(s));
1392
1393                 if (c == NULL)
1394                         {
1395                         al=SSL_AD_HANDSHAKE_FAILURE;
1396                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1397                         goto f_err;
1398                         }
1399                 s->s3->tmp.new_cipher=c;
1400                 }
1401         else
1402                 {
1403                 /* Session-id reuse */
1404 #ifdef REUSE_CIPHER_BUG
1405                 STACK_OF(SSL_CIPHER) *sk;
1406                 SSL_CIPHER *nc=NULL;
1407                 SSL_CIPHER *ec=NULL;
1408
1409                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1410                         {
1411                         sk=s->session->ciphers;
1412                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1413                                 {
1414                                 c=sk_SSL_CIPHER_value(sk,i);
1415                                 if (c->algorithm_enc & SSL_eNULL)
1416                                         nc=c;
1417                                 if (SSL_C_IS_EXPORT(c))
1418                                         ec=c;
1419                                 }
1420                         if (nc != NULL)
1421                                 s->s3->tmp.new_cipher=nc;
1422                         else if (ec != NULL)
1423                                 s->s3->tmp.new_cipher=ec;
1424                         else
1425                                 s->s3->tmp.new_cipher=s->session->cipher;
1426                         }
1427                 else
1428 #endif
1429                 s->s3->tmp.new_cipher=s->session->cipher;
1430                 }
1431
1432         if (TLS1_get_version(s) < TLS1_2_VERSION || !(s->verify_mode & SSL_VERIFY_PEER))
1433                 {
1434                 if (!ssl3_digest_cached_records(s))
1435                         {
1436                         al = SSL_AD_INTERNAL_ERROR;
1437                         goto f_err;
1438                         }
1439                 }
1440         
1441         /*-
1442          * we now have the following setup. 
1443          * client_random
1444          * cipher_list          - our prefered list of ciphers
1445          * ciphers              - the clients prefered list of ciphers
1446          * compression          - basically ignored right now
1447          * ssl version is set   - sslv3
1448          * s->session           - The ssl session has been setup.
1449          * s->hit               - session reuse flag
1450          * s->tmp.new_cipher    - the new cipher to use.
1451          */
1452
1453         /* Handles TLS extensions that we couldn't check earlier */
1454         if (s->version >= SSL3_VERSION)
1455                 {
1456                 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1457                         {
1458                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1459                         goto err;
1460                         }
1461                 }
1462
1463         if (ret < 0) ret=1;
1464         if (0)
1465                 {
1466 f_err:
1467                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1468                 }
1469 err:
1470         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1471         return(ret);
1472         }
1473
1474 int ssl3_send_server_hello(SSL *s)
1475         {
1476         unsigned char *buf;
1477         unsigned char *p,*d;
1478         int i,sl;
1479         unsigned long l;
1480
1481         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1482                 {
1483                 buf=(unsigned char *)s->init_buf->data;
1484 #ifdef OPENSSL_NO_TLSEXT
1485                 p=s->s3->server_random;
1486                 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1487                         return -1;
1488 #endif
1489                 /* Do the message type and length last */
1490                 d=p= &(buf[4]);
1491
1492                 *(p++)=s->version>>8;
1493                 *(p++)=s->version&0xff;
1494
1495                 /* Random stuff */
1496                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1497                 p+=SSL3_RANDOM_SIZE;
1498
1499                 /*-
1500                  * There are several cases for the session ID to send
1501                  * back in the server hello:
1502                  * - For session reuse from the session cache,
1503                  *   we send back the old session ID.
1504                  * - If stateless session reuse (using a session ticket)
1505                  *   is successful, we send back the client's "session ID"
1506                  *   (which doesn't actually identify the session).
1507                  * - If it is a new session, we send back the new
1508                  *   session ID.
1509                  * - However, if we want the new session to be single-use,
1510                  *   we send back a 0-length session ID.
1511                  * s->hit is non-zero in either case of session reuse,
1512                  * so the following won't overwrite an ID that we're supposed
1513                  * to send back.
1514                  */
1515                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1516                         && !s->hit)
1517                         s->session->session_id_length=0;
1518
1519                 sl=s->session->session_id_length;
1520                 if (sl > (int)sizeof(s->session->session_id))
1521                         {
1522                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1523                         return -1;
1524                         }
1525                 *(p++)=sl;
1526                 memcpy(p,s->session->session_id,sl);
1527                 p+=sl;
1528
1529                 /* put the cipher */
1530                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1531                 p+=i;
1532
1533                 /* put the compression method */
1534 #ifdef OPENSSL_NO_COMP
1535                         *(p++)=0;
1536 #else
1537                 if (s->s3->tmp.new_compression == NULL)
1538                         *(p++)=0;
1539                 else
1540                         *(p++)=s->s3->tmp.new_compression->id;
1541 #endif
1542 #ifndef OPENSSL_NO_TLSEXT
1543                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1544                         {
1545                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1546                         return -1;
1547                         }
1548                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1549                         {
1550                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1551                         return -1;
1552                         }
1553 #endif
1554                 /* do the header */
1555                 l=(p-d);
1556                 d=buf;
1557                 *(d++)=SSL3_MT_SERVER_HELLO;
1558                 l2n3(l,d);
1559
1560                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1561                 /* number of bytes to write */
1562                 s->init_num=p-buf;
1563                 s->init_off=0;
1564                 }
1565
1566         /* SSL3_ST_SW_SRVR_HELLO_B */
1567         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1568         }
1569
1570 int ssl3_send_server_done(SSL *s)
1571         {
1572         unsigned char *p;
1573
1574         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1575                 {
1576                 p=(unsigned char *)s->init_buf->data;
1577
1578                 /* do the header */
1579                 *(p++)=SSL3_MT_SERVER_DONE;
1580                 *(p++)=0;
1581                 *(p++)=0;
1582                 *(p++)=0;
1583
1584                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1585                 /* number of bytes to write */
1586                 s->init_num=4;
1587                 s->init_off=0;
1588                 }
1589
1590         /* SSL3_ST_SW_SRVR_DONE_B */
1591         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1592         }
1593
1594 int ssl3_send_server_key_exchange(SSL *s)
1595         {
1596 #ifndef OPENSSL_NO_RSA
1597         unsigned char *q;
1598         int j,num;
1599         RSA *rsa;
1600         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1601         unsigned int u;
1602 #endif
1603 #ifndef OPENSSL_NO_DH
1604         DH *dh=NULL,*dhp;
1605 #endif
1606 #ifndef OPENSSL_NO_ECDH
1607         EC_KEY *ecdh=NULL, *ecdhp;
1608         unsigned char *encodedPoint = NULL;
1609         int encodedlen = 0;
1610         int curve_id = 0;
1611         BN_CTX *bn_ctx = NULL; 
1612 #endif
1613         EVP_PKEY *pkey;
1614         const EVP_MD *md = NULL;
1615         unsigned char *p,*d;
1616         int al,i;
1617         unsigned long type;
1618         int n;
1619         CERT *cert;
1620         BIGNUM *r[4];
1621         int nr[4],kn;
1622         BUF_MEM *buf;
1623         EVP_MD_CTX md_ctx;
1624
1625         EVP_MD_CTX_init(&md_ctx);
1626         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1627                 {
1628                 type=s->s3->tmp.new_cipher->algorithm_mkey;
1629                 cert=s->cert;
1630
1631                 buf=s->init_buf;
1632
1633                 r[0]=r[1]=r[2]=r[3]=NULL;
1634                 n=0;
1635 #ifndef OPENSSL_NO_RSA
1636                 if (type & SSL_kRSA)
1637                         {
1638                         rsa=cert->rsa_tmp;
1639                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1640                                 {
1641                                 rsa=s->cert->rsa_tmp_cb(s,
1642                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1643                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1644                                 if(rsa == NULL)
1645                                 {
1646                                         al=SSL_AD_HANDSHAKE_FAILURE;
1647                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1648                                         goto f_err;
1649                                 }
1650                                 RSA_up_ref(rsa);
1651                                 cert->rsa_tmp=rsa;
1652                                 }
1653                         if (rsa == NULL)
1654                                 {
1655                                 al=SSL_AD_HANDSHAKE_FAILURE;
1656                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1657                                 goto f_err;
1658                                 }
1659                         r[0]=rsa->n;
1660                         r[1]=rsa->e;
1661                         s->s3->tmp.use_rsa_tmp=1;
1662                         }
1663                 else
1664 #endif
1665 #ifndef OPENSSL_NO_DH
1666                         if (type & SSL_kEDH)
1667                         {
1668                         dhp=cert->dh_tmp;
1669                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1670                                 dhp=s->cert->dh_tmp_cb(s,
1671                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1672                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1673                         if (dhp == NULL)
1674                                 {
1675                                 al=SSL_AD_HANDSHAKE_FAILURE;
1676                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1677                                 goto f_err;
1678                                 }
1679
1680                         if (s->s3->tmp.dh != NULL)
1681                                 {
1682                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1683                                 goto err;
1684                                 }
1685
1686                         if ((dh=DHparams_dup(dhp)) == NULL)
1687                                 {
1688                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1689                                 goto err;
1690                                 }
1691
1692                         s->s3->tmp.dh=dh;
1693                         if ((dhp->pub_key == NULL ||
1694                              dhp->priv_key == NULL ||
1695                              (s->options & SSL_OP_SINGLE_DH_USE)))
1696                                 {
1697                                 if(!DH_generate_key(dh))
1698                                     {
1699                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1700                                            ERR_R_DH_LIB);
1701                                     goto err;
1702                                     }
1703                                 }
1704                         else
1705                                 {
1706                                 dh->pub_key=BN_dup(dhp->pub_key);
1707                                 dh->priv_key=BN_dup(dhp->priv_key);
1708                                 if ((dh->pub_key == NULL) ||
1709                                         (dh->priv_key == NULL))
1710                                         {
1711                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1712                                         goto err;
1713                                         }
1714                                 }
1715                         r[0]=dh->p;
1716                         r[1]=dh->g;
1717                         r[2]=dh->pub_key;
1718                         }
1719                 else 
1720 #endif
1721 #ifndef OPENSSL_NO_ECDH
1722                         if (type & SSL_kEECDH)
1723                         {
1724                         const EC_GROUP *group;
1725
1726                         ecdhp=cert->ecdh_tmp;
1727                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1728                                 {
1729                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1730                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1731                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1732                                 }
1733                         if (ecdhp == NULL)
1734                                 {
1735                                 al=SSL_AD_HANDSHAKE_FAILURE;
1736                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1737                                 goto f_err;
1738                                 }
1739
1740                         if (s->s3->tmp.ecdh != NULL)
1741                                 {
1742                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1743                                 goto err;
1744                                 }
1745
1746                         /* Duplicate the ECDH structure. */
1747                         if (ecdhp == NULL)
1748                                 {
1749                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1750                                 goto err;
1751                                 }
1752                         if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1753                                 {
1754                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1755                                 goto err;
1756                                 }
1757
1758                         s->s3->tmp.ecdh=ecdh;
1759                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1760                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1761                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1762                                 {
1763                                 if(!EC_KEY_generate_key(ecdh))
1764                                     {
1765                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1766                                     goto err;
1767                                     }
1768                                 }
1769
1770                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1771                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1772                             (EC_KEY_get0_private_key(ecdh) == NULL))
1773                                 {
1774                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1775                                 goto err;
1776                                 }
1777
1778                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1779                             (EC_GROUP_get_degree(group) > 163)) 
1780                                 {
1781                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1782                                 goto err;
1783                                 }
1784
1785                         /* XXX: For now, we only support ephemeral ECDH
1786                          * keys over named (not generic) curves. For 
1787                          * supported named curves, curve_id is non-zero.
1788                          */
1789                         if ((curve_id = 
1790                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1791                             == 0)
1792                                 {
1793                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1794                                 goto err;
1795                                 }
1796
1797                         /* Encode the public key.
1798                          * First check the size of encoding and
1799                          * allocate memory accordingly.
1800                          */
1801                         encodedlen = EC_POINT_point2oct(group, 
1802                             EC_KEY_get0_public_key(ecdh),
1803                             POINT_CONVERSION_UNCOMPRESSED, 
1804                             NULL, 0, NULL);
1805
1806                         encodedPoint = (unsigned char *) 
1807                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1808                         bn_ctx = BN_CTX_new();
1809                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1810                                 {
1811                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1812                                 goto err;
1813                                 }
1814
1815
1816                         encodedlen = EC_POINT_point2oct(group, 
1817                             EC_KEY_get0_public_key(ecdh), 
1818                             POINT_CONVERSION_UNCOMPRESSED, 
1819                             encodedPoint, encodedlen, bn_ctx);
1820
1821                         if (encodedlen == 0) 
1822                                 {
1823                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1824                                 goto err;
1825                                 }
1826
1827                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1828
1829                         /* XXX: For now, we only support named (not 
1830                          * generic) curves in ECDH ephemeral key exchanges.
1831                          * In this situation, we need four additional bytes
1832                          * to encode the entire ServerECDHParams
1833                          * structure. 
1834                          */
1835                         n = 4 + encodedlen;
1836
1837                         /* We'll generate the serverKeyExchange message
1838                          * explicitly so we can set these to NULLs
1839                          */
1840                         r[0]=NULL;
1841                         r[1]=NULL;
1842                         r[2]=NULL;
1843                         r[3]=NULL;
1844                         }
1845                 else 
1846 #endif /* !OPENSSL_NO_ECDH */
1847 #ifndef OPENSSL_NO_PSK
1848                         if (type & SSL_kPSK)
1849                                 {
1850                                 /* reserve size for record length and PSK identity hint*/
1851                                 n+=2+strlen(s->ctx->psk_identity_hint);
1852                                 }
1853                         else
1854 #endif /* !OPENSSL_NO_PSK */
1855 #ifndef OPENSSL_NO_SRP
1856                 if (type & SSL_kSRP)
1857                         {
1858                         if ((s->srp_ctx.N == NULL) ||
1859                                 (s->srp_ctx.g == NULL) ||
1860                                 (s->srp_ctx.s == NULL) ||
1861                                 (s->srp_ctx.B == NULL))
1862                                 {
1863                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1864                                 goto err;
1865                                 }
1866                         r[0]=s->srp_ctx.N;
1867                         r[1]=s->srp_ctx.g;
1868                         r[2]=s->srp_ctx.s;
1869                         r[3]=s->srp_ctx.B;
1870                         }
1871                 else 
1872 #endif
1873                         {
1874                         al=SSL_AD_HANDSHAKE_FAILURE;
1875                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1876                         goto f_err;
1877                         }
1878                 for (i=0; i < 4 && r[i] != NULL; i++)
1879                         {
1880                         nr[i]=BN_num_bytes(r[i]);
1881 #ifndef OPENSSL_NO_SRP
1882                         if ((i == 2) && (type & SSL_kSRP))
1883                                 n+=1+nr[i];
1884                         else
1885 #endif
1886                         n+=2+nr[i];
1887                         }
1888
1889                 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1890                         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1891                         {
1892                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1893                                 == NULL)
1894                                 {
1895                                 al=SSL_AD_DECODE_ERROR;
1896                                 goto f_err;
1897                                 }
1898                         kn=EVP_PKEY_size(pkey);
1899                         }
1900                 else
1901                         {
1902                         pkey=NULL;
1903                         kn=0;
1904                         }
1905
1906                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1907                         {
1908                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1909                         goto err;
1910                         }
1911                 d=(unsigned char *)s->init_buf->data;
1912                 p= &(d[4]);
1913
1914                 for (i=0; i < 4 && r[i] != NULL; i++)
1915                         {
1916 #ifndef OPENSSL_NO_SRP
1917                         if ((i == 2) && (type & SSL_kSRP))
1918                                 {
1919                                 *p = nr[i];
1920                                 p++;
1921                                 }
1922                         else
1923 #endif
1924                         s2n(nr[i],p);
1925                         BN_bn2bin(r[i],p);
1926                         p+=nr[i];
1927                         }
1928
1929 #ifndef OPENSSL_NO_ECDH
1930                 if (type & SSL_kEECDH) 
1931                         {
1932                         /* XXX: For now, we only support named (not generic) curves.
1933                          * In this situation, the serverKeyExchange message has:
1934                          * [1 byte CurveType], [2 byte CurveName]
1935                          * [1 byte length of encoded point], followed by
1936                          * the actual encoded point itself
1937                          */
1938                         *p = NAMED_CURVE_TYPE;
1939                         p += 1;
1940                         *p = 0;
1941                         p += 1;
1942                         *p = curve_id;
1943                         p += 1;
1944                         *p = encodedlen;
1945                         p += 1;
1946                         memcpy((unsigned char*)p, 
1947                             (unsigned char *)encodedPoint, 
1948                             encodedlen);
1949                         OPENSSL_free(encodedPoint);
1950                         encodedPoint = NULL;
1951                         p += encodedlen;
1952                         }
1953 #endif
1954
1955 #ifndef OPENSSL_NO_PSK
1956                 if (type & SSL_kPSK)
1957                         {
1958                         /* copy PSK identity hint */
1959                         s2n(strlen(s->ctx->psk_identity_hint), p); 
1960                         strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1961                         p+=strlen(s->ctx->psk_identity_hint);
1962                         }
1963 #endif
1964
1965                 /* not anonymous */
1966                 if (pkey != NULL)
1967                         {
1968                         /* n is the length of the params, they start at &(d[4])
1969                          * and p points to the space at the end. */
1970 #ifndef OPENSSL_NO_RSA
1971                         if (pkey->type == EVP_PKEY_RSA
1972                                         && TLS1_get_version(s) < TLS1_2_VERSION)
1973                                 {
1974                                 q=md_buf;
1975                                 j=0;
1976                                 for (num=2; num > 0; num--)
1977                                         {
1978                                         EVP_MD_CTX_set_flags(&md_ctx,
1979                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1980                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1981                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1982                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1983                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1984                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1985                                         EVP_DigestFinal_ex(&md_ctx,q,
1986                                                 (unsigned int *)&i);
1987                                         q+=i;
1988                                         j+=i;
1989                                         }
1990                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1991                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1992                                         {
1993                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1994                                         goto err;
1995                                         }
1996                                 s2n(u,p);
1997                                 n+=u+2;
1998                                 }
1999                         else
2000 #endif
2001                         if (md)
2002                                 {
2003                                 /* For TLS1.2 and later send signature
2004                                  * algorithm */
2005                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2006                                         {
2007                                         if (!tls12_get_sigandhash(p, pkey, md))
2008                                                 {
2009                                                 /* Should never happen */
2010                                                 al=SSL_AD_INTERNAL_ERROR;
2011                                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2012                                                 goto f_err;
2013                                                 }
2014                                         p+=2;
2015                                         }
2016 #ifdef SSL_DEBUG
2017                                 fprintf(stderr, "Using hash %s\n",
2018                                                         EVP_MD_name(md));
2019 #endif
2020                                 EVP_SignInit_ex(&md_ctx, md, NULL);
2021                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2022                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2023                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
2024                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2025                                         (unsigned int *)&i,pkey))
2026                                         {
2027                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2028                                         goto err;
2029                                         }
2030                                 s2n(i,p);
2031                                 n+=i+2;
2032                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2033                                         n+= 2;
2034                                 }
2035                         else
2036                                 {
2037                                 /* Is this error check actually needed? */
2038                                 al=SSL_AD_HANDSHAKE_FAILURE;
2039                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2040                                 goto f_err;
2041                                 }
2042                         }
2043
2044                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
2045                 l2n3(n,d);
2046
2047                 /* we should now have things packed up, so lets send
2048                  * it off */
2049                 s->init_num=n+4;
2050                 s->init_off=0;
2051                 }
2052
2053         s->state = SSL3_ST_SW_KEY_EXCH_B;
2054         EVP_MD_CTX_cleanup(&md_ctx);
2055         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2056 f_err:
2057         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2058 err:
2059 #ifndef OPENSSL_NO_ECDH
2060         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2061         BN_CTX_free(bn_ctx);
2062 #endif
2063         EVP_MD_CTX_cleanup(&md_ctx);
2064         return(-1);
2065         }
2066
2067 int ssl3_send_certificate_request(SSL *s)
2068         {
2069         unsigned char *p,*d;
2070         int i,j,nl,off,n;
2071         STACK_OF(X509_NAME) *sk=NULL;
2072         X509_NAME *name;
2073         BUF_MEM *buf;
2074
2075         if (s->state == SSL3_ST_SW_CERT_REQ_A)
2076                 {
2077                 buf=s->init_buf;
2078
2079                 d=p=(unsigned char *)&(buf->data[4]);
2080
2081                 /* get the list of acceptable cert types */
2082                 p++;
2083                 n=ssl3_get_req_cert_type(s,p);
2084                 d[0]=n;
2085                 p+=n;
2086                 n++;
2087
2088                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2089                         {
2090                         nl = tls12_get_req_sig_algs(s, p + 2);
2091                         s2n(nl, p);
2092                         p += nl + 2;
2093                         n += nl + 2;
2094                         }
2095
2096                 off=n;
2097                 p+=2;
2098                 n+=2;
2099
2100                 sk=SSL_get_client_CA_list(s);
2101                 nl=0;
2102                 if (sk != NULL)
2103                         {
2104                         for (i=0; i<sk_X509_NAME_num(sk); i++)
2105                                 {
2106                                 name=sk_X509_NAME_value(sk,i);
2107                                 j=i2d_X509_NAME(name,NULL);
2108                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
2109                                         {
2110                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2111                                         goto err;
2112                                         }
2113                                 p=(unsigned char *)&(buf->data[4+n]);
2114                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2115                                         {
2116                                         s2n(j,p);
2117                                         i2d_X509_NAME(name,&p);
2118                                         n+=2+j;
2119                                         nl+=2+j;
2120                                         }
2121                                 else
2122                                         {
2123                                         d=p;
2124                                         i2d_X509_NAME(name,&p);
2125                                         j-=2; s2n(j,d); j+=2;
2126                                         n+=j;
2127                                         nl+=j;
2128                                         }
2129                                 }
2130                         }
2131                 /* else no CA names */
2132                 p=(unsigned char *)&(buf->data[4+off]);
2133                 s2n(nl,p);
2134
2135                 d=(unsigned char *)buf->data;
2136                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
2137                 l2n3(n,d);
2138
2139                 /* we should now have things packed up, so lets send
2140                  * it off */
2141
2142                 s->init_num=n+4;
2143                 s->init_off=0;
2144 #ifdef NETSCAPE_HANG_BUG
2145                 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2146                         {
2147                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2148                         goto err;
2149                         }
2150                 p=(unsigned char *)s->init_buf->data + s->init_num;
2151
2152                 /* do the header */
2153                 *(p++)=SSL3_MT_SERVER_DONE;
2154                 *(p++)=0;
2155                 *(p++)=0;
2156                 *(p++)=0;
2157                 s->init_num += 4;
2158 #endif
2159
2160                 s->state = SSL3_ST_SW_CERT_REQ_B;
2161                 }
2162
2163         /* SSL3_ST_SW_CERT_REQ_B */
2164         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2165 err:
2166         return(-1);
2167         }
2168
2169 int ssl3_get_client_key_exchange(SSL *s)
2170         {
2171         int i,al,ok;
2172         long n;
2173         unsigned long alg_k;
2174         unsigned char *p;
2175 #ifndef OPENSSL_NO_RSA
2176         RSA *rsa=NULL;
2177         EVP_PKEY *pkey=NULL;
2178 #endif
2179 #ifndef OPENSSL_NO_DH
2180         BIGNUM *pub=NULL;
2181         DH *dh_srvr;
2182 #endif
2183 #ifndef OPENSSL_NO_KRB5
2184         KSSL_ERR kssl_err;
2185 #endif /* OPENSSL_NO_KRB5 */
2186
2187 #ifndef OPENSSL_NO_ECDH
2188         EC_KEY *srvr_ecdh = NULL;
2189         EVP_PKEY *clnt_pub_pkey = NULL;
2190         EC_POINT *clnt_ecpoint = NULL;
2191         BN_CTX *bn_ctx = NULL; 
2192 #endif
2193
2194         n=s->method->ssl_get_message(s,
2195                 SSL3_ST_SR_KEY_EXCH_A,
2196                 SSL3_ST_SR_KEY_EXCH_B,
2197                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2198                 2048, /* ??? */
2199                 &ok);
2200
2201         if (!ok) return((int)n);
2202         p=(unsigned char *)s->init_msg;
2203
2204         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2205
2206 #ifndef OPENSSL_NO_RSA
2207         if (alg_k & SSL_kRSA)
2208                 {
2209                 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2210                 int decrypt_len;
2211                 unsigned char decrypt_good, version_good;
2212                 size_t j;
2213
2214                 /* FIX THIS UP EAY EAY EAY EAY */
2215                 if (s->s3->tmp.use_rsa_tmp)
2216                         {
2217                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2218                                 rsa=s->cert->rsa_tmp;
2219                         /* Don't do a callback because rsa_tmp should
2220                          * be sent already */
2221                         if (rsa == NULL)
2222                                 {
2223                                 al=SSL_AD_HANDSHAKE_FAILURE;
2224                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2225                                 goto f_err;
2226
2227                                 }
2228                         }
2229                 else
2230                         {
2231                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2232                         if (    (pkey == NULL) ||
2233                                 (pkey->type != EVP_PKEY_RSA) ||
2234                                 (pkey->pkey.rsa == NULL))
2235                                 {
2236                                 al=SSL_AD_HANDSHAKE_FAILURE;
2237                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2238                                 goto f_err;
2239                                 }
2240                         rsa=pkey->pkey.rsa;
2241                         }
2242
2243                 /* TLS and [incidentally] DTLS{0xFEFF} */
2244                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2245                         {
2246                         n2s(p,i);
2247                         if (n != i+2)
2248                                 {
2249                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2250                                         {
2251                                         al = SSL_AD_DECODE_ERROR;
2252                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2253                                         goto f_err;
2254                                         }
2255                                 else
2256                                         p-=2;
2257                                 }
2258                         else
2259                                 n=i;
2260                         }
2261
2262                 /*
2263                  * Reject overly short RSA ciphertext because we want to be sure
2264                  * that the buffer size makes it safe to iterate over the entire
2265                  * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2266                  * actual expected size is larger due to RSA padding, but the
2267                  * bound is sufficient to be safe.
2268                  */
2269                 if (n < SSL_MAX_MASTER_KEY_LENGTH)
2270                         {
2271                         al = SSL_AD_DECRYPT_ERROR;
2272                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2273                         goto f_err;
2274                         }
2275
2276                 /* We must not leak whether a decryption failure occurs because
2277                  * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2278                  * RFC 2246, section 7.4.7.1). The code follows that advice of
2279                  * the TLS RFC and generates a random premaster secret for the
2280                  * case that the decrypt fails. See
2281                  * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2282
2283                 /* should be RAND_bytes, but we cannot work around a failure. */
2284                 if (RAND_pseudo_bytes(rand_premaster_secret,
2285                                       sizeof(rand_premaster_secret)) <= 0)
2286                         goto err;
2287                 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2288                 ERR_clear_error();
2289
2290                 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2291                  * decrypt_good will be 0xff if so and zero otherwise. */
2292                 decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2293
2294                 /* If the version in the decrypted pre-master secret is correct
2295                  * then version_good will be 0xff, otherwise it'll be zero.
2296                  * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2297                  * (http://eprint.iacr.org/2003/052/) exploits the version
2298                  * number check as a "bad version oracle". Thus version checks
2299                  * are done in constant time and are treated like any other
2300                  * decryption error. */
2301                 version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2302                 version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2303
2304                 /* The premaster secret must contain the same version number as
2305                  * the ClientHello to detect version rollback attacks
2306                  * (strangely, the protocol does not offer such protection for
2307                  * DH ciphersuites). However, buggy clients exist that send the
2308                  * negotiated protocol version instead if the server does not
2309                  * support the requested protocol version. If
2310                  * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2311                 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2312                         {
2313                         unsigned char workaround_good;
2314                         workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2315                         workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2316                         version_good |= workaround_good;
2317                         }
2318
2319                 /* Both decryption and version must be good for decrypt_good
2320                  * to remain non-zero (0xff). */
2321                 decrypt_good &= version_good;
2322
2323                 /*
2324                  * Now copy rand_premaster_secret over from p using
2325                  * decrypt_good_mask. If decryption failed, then p does not
2326                  * contain valid plaintext, however, a check above guarantees
2327                  * it is still sufficiently large to read from.
2328                  */
2329                 for (j = 0; j < sizeof(rand_premaster_secret); j++)
2330                         {
2331                         p[j] = constant_time_select_8(decrypt_good, p[j],
2332                                                       rand_premaster_secret[j]);
2333                         }
2334
2335                 s->session->master_key_length=
2336                         s->method->ssl3_enc->generate_master_secret(s,
2337                                 s->session->master_key,
2338                                 p,sizeof(rand_premaster_secret));
2339                 OPENSSL_cleanse(p,sizeof(rand_premaster_secret));
2340                 }
2341         else
2342 #endif
2343 #ifndef OPENSSL_NO_DH
2344                 if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2345                 {
2346                 n2s(p,i);
2347                 if (n != i+2)
2348                         {
2349                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2350                                 {
2351                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2352                                 goto err;
2353                                 }
2354                         else
2355                                 {
2356                                 p-=2;
2357                                 i=(int)n;
2358                                 }
2359                         }
2360
2361                 if (n == 0L) /* the parameters are in the cert */
2362                         {
2363                         al=SSL_AD_HANDSHAKE_FAILURE;
2364                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
2365                         goto f_err;
2366                         }
2367                 else
2368                         {
2369                         if (s->s3->tmp.dh == NULL)
2370                                 {
2371                                 al=SSL_AD_HANDSHAKE_FAILURE;
2372                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2373                                 goto f_err;
2374                                 }
2375                         else
2376                                 dh_srvr=s->s3->tmp.dh;
2377                         }
2378
2379                 pub=BN_bin2bn(p,i,NULL);
2380                 if (pub == NULL)
2381                         {
2382                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2383                         goto err;
2384                         }
2385
2386                 i=DH_compute_key(p,pub,dh_srvr);
2387
2388                 if (i <= 0)
2389                         {
2390                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2391                         BN_clear_free(pub);
2392                         goto err;
2393                         }
2394
2395                 DH_free(s->s3->tmp.dh);
2396                 s->s3->tmp.dh=NULL;
2397
2398                 BN_clear_free(pub);
2399                 pub=NULL;
2400                 s->session->master_key_length=
2401                         s->method->ssl3_enc->generate_master_secret(s,
2402                                 s->session->master_key,p,i);
2403                 OPENSSL_cleanse(p,i);
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)
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 (TLS1_get_version(s) >= TLS1_2_VERSION)
3063                         {
3064                         int sigalg = tls12_get_sigid(pkey);
3065                         /* Should never happen */
3066                         if (sigalg == -1)
3067                                 {
3068                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3069                                 al=SSL_AD_INTERNAL_ERROR;
3070                                 goto f_err;
3071                                 }
3072                         /* Check key type is consistent with signature */
3073                         if (sigalg != (int)p[1])
3074                                 {
3075                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_TYPE);
3076                                 al=SSL_AD_DECODE_ERROR;
3077                                 goto f_err;
3078                                 }
3079                         md = tls12_get_hash(p[0]);
3080                         if (md == NULL)
3081                                 {
3082                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_UNKNOWN_DIGEST);
3083                                 al=SSL_AD_DECODE_ERROR;
3084                                 goto f_err;
3085                                 }
3086 #ifdef SSL_DEBUG
3087 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3088 #endif
3089                         p += 2;
3090                         n -= 2;
3091                         }
3092                 n2s(p,i);
3093                 n-=2;
3094                 if (i > n)
3095                         {
3096                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3097                         al=SSL_AD_DECODE_ERROR;
3098                         goto f_err;
3099                         }
3100         }
3101         j=EVP_PKEY_size(pkey);
3102         if ((i > j) || (n > j) || (n <= 0))
3103                 {
3104                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3105                 al=SSL_AD_DECODE_ERROR;
3106                 goto f_err;
3107                 }
3108
3109         if (TLS1_get_version(s) >= TLS1_2_VERSION)
3110                 {
3111                 long hdatalen = 0;
3112                 void *hdata;
3113                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3114                 if (hdatalen <= 0)
3115                         {
3116                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3117                         al=SSL_AD_INTERNAL_ERROR;
3118                         goto f_err;
3119                         }
3120 #ifdef SSL_DEBUG
3121                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3122                                                         EVP_MD_name(md));
3123 #endif
3124                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3125                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3126                         {
3127                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3128                         al=SSL_AD_INTERNAL_ERROR;
3129                         goto f_err;
3130                         }
3131
3132                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3133                         {
3134                         al=SSL_AD_DECRYPT_ERROR;
3135                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3136                         goto f_err;
3137                         }
3138                 }
3139         else
3140 #ifndef OPENSSL_NO_RSA 
3141         if (pkey->type == EVP_PKEY_RSA)
3142                 {
3143                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3144                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3145                                                         pkey->pkey.rsa);
3146                 if (i < 0)
3147                         {
3148                         al=SSL_AD_DECRYPT_ERROR;
3149                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3150                         goto f_err;
3151                         }
3152                 if (i == 0)
3153                         {
3154                         al=SSL_AD_DECRYPT_ERROR;
3155                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3156                         goto f_err;
3157                         }
3158                 }
3159         else
3160 #endif
3161 #ifndef OPENSSL_NO_DSA
3162                 if (pkey->type == EVP_PKEY_DSA)
3163                 {
3164                 j=DSA_verify(pkey->save_type,
3165                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3166                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3167                 if (j <= 0)
3168                         {
3169                         /* bad signature */
3170                         al=SSL_AD_DECRYPT_ERROR;
3171                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3172                         goto f_err;
3173                         }
3174                 }
3175         else
3176 #endif
3177 #ifndef OPENSSL_NO_ECDSA
3178                 if (pkey->type == EVP_PKEY_EC)
3179                 {
3180                 j=ECDSA_verify(pkey->save_type,
3181                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3182                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3183                 if (j <= 0)
3184                         {
3185                         /* bad signature */
3186                         al=SSL_AD_DECRYPT_ERROR;
3187                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3188                             SSL_R_BAD_ECDSA_SIGNATURE);
3189                         goto f_err;
3190                         }
3191                 }
3192         else
3193 #endif
3194         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3195                 {   unsigned char signature[64];
3196                         int idx;
3197                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3198                         EVP_PKEY_verify_init(pctx);
3199                         if (i!=64) {
3200                                 fprintf(stderr,"GOST signature length is %d",i);
3201                         }       
3202                         for (idx=0;idx<64;idx++) {
3203                                 signature[63-idx]=p[idx];
3204                         }       
3205                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3206                         EVP_PKEY_CTX_free(pctx);
3207                         if (j<=0) 
3208                                 {
3209                                 al=SSL_AD_DECRYPT_ERROR;
3210                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3211                                         SSL_R_BAD_ECDSA_SIGNATURE);
3212                                 goto f_err;
3213                                 }       
3214                 }
3215         else    
3216                 {
3217                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3218                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3219                 goto f_err;
3220                 }
3221
3222
3223         ret=1;
3224         if (0)
3225                 {
3226 f_err:
3227                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3228                 }
3229 end:
3230         if (s->s3->handshake_buffer)
3231                 {
3232                 BIO_free(s->s3->handshake_buffer);
3233                 s->s3->handshake_buffer = NULL;
3234                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3235                 }
3236         EVP_MD_CTX_cleanup(&mctx);
3237         EVP_PKEY_free(pkey);
3238         return(ret);
3239         }
3240
3241 int ssl3_get_client_certificate(SSL *s)
3242         {
3243         int i,ok,al,ret= -1;
3244         X509 *x=NULL;
3245         unsigned long l,nc,llen,n;
3246         const unsigned char *p,*q;
3247         unsigned char *d;
3248         STACK_OF(X509) *sk=NULL;
3249
3250         n=s->method->ssl_get_message(s,
3251                 SSL3_ST_SR_CERT_A,
3252                 SSL3_ST_SR_CERT_B,
3253                 -1,
3254                 s->max_cert_list,
3255                 &ok);
3256
3257         if (!ok) return((int)n);
3258
3259         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3260                 {
3261                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3262                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3263                         {
3264                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3265                         al=SSL_AD_HANDSHAKE_FAILURE;
3266                         goto f_err;
3267                         }
3268                 /* If tls asked for a client cert, the client must return a 0 list */
3269                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3270                         {
3271                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3272                         al=SSL_AD_UNEXPECTED_MESSAGE;
3273                         goto f_err;
3274                         }
3275                 s->s3->tmp.reuse_message=1;
3276                 return(1);
3277                 }
3278
3279         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3280                 {
3281                 al=SSL_AD_UNEXPECTED_MESSAGE;
3282                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3283                 goto f_err;
3284                 }
3285         p=d=(unsigned char *)s->init_msg;
3286
3287         if ((sk=sk_X509_new_null()) == NULL)
3288                 {
3289                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3290                 goto err;
3291                 }
3292
3293         n2l3(p,llen);
3294         if (llen+3 != n)
3295                 {
3296                 al=SSL_AD_DECODE_ERROR;
3297                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3298                 goto f_err;
3299                 }
3300         for (nc=0; nc<llen; )
3301                 {
3302                 n2l3(p,l);
3303                 if ((l+nc+3) > llen)
3304                         {
3305                         al=SSL_AD_DECODE_ERROR;
3306                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3307                         goto f_err;
3308                         }
3309
3310                 q=p;
3311                 x=d2i_X509(NULL,&p,l);
3312                 if (x == NULL)
3313                         {
3314                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3315                         goto err;
3316                         }
3317                 if (p != (q+l))
3318                         {
3319                         al=SSL_AD_DECODE_ERROR;
3320                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3321                         goto f_err;
3322                         }
3323                 if (!sk_X509_push(sk,x))
3324                         {
3325                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3326                         goto err;
3327                         }
3328                 x=NULL;
3329                 nc+=l+3;
3330                 }
3331
3332         if (sk_X509_num(sk) <= 0)
3333                 {
3334                 /* TLS does not mind 0 certs returned */
3335                 if (s->version == SSL3_VERSION)
3336                         {
3337                         al=SSL_AD_HANDSHAKE_FAILURE;
3338                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3339                         goto f_err;
3340                         }
3341                 /* Fail for TLS only if we required a certificate */
3342                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3343                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3344                         {
3345                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3346                         al=SSL_AD_HANDSHAKE_FAILURE;
3347                         goto f_err;
3348                         }
3349                 /* No client certificate so digest cached records */
3350                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3351                         {
3352                         al=SSL_AD_INTERNAL_ERROR;
3353                         goto f_err;
3354                         }
3355                 }
3356         else
3357                 {
3358                 i=ssl_verify_cert_chain(s,sk);
3359                 if (i <= 0)
3360                         {
3361                         al=ssl_verify_alarm_type(s->verify_result);
3362                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
3363                         goto f_err;
3364                         }
3365                 }
3366
3367         if (s->session->peer != NULL) /* This should not be needed */
3368                 X509_free(s->session->peer);
3369         s->session->peer=sk_X509_shift(sk);
3370         s->session->verify_result = s->verify_result;
3371
3372         /* With the current implementation, sess_cert will always be NULL
3373          * when we arrive here. */
3374         if (s->session->sess_cert == NULL)
3375                 {
3376                 s->session->sess_cert = ssl_sess_cert_new();
3377                 if (s->session->sess_cert == NULL)
3378                         {
3379                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3380                         goto err;
3381                         }
3382                 }
3383         if (s->session->sess_cert->cert_chain != NULL)
3384                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3385         s->session->sess_cert->cert_chain=sk;
3386         /* Inconsistency alert: cert_chain does *not* include the
3387          * peer's own certificate, while we do include it in s3_clnt.c */
3388
3389         sk=NULL;
3390
3391         ret=1;
3392         if (0)
3393                 {
3394 f_err:
3395                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3396                 }
3397 err:
3398         if (x != NULL) X509_free(x);
3399         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3400         return(ret);
3401         }
3402
3403 int ssl3_send_server_certificate(SSL *s)
3404         {
3405         unsigned long l;
3406         X509 *x;
3407
3408         if (s->state == SSL3_ST_SW_CERT_A)
3409                 {
3410                 x=ssl_get_server_send_cert(s);
3411                 if (x == NULL)
3412                         {
3413                         /* VRS: allow null cert if auth == KRB5 */
3414                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3415                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3416                                 {
3417                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3418                                 return(0);
3419                                 }
3420                         }
3421
3422                 l=ssl3_output_cert_chain(s,x);
3423                 if (!l)
3424                         {
3425                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3426                         return(0);
3427                         }
3428                 s->state=SSL3_ST_SW_CERT_B;
3429                 s->init_num=(int)l;
3430                 s->init_off=0;
3431                 }
3432
3433         /* SSL3_ST_SW_CERT_B */
3434         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3435         }
3436
3437 #ifndef OPENSSL_NO_TLSEXT
3438 /* send a new session ticket (not necessarily for a new session) */
3439 int ssl3_send_newsession_ticket(SSL *s)
3440         {
3441         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3442                 {
3443                 unsigned char *p, *senc, *macstart;
3444                 const unsigned char *const_p;
3445                 int len, slen_full, slen;
3446                 SSL_SESSION *sess;
3447                 unsigned int hlen;
3448                 EVP_CIPHER_CTX ctx;
3449                 HMAC_CTX hctx;
3450                 SSL_CTX *tctx = s->initial_ctx;
3451                 unsigned char iv[EVP_MAX_IV_LENGTH];
3452                 unsigned char key_name[16];
3453
3454                 /* get session encoding length */
3455                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3456                 /* Some length values are 16 bits, so forget it if session is
3457                  * too long
3458                  */
3459                 if (slen_full > 0xFF00)
3460                         return -1;
3461                 senc = OPENSSL_malloc(slen_full);
3462                 if (!senc)
3463                         return -1;
3464                 p = senc;
3465                 i2d_SSL_SESSION(s->session, &p);
3466
3467                 /* create a fresh copy (not shared with other threads) to clean up */
3468                 const_p = senc;
3469                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3470                 if (sess == NULL)
3471                         {
3472                         OPENSSL_free(senc);
3473                         return -1;
3474                         }
3475                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3476
3477                 slen = i2d_SSL_SESSION(sess, NULL);
3478                 if (slen > slen_full) /* shouldn't ever happen */
3479                         {
3480                         OPENSSL_free(senc);
3481                         return -1;
3482                         }
3483                 p = senc;
3484                 i2d_SSL_SESSION(sess, &p);
3485                 SSL_SESSION_free(sess);
3486
3487                 /*-
3488                  * Grow buffer if need be: the length calculation is as
3489                  * follows 1 (size of message name) + 3 (message length
3490                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
3491                  * 16 (key name) + max_iv_len (iv length) +
3492                  * session_length + max_enc_block_size (max encrypted session
3493                  * length) + max_md_size (HMAC).
3494                  */
3495                 if (!BUF_MEM_grow(s->init_buf,
3496                         26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
3497                         EVP_MAX_MD_SIZE + slen))
3498                         return -1;
3499
3500                 p=(unsigned char *)s->init_buf->data;
3501                 /* do the header */
3502                 *(p++)=SSL3_MT_NEWSESSION_TICKET;
3503                 /* Skip message length for now */
3504                 p += 3;
3505                 EVP_CIPHER_CTX_init(&ctx);
3506                 HMAC_CTX_init(&hctx);
3507                 /* Initialize HMAC and cipher contexts. If callback present
3508                  * it does all the work otherwise use generated values
3509                  * from parent ctx.
3510                  */
3511                 if (tctx->tlsext_ticket_key_cb)
3512                         {
3513                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3514                                                          &hctx, 1) < 0)
3515                                 {
3516                                 OPENSSL_free(senc);
3517                                 return -1;
3518                                 }
3519                         }
3520                 else
3521                         {
3522                         RAND_pseudo_bytes(iv, 16);
3523                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3524                                         tctx->tlsext_tick_aes_key, iv);
3525                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3526                                         tlsext_tick_md(), NULL);
3527                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3528                         }
3529
3530                 /* Ticket lifetime hint (advisory only):
3531                  * We leave this unspecified for resumed session (for simplicity),
3532                  * and guess that tickets for new sessions will live as long
3533                  * as their sessions. */
3534                 l2n(s->hit ? 0 : s->session->timeout, p);
3535
3536                 /* Skip ticket length for now */
3537                 p += 2;
3538                 /* Output key name */
3539                 macstart = p;
3540                 memcpy(p, key_name, 16);
3541                 p += 16;
3542                 /* output IV */
3543                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3544                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3545                 /* Encrypt session data */
3546                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3547                 p += len;
3548                 EVP_EncryptFinal(&ctx, p, &len);
3549                 p += len;
3550                 EVP_CIPHER_CTX_cleanup(&ctx);
3551
3552                 HMAC_Update(&hctx, macstart, p - macstart);
3553                 HMAC_Final(&hctx, p, &hlen);
3554                 HMAC_CTX_cleanup(&hctx);
3555
3556                 p += hlen;
3557                 /* Now write out lengths: p points to end of data written */
3558                 /* Total length */
3559                 len = p - (unsigned char *)s->init_buf->data;
3560                 p=(unsigned char *)s->init_buf->data + 1;
3561                 l2n3(len - 4, p); /* Message length */
3562                 p += 4;
3563                 s2n(len - 10, p);  /* Ticket length */
3564
3565                 /* number of bytes to write */
3566                 s->init_num= len;
3567                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3568                 s->init_off=0;
3569                 OPENSSL_free(senc);
3570                 }
3571
3572         /* SSL3_ST_SW_SESSION_TICKET_B */
3573         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3574         }
3575
3576 int ssl3_send_cert_status(SSL *s)
3577         {
3578         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3579                 {
3580                 unsigned char *p;
3581                 /*-
3582                  * Grow buffer if need be: the length calculation is as
3583                  * follows 1 (message type) + 3 (message length) +
3584                  * 1 (ocsp response type) + 3 (ocsp response length)
3585                  * + (ocsp response)
3586                  */
3587                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3588                         return -1;
3589
3590                 p=(unsigned char *)s->init_buf->data;
3591
3592                 /* do the header */
3593                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3594                 /* message length */
3595                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3596                 /* status type */
3597                 *(p++)= s->tlsext_status_type;
3598                 /* length of OCSP response */
3599                 l2n3(s->tlsext_ocsp_resplen, p);
3600                 /* actual response */
3601                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3602                 /* number of bytes to write */
3603                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3604                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3605                 s->init_off = 0;
3606                 }
3607
3608         /* SSL3_ST_SW_CERT_STATUS_B */
3609         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3610         }
3611
3612 # ifndef OPENSSL_NO_NEXTPROTONEG
3613 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3614  * sets the next_proto member in s if found */
3615 int ssl3_get_next_proto(SSL *s)
3616         {
3617         int ok;
3618         int proto_len, padding_len;
3619         long n;
3620         const unsigned char *p;
3621
3622         /* Clients cannot send a NextProtocol message if we didn't see the
3623          * extension in their ClientHello */
3624         if (!s->s3->next_proto_neg_seen)
3625                 {
3626                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3627                 return -1;
3628                 }
3629
3630         n=s->method->ssl_get_message(s,
3631                 SSL3_ST_SR_NEXT_PROTO_A,
3632                 SSL3_ST_SR_NEXT_PROTO_B,
3633                 SSL3_MT_NEXT_PROTO,
3634                 514,  /* See the payload format below */
3635                 &ok);
3636
3637         if (!ok)
3638                 return((int)n);
3639
3640         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3641          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3642          * by ssl3_get_finished). */
3643         if (!s->s3->change_cipher_spec)
3644                 {
3645                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3646                 return -1;
3647                 }
3648
3649         if (n < 2)
3650                 return 0;  /* The body must be > 1 bytes long */
3651
3652         p=(unsigned char *)s->init_msg;
3653
3654         /*-
3655          * The payload looks like:
3656          *   uint8 proto_len;
3657          *   uint8 proto[proto_len];
3658          *   uint8 padding_len;
3659          *   uint8 padding[padding_len];
3660          */
3661         proto_len = p[0];
3662         if (proto_len + 2 > s->init_num)
3663                 return 0;
3664         padding_len = p[proto_len + 1];
3665         if (proto_len + padding_len + 2 != s->init_num)
3666                 return 0;
3667
3668         s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3669         if (!s->next_proto_negotiated)
3670                 {
3671                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3672                 return 0;
3673                 }
3674         memcpy(s->next_proto_negotiated, p + 1, proto_len);
3675         s->next_proto_negotiated_len = proto_len;
3676
3677         return 1;
3678         }
3679 # endif
3680 #endif