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