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