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