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