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