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