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