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