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