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