55f8f7b9a1c3006a49bc91dae19cb88743505282
[openssl.git] / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
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 #include <stdio.h>
152 #include "ssl_locl.h"
153 #include "kssl_lcl.h"
154 #include <openssl/buffer.h>
155 #include <openssl/rand.h>
156 #include <openssl/objects.h>
157 #include <openssl/evp.h>
158 #include <openssl/md5.h>
159 #ifdef OPENSSL_FIPS
160 #include <openssl/fips.h>
161 #endif
162 #ifndef OPENSSL_NO_DH
163 #include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #ifndef OPENSSL_NO_ENGINE
167 #include <openssl/engine.h>
168 #endif
169
170 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
171
172 #ifndef OPENSSL_NO_SSL3_METHOD
173 static const SSL_METHOD *ssl3_get_client_method(int ver)
174         {
175         if (ver == SSL3_VERSION)
176                 return(SSLv3_client_method());
177         else
178                 return(NULL);
179         }
180
181 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
182                         ssl_undefined_function,
183                         ssl3_connect,
184                         ssl3_get_client_method)
185 #endif
186
187 int ssl3_connect(SSL *s)
188         {
189         BUF_MEM *buf=NULL;
190         unsigned long Time=(unsigned long)time(NULL);
191         void (*cb)(const SSL *ssl,int type,int val)=NULL;
192         int ret= -1;
193         int new_state,state,skip=0;
194
195         RAND_add(&Time,sizeof(Time),0);
196         ERR_clear_error();
197         clear_sys_error();
198
199         if (s->info_callback != NULL)
200                 cb=s->info_callback;
201         else if (s->ctx->info_callback != NULL)
202                 cb=s->ctx->info_callback;
203         
204         s->in_handshake++;
205         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
206
207 #ifndef OPENSSL_NO_HEARTBEATS
208         /* If we're awaiting a HeartbeatResponse, pretend we
209          * already got and don't await it anymore, because
210          * Heartbeats don't make sense during handshakes anyway.
211          */
212         if (s->tlsext_hb_pending)
213                 {
214                 s->tlsext_hb_pending = 0;
215                 s->tlsext_hb_seq++;
216                 }
217 #endif
218
219         for (;;)
220                 {
221                 state=s->state;
222
223                 switch(s->state)
224                         {
225                 case SSL_ST_RENEGOTIATE:
226                         s->renegotiate=1;
227                         s->state=SSL_ST_CONNECT;
228                         s->ctx->stats.sess_connect_renegotiate++;
229                         /* break */
230                 case SSL_ST_BEFORE:
231                 case SSL_ST_CONNECT:
232                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
233                 case SSL_ST_OK|SSL_ST_CONNECT:
234
235                         s->server=0;
236                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
237
238                         if ((s->version & 0xff00 ) != 0x0300)
239                                 {
240                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
241                                 ret = -1;
242                                 goto end;
243                                 }
244
245                         if (!ssl_security(s, SSL_SECOP_VERSION, 0,
246                                                         s->version, NULL))
247                                 {
248                                 SSLerr(SSL_F_SSL3_CONNECT, SSL_R_VERSION_TOO_LOW);
249                                 return -1;
250                                 }
251                                 
252                         /* s->version=SSL3_VERSION; */
253                         s->type=SSL_ST_CONNECT;
254
255                         if (s->init_buf == NULL)
256                                 {
257                                 if ((buf=BUF_MEM_new()) == NULL)
258                                         {
259                                         ret= -1;
260                                         goto end;
261                                         }
262                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
263                                         {
264                                         ret= -1;
265                                         goto end;
266                                         }
267                                 s->init_buf=buf;
268                                 buf=NULL;
269                                 }
270
271                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
272
273                         /* setup buffing BIO */
274                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
275
276                         /* don't push the buffering BIO quite yet */
277
278                         ssl3_init_finished_mac(s);
279
280                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
281                         s->ctx->stats.sess_connect++;
282                         s->init_num=0;
283                         break;
284
285                 case SSL3_ST_CW_CLNT_HELLO_A:
286                 case SSL3_ST_CW_CLNT_HELLO_B:
287
288                         s->shutdown=0;
289                         ret=ssl3_client_hello(s);
290                         if (ret <= 0) goto end;
291                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
292                         s->init_num=0;
293
294                         /* turn on buffering for the next lot of output */
295                         if (s->bbio != s->wbio)
296                                 s->wbio=BIO_push(s->bbio,s->wbio);
297
298                         break;
299
300                 case SSL3_ST_CR_SRVR_HELLO_A:
301                 case SSL3_ST_CR_SRVR_HELLO_B:
302                         ret=ssl3_get_server_hello(s);
303                         if (ret <= 0) goto end;
304
305                         if (s->hit)
306                                 {
307                                 s->state=SSL3_ST_CR_FINISHED_A;
308 #ifndef OPENSSL_NO_TLSEXT
309                                 if (s->tlsext_ticket_expected)
310                                         {
311                                         /* receive renewed session ticket */
312                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
313                                         }
314 #endif
315                                 }
316                         else
317                                 {
318                                         s->state=SSL3_ST_CR_CERT_A;
319                                 }
320                         s->init_num=0;
321                         break;
322                 case SSL3_ST_CR_CERT_A:
323                 case SSL3_ST_CR_CERT_B:
324 #ifndef OPENSSL_NO_TLSEXT
325                         ret=ssl3_check_finished(s);
326                         if (ret <= 0) goto end;
327                         if (ret == 2)
328                                 {
329                                 s->hit = 1;
330                                 if (s->tlsext_ticket_expected)
331                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
332                                 else
333                                         s->state=SSL3_ST_CR_FINISHED_A;
334                                 s->init_num=0;
335                                 break;
336                                 }
337 #endif
338                         /* Check if it is anon DH/ECDH, SRP auth */
339                         /* or PSK */
340                         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) &&
341                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
342                                 {
343                                 ret=ssl3_get_server_certificate(s);
344                                 if (ret <= 0) goto end;
345 #ifndef OPENSSL_NO_TLSEXT
346                                 if (s->tlsext_status_expected)
347                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
348                                 else
349                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
350                                 }
351                         else
352                                 {
353                                 skip = 1;
354                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
355                                 }
356 #else
357                                 }
358                         else
359                                 skip=1;
360
361                         s->state=SSL3_ST_CR_KEY_EXCH_A;
362 #endif
363                         s->init_num=0;
364                         break;
365
366                 case SSL3_ST_CR_KEY_EXCH_A:
367                 case SSL3_ST_CR_KEY_EXCH_B:
368                         ret=ssl3_get_key_exchange(s);
369                         if (ret <= 0) goto end;
370                         s->state=SSL3_ST_CR_CERT_REQ_A;
371                         s->init_num=0;
372
373                         /* at this point we check that we have the
374                          * required stuff from the server */
375                         if (!ssl3_check_cert_and_algorithm(s))
376                                 {
377                                 ret= -1;
378                                 goto end;
379                                 }
380                         break;
381
382                 case SSL3_ST_CR_CERT_REQ_A:
383                 case SSL3_ST_CR_CERT_REQ_B:
384                         ret=ssl3_get_certificate_request(s);
385                         if (ret <= 0) goto end;
386                         s->state=SSL3_ST_CR_SRVR_DONE_A;
387                         s->init_num=0;
388                         break;
389
390                 case SSL3_ST_CR_SRVR_DONE_A:
391                 case SSL3_ST_CR_SRVR_DONE_B:
392                         ret=ssl3_get_server_done(s);
393                         if (ret <= 0) goto end;
394 #ifndef OPENSSL_NO_SRP
395                         if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
396                                 {
397                                 if ((ret = SRP_Calc_A_param(s))<=0)
398                                         {
399                                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
400                                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
401                                         goto end;
402                                         }
403                                 }
404 #endif
405                         if (s->s3->tmp.cert_req)
406                                 s->state=SSL3_ST_CW_CERT_A;
407                         else
408                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
409                         s->init_num=0;
410
411                         break;
412
413                 case SSL3_ST_CW_CERT_A:
414                 case SSL3_ST_CW_CERT_B:
415                 case SSL3_ST_CW_CERT_C:
416                 case SSL3_ST_CW_CERT_D:
417                         ret=ssl3_send_client_certificate(s);
418                         if (ret <= 0) goto end;
419                         s->state=SSL3_ST_CW_KEY_EXCH_A;
420                         s->init_num=0;
421                         break;
422
423                 case SSL3_ST_CW_KEY_EXCH_A:
424                 case SSL3_ST_CW_KEY_EXCH_B:
425                         ret=ssl3_send_client_key_exchange(s);
426                         if (ret <= 0) goto end;
427                         /* EAY EAY EAY need to check for DH fix cert
428                          * sent back */
429                         /* For TLS, cert_req is set to 2, so a cert chain
430                          * of nothing is sent, but no verify packet is sent */
431                         /* XXX: For now, we do not support client 
432                          * authentication in ECDH cipher suites with
433                          * ECDH (rather than ECDSA) certificates.
434                          * We need to skip the certificate verify 
435                          * message when client's ECDH public key is sent 
436                          * inside the client certificate.
437                          */
438                         if (s->s3->tmp.cert_req == 1)
439                                 {
440                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
441                                 }
442                         else
443                                 {
444                                 s->state=SSL3_ST_CW_CHANGE_A;
445                                 s->s3->change_cipher_spec=0;
446                                 }
447                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
448                                 {
449                                 s->state=SSL3_ST_CW_CHANGE_A;
450                                 s->s3->change_cipher_spec=0;
451                                 }
452
453                         s->init_num=0;
454                         break;
455
456                 case SSL3_ST_CW_CERT_VRFY_A:
457                 case SSL3_ST_CW_CERT_VRFY_B:
458                         ret=ssl3_send_client_verify(s);
459                         if (ret <= 0) goto end;
460                         s->state=SSL3_ST_CW_CHANGE_A;
461                         s->init_num=0;
462                         s->s3->change_cipher_spec=0;
463                         break;
464
465                 case SSL3_ST_CW_CHANGE_A:
466                 case SSL3_ST_CW_CHANGE_B:
467                         ret=ssl3_send_change_cipher_spec(s,
468                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
469                         if (ret <= 0) goto end;
470
471 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
472                         s->state=SSL3_ST_CW_FINISHED_A;
473 #else
474                         if (s->s3->next_proto_neg_seen)
475                                 s->state=SSL3_ST_CW_NEXT_PROTO_A;
476                         else
477                                 s->state=SSL3_ST_CW_FINISHED_A;
478 #endif
479                         s->init_num=0;
480
481                         s->session->cipher=s->s3->tmp.new_cipher;
482 #ifdef OPENSSL_NO_COMP
483                         s->session->compress_meth=0;
484 #else
485                         if (s->s3->tmp.new_compression == NULL)
486                                 s->session->compress_meth=0;
487                         else
488                                 s->session->compress_meth=
489                                         s->s3->tmp.new_compression->id;
490 #endif
491                         if (!s->method->ssl3_enc->setup_key_block(s))
492                                 {
493                                 ret= -1;
494                                 goto end;
495                                 }
496
497                         if (!s->method->ssl3_enc->change_cipher_state(s,
498                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
499                                 {
500                                 ret= -1;
501                                 goto end;
502                                 }
503
504                         break;
505
506 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
507                 case SSL3_ST_CW_NEXT_PROTO_A:
508                 case SSL3_ST_CW_NEXT_PROTO_B:
509                         ret=ssl3_send_next_proto(s);
510                         if (ret <= 0) goto end;
511                         s->state=SSL3_ST_CW_FINISHED_A;
512                         break;
513 #endif
514
515                 case SSL3_ST_CW_FINISHED_A:
516                 case SSL3_ST_CW_FINISHED_B:
517                         ret=ssl3_send_finished(s,
518                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
519                                 s->method->ssl3_enc->client_finished_label,
520                                 s->method->ssl3_enc->client_finished_label_len);
521                         if (ret <= 0) goto end;
522                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
523                         s->state=SSL3_ST_CW_FLUSH;
524
525                         /* clear flags */
526                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
527                         if (s->hit)
528                                 {
529                                 s->s3->tmp.next_state=SSL_ST_OK;
530                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
531                                         {
532                                         s->state=SSL_ST_OK;
533                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
534                                         s->s3->delay_buf_pop_ret=0;
535                                         }
536                                 }
537                         else
538                                 {
539 #ifndef OPENSSL_NO_TLSEXT
540                                 /* Allow NewSessionTicket if ticket expected */
541                                 if (s->tlsext_ticket_expected)
542                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
543                                 else
544 #endif
545                                 
546                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
547                                 }
548                         s->init_num=0;
549                         break;
550
551 #ifndef OPENSSL_NO_TLSEXT
552                 case SSL3_ST_CR_SESSION_TICKET_A:
553                 case SSL3_ST_CR_SESSION_TICKET_B:
554                         ret=ssl3_get_new_session_ticket(s);
555                         if (ret <= 0) goto end;
556                         s->state=SSL3_ST_CR_FINISHED_A;
557                         s->init_num=0;
558                 break;
559
560                 case SSL3_ST_CR_CERT_STATUS_A:
561                 case SSL3_ST_CR_CERT_STATUS_B:
562                         ret=ssl3_get_cert_status(s);
563                         if (ret <= 0) goto end;
564                         s->state=SSL3_ST_CR_KEY_EXCH_A;
565                         s->init_num=0;
566                 break;
567 #endif
568
569                 case SSL3_ST_CR_FINISHED_A:
570                 case SSL3_ST_CR_FINISHED_B:
571
572                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
573                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
574                                 SSL3_ST_CR_FINISHED_B);
575                         if (ret <= 0) goto end;
576
577                         if (s->hit)
578                                 s->state=SSL3_ST_CW_CHANGE_A;
579                         else
580                                 s->state=SSL_ST_OK;
581                         s->init_num=0;
582                         break;
583
584                 case SSL3_ST_CW_FLUSH:
585                         s->rwstate=SSL_WRITING;
586                         if (BIO_flush(s->wbio) <= 0)
587                                 {
588                                 ret= -1;
589                                 goto end;
590                                 }
591                         s->rwstate=SSL_NOTHING;
592                         s->state=s->s3->tmp.next_state;
593                         break;
594
595                 case SSL_ST_OK:
596                         /* clean a few things up */
597                         ssl3_cleanup_key_block(s);
598
599                         if (s->init_buf != NULL)
600                                 {
601                                 BUF_MEM_free(s->init_buf);
602                                 s->init_buf=NULL;
603                                 }
604
605                         /* If we are not 'joining' the last two packets,
606                          * remove the buffering now */
607                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
608                                 ssl_free_wbio_buffer(s);
609                         /* else do it later in ssl3_write */
610
611                         s->init_num=0;
612                         s->renegotiate=0;
613                         s->new_session=0;
614
615                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
616                         if (s->hit) s->ctx->stats.sess_hit++;
617
618                         ret=1;
619                         /* s->server=0; */
620                         s->handshake_func=ssl3_connect;
621                         s->ctx->stats.sess_connect_good++;
622
623                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
624
625                         goto end;
626                         /* break; */
627                         
628                 default:
629                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
630                         ret= -1;
631                         goto end;
632                         /* break; */
633                         }
634
635                 /* did we do anything */
636                 if (!s->s3->tmp.reuse_message && !skip)
637                         {
638                         if (s->debug)
639                                 {
640                                 if ((ret=BIO_flush(s->wbio)) <= 0)
641                                         goto end;
642                                 }
643
644                         if ((cb != NULL) && (s->state != state))
645                                 {
646                                 new_state=s->state;
647                                 s->state=state;
648                                 cb(s,SSL_CB_CONNECT_LOOP,1);
649                                 s->state=new_state;
650                                 }
651                         }
652                 skip=0;
653                 }
654 end:
655         s->in_handshake--;
656         if (buf != NULL)
657                 BUF_MEM_free(buf);
658         if (cb != NULL)
659                 cb(s,SSL_CB_CONNECT_EXIT,ret);
660         return(ret);
661         }
662
663
664 int ssl3_client_hello(SSL *s)
665         {
666         unsigned char *buf;
667         unsigned char *p,*d;
668         int i;
669         unsigned long l;
670         int al = 0;
671 #ifndef OPENSSL_NO_COMP
672         int j;
673         SSL_COMP *comp;
674 #endif
675
676         buf=(unsigned char *)s->init_buf->data;
677         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
678                 {
679                 SSL_SESSION *sess = s->session;
680                 if ((sess == NULL) ||
681                         (sess->ssl_version != s->version) ||
682 #ifdef OPENSSL_NO_TLSEXT
683                         !sess->session_id_length ||
684 #else
685                         (!sess->session_id_length && !sess->tlsext_tick) ||
686 #endif
687                         (sess->not_resumable))
688                         {
689                         if (!ssl_get_new_session(s,0))
690                                 goto err;
691                         }
692                 if (s->method->version == DTLS_ANY_VERSION)
693                         {
694                         /* Determine which DTLS version to use */
695                         int options = s->options;
696                         /* If DTLS 1.2 disabled correct the version number */
697                         if (options & SSL_OP_NO_DTLSv1_2)
698                                 {
699                                 if (tls1_suiteb(s))
700                                         {
701                                         SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
702                                         goto err;
703                                         }
704                                 /* Disabling all versions is silly: return an
705                                  * error.
706                                  */
707                                 if (options & SSL_OP_NO_DTLSv1)
708                                         {
709                                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_WRONG_SSL_VERSION);
710                                         goto err;
711                                         }
712                                 /* Update method so we don't use any DTLS 1.2
713                                  * features.
714                                  */
715                                 s->method = DTLSv1_client_method();
716                                 s->version = DTLS1_VERSION;
717                                 }
718                         else
719                                 {
720                                 /* We only support one version: update method */
721                                 if (options & SSL_OP_NO_DTLSv1)
722                                         s->method = DTLSv1_2_client_method();
723                                 s->version = DTLS1_2_VERSION;
724                                 }
725                         s->client_version = s->version;
726                         }
727                 /* else use the pre-loaded session */
728
729                 p=s->s3->client_random;
730
731                 /* for DTLS if client_random is initialized, reuse it, we are
732                  * required to use same upon reply to HelloVerify */
733                 if (SSL_IS_DTLS(s))
734                         {
735                         size_t idx;
736                         i = 1;
737                         for (idx=0; idx < sizeof(s->s3->client_random); idx++)
738                                 {
739                                 if (p[idx])
740                                         {
741                                         i = 0;
742                                         break;
743                                         }
744                                 }
745                         }
746                 else 
747                         i = 1;
748
749                 if (i)
750                         ssl_fill_hello_random(s, 0, p,
751                                               sizeof(s->s3->client_random));
752
753                 /* Do the message type and length last */
754                 d=p= ssl_handshake_start(s);
755
756                 /* version indicates the negotiated version: for example from
757                  * an SSLv2/v3 compatible client hello). The client_version
758                  * field is the maximum version we permit and it is also
759                  * used in RSA encrypted premaster secrets. Some servers can
760                  * choke if we initially report a higher version then
761                  * renegotiate to a lower one in the premaster secret. This
762                  * didn't happen with TLS 1.0 as most servers supported it
763                  * but it can with TLS 1.1 or later if the server only supports
764                  * 1.0.
765                  *
766                  * Possible scenario with previous logic:
767                  *      1. Client hello indicates TLS 1.2
768                  *      2. Server hello says TLS 1.0
769                  *      3. RSA encrypted premaster secret uses 1.2.
770                  *      4. Handhaked proceeds using TLS 1.0.
771                  *      5. Server sends hello request to renegotiate.
772                  *      6. Client hello indicates TLS v1.0 as we now
773                  *         know that is maximum server supports.
774                  *      7. Server chokes on RSA encrypted premaster secret
775                  *         containing version 1.0.
776                  *
777                  * For interoperability it should be OK to always use the
778                  * maximum version we support in client hello and then rely
779                  * on the checking of version to ensure the servers isn't
780                  * being inconsistent: for example initially negotiating with
781                  * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
782                  * client_version in client hello and not resetting it to
783                  * the negotiated version.
784                  */
785 #if 0
786                 *(p++)=s->version>>8;
787                 *(p++)=s->version&0xff;
788                 s->client_version=s->version;
789 #else
790                 *(p++)=s->client_version>>8;
791                 *(p++)=s->client_version&0xff;
792 #endif
793
794                 /* Random stuff */
795                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
796                 p+=SSL3_RANDOM_SIZE;
797
798                 /* Session ID */
799                 if (s->new_session)
800                         i=0;
801                 else
802                         i=s->session->session_id_length;
803                 *(p++)=i;
804                 if (i != 0)
805                         {
806                         if (i > (int)sizeof(s->session->session_id))
807                                 {
808                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
809                                 goto err;
810                                 }
811                         memcpy(p,s->session->session_id,i);
812                         p+=i;
813                         }
814                 
815                 /* cookie stuff for DTLS */
816                 if (SSL_IS_DTLS(s))
817                         {
818                         if ( s->d1->cookie_len > sizeof(s->d1->cookie))
819                                 {
820                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
821                                 goto err;
822                                 }
823                         *(p++) = s->d1->cookie_len;
824                         memcpy(p, s->d1->cookie, s->d1->cookie_len);
825                         p += s->d1->cookie_len;
826                         }
827                 
828                 /* Ciphers supported */
829                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
830                 if (i == 0)
831                         {
832                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
833                         goto err;
834                         }
835 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
836                         /* Some servers hang if client hello > 256 bytes
837                          * as hack workaround chop number of supported ciphers
838                          * to keep it well below this if we use TLS v1.2
839                          */
840                         if (TLS1_get_version(s) >= TLS1_2_VERSION
841                                 && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
842                                 i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
843 #endif
844                 s2n(i,p);
845                 p+=i;
846
847                 /* COMPRESSION */
848 #ifdef OPENSSL_NO_COMP
849                 *(p++)=1;
850 #else
851
852                 if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
853                         j=0;
854                 else
855                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
856                 *(p++)=1+j;
857                 for (i=0; i<j; i++)
858                         {
859                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
860                         *(p++)=comp->id;
861                         }
862 #endif
863                 *(p++)=0; /* Add the NULL method */
864
865 #ifndef OPENSSL_NO_TLSEXT
866                 /* TLS extensions*/
867                 if (ssl_prepare_clienthello_tlsext(s) <= 0)
868                         {
869                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
870                         goto err;
871                         }
872                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
873                         {
874                         ssl3_send_alert(s,SSL3_AL_FATAL,al);
875                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
876                         goto err;
877                         }
878 #endif
879                 
880                 l= p-d;
881                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
882                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
883                 }
884
885         /* SSL3_ST_CW_CLNT_HELLO_B */
886         return ssl_do_write(s);
887 err:
888         return(-1);
889         }
890
891 int ssl3_get_server_hello(SSL *s)
892         {
893         STACK_OF(SSL_CIPHER) *sk;
894         const SSL_CIPHER *c;
895         CERT *ct = s->cert;
896         unsigned char *p,*d;
897         int i,al=SSL_AD_INTERNAL_ERROR,ok;
898         unsigned int j;
899         long n;
900 #ifndef OPENSSL_NO_COMP
901         SSL_COMP *comp;
902 #endif
903         /* Hello verify request and/or server hello version may not
904          * match so set first packet if we're negotiating version.
905          */
906         if (SSL_IS_DTLS(s))
907                 s->first_packet = 1;
908
909         n=s->method->ssl_get_message(s,
910                 SSL3_ST_CR_SRVR_HELLO_A,
911                 SSL3_ST_CR_SRVR_HELLO_B,
912                 -1,
913                 20000, /* ?? */
914                 &ok);
915
916         if (!ok) return((int)n);
917
918         if (SSL_IS_DTLS(s))
919                 {
920                 s->first_packet = 0;
921                 if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
922                         {
923                         if ( s->d1->send_cookie == 0)
924                                 {
925                                 s->s3->tmp.reuse_message = 1;
926                                 return 1;
927                                 }
928                         else /* already sent a cookie */
929                                 {
930                                 al=SSL_AD_UNEXPECTED_MESSAGE;
931                                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
932                                 goto f_err;
933                                 }
934                         }
935                 }
936         
937         if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
938                 {
939                 al=SSL_AD_UNEXPECTED_MESSAGE;
940                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
941                 goto f_err;
942                 }
943
944         d=p=(unsigned char *)s->init_msg;
945         if (s->method->version == DTLS_ANY_VERSION)
946                 {
947                 /* Work out correct protocol version to use */
948                 int hversion = (p[0] << 8)|p[1];
949                 int options = s->options;
950                 if (hversion == DTLS1_2_VERSION
951                         && !(options & SSL_OP_NO_DTLSv1_2))
952                         s->method = DTLSv1_2_client_method();
953                 else if (tls1_suiteb(s))
954                         {
955                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
956                         s->version = hversion;
957                         al = SSL_AD_PROTOCOL_VERSION;
958                         goto f_err;
959                         }
960                 else if (hversion == DTLS1_VERSION
961                         && !(options & SSL_OP_NO_DTLSv1))
962                         s->method = DTLSv1_client_method();
963                 else
964                         {
965                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
966                         s->version = hversion;
967                         al = SSL_AD_PROTOCOL_VERSION;
968                         goto f_err;
969                         }
970                 s->version = s->client_version = s->method->version;
971                 }
972
973         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
974                 {
975                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
976                 s->version=(s->version&0xff00)|p[1];
977                 al=SSL_AD_PROTOCOL_VERSION;
978                 goto f_err;
979                 }
980         p+=2;
981
982         /* load the server hello data */
983         /* load the server random */
984         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
985         p+=SSL3_RANDOM_SIZE;
986
987         s->hit = 0;
988
989         /* get the session-id */
990         j= *(p++);
991
992         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
993                 {
994                 al=SSL_AD_ILLEGAL_PARAMETER;
995                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
996                 goto f_err;
997                 }
998
999 #ifndef OPENSSL_NO_TLSEXT
1000         /* check if we want to resume the session based on external pre-shared secret */
1001         if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1002                 {
1003                 SSL_CIPHER *pref_cipher=NULL;
1004                 s->session->master_key_length=sizeof(s->session->master_key);
1005                 if (s->tls_session_secret_cb(s, s->session->master_key,
1006                                              &s->session->master_key_length,
1007                                              NULL, &pref_cipher,
1008                                              s->tls_session_secret_cb_arg))
1009                         {
1010                         s->session->cipher = pref_cipher ?
1011                                 pref_cipher : ssl_get_cipher_by_char(s, p+j);
1012                         s->hit = 1;
1013                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
1014                         }
1015                 }
1016 #endif /* OPENSSL_NO_TLSEXT */
1017
1018         if (!s->hit && j != 0 && j == s->session->session_id_length
1019             && memcmp(p,s->session->session_id,j) == 0)
1020             {
1021             if(s->sid_ctx_length != s->session->sid_ctx_length
1022                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
1023                 {
1024                 /* actually a client application bug */
1025                 al=SSL_AD_ILLEGAL_PARAMETER;
1026                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1027                 goto f_err;
1028                 }
1029             s->s3->flags |= SSL3_FLAGS_CCS_OK;
1030             s->hit=1;
1031             }
1032         /* a miss or crap from the other end */
1033         if (!s->hit)
1034                 {
1035                 /* If we were trying for session-id reuse, make a new
1036                  * SSL_SESSION so we don't stuff up other people */
1037                 if (s->session->session_id_length > 0)
1038                         {
1039                         if (!ssl_get_new_session(s,0))
1040                                 {
1041                                 goto f_err;
1042                                 }
1043                         }
1044                 s->session->session_id_length=j;
1045                 memcpy(s->session->session_id,p,j); /* j could be 0 */
1046                 }
1047         p+=j;
1048         c=ssl_get_cipher_by_char(s,p);
1049         if (c == NULL)
1050                 {
1051                 /* unknown cipher */
1052                 al=SSL_AD_ILLEGAL_PARAMETER;
1053                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
1054                 goto f_err;
1055                 }
1056         /* Set version disabled mask now we know version */
1057         if (!SSL_USE_TLS1_2_CIPHERS(s))
1058                 ct->mask_ssl = SSL_TLSV1_2;
1059         else
1060                 ct->mask_ssl = 0;
1061         /* If it is a disabled cipher we didn't send it in client hello,
1062          * so return an error.
1063          */
1064         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK))
1065                 {
1066                 al=SSL_AD_ILLEGAL_PARAMETER;
1067                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
1068                 goto f_err;
1069                 }
1070         p+=ssl_put_cipher_by_char(s,NULL,NULL);
1071
1072         sk=ssl_get_ciphers_by_id(s);
1073         i=sk_SSL_CIPHER_find(sk,c);
1074         if (i < 0)
1075                 {
1076                 /* we did not say we would use this cipher */
1077                 al=SSL_AD_ILLEGAL_PARAMETER;
1078                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
1079                 goto f_err;
1080                 }
1081
1082         /* Depending on the session caching (internal/external), the cipher
1083            and/or cipher_id values may not be set. Make sure that
1084            cipher_id is set and use it for comparison. */
1085         if (s->session->cipher)
1086                 s->session->cipher_id = s->session->cipher->id;
1087         if (s->hit && (s->session->cipher_id != c->id))
1088                 {
1089 /* Workaround is now obsolete */
1090 #if 0
1091                 if (!(s->options &
1092                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
1093 #endif
1094                         {
1095                         al=SSL_AD_ILLEGAL_PARAMETER;
1096                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1097                         goto f_err;
1098                         }
1099                 }
1100         s->s3->tmp.new_cipher=c;
1101         /* Don't digest cached records if no sigalgs: we may need them for
1102          * client authentication.
1103          */
1104         if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s))
1105                 goto f_err;
1106         /* lets get the compression algorithm */
1107         /* COMPRESSION */
1108 #ifdef OPENSSL_NO_COMP
1109         if (*(p++) != 0)
1110                 {
1111                 al=SSL_AD_ILLEGAL_PARAMETER;
1112                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1113                 goto f_err;
1114                 }
1115         /* If compression is disabled we'd better not try to resume a session
1116          * using compression.
1117          */
1118         if (s->session->compress_meth != 0)
1119                 {
1120                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1121                 goto f_err;
1122                 }
1123 #else
1124         j= *(p++);
1125         if (s->hit && j != s->session->compress_meth)
1126                 {
1127                 al=SSL_AD_ILLEGAL_PARAMETER;
1128                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1129                 goto f_err;
1130                 }
1131         if (j == 0)
1132                 comp=NULL;
1133         else if (!ssl_allow_compression(s))
1134                 {
1135                 al=SSL_AD_ILLEGAL_PARAMETER;
1136                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
1137                 goto f_err;
1138                 }
1139         else
1140                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
1141         
1142         if ((j != 0) && (comp == NULL))
1143                 {
1144                 al=SSL_AD_ILLEGAL_PARAMETER;
1145                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1146                 goto f_err;
1147                 }
1148         else
1149                 {
1150                 s->s3->tmp.new_compression=comp;
1151                 }
1152 #endif
1153
1154 #ifndef OPENSSL_NO_TLSEXT
1155         /* TLS extensions*/
1156         if (!ssl_parse_serverhello_tlsext(s,&p,d,n))
1157                 {
1158                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
1159                 goto err; 
1160                 }
1161 #endif
1162
1163         if (p != (d+n))
1164                 {
1165                 /* wrong packet length */
1166                 al=SSL_AD_DECODE_ERROR;
1167                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
1168                 goto f_err;
1169                 }
1170
1171         return(1);
1172 f_err:
1173         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1174 err:
1175         return(-1);
1176         }
1177
1178 int ssl3_get_server_certificate(SSL *s)
1179         {
1180         int al,i,ok,ret= -1;
1181         unsigned long n,nc,llen,l;
1182         X509 *x=NULL;
1183         const unsigned char *q,*p;
1184         unsigned char *d;
1185         STACK_OF(X509) *sk=NULL;
1186         SESS_CERT *sc;
1187         EVP_PKEY *pkey=NULL;
1188         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
1189
1190         n=s->method->ssl_get_message(s,
1191                 SSL3_ST_CR_CERT_A,
1192                 SSL3_ST_CR_CERT_B,
1193                 -1,
1194                 s->max_cert_list,
1195                 &ok);
1196
1197         if (!ok) return((int)n);
1198
1199         if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1200                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && 
1201                 (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)))
1202                 {
1203                 s->s3->tmp.reuse_message=1;
1204                 return(1);
1205                 }
1206
1207         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1208                 {
1209                 al=SSL_AD_UNEXPECTED_MESSAGE;
1210                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
1211                 goto f_err;
1212                 }
1213         p=d=(unsigned char *)s->init_msg;
1214
1215         if ((sk=sk_X509_new_null()) == NULL)
1216                 {
1217                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1218                 goto err;
1219                 }
1220
1221         n2l3(p,llen);
1222         if (llen+3 != n)
1223                 {
1224                 al=SSL_AD_DECODE_ERROR;
1225                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1226                 goto f_err;
1227                 }
1228         for (nc=0; nc<llen; )
1229                 {
1230                 n2l3(p,l);
1231                 if ((l+nc+3) > llen)
1232                         {
1233                         al=SSL_AD_DECODE_ERROR;
1234                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1235                         goto f_err;
1236                         }
1237
1238                 q=p;
1239                 x=d2i_X509(NULL,&q,l);
1240                 if (x == NULL)
1241                         {
1242                         al=SSL_AD_BAD_CERTIFICATE;
1243                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
1244                         goto f_err;
1245                         }
1246                 if (q != (p+l))
1247                         {
1248                         al=SSL_AD_DECODE_ERROR;
1249                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1250                         goto f_err;
1251                         }
1252                 if (!sk_X509_push(sk,x))
1253                         {
1254                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1255                         goto err;
1256                         }
1257                 x=NULL;
1258                 nc+=l+3;
1259                 p=q;
1260                 }
1261
1262         i=ssl_verify_cert_chain(s,sk);
1263         if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1264 #ifndef OPENSSL_NO_KRB5
1265             && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1266                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1267 #endif /* OPENSSL_NO_KRB5 */
1268                 )
1269                 {
1270                 al=ssl_verify_alarm_type(s->verify_result);
1271                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1272                 goto f_err; 
1273                 }
1274         ERR_clear_error(); /* but we keep s->verify_result */
1275         if (i > 1)
1276                 {
1277                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, i);
1278                 al = SSL_AD_HANDSHAKE_FAILURE;
1279                 goto f_err;
1280                 }
1281
1282         sc=ssl_sess_cert_new();
1283         if (sc == NULL) goto err;
1284
1285         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1286         s->session->sess_cert=sc;
1287
1288         sc->cert_chain=sk;
1289         /* Inconsistency alert: cert_chain does include the peer's
1290          * certificate, which we don't include in s3_srvr.c */
1291         x=sk_X509_value(sk,0);
1292         sk=NULL;
1293         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1294
1295         pkey=X509_get_pubkey(x);
1296
1297         /* VRS: allow null cert if auth == KRB5 */
1298         need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1299                     (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1300                     ? 0 : 1;
1301
1302 #ifdef KSSL_DEBUG
1303         printf("pkey,x = %p, %p\n", pkey,x);
1304         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
1305         printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
1306                 s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1307 #endif    /* KSSL_DEBUG */
1308
1309         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
1310                 {
1311                 x=NULL;
1312                 al=SSL3_AL_FATAL;
1313                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1314                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1315                 goto f_err;
1316                 }
1317
1318         i=ssl_cert_type(x,pkey);
1319         if (need_cert && i < 0)
1320                 {
1321                 x=NULL;
1322                 al=SSL3_AL_FATAL;
1323                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1324                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1325                 goto f_err;
1326                 }
1327
1328         if (need_cert)
1329                 {
1330                 int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1331                 if (exp_idx >= 0 && i != exp_idx)
1332                         {
1333                         x=NULL;
1334                         al=SSL_AD_ILLEGAL_PARAMETER;
1335                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1336                                 SSL_R_WRONG_CERTIFICATE_TYPE);
1337                         goto f_err;
1338                         }
1339                 sc->peer_cert_type=i;
1340                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1341                 /* Why would the following ever happen?
1342                  * We just created sc a couple of lines ago. */
1343                 if (sc->peer_pkeys[i].x509 != NULL)
1344                         X509_free(sc->peer_pkeys[i].x509);
1345                 sc->peer_pkeys[i].x509=x;
1346                 sc->peer_key= &(sc->peer_pkeys[i]);
1347
1348                 if (s->session->peer != NULL)
1349                         X509_free(s->session->peer);
1350                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1351                 s->session->peer=x;
1352                 }
1353         else
1354                 {
1355                 sc->peer_cert_type=i;
1356                 sc->peer_key= NULL;
1357
1358                 if (s->session->peer != NULL)
1359                         X509_free(s->session->peer);
1360                 s->session->peer=NULL;
1361                 }
1362         s->session->verify_result = s->verify_result;
1363
1364         x=NULL;
1365         ret=1;
1366         if (0)
1367                 {
1368 f_err:
1369                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1370                 }
1371 err:
1372         EVP_PKEY_free(pkey);
1373         X509_free(x);
1374         sk_X509_pop_free(sk,X509_free);
1375         return(ret);
1376         }
1377
1378 int ssl3_get_key_exchange(SSL *s)
1379         {
1380 #ifndef OPENSSL_NO_RSA
1381         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
1382 #endif
1383         EVP_MD_CTX md_ctx;
1384         unsigned char *param,*p;
1385         int al,j,ok;
1386         long i,param_len,n,alg_k,alg_a;
1387         EVP_PKEY *pkey=NULL;
1388         const EVP_MD *md = NULL;
1389 #ifndef OPENSSL_NO_RSA
1390         RSA *rsa=NULL;
1391 #endif
1392 #ifndef OPENSSL_NO_DH
1393         DH *dh=NULL;
1394 #endif
1395 #ifndef OPENSSL_NO_ECDH
1396         EC_KEY *ecdh = NULL;
1397         BN_CTX *bn_ctx = NULL;
1398         EC_POINT *srvr_ecpoint = NULL;
1399         int curve_nid = 0;
1400         int encoded_pt_len = 0;
1401 #endif
1402
1403         /* use same message size as in ssl3_get_certificate_request()
1404          * as ServerKeyExchange message may be skipped */
1405         n=s->method->ssl_get_message(s,
1406                 SSL3_ST_CR_KEY_EXCH_A,
1407                 SSL3_ST_CR_KEY_EXCH_B,
1408                 -1,
1409                 s->max_cert_list,
1410                 &ok);
1411         if (!ok) return((int)n);
1412
1413         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1414                 {
1415 #ifndef OPENSSL_NO_PSK
1416                 /* In plain PSK ciphersuite, ServerKeyExchange can be
1417                    omitted if no identity hint is sent. Set
1418                    session->sess_cert anyway to avoid problems
1419                    later.*/
1420                 if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
1421                         {
1422                         s->session->sess_cert=ssl_sess_cert_new();
1423                         if (s->ctx->psk_identity_hint)
1424                                 OPENSSL_free(s->ctx->psk_identity_hint);
1425                         s->ctx->psk_identity_hint = NULL;
1426                         }
1427 #endif
1428                 s->s3->tmp.reuse_message=1;
1429                 return(1);
1430                 }
1431
1432         param=p=(unsigned char *)s->init_msg;
1433         if (s->session->sess_cert != NULL)
1434                 {
1435 #ifndef OPENSSL_NO_RSA
1436                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1437                         {
1438                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1439                         s->session->sess_cert->peer_rsa_tmp=NULL;
1440                         }
1441 #endif
1442 #ifndef OPENSSL_NO_DH
1443                 if (s->session->sess_cert->peer_dh_tmp)
1444                         {
1445                         DH_free(s->session->sess_cert->peer_dh_tmp);
1446                         s->session->sess_cert->peer_dh_tmp=NULL;
1447                         }
1448 #endif
1449 #ifndef OPENSSL_NO_ECDH
1450                 if (s->session->sess_cert->peer_ecdh_tmp)
1451                         {
1452                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1453                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1454                         }
1455 #endif
1456                 }
1457         else
1458                 {
1459                 s->session->sess_cert=ssl_sess_cert_new();
1460                 }
1461
1462         /* Total length of the parameters including the length prefix */
1463         param_len=0;
1464
1465         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1466         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1467         EVP_MD_CTX_init(&md_ctx);
1468
1469         al=SSL_AD_DECODE_ERROR;
1470
1471 #ifndef OPENSSL_NO_PSK
1472         if (alg_k & SSL_kPSK)
1473                 {
1474                 char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
1475
1476                 param_len = 2;
1477                 if (param_len > n)
1478                         {
1479                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1480                                 SSL_R_LENGTH_TOO_SHORT);
1481                         goto f_err;
1482                         }
1483                 n2s(p,i);
1484
1485                 /* Store PSK identity hint for later use, hint is used
1486                  * in ssl3_send_client_key_exchange.  Assume that the
1487                  * maximum length of a PSK identity hint can be as
1488                  * long as the maximum length of a PSK identity. */
1489                 if (i > PSK_MAX_IDENTITY_LEN)
1490                         {
1491                         al=SSL_AD_HANDSHAKE_FAILURE;
1492                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1493                                 SSL_R_DATA_LENGTH_TOO_LONG);
1494                         goto f_err;
1495                         }
1496                 if (i > n - param_len)
1497                         {
1498                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1499                                 SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1500                         goto f_err;
1501                         }
1502                 param_len += i;
1503
1504                 /* If received PSK identity hint contains NULL
1505                  * characters, the hint is truncated from the first
1506                  * NULL. p may not be ending with NULL, so create a
1507                  * NULL-terminated string. */
1508                 memcpy(tmp_id_hint, p, i);
1509                 memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1510                 if (s->ctx->psk_identity_hint != NULL)
1511                         OPENSSL_free(s->ctx->psk_identity_hint);
1512                 s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1513                 if (s->ctx->psk_identity_hint == NULL)
1514                         {
1515                         al=SSL_AD_HANDSHAKE_FAILURE;
1516                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1517                         goto f_err;
1518                         }          
1519
1520                 p+=i;
1521                 n-=param_len;
1522                 }
1523         else
1524 #endif /* !OPENSSL_NO_PSK */
1525 #ifndef OPENSSL_NO_SRP
1526         if (alg_k & SSL_kSRP)
1527                 {
1528                 param_len = 2;
1529                 if (param_len > n)
1530                         {
1531                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1532                                 SSL_R_LENGTH_TOO_SHORT);
1533                         goto f_err;
1534                         }
1535                 n2s(p,i);
1536
1537                 if (i > n - param_len)
1538                         {
1539                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
1540                         goto f_err;
1541                         }
1542                 param_len += i;
1543
1544                 if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
1545                         {
1546                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1547                         goto err;
1548                         }
1549                 p+=i;
1550
1551
1552                 if (2 > n - param_len)
1553                         {
1554                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1555                                 SSL_R_LENGTH_TOO_SHORT);
1556                         goto f_err;
1557                         }
1558                 param_len += 2;
1559
1560                 n2s(p,i);
1561
1562                 if (i > n - param_len)
1563                         {
1564                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
1565                         goto f_err;
1566                         }
1567                 param_len += i;
1568
1569                 if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
1570                         {
1571                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1572                         goto err;
1573                         }
1574                 p+=i;
1575
1576
1577                 if (1 > n - param_len)
1578                         {
1579                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1580                                 SSL_R_LENGTH_TOO_SHORT);
1581                         goto f_err;
1582                         }
1583                 param_len += 1;
1584
1585                 i = (unsigned int)(p[0]);
1586                 p++;
1587
1588                 if (i > n - param_len)
1589                         {
1590                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
1591                         goto f_err;
1592                         }
1593                 param_len += i;
1594
1595                 if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
1596                         {
1597                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1598                         goto err;
1599                         }
1600                 p+=i;
1601
1602                 if (2 > n - param_len)
1603                         {
1604                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1605                                 SSL_R_LENGTH_TOO_SHORT);
1606                         goto f_err;
1607                         }
1608                 param_len += 2;
1609
1610                 n2s(p,i);
1611
1612                 if (i > n - param_len)
1613                         {
1614                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
1615                         goto f_err;
1616                         }
1617                 param_len += i;
1618
1619                 if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
1620                         {
1621                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1622                         goto err;
1623                         }
1624                 p+=i;
1625                 n-=param_len;
1626
1627                 if (!srp_verify_server_param(s, &al))
1628                         {
1629                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
1630                         goto f_err;
1631                         }
1632
1633 /* We must check if there is a certificate */
1634 #ifndef OPENSSL_NO_RSA
1635                 if (alg_a & SSL_aRSA)
1636                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1637 #else
1638                 if (0)
1639                         ;
1640 #endif
1641 #ifndef OPENSSL_NO_DSA
1642                 else if (alg_a & SSL_aDSS)
1643                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1644 #endif
1645                 }
1646         else
1647 #endif /* !OPENSSL_NO_SRP */
1648 #ifndef OPENSSL_NO_RSA
1649         if (alg_k & SSL_kRSA)
1650                 {
1651                 if ((rsa=RSA_new()) == NULL)
1652                         {
1653                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1654                         goto err;
1655                         }
1656
1657                 param_len = 2;
1658                 if (param_len > n)
1659                         {
1660                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1661                                 SSL_R_LENGTH_TOO_SHORT);
1662                         goto f_err;
1663                         }
1664                 n2s(p,i);
1665
1666                 if (i > n - param_len)
1667                         {
1668                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1669                         goto f_err;
1670                         }
1671                 param_len += i;
1672
1673                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1674                         {
1675                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1676                         goto err;
1677                         }
1678                 p+=i;
1679
1680                 if (2 > n - param_len)
1681                         {
1682                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1683                                 SSL_R_LENGTH_TOO_SHORT);
1684                         goto f_err;
1685                         }
1686                 param_len += 2;
1687
1688                 n2s(p,i);
1689
1690                 if (i > n - param_len)
1691                         {
1692                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1693                         goto f_err;
1694                         }
1695                 param_len += i;
1696
1697                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1698                         {
1699                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1700                         goto err;
1701                         }
1702                 p+=i;
1703                 n-=param_len;
1704
1705                 /* this should be because we are using an export cipher */
1706                 if (alg_a & SSL_aRSA)
1707                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1708                 else
1709                         {
1710                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1711                         goto err;
1712                         }
1713                 s->session->sess_cert->peer_rsa_tmp=rsa;
1714                 rsa=NULL;
1715                 }
1716 #else /* OPENSSL_NO_RSA */
1717         if (0)
1718                 ;
1719 #endif
1720 #ifndef OPENSSL_NO_DH
1721         else if (alg_k & SSL_kDHE)
1722                 {
1723                 if ((dh=DH_new()) == NULL)
1724                         {
1725                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1726                         goto err;
1727                         }
1728
1729                 param_len = 2;
1730                 if (param_len > n)
1731                         {
1732                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1733                                 SSL_R_LENGTH_TOO_SHORT);
1734                         goto f_err;
1735                         }
1736                 n2s(p,i);
1737
1738                 if (i > n - param_len)
1739                         {
1740                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1741                         goto f_err;
1742                         }
1743                 param_len += i;
1744
1745                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1746                         {
1747                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1748                         goto err;
1749                         }
1750                 p+=i;
1751
1752                 if (2 > n - param_len)
1753                         {
1754                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1755                                 SSL_R_LENGTH_TOO_SHORT);
1756                         goto f_err;
1757                         }
1758                 param_len += 2;
1759
1760                 n2s(p,i);
1761
1762                 if (i > n - param_len)
1763                         {
1764                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1765                         goto f_err;
1766                         }
1767                 param_len += i;
1768
1769                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1770                         {
1771                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1772                         goto err;
1773                         }
1774                 p+=i;
1775
1776                 if (2 > n - param_len)
1777                         {
1778                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1779                                 SSL_R_LENGTH_TOO_SHORT);
1780                         goto f_err;
1781                         }
1782                 param_len += 2;
1783
1784                 n2s(p,i);
1785
1786                 if (i > n - param_len)
1787                         {
1788                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1789                         goto f_err;
1790                         }
1791                 param_len += i;
1792
1793                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1794                         {
1795                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1796                         goto err;
1797                         }
1798                 p+=i;
1799                 n-=param_len;
1800
1801                 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1802                                                 DH_security_bits(dh), 0, dh))
1803                         {
1804                         al=SSL_AD_HANDSHAKE_FAILURE;
1805                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
1806                         goto f_err;
1807                         }
1808
1809 #ifndef OPENSSL_NO_RSA
1810                 if (alg_a & SSL_aRSA)
1811                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1812 #else
1813                 if (0)
1814                         ;
1815 #endif
1816 #ifndef OPENSSL_NO_DSA
1817                 else if (alg_a & SSL_aDSS)
1818                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1819 #endif
1820                 /* else anonymous DH, so no certificate or pkey. */
1821
1822                 s->session->sess_cert->peer_dh_tmp=dh;
1823                 dh=NULL;
1824                 }
1825         else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
1826                 {
1827                 al=SSL_AD_ILLEGAL_PARAMETER;
1828                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1829                 goto f_err;
1830                 }
1831 #endif /* !OPENSSL_NO_DH */
1832
1833 #ifndef OPENSSL_NO_ECDH
1834         else if (alg_k & SSL_kECDHE)
1835                 {
1836                 EC_GROUP *ngroup;
1837                 const EC_GROUP *group;
1838
1839                 if ((ecdh=EC_KEY_new()) == NULL)
1840                         {
1841                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1842                         goto err;
1843                         }
1844
1845                 /* Extract elliptic curve parameters and the
1846                  * server's ephemeral ECDH public key.
1847                  * Keep accumulating lengths of various components in
1848                  * param_len and make sure it never exceeds n.
1849                  */
1850
1851                 /* XXX: For now we only support named (not generic) curves
1852                  * and the ECParameters in this case is just three bytes. We
1853                  * also need one byte for the length of the encoded point
1854                  */
1855                 param_len=4;
1856                 if (param_len > n)
1857                         {
1858                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1859                                 SSL_R_LENGTH_TOO_SHORT);
1860                         goto f_err;
1861                         }
1862                 /* Check curve is one of our preferences, if not server has
1863                  * sent an invalid curve. ECParameters is 3 bytes.
1864                  */
1865                 if (!tls1_check_curve(s, p, 3))
1866                         {
1867                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE);
1868                         goto f_err;
1869                         }
1870
1871                 if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) 
1872                         {
1873                         al=SSL_AD_INTERNAL_ERROR;
1874                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1875                         goto f_err;
1876                         }
1877
1878                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1879                 if (ngroup == NULL)
1880                         {
1881                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1882                         goto err;
1883                         }
1884                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1885                         {
1886                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1887                         goto err;
1888                         }
1889                 EC_GROUP_free(ngroup);
1890
1891                 group = EC_KEY_get0_group(ecdh);
1892
1893                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1894                     (EC_GROUP_get_degree(group) > 163))
1895                         {
1896                         al=SSL_AD_EXPORT_RESTRICTION;
1897                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1898                         goto f_err;
1899                         }
1900
1901                 p+=3;
1902
1903                 /* Next, get the encoded ECPoint */
1904                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1905                     ((bn_ctx = BN_CTX_new()) == NULL))
1906                         {
1907                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1908                         goto err;
1909                         }
1910
1911                 encoded_pt_len = *p;  /* length of encoded point */
1912                 p+=1;
1913
1914                 if ((encoded_pt_len > n - param_len) ||
1915                     (EC_POINT_oct2point(group, srvr_ecpoint, 
1916                         p, encoded_pt_len, bn_ctx) == 0))
1917                         {
1918                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1919                         goto f_err;
1920                         }
1921                 param_len += encoded_pt_len;
1922
1923                 n-=param_len;
1924                 p+=encoded_pt_len;
1925
1926                 /* The ECC/TLS specification does not mention
1927                  * the use of DSA to sign ECParameters in the server
1928                  * key exchange message. We do support RSA and ECDSA.
1929                  */
1930                 if (0) ;
1931 #ifndef OPENSSL_NO_RSA
1932                 else if (alg_a & SSL_aRSA)
1933                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1934 #endif
1935 #ifndef OPENSSL_NO_ECDSA
1936                 else if (alg_a & SSL_aECDSA)
1937                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1938 #endif
1939                 /* else anonymous ECDH, so no certificate or pkey. */
1940                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1941                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1942                 ecdh=NULL;
1943                 BN_CTX_free(bn_ctx);
1944                 bn_ctx = NULL;
1945                 EC_POINT_free(srvr_ecpoint);
1946                 srvr_ecpoint = NULL;
1947                 }
1948         else if (alg_k)
1949                 {
1950                 al=SSL_AD_UNEXPECTED_MESSAGE;
1951                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1952                 goto f_err;
1953                 }
1954 #endif /* !OPENSSL_NO_ECDH */
1955
1956
1957         /* p points to the next byte, there are 'n' bytes left */
1958
1959         /* if it was signed, check the signature */
1960         if (pkey != NULL)
1961                 {
1962                 if (SSL_USE_SIGALGS(s))
1963                         {
1964                         int rv;
1965                         if (2 > n)
1966                                 {
1967                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1968                                         SSL_R_LENGTH_TOO_SHORT);
1969                                 goto f_err;
1970                                 }
1971                         rv = tls12_check_peer_sigalg(&md, s, p, pkey);
1972                         if (rv == -1)
1973                                 goto err;
1974                         else if (rv == 0)
1975                                 {
1976                                 goto f_err;
1977                                 }
1978 #ifdef SSL_DEBUG
1979 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1980 #endif
1981                         p += 2;
1982                         n -= 2;
1983                         }
1984                 else
1985                         md = EVP_sha1();
1986
1987                 if (2 > n)
1988                         {
1989                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1990                                 SSL_R_LENGTH_TOO_SHORT);
1991                         goto f_err;
1992                         }
1993                 n2s(p,i);
1994                 n-=2;
1995                 j=EVP_PKEY_size(pkey);
1996
1997                 /* Check signature length. If n is 0 then signature is empty */
1998                 if ((i != n) || (n > j) || (n <= 0))
1999                         {
2000                         /* wrong packet length */
2001                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
2002                         goto f_err;
2003                         }
2004
2005 #ifndef OPENSSL_NO_RSA
2006                 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
2007                         {
2008                         int num;
2009                         unsigned int size;
2010
2011                         j=0;
2012                         q=md_buf;
2013                         for (num=2; num > 0; num--)
2014                                 {
2015                                 EVP_MD_CTX_set_flags(&md_ctx,
2016                                         EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2017                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
2018                                         ?s->ctx->md5:s->ctx->sha1, NULL);
2019                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2020                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2021                                 EVP_DigestUpdate(&md_ctx,param,param_len);
2022                                 EVP_DigestFinal_ex(&md_ctx,q,&size);
2023                                 q+=size;
2024                                 j+=size;
2025                                 }
2026                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
2027                                                                 pkey->pkey.rsa);
2028                         if (i < 0)
2029                                 {
2030                                 al=SSL_AD_DECRYPT_ERROR;
2031                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
2032                                 goto f_err;
2033                                 }
2034                         if (i == 0)
2035                                 {
2036                                 /* bad signature */
2037                                 al=SSL_AD_DECRYPT_ERROR;
2038                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
2039                                 goto f_err;
2040                                 }
2041                         }
2042                 else
2043 #endif
2044                         {
2045                         EVP_VerifyInit_ex(&md_ctx, md, NULL);
2046                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2047                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2048                         EVP_VerifyUpdate(&md_ctx,param,param_len);
2049                         if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
2050                                 {
2051                                 /* bad signature */
2052                                 al=SSL_AD_DECRYPT_ERROR;
2053                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
2054                                 goto f_err;
2055                                 }
2056                         }
2057                 }
2058         else
2059                 {
2060                 /* aNULL, aSRP or kPSK do not need public keys */
2061                 if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))
2062                         {
2063                         /* Might be wrong key type, check it */
2064                         if (ssl3_check_cert_and_algorithm(s))
2065                                 /* Otherwise this shouldn't happen */
2066                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2067                         goto err;
2068                         }
2069                 /* still data left over */
2070                 if (n != 0)
2071                         {
2072                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
2073                         goto f_err;
2074                         }
2075                 }
2076         EVP_PKEY_free(pkey);
2077         EVP_MD_CTX_cleanup(&md_ctx);
2078         return(1);
2079 f_err:
2080         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2081 err:
2082         EVP_PKEY_free(pkey);
2083 #ifndef OPENSSL_NO_RSA
2084         if (rsa != NULL)
2085                 RSA_free(rsa);
2086 #endif
2087 #ifndef OPENSSL_NO_DH
2088         if (dh != NULL)
2089                 DH_free(dh);
2090 #endif
2091 #ifndef OPENSSL_NO_ECDH
2092         BN_CTX_free(bn_ctx);
2093         EC_POINT_free(srvr_ecpoint);
2094         if (ecdh != NULL)
2095                 EC_KEY_free(ecdh);
2096 #endif
2097         EVP_MD_CTX_cleanup(&md_ctx);
2098         return(-1);
2099         }
2100
2101 int ssl3_get_certificate_request(SSL *s)
2102         {
2103         int ok,ret=0;
2104         unsigned long n,nc,l;
2105         unsigned int llen, ctype_num,i;
2106         X509_NAME *xn=NULL;
2107         const unsigned char *p,*q;
2108         unsigned char *d;
2109         STACK_OF(X509_NAME) *ca_sk=NULL;
2110
2111         n=s->method->ssl_get_message(s,
2112                 SSL3_ST_CR_CERT_REQ_A,
2113                 SSL3_ST_CR_CERT_REQ_B,
2114                 -1,
2115                 s->max_cert_list,
2116                 &ok);
2117
2118         if (!ok) return((int)n);
2119
2120         s->s3->tmp.cert_req=0;
2121
2122         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
2123                 {
2124                 s->s3->tmp.reuse_message=1;
2125                 /* If we get here we don't need any cached handshake records
2126                  * as we wont be doing client auth.
2127                  */
2128                 if (s->s3->handshake_buffer)
2129                         {
2130                         if (!ssl3_digest_cached_records(s))
2131                                 goto err;
2132                         }
2133                 return(1);
2134                 }
2135
2136         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
2137                 {
2138                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2139                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
2140                 goto err;
2141                 }
2142
2143         /* TLS does not like anon-DH with client cert */
2144         if (s->version > SSL3_VERSION)
2145                 {
2146                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
2147                         {
2148                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2149                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
2150                         goto err;
2151                         }
2152                 }
2153
2154         p=d=(unsigned char *)s->init_msg;
2155
2156         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
2157                 {
2158                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2159                 goto err;
2160                 }
2161
2162         /* get the certificate types */
2163         ctype_num= *(p++);
2164         if (s->cert->ctypes)
2165                 {
2166                 OPENSSL_free(s->cert->ctypes);
2167                 s->cert->ctypes = NULL;
2168                 }
2169         if (ctype_num > SSL3_CT_NUMBER)
2170                 {
2171                 /* If we exceed static buffer copy all to cert structure */
2172                 s->cert->ctypes = OPENSSL_malloc(ctype_num);
2173                 memcpy(s->cert->ctypes, p, ctype_num);
2174                 s->cert->ctype_num = (size_t)ctype_num;
2175                 ctype_num=SSL3_CT_NUMBER;
2176                 }
2177         for (i=0; i<ctype_num; i++)
2178                 s->s3->tmp.ctype[i]= p[i];
2179         p+=p[-1];
2180         if (SSL_USE_SIGALGS(s))
2181                 {
2182                 n2s(p, llen);
2183                 /* Check we have enough room for signature algorithms and
2184                  * following length value.
2185                  */
2186                 if ((unsigned long)(p - d + llen + 2) > n)
2187                         {
2188                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2189                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG);
2190                         goto err;
2191                         }
2192                 /* Clear certificate digests and validity flags */
2193                 for (i = 0; i < SSL_PKEY_NUM; i++)
2194                         {
2195                         s->cert->pkeys[i].digest = NULL;
2196                         s->cert->pkeys[i].valid_flags = 0;
2197                         }
2198                 if ((llen & 1) || !tls1_save_sigalgs(s, p, llen))
2199                         {
2200                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2201                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2202                         goto err;
2203                         }
2204                 if (!tls1_process_sigalgs(s))
2205                         {
2206                         ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2207                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2208                         goto err;
2209                         }
2210                 p += llen;
2211                 }
2212
2213         /* get the CA RDNs */
2214         n2s(p,llen);
2215 #if 0
2216 {
2217 FILE *out;
2218 out=fopen("/tmp/vsign.der","w");
2219 fwrite(p,1,llen,out);
2220 fclose(out);
2221 }
2222 #endif
2223
2224         if ((unsigned long)(p - d + llen) != n)
2225                 {
2226                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2227                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
2228                 goto err;
2229                 }
2230
2231         for (nc=0; nc<llen; )
2232                 {
2233                 n2s(p,l);
2234                 if ((l+nc+2) > llen)
2235                         {
2236                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2237                                 goto cont; /* netscape bugs */
2238                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2239                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
2240                         goto err;
2241                         }
2242
2243                 q=p;
2244
2245                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
2246                         {
2247                         /* If netscape tolerance is on, ignore errors */
2248                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2249                                 goto cont;
2250                         else
2251                                 {
2252                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2253                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
2254                                 goto err;
2255                                 }
2256                         }
2257
2258                 if (q != (p+l))
2259                         {
2260                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2261                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
2262                         goto err;
2263                         }
2264                 if (!sk_X509_NAME_push(ca_sk,xn))
2265                         {
2266                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2267                         goto err;
2268                         }
2269
2270                 p+=l;
2271                 nc+=l+2;
2272                 }
2273
2274         if (0)
2275                 {
2276 cont:
2277                 ERR_clear_error();
2278                 }
2279
2280         /* we should setup a certificate to return.... */
2281         s->s3->tmp.cert_req=1;
2282         s->s3->tmp.ctype_num=ctype_num;
2283         if (s->s3->tmp.ca_names != NULL)
2284                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
2285         s->s3->tmp.ca_names=ca_sk;
2286         ca_sk=NULL;
2287
2288         ret=1;
2289 err:
2290         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
2291         return(ret);
2292         }
2293
2294 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
2295         {
2296         return(X509_NAME_cmp(*a,*b));
2297         }
2298 #ifndef OPENSSL_NO_TLSEXT
2299 int ssl3_get_new_session_ticket(SSL *s)
2300         {
2301         int ok,al,ret=0, ticklen;
2302         long n;
2303         const unsigned char *p;
2304         unsigned char *d;
2305
2306         n=s->method->ssl_get_message(s,
2307                 SSL3_ST_CR_SESSION_TICKET_A,
2308                 SSL3_ST_CR_SESSION_TICKET_B,
2309                 -1,
2310                 16384,
2311                 &ok);
2312
2313         if (!ok)
2314                 return((int)n);
2315
2316         if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
2317                 {
2318                 s->s3->tmp.reuse_message=1;
2319                 return(1);
2320                 }
2321         if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
2322                 {
2323                 al=SSL_AD_UNEXPECTED_MESSAGE;
2324                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
2325                 goto f_err;
2326                 }
2327         if (n < 6)
2328                 {
2329                 /* need at least ticket_lifetime_hint + ticket length */
2330                 al = SSL_AD_DECODE_ERROR;
2331                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2332                 goto f_err;
2333                 }
2334
2335         p=d=(unsigned char *)s->init_msg;
2336         n2l(p, s->session->tlsext_tick_lifetime_hint);
2337         n2s(p, ticklen);
2338         /* ticket_lifetime_hint + ticket_length + ticket */
2339         if (ticklen + 6 != n)
2340                 {
2341                 al = SSL_AD_DECODE_ERROR;
2342                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2343                 goto f_err;
2344                 }
2345         if (s->session->tlsext_tick)
2346                 {
2347                 OPENSSL_free(s->session->tlsext_tick);
2348                 s->session->tlsext_ticklen = 0;
2349                 }
2350         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2351         if (!s->session->tlsext_tick)
2352                 {
2353                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
2354                 goto err;
2355                 }
2356         memcpy(s->session->tlsext_tick, p, ticklen);
2357         s->session->tlsext_ticklen = ticklen;
2358         /* There are two ways to detect a resumed ticket session.
2359          * One is to set an appropriate session ID and then the server
2360          * must return a match in ServerHello. This allows the normal
2361          * client session ID matching to work and we know much 
2362          * earlier that the ticket has been accepted.
2363          * 
2364          * The other way is to set zero length session ID when the
2365          * ticket is presented and rely on the handshake to determine
2366          * session resumption.
2367          *
2368          * We choose the former approach because this fits in with
2369          * assumptions elsewhere in OpenSSL. The session ID is set
2370          * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
2371          * ticket.
2372          */ 
2373         EVP_Digest(p, ticklen,
2374                         s->session->session_id, &s->session->session_id_length,
2375 #ifndef OPENSSL_NO_SHA256
2376                                                         EVP_sha256(), NULL);
2377 #else
2378                                                         EVP_sha1(), NULL);
2379 #endif
2380         ret=1;
2381         return(ret);
2382 f_err:
2383         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2384 err:
2385         return(-1);
2386         }
2387
2388 int ssl3_get_cert_status(SSL *s)
2389         {
2390         int ok, al;
2391         unsigned long resplen,n;
2392         const unsigned char *p;
2393
2394         n=s->method->ssl_get_message(s,
2395                 SSL3_ST_CR_CERT_STATUS_A,
2396                 SSL3_ST_CR_CERT_STATUS_B,
2397                 SSL3_MT_CERTIFICATE_STATUS,
2398                 16384,
2399                 &ok);
2400
2401         if (!ok) return((int)n);
2402         if (n < 4)
2403                 {
2404                 /* need at least status type + length */
2405                 al = SSL_AD_DECODE_ERROR;
2406                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2407                 goto f_err;
2408                 }
2409         p = (unsigned char *)s->init_msg;
2410         if (*p++ != TLSEXT_STATUSTYPE_ocsp)
2411                 {
2412                 al = SSL_AD_DECODE_ERROR;
2413                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
2414                 goto f_err;
2415                 }
2416         n2l3(p, resplen);
2417         if (resplen + 4 != n)
2418                 {
2419                 al = SSL_AD_DECODE_ERROR;
2420                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2421                 goto f_err;
2422                 }
2423         if (s->tlsext_ocsp_resp)
2424                 OPENSSL_free(s->tlsext_ocsp_resp);
2425         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2426         if (!s->tlsext_ocsp_resp)
2427                 {
2428                 al = SSL_AD_INTERNAL_ERROR;
2429                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2430                 goto f_err;
2431                 }
2432         s->tlsext_ocsp_resplen = resplen;
2433         if (s->ctx->tlsext_status_cb)
2434                 {
2435                 int ret;
2436                 ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2437                 if (ret == 0)
2438                         {
2439                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2440                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
2441                         goto f_err;
2442                         }
2443                 if (ret < 0)
2444                         {
2445                         al = SSL_AD_INTERNAL_ERROR;
2446                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2447                         goto f_err;
2448                         }
2449                 }
2450         return 1;
2451 f_err:
2452         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2453         return(-1);
2454         }
2455 #endif
2456
2457 int ssl3_get_server_done(SSL *s)
2458         {
2459         int ok,ret=0;
2460         long n;
2461
2462         n=s->method->ssl_get_message(s,
2463                 SSL3_ST_CR_SRVR_DONE_A,
2464                 SSL3_ST_CR_SRVR_DONE_B,
2465                 SSL3_MT_SERVER_DONE,
2466                 30, /* should be very small, like 0 :-) */
2467                 &ok);
2468
2469         if (!ok) return((int)n);
2470         if (n > 0)
2471                 {
2472                 /* should contain no data */
2473                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2474                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
2475                 return -1;
2476                 }
2477         ret=1;
2478         return(ret);
2479         }
2480
2481
2482 int ssl3_send_client_key_exchange(SSL *s)
2483         {
2484         unsigned char *p;
2485         int n;
2486         unsigned long alg_k;
2487 #ifndef OPENSSL_NO_RSA
2488         unsigned char *q;
2489         EVP_PKEY *pkey=NULL;
2490 #endif
2491 #ifndef OPENSSL_NO_KRB5
2492         KSSL_ERR kssl_err;
2493 #endif /* OPENSSL_NO_KRB5 */
2494 #ifndef OPENSSL_NO_ECDH
2495         EC_KEY *clnt_ecdh = NULL;
2496         const EC_POINT *srvr_ecpoint = NULL;
2497         EVP_PKEY *srvr_pub_pkey = NULL;
2498         unsigned char *encodedPoint = NULL;
2499         int encoded_pt_len = 0;
2500         BN_CTX * bn_ctx = NULL;
2501 #endif
2502
2503         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
2504                 {
2505                 p = ssl_handshake_start(s);
2506
2507                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2508
2509                 /* Fool emacs indentation */
2510                 if (0) {}
2511 #ifndef OPENSSL_NO_RSA
2512                 else if (alg_k & SSL_kRSA)
2513                         {
2514                         RSA *rsa;
2515                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2516
2517                         if (s->session->sess_cert == NULL)
2518                                 {
2519                                 /* We should always have a server certificate with SSL_kRSA. */
2520                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2521                                 goto err;
2522                                 }
2523
2524                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
2525                                 rsa=s->session->sess_cert->peer_rsa_tmp;
2526                         else
2527                                 {
2528                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
2529                                 if ((pkey == NULL) ||
2530                                         (pkey->type != EVP_PKEY_RSA) ||
2531                                         (pkey->pkey.rsa == NULL))
2532                                         {
2533                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2534                                         goto err;
2535                                         }
2536                                 rsa=pkey->pkey.rsa;
2537                                 EVP_PKEY_free(pkey);
2538                                 }
2539                                 
2540                         tmp_buf[0]=s->client_version>>8;
2541                         tmp_buf[1]=s->client_version&0xff;
2542                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2543                                         goto err;
2544
2545                         s->session->master_key_length=sizeof tmp_buf;
2546
2547                         q=p;
2548                         /* Fix buf for TLS and beyond */
2549                         if (s->version > SSL3_VERSION)
2550                                 p+=2;
2551                         n=RSA_public_encrypt(sizeof tmp_buf,
2552                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
2553 #ifdef PKCS1_CHECK
2554                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
2555                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
2556 #endif
2557                         if (n <= 0)
2558                                 {
2559                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
2560                                 goto err;
2561                                 }
2562
2563                         /* Fix buf for TLS and beyond */
2564                         if (s->version > SSL3_VERSION)
2565                                 {
2566                                 s2n(n,q);
2567                                 n+=2;
2568                                 }
2569
2570                         s->session->master_key_length=
2571                                 s->method->ssl3_enc->generate_master_secret(s,
2572                                         s->session->master_key,
2573                                         tmp_buf,sizeof tmp_buf);
2574                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2575                         }
2576 #endif
2577 #ifndef OPENSSL_NO_KRB5
2578                 else if (alg_k & SSL_kKRB5)
2579                         {
2580                         krb5_error_code krb5rc;
2581                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
2582                         /*  krb5_data   krb5_ap_req;  */
2583                         krb5_data       *enc_ticket;
2584                         krb5_data       authenticator, *authp = NULL;
2585                         EVP_CIPHER_CTX  ciph_ctx;
2586                         const EVP_CIPHER *enc = NULL;
2587                         unsigned char   iv[EVP_MAX_IV_LENGTH];
2588                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2589                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
2590                                                 + EVP_MAX_IV_LENGTH];
2591                         int             padl, outl = sizeof(epms);
2592
2593                         EVP_CIPHER_CTX_init(&ciph_ctx);
2594
2595 #ifdef KSSL_DEBUG
2596                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2597                                 alg_k, SSL_kKRB5);
2598 #endif  /* KSSL_DEBUG */
2599
2600                         authp = NULL;
2601 #ifdef KRB5SENDAUTH
2602                         if (KRB5SENDAUTH)  authp = &authenticator;
2603 #endif  /* KRB5SENDAUTH */
2604
2605                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2606                                 &kssl_err);
2607                         enc = kssl_map_enc(kssl_ctx->enctype);
2608                         if (enc == NULL)
2609                             goto err;
2610 #ifdef KSSL_DEBUG
2611                         {
2612                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
2613                         if (krb5rc && kssl_err.text)
2614                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2615                         }
2616 #endif  /* KSSL_DEBUG */
2617
2618                         if (krb5rc)
2619                                 {
2620                                 ssl3_send_alert(s,SSL3_AL_FATAL,
2621                                                 SSL_AD_HANDSHAKE_FAILURE);
2622                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2623                                                 kssl_err.reason);
2624                                 goto err;
2625                                 }
2626
2627                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2628                         **  in place of RFC 2712 KerberosWrapper, as in:
2629                         **
2630                         **  Send ticket (copy to *p, set n = length)
2631                         **  n = krb5_ap_req.length;
2632                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2633                         **  if (krb5_ap_req.data)  
2634                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2635                         **
2636                         **  Now using real RFC 2712 KerberosWrapper
2637                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2638                         **  Note: 2712 "opaque" types are here replaced
2639                         **  with a 2-byte length followed by the value.
2640                         **  Example:
2641                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2642                         **  Where "xx xx" = length bytes.  Shown here with
2643                         **  optional authenticator omitted.
2644                         */
2645
2646                         /*  KerberosWrapper.Ticket              */
2647                         s2n(enc_ticket->length,p);
2648                         memcpy(p, enc_ticket->data, enc_ticket->length);
2649                         p+= enc_ticket->length;
2650                         n = enc_ticket->length + 2;
2651
2652                         /*  KerberosWrapper.Authenticator       */
2653                         if (authp  &&  authp->length)  
2654                                 {
2655                                 s2n(authp->length,p);
2656                                 memcpy(p, authp->data, authp->length);
2657                                 p+= authp->length;
2658                                 n+= authp->length + 2;
2659                                 
2660                                 free(authp->data);
2661                                 authp->data = NULL;
2662                                 authp->length = 0;
2663                                 }
2664                         else
2665                                 {
2666                                 s2n(0,p);/*  null authenticator length  */
2667                                 n+=2;
2668                                 }
2669  
2670                             tmp_buf[0]=s->client_version>>8;
2671                             tmp_buf[1]=s->client_version&0xff;
2672                             if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2673                                 goto err;
2674
2675                         /*  20010420 VRS.  Tried it this way; failed.
2676                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2677                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2678                         **                              kssl_ctx->length);
2679                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2680                         */
2681
2682                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2683                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2684                                 kssl_ctx->key,iv);
2685                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2686                                 sizeof tmp_buf);
2687                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2688                         outl += padl;
2689                         if (outl > (int)sizeof epms)
2690                                 {
2691                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2692                                 goto err;
2693                                 }
2694                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2695
2696                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
2697                         s2n(outl,p);
2698                         memcpy(p, epms, outl);
2699                         p+=outl;
2700                         n+=outl + 2;
2701
2702                         s->session->master_key_length=
2703                                 s->method->ssl3_enc->generate_master_secret(s,
2704                                         s->session->master_key,
2705                                         tmp_buf, sizeof tmp_buf);
2706
2707                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2708                         OPENSSL_cleanse(epms, outl);
2709                         }
2710 #endif
2711 #ifndef OPENSSL_NO_DH
2712                 else if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
2713                         {
2714                         DH *dh_srvr,*dh_clnt;
2715                         SESS_CERT *scert = s->session->sess_cert;
2716
2717                         if (scert == NULL) 
2718                                 {
2719                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2720                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2721                                 goto err;
2722                                 }
2723
2724                         if (scert->peer_dh_tmp != NULL)
2725                                 dh_srvr=scert->peer_dh_tmp;
2726                         else
2727                                 {
2728                                 /* we get them from the cert */
2729                                 int idx = scert->peer_cert_type;
2730                                 EVP_PKEY *spkey = NULL;
2731                                 dh_srvr = NULL;
2732                                 if (idx >= 0)
2733                                         spkey = X509_get_pubkey(
2734                                                 scert->peer_pkeys[idx].x509);
2735                                 if (spkey)
2736                                         {
2737                                         dh_srvr = EVP_PKEY_get1_DH(spkey);
2738                                         EVP_PKEY_free(spkey);
2739                                         }
2740                                 if (dh_srvr == NULL)
2741                                         {
2742                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2743                                             ERR_R_INTERNAL_ERROR);
2744                                         goto err;
2745                                         }
2746                                 }
2747                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2748                                 {
2749                                 /* Use client certificate key */
2750                                 EVP_PKEY *clkey = s->cert->key->privatekey;
2751                                 dh_clnt = NULL;
2752                                 if (clkey)
2753                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2754                                 if (dh_clnt == NULL)
2755                                         {
2756                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2757                                             ERR_R_INTERNAL_ERROR);
2758                                         goto err;
2759                                         }
2760                                 }
2761                         else
2762                                 {
2763                                 /* generate a new random key */
2764                                 if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2765                                         {
2766                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2767                                         goto err;
2768                                         }
2769                                 if (!DH_generate_key(dh_clnt))
2770                                         {
2771                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2772                                         DH_free(dh_clnt);
2773                                         goto err;
2774                                         }
2775                                 }
2776
2777                         /* use the 'p' output buffer for the DH key, but
2778                          * make sure to clear it out afterwards */
2779
2780                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2781                         if (scert->peer_dh_tmp == NULL)
2782                                 DH_free(dh_srvr);
2783
2784                         if (n <= 0)
2785                                 {
2786                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2787                                 DH_free(dh_clnt);
2788                                 goto err;
2789                                 }
2790
2791                         /* generate master key from the result */
2792                         s->session->master_key_length=
2793                                 s->method->ssl3_enc->generate_master_secret(s,
2794                                         s->session->master_key,p,n);
2795                         /* clean up */
2796                         memset(p,0,n);
2797
2798                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2799                                 n = 0;
2800                         else
2801                                 {
2802                                 /* send off the data */
2803                                 n=BN_num_bytes(dh_clnt->pub_key);
2804                                 s2n(n,p);
2805                                 BN_bn2bin(dh_clnt->pub_key,p);
2806                                 n+=2;
2807                                 }
2808
2809                         DH_free(dh_clnt);
2810
2811                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
2812                         }
2813 #endif
2814
2815 #ifndef OPENSSL_NO_ECDH 
2816                 else if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe))
2817                         {
2818                         const EC_GROUP *srvr_group = NULL;
2819                         EC_KEY *tkey;
2820                         int ecdh_clnt_cert = 0;
2821                         int field_size = 0;
2822
2823                         if (s->session->sess_cert == NULL) 
2824                                 {
2825                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2826                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2827                                 goto err;
2828                                 }
2829
2830                         /* Did we send out the client's
2831                          * ECDH share for use in premaster
2832                          * computation as part of client certificate?
2833                          * If so, set ecdh_clnt_cert to 1.
2834                          */
2835                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
2836                                 {
2837                                 /* XXX: For now, we do not support client
2838                                  * authentication using ECDH certificates.
2839                                  * To add such support, one needs to add
2840                                  * code that checks for appropriate 
2841                                  * conditions and sets ecdh_clnt_cert to 1.
2842                                  * For example, the cert have an ECC
2843                                  * key on the same curve as the server's
2844                                  * and the key should be authorized for
2845                                  * key agreement.
2846                                  *
2847                                  * One also needs to add code in ssl3_connect
2848                                  * to skip sending the certificate verify
2849                                  * message.
2850                                  *
2851                                  * if ((s->cert->key->privatekey != NULL) &&
2852                                  *     (s->cert->key->privatekey->type ==
2853                                  *      EVP_PKEY_EC) && ...)
2854                                  * ecdh_clnt_cert = 1;
2855                                  */
2856                                 }
2857
2858                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2859                                 {
2860                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2861                                 }
2862                         else
2863                                 {
2864                                 /* Get the Server Public Key from Cert */
2865                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
2866                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2867                                 if ((srvr_pub_pkey == NULL) ||
2868                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2869                                     (srvr_pub_pkey->pkey.ec == NULL))
2870                                         {
2871                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2872                                             ERR_R_INTERNAL_ERROR);
2873                                         goto err;
2874                                         }
2875
2876                                 tkey = srvr_pub_pkey->pkey.ec;
2877                                 }
2878
2879                         srvr_group   = EC_KEY_get0_group(tkey);
2880                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2881
2882                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2883                                 {
2884                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2885                                     ERR_R_INTERNAL_ERROR);
2886                                 goto err;
2887                                 }
2888
2889                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2890                                 {
2891                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2892                                 goto err;
2893                                 }
2894
2895                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2896                                 {
2897                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2898                                 goto err;
2899                                 }
2900                         if (ecdh_clnt_cert) 
2901                                 { 
2902                                 /* Reuse key info from our certificate
2903                                  * We only need our private key to perform
2904                                  * the ECDH computation.
2905                                  */
2906                                 const BIGNUM *priv_key;
2907                                 tkey = s->cert->key->privatekey->pkey.ec;
2908                                 priv_key = EC_KEY_get0_private_key(tkey);
2909                                 if (priv_key == NULL)
2910                                         {
2911                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2912                                         goto err;
2913                                         }
2914                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2915                                         {
2916                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2917                                         goto err;
2918                                         }
2919                                 }
2920                         else 
2921                                 {
2922                                 /* Generate a new ECDH key pair */
2923                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
2924                                         {
2925                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2926                                         goto err;
2927                                         }
2928                                 }
2929
2930                         /* use the 'p' output buffer for the ECDH key, but
2931                          * make sure to clear it out afterwards
2932                          */
2933
2934                         field_size = EC_GROUP_get_degree(srvr_group);
2935                         if (field_size <= 0)
2936                                 {
2937                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2938                                        ERR_R_ECDH_LIB);
2939                                 goto err;
2940                                 }
2941                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2942                         if (n <= 0)
2943                                 {
2944                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2945                                        ERR_R_ECDH_LIB);
2946                                 goto err;
2947                                 }
2948
2949                         /* generate master key from the result */
2950                         s->session->master_key_length = s->method->ssl3_enc \
2951                             -> generate_master_secret(s, 
2952                                 s->session->master_key,
2953                                 p, n);
2954
2955                         memset(p, 0, n); /* clean up */
2956
2957                         if (ecdh_clnt_cert) 
2958                                 {
2959                                 /* Send empty client key exch message */
2960                                 n = 0;
2961                                 }
2962                         else 
2963                                 {
2964                                 /* First check the size of encoding and
2965                                  * allocate memory accordingly.
2966                                  */
2967                                 encoded_pt_len = 
2968                                     EC_POINT_point2oct(srvr_group, 
2969                                         EC_KEY_get0_public_key(clnt_ecdh), 
2970                                         POINT_CONVERSION_UNCOMPRESSED, 
2971                                         NULL, 0, NULL);
2972
2973                                 encodedPoint = (unsigned char *) 
2974                                     OPENSSL_malloc(encoded_pt_len * 
2975                                         sizeof(unsigned char)); 
2976                                 bn_ctx = BN_CTX_new();
2977                                 if ((encodedPoint == NULL) || 
2978                                     (bn_ctx == NULL)) 
2979                                         {
2980                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2981                                         goto err;
2982                                         }
2983
2984                                 /* Encode the public key */
2985                                 n = EC_POINT_point2oct(srvr_group, 
2986                                     EC_KEY_get0_public_key(clnt_ecdh), 
2987                                     POINT_CONVERSION_UNCOMPRESSED, 
2988                                     encodedPoint, encoded_pt_len, bn_ctx);
2989
2990                                 *p = n; /* length of encoded point */
2991                                 /* Encoded point will be copied here */
2992                                 p += 1; 
2993                                 /* copy the point */
2994                                 memcpy((unsigned char *)p, encodedPoint, n);
2995                                 /* increment n to account for length field */
2996                                 n += 1; 
2997                                 }
2998
2999                         /* Free allocated memory */
3000                         BN_CTX_free(bn_ctx);
3001                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
3002                         if (clnt_ecdh != NULL) 
3003                                  EC_KEY_free(clnt_ecdh);
3004                         EVP_PKEY_free(srvr_pub_pkey);
3005                         }
3006 #endif /* !OPENSSL_NO_ECDH */
3007                 else if (alg_k & SSL_kGOST) 
3008                         {
3009                         /* GOST key exchange message creation */
3010                         EVP_PKEY_CTX *pkey_ctx;
3011                         X509 *peer_cert; 
3012                         size_t msglen;
3013                         unsigned int md_len;
3014                         int keytype;
3015                         unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
3016                         EVP_MD_CTX *ukm_hash;
3017                         EVP_PKEY *pub_key;
3018
3019                         /* Get server sertificate PKEY and create ctx from it */
3020                         peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
3021                         if (!peer_cert) 
3022                                 peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
3023                         if (!peer_cert)         {
3024                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3025                                         goto err;
3026                                 }       
3027                                 
3028                         pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
3029                         /* If we have send a certificate, and certificate key
3030
3031                          * parameters match those of server certificate, use
3032                          * certificate key for key exchange
3033                          */
3034
3035                          /* Otherwise, generate ephemeral key pair */
3036                                         
3037                         EVP_PKEY_encrypt_init(pkey_ctx);
3038                           /* Generate session key */    
3039                     RAND_bytes(premaster_secret,32);
3040                         /* If we have client certificate, use its secret as peer key */
3041                         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
3042                                 if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
3043                                         /* If there was an error - just ignore it. Ephemeral key
3044                                         * would be used
3045                                         */
3046                                         ERR_clear_error();
3047                                 }
3048                         }                       
3049                         /* Compute shared IV and store it in algorithm-specific
3050                          * context data */
3051                         ukm_hash = EVP_MD_CTX_create();
3052                         EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
3053                         EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
3054                         EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
3055                         EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
3056                         EVP_MD_CTX_destroy(ukm_hash);
3057                         if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
3058                                 8,shared_ukm)<0) {
3059                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3060                                                 SSL_R_LIBRARY_BUG);
3061                                         goto err;
3062                                 }       
3063                         /* Make GOST keytransport blob message */
3064                         /*Encapsulate it into sequence */
3065                         *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
3066                         msglen=255;
3067                         if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
3068                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3069                                         SSL_R_LIBRARY_BUG);
3070                                 goto err;
3071                         }
3072                         if (msglen >= 0x80)
3073                                 {
3074                                 *(p++)=0x81;
3075                                 *(p++)= msglen & 0xff;
3076                                 n=msglen+3;
3077                                 }
3078                         else
3079                                 {
3080                                 *(p++)= msglen & 0xff;
3081                                 n=msglen+2;
3082                                 }
3083                         memcpy(p, tmp, msglen);
3084                         /* Check if pubkey from client certificate was used */
3085                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3086                                 {
3087                                 /* Set flag "skip certificate verify" */
3088                                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3089                                 }
3090                         EVP_PKEY_CTX_free(pkey_ctx);
3091                         s->session->master_key_length=
3092                                 s->method->ssl3_enc->generate_master_secret(s,
3093                                         s->session->master_key,premaster_secret,32);
3094                         EVP_PKEY_free(pub_key);
3095
3096                         }
3097 #ifndef OPENSSL_NO_SRP
3098                 else if (alg_k & SSL_kSRP)
3099                         {
3100                         if (s->srp_ctx.A != NULL)
3101                                 {
3102                                 /* send off the data */
3103                                 n=BN_num_bytes(s->srp_ctx.A);
3104                                 s2n(n,p);
3105                                 BN_bn2bin(s->srp_ctx.A,p);
3106                                 n+=2;
3107                                 }
3108                         else
3109                                 {
3110                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3111                                 goto err;
3112                                 }
3113                         if (s->session->srp_username != NULL)
3114                                 OPENSSL_free(s->session->srp_username);
3115                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
3116                         if (s->session->srp_username == NULL)
3117                                 {
3118                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3119                                         ERR_R_MALLOC_FAILURE);
3120                                 goto err;
3121                                 }
3122
3123                         if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0)
3124                                 {
3125                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3126                                 goto err;
3127                                 }
3128                         }
3129 #endif
3130 #ifndef OPENSSL_NO_PSK
3131                 else if (alg_k & SSL_kPSK)
3132                         {
3133                         /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes
3134                          * to return a \0-terminated identity. The last byte
3135                          * is for us for simulating strnlen. */
3136                         char identity[PSK_MAX_IDENTITY_LEN + 2];
3137                         size_t identity_len;
3138                         unsigned char *t = NULL;
3139                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
3140                         unsigned int pre_ms_len = 0, psk_len = 0;
3141                         int psk_err = 1;
3142
3143                         n = 0;
3144                         if (s->psk_client_callback == NULL)
3145                                 {
3146                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3147                                         SSL_R_PSK_NO_CLIENT_CB);
3148                                 goto err;
3149                                 }
3150
3151                         memset(identity, 0, sizeof(identity));
3152                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
3153                                 identity, sizeof(identity) - 1,
3154                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
3155                         if (psk_len > PSK_MAX_PSK_LEN)
3156                                 {
3157                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3158                                         ERR_R_INTERNAL_ERROR);
3159                                 goto psk_err;
3160                                 }
3161                         else if (psk_len == 0)
3162                                 {
3163                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3164                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
3165                                 goto psk_err;
3166                                 }
3167                         identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
3168                         identity_len = strlen(identity);
3169                         if (identity_len > PSK_MAX_IDENTITY_LEN)
3170                                 {
3171                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3172                                         ERR_R_INTERNAL_ERROR);
3173                                 goto psk_err;
3174                                 }
3175                         /* create PSK pre_master_secret */
3176                         pre_ms_len = 2+psk_len+2+psk_len;
3177                         t = psk_or_pre_ms;
3178                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
3179                         s2n(psk_len, t);
3180                         memset(t, 0, psk_len);
3181                         t+=psk_len;
3182                         s2n(psk_len, t);
3183
3184                         if (s->session->psk_identity_hint != NULL)
3185                                 OPENSSL_free(s->session->psk_identity_hint);
3186                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
3187                         if (s->ctx->psk_identity_hint != NULL &&
3188                                 s->session->psk_identity_hint == NULL)
3189                                 {
3190                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3191                                         ERR_R_MALLOC_FAILURE);
3192                                 goto psk_err;
3193                                 }
3194
3195                         if (s->session->psk_identity != NULL)
3196                                 OPENSSL_free(s->session->psk_identity);
3197                         s->session->psk_identity = BUF_strdup(identity);
3198                         if (s->session->psk_identity == NULL)
3199                                 {
3200                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3201                                         ERR_R_MALLOC_FAILURE);
3202                                 goto psk_err;
3203                                 }
3204
3205                         s->session->master_key_length =
3206                                 s->method->ssl3_enc->generate_master_secret(s,
3207                                         s->session->master_key,
3208                                         psk_or_pre_ms, pre_ms_len);
3209                         s2n(identity_len, p);
3210                         memcpy(p, identity, identity_len);
3211                         n = 2 + identity_len;
3212                         psk_err = 0;
3213                 psk_err:
3214                         OPENSSL_cleanse(identity, sizeof(identity));
3215                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3216                         if (psk_err != 0)
3217                                 {
3218                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3219                                 goto err;
3220                                 }
3221                         }
3222 #endif
3223                 else
3224                         {
3225                         ssl3_send_alert(s, SSL3_AL_FATAL,
3226                             SSL_AD_HANDSHAKE_FAILURE);
3227                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3228                             ERR_R_INTERNAL_ERROR);
3229                         goto err;
3230                         }
3231
3232                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
3233                 s->state=SSL3_ST_CW_KEY_EXCH_B;
3234                 }
3235
3236         /* SSL3_ST_CW_KEY_EXCH_B */
3237         return ssl_do_write(s);
3238 err:
3239 #ifndef OPENSSL_NO_ECDH
3240         BN_CTX_free(bn_ctx);
3241         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
3242         if (clnt_ecdh != NULL) 
3243                 EC_KEY_free(clnt_ecdh);
3244         EVP_PKEY_free(srvr_pub_pkey);
3245 #endif
3246         return(-1);
3247         }
3248
3249 int ssl3_send_client_verify(SSL *s)
3250         {
3251         unsigned char *p;
3252         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
3253         EVP_PKEY *pkey;
3254         EVP_PKEY_CTX *pctx=NULL;
3255         EVP_MD_CTX mctx;
3256         unsigned u=0;
3257         unsigned long n;
3258         int j;
3259
3260         EVP_MD_CTX_init(&mctx);
3261
3262         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
3263                 {
3264                 p= ssl_handshake_start(s);
3265                 pkey=s->cert->key->privatekey;
3266 /* Create context from key and test if sha1 is allowed as digest */
3267                 pctx = EVP_PKEY_CTX_new(pkey,NULL);
3268                 EVP_PKEY_sign_init(pctx);
3269                 if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
3270                         {
3271                         if (!SSL_USE_SIGALGS(s))
3272                                 s->method->ssl3_enc->cert_verify_mac(s,
3273                                                 NID_sha1,
3274                                                 &(data[MD5_DIGEST_LENGTH]));
3275                         }
3276                 else
3277                         {
3278                         ERR_clear_error();
3279                         }
3280                 /* For TLS v1.2 send signature algorithm and signature
3281                  * using agreed digest and cached handshake records.
3282                  */
3283                 if (SSL_USE_SIGALGS(s))
3284                         {
3285                         long hdatalen = 0;
3286                         void *hdata;
3287                         const EVP_MD *md = s->cert->key->digest;
3288                         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer,
3289                                                                 &hdata);
3290                         if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md))
3291                                 {
3292                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3293                                                 ERR_R_INTERNAL_ERROR);
3294                                 goto err;
3295                                 }
3296                         p += 2;
3297 #ifdef SSL_DEBUG
3298                         fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3299                                                         EVP_MD_name(md));
3300 #endif
3301                         if (!EVP_SignInit_ex(&mctx, md, NULL)
3302                                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3303                                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey))
3304                                 {
3305                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3306                                                 ERR_R_EVP_LIB);
3307                                 goto err;
3308                                 }
3309                         s2n(u,p);
3310                         n = u + 4;
3311                         if (!ssl3_digest_cached_records(s))
3312                                 goto err;
3313                         }
3314                 else
3315 #ifndef OPENSSL_NO_RSA
3316                 if (pkey->type == EVP_PKEY_RSA)
3317                         {
3318                         s->method->ssl3_enc->cert_verify_mac(s,
3319                                 NID_md5,
3320                                 &(data[0]));
3321                         if (RSA_sign(NID_md5_sha1, data,
3322                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
3323                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
3324                                 {
3325                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
3326                                 goto err;
3327                                 }
3328                         s2n(u,p);
3329                         n=u+2;
3330                         }
3331                 else
3332 #endif
3333 #ifndef OPENSSL_NO_DSA
3334                         if (pkey->type == EVP_PKEY_DSA)
3335                         {
3336                         if (!DSA_sign(pkey->save_type,
3337                                 &(data[MD5_DIGEST_LENGTH]),
3338                                 SHA_DIGEST_LENGTH,&(p[2]),
3339                                 (unsigned int *)&j,pkey->pkey.dsa))
3340                                 {
3341                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
3342                                 goto err;
3343                                 }
3344                         s2n(j,p);
3345                         n=j+2;
3346                         }
3347                 else
3348 #endif
3349 #ifndef OPENSSL_NO_ECDSA
3350                         if (pkey->type == EVP_PKEY_EC)
3351                         {
3352                         if (!ECDSA_sign(pkey->save_type,
3353                                 &(data[MD5_DIGEST_LENGTH]),
3354                                 SHA_DIGEST_LENGTH,&(p[2]),
3355                                 (unsigned int *)&j,pkey->pkey.ec))
3356                                 {
3357                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3358                                     ERR_R_ECDSA_LIB);
3359                                 goto err;
3360                                 }
3361                         s2n(j,p);
3362                         n=j+2;
3363                         }
3364                 else
3365 #endif
3366                 if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) 
3367                 {
3368                 unsigned char signbuf[64];
3369                 int i;
3370                 size_t sigsize=64;
3371                 s->method->ssl3_enc->cert_verify_mac(s,
3372                         NID_id_GostR3411_94,
3373                         data);
3374                 if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3375                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3376                         ERR_R_INTERNAL_ERROR);
3377                         goto err;
3378                 }
3379                 for (i=63,j=0; i>=0; j++, i--) {
3380                         p[2+j]=signbuf[i];
3381                 }       
3382                 s2n(j,p);
3383                 n=j+2;
3384                 }
3385                 else
3386                 {
3387                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
3388                         goto err;
3389                 }
3390                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
3391                 s->state=SSL3_ST_CW_CERT_VRFY_B;
3392                 }
3393         EVP_MD_CTX_cleanup(&mctx);
3394         EVP_PKEY_CTX_free(pctx);
3395         return ssl_do_write(s);
3396 err:
3397         EVP_MD_CTX_cleanup(&mctx);
3398         EVP_PKEY_CTX_free(pctx);
3399         return(-1);
3400         }
3401
3402 /* Check a certificate can be used for client authentication. Currently
3403  * check cert exists, if we have a suitable digest for TLS 1.2 if
3404  * static DH client certificates can be used and optionally checks
3405  * suitability for Suite B.
3406  */
3407 static int ssl3_check_client_certificate(SSL *s)
3408         {
3409         unsigned long alg_k;
3410         if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
3411                 return 0;
3412         /* If no suitable signature algorithm can't use certificate */
3413         if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
3414                 return 0;
3415         /* If strict mode check suitability of chain before using it.
3416          * This also adjusts suite B digest if necessary.
3417          */
3418         if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3419                 !tls1_check_chain(s, NULL, NULL, NULL, -2))
3420                 return 0;
3421         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3422         /* See if we can use client certificate for fixed DH */
3423         if (alg_k & (SSL_kDHr|SSL_kDHd))
3424                 {
3425                 SESS_CERT *scert = s->session->sess_cert;
3426                 int i = scert->peer_cert_type;
3427                 EVP_PKEY *clkey = NULL, *spkey = NULL;
3428                 clkey = s->cert->key->privatekey;
3429                 /* If client key not DH assume it can be used */
3430                 if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
3431                         return 1;
3432                 if (i >= 0)
3433                         spkey = X509_get_pubkey(scert->peer_pkeys[i].x509);
3434                 if (spkey)
3435                         {
3436                         /* Compare server and client parameters */
3437                         i = EVP_PKEY_cmp_parameters(clkey, spkey);
3438                         EVP_PKEY_free(spkey);
3439                         if (i != 1)
3440                                 return 0;
3441                         }
3442                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3443                 }
3444         return 1;
3445         }
3446
3447 int ssl3_send_client_certificate(SSL *s)
3448         {
3449         X509 *x509=NULL;
3450         EVP_PKEY *pkey=NULL;
3451         int i;
3452
3453         if (s->state == SSL3_ST_CW_CERT_A)
3454                 {
3455                 /* Let cert callback update client certificates if required */
3456                 if (s->cert->cert_cb)
3457                         {
3458                         i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
3459                         if (i < 0)
3460                                 {
3461                                 s->rwstate=SSL_X509_LOOKUP;
3462                                 return -1;
3463                                 }
3464                         if (i == 0)
3465                                 {
3466                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
3467                                 return 0;
3468                                 }
3469                         s->rwstate=SSL_NOTHING;
3470                         }
3471                 if (ssl3_check_client_certificate(s))
3472                         s->state=SSL3_ST_CW_CERT_C;
3473                 else
3474                         s->state=SSL3_ST_CW_CERT_B;
3475                 }
3476
3477         /* We need to get a client cert */
3478         if (s->state == SSL3_ST_CW_CERT_B)
3479                 {
3480                 /* If we get an error, we need to
3481                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
3482                  * We then get retied later */
3483                 i=0;
3484                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
3485                 if (i < 0)
3486                         {
3487                         s->rwstate=SSL_X509_LOOKUP;
3488                         return(-1);
3489                         }
3490                 s->rwstate=SSL_NOTHING;
3491                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
3492                         {
3493                         s->state=SSL3_ST_CW_CERT_B;
3494                         if (    !SSL_use_certificate(s,x509) ||
3495                                 !SSL_use_PrivateKey(s,pkey))
3496                                 i=0;
3497                         }
3498                 else if (i == 1)
3499                         {
3500                         i=0;
3501                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3502                         }
3503
3504                 if (x509 != NULL) X509_free(x509);
3505                 if (pkey != NULL) EVP_PKEY_free(pkey);
3506                 if (i && !ssl3_check_client_certificate(s))
3507                         i = 0;
3508                 if (i == 0)
3509                         {
3510                         if (s->version == SSL3_VERSION)
3511                                 {
3512                                 s->s3->tmp.cert_req=0;
3513                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
3514                                 return(1);
3515                                 }
3516                         else
3517                                 {
3518                                 s->s3->tmp.cert_req=2;
3519                                 }
3520                         }
3521
3522                 /* Ok, we have a cert */
3523                 s->state=SSL3_ST_CW_CERT_C;
3524                 }
3525
3526         if (s->state == SSL3_ST_CW_CERT_C)
3527                 {
3528                 s->state=SSL3_ST_CW_CERT_D;
3529                 if (!ssl3_output_cert_chain(s,
3530                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key))
3531                         {
3532                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3533                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
3534                         return 0;
3535                         }
3536                 }
3537         /* SSL3_ST_CW_CERT_D */
3538         return ssl_do_write(s);
3539         }
3540
3541 #define has_bits(i,m)   (((i)&(m)) == (m))
3542
3543 int ssl3_check_cert_and_algorithm(SSL *s)
3544         {
3545         int i,idx;
3546         long alg_k,alg_a;
3547         EVP_PKEY *pkey=NULL;
3548         SESS_CERT *sc;
3549 #ifndef OPENSSL_NO_RSA
3550         RSA *rsa;
3551 #endif
3552 #ifndef OPENSSL_NO_DH
3553         DH *dh;
3554 #endif
3555
3556         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3557         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
3558
3559         /* we don't have a certificate */
3560         if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK))
3561                 return(1);
3562
3563         sc=s->session->sess_cert;
3564         if (sc == NULL)
3565                 {
3566                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
3567                 goto err;
3568                 }
3569
3570 #ifndef OPENSSL_NO_RSA
3571         rsa=s->session->sess_cert->peer_rsa_tmp;
3572 #endif
3573 #ifndef OPENSSL_NO_DH
3574         dh=s->session->sess_cert->peer_dh_tmp;
3575 #endif
3576
3577         /* This is the passed certificate */
3578
3579         idx=sc->peer_cert_type;
3580 #ifndef OPENSSL_NO_ECDH
3581         if (idx == SSL_PKEY_ECC)
3582                 {
3583                 if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
3584                                                                 s) == 0) 
3585                         { /* check failed */
3586                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
3587                         goto f_err;
3588                         }
3589                 else 
3590                         {
3591                         return 1;
3592                         }
3593                 }
3594         else if (alg_a & SSL_aECDSA)
3595                 {
3596                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT);
3597                 goto f_err;
3598                 }
3599         else if (alg_k & (SSL_kECDHr|SSL_kECDHe))
3600                 {
3601                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT);
3602                 goto f_err;
3603                 }
3604 #endif
3605         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
3606         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
3607         EVP_PKEY_free(pkey);
3608
3609         
3610         /* Check that we have a certificate if we require one */
3611         if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
3612                 {
3613                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
3614                 goto f_err;
3615                 }
3616 #ifndef OPENSSL_NO_DSA
3617         else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
3618                 {
3619                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
3620                 goto f_err;
3621                 }
3622 #endif
3623 #ifndef OPENSSL_NO_RSA
3624         if ((alg_k & SSL_kRSA) &&
3625                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
3626                 {
3627                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3628                 goto f_err;
3629                 }
3630 #endif
3631 #ifndef OPENSSL_NO_DH
3632         if ((alg_k & SSL_kDHE) && 
3633                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
3634                 {
3635                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
3636                 goto f_err;
3637                 }
3638         else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
3639                 !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
3640                 {
3641                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
3642                 goto f_err;
3643                 }
3644 #ifndef OPENSSL_NO_DSA
3645         else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
3646                 !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
3647                 {
3648                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
3649                 goto f_err;
3650                 }
3651 #endif
3652 #endif
3653
3654         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
3655                 {
3656 #ifndef OPENSSL_NO_RSA
3657                 if (alg_k & SSL_kRSA)
3658                         {
3659                         if (rsa == NULL
3660                             || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3661                                 {
3662                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3663                                 goto f_err;
3664                                 }
3665                         }
3666                 else
3667 #endif
3668 #ifndef OPENSSL_NO_DH
3669                         if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
3670                             {
3671                             if (dh == NULL
3672                                 || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3673                                 {
3674                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3675                                 goto f_err;
3676                                 }
3677                         }
3678                 else
3679 #endif
3680                         {
3681                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3682                         goto f_err;
3683                         }
3684                 }
3685         return(1);
3686 f_err:
3687         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
3688 err:
3689         return(0);
3690         }
3691
3692 /* Check to see if handshake is full or resumed. Usually this is just a
3693  * case of checking to see if a cache hit has occurred. In the case of
3694  * session tickets we have to check the next message to be sure.
3695  */
3696
3697 #ifndef OPENSSL_NO_TLSEXT
3698 # ifndef OPENSSL_NO_NEXTPROTONEG
3699 int ssl3_send_next_proto(SSL *s)
3700         {
3701         unsigned int len, padding_len;
3702         unsigned char *d;
3703
3704         if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
3705                 {
3706                 len = s->next_proto_negotiated_len;
3707                 padding_len = 32 - ((len + 2) % 32);
3708                 d = (unsigned char *)s->init_buf->data;
3709                 d[4] = len;
3710                 memcpy(d + 5, s->next_proto_negotiated, len);
3711                 d[5 + len] = padding_len;
3712                 memset(d + 6 + len, 0, padding_len);
3713                 *(d++)=SSL3_MT_NEXT_PROTO;
3714                 l2n3(2 + len + padding_len, d);
3715                 s->state = SSL3_ST_CW_NEXT_PROTO_B;
3716                 s->init_num = 4 + 2 + len + padding_len;
3717                 s->init_off = 0;
3718                 }
3719
3720         return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3721         }
3722 # endif
3723
3724 int ssl3_check_finished(SSL *s)
3725         {
3726         int ok;
3727         long n;
3728
3729         /* If we have no ticket it cannot be a resumed session. */
3730         if (!s->session->tlsext_tick)
3731                 return 1;
3732         /* this function is called when we really expect a Certificate
3733          * message, so permit appropriate message length */
3734         n=s->method->ssl_get_message(s,
3735                 SSL3_ST_CR_CERT_A,
3736                 SSL3_ST_CR_CERT_B,
3737                 -1,
3738                 s->max_cert_list,
3739                 &ok);
3740         if (!ok) return((int)n);
3741         s->s3->tmp.reuse_message = 1;
3742
3743         if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
3744                 || (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
3745                 return 2;
3746
3747         return 1;
3748         }
3749 #endif
3750
3751 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3752         {
3753         int i = 0;
3754 #ifndef OPENSSL_NO_ENGINE
3755         if (s->ctx->client_cert_engine)
3756                 {
3757                 i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3758                                                 SSL_get_client_CA_list(s),
3759                                                 px509, ppkey, NULL, NULL, NULL);
3760                 if (i != 0)
3761                         return i;
3762                 }
3763 #endif
3764         if (s->ctx->client_cert_cb)
3765                 i = s->ctx->client_cert_cb(s,px509,ppkey);
3766         return i;
3767         }