Further TLS extension updates
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.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-2006 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 #define REUSE_CIPHER_BUG
126 #define NETSCAPE_HANG_BUG
127
128 #include <stdio.h>
129 #include "ssl_locl.h"
130 #include "kssl_lcl.h"
131 #include <openssl/buffer.h>
132 #include <openssl/rand.h>
133 #include <openssl/objects.h>
134 #include <openssl/evp.h>
135 #include <openssl/x509.h>
136 #ifndef OPENSSL_NO_DH
137 #include <openssl/dh.h>
138 #endif
139 #include <openssl/bn.h>
140 #ifndef OPENSSL_NO_KRB5
141 #include <openssl/krb5_asn.h>
142 #endif
143 #include <openssl/md5.h>
144
145 static const SSL_METHOD *ssl3_get_server_method(int ver);
146
147 #ifndef OPENSSL_NO_ECDH
148 static int nid2curve_id(int nid);
149 #endif
150
151 static const SSL_METHOD *ssl3_get_server_method(int ver)
152         {
153         if (ver == SSL3_VERSION)
154                 return(SSLv3_server_method());
155         else
156                 return(NULL);
157         }
158
159 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
160                         ssl3_accept,
161                         ssl_undefined_function,
162                         ssl3_get_server_method)
163
164 int ssl3_accept(SSL *s)
165         {
166         BUF_MEM *buf;
167         unsigned long l,Time=(unsigned long)time(NULL);
168         void (*cb)(const SSL *ssl,int type,int val)=NULL;
169         long num1;
170         int ret= -1;
171         int new_state,state,skip=0;
172
173         RAND_add(&Time,sizeof(Time),0);
174         ERR_clear_error();
175         clear_sys_error();
176
177         if (s->info_callback != NULL)
178                 cb=s->info_callback;
179         else if (s->ctx->info_callback != NULL)
180                 cb=s->ctx->info_callback;
181
182         /* init things to blank */
183         s->in_handshake++;
184         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
185
186         if (s->cert == NULL)
187                 {
188                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
189                 return(-1);
190                 }
191
192         for (;;)
193                 {
194                 state=s->state;
195
196                 switch (s->state)
197                         {
198                 case SSL_ST_RENEGOTIATE:
199                         s->new_session=1;
200                         /* s->state=SSL_ST_ACCEPT; */
201
202                 case SSL_ST_BEFORE:
203                 case SSL_ST_ACCEPT:
204                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
205                 case SSL_ST_OK|SSL_ST_ACCEPT:
206
207                         s->server=1;
208                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
209
210                         if ((s->version>>8) != 3)
211                                 {
212                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
213                                 return -1;
214                                 }
215                         s->type=SSL_ST_ACCEPT;
216
217                         if (s->init_buf == NULL)
218                                 {
219                                 if ((buf=BUF_MEM_new()) == NULL)
220                                         {
221                                         ret= -1;
222                                         goto end;
223                                         }
224                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
225                                         {
226                                         ret= -1;
227                                         goto end;
228                                         }
229                                 s->init_buf=buf;
230                                 }
231
232                         if (!ssl3_setup_buffers(s))
233                                 {
234                                 ret= -1;
235                                 goto end;
236                                 }
237
238                         s->init_num=0;
239
240                         if (s->state != SSL_ST_RENEGOTIATE)
241                                 {
242                                 /* Ok, we now need to push on a buffering BIO so that
243                                  * the output is sent in a way that TCP likes :-)
244                                  */
245                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
246                                 
247                                 ssl3_init_finished_mac(s);
248                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
249                                 s->ctx->stats.sess_accept++;
250                                 }
251                         else
252                                 {
253                                 /* s->state == SSL_ST_RENEGOTIATE,
254                                  * we will just send a HelloRequest */
255                                 s->ctx->stats.sess_accept_renegotiate++;
256                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
257                                 }
258                         break;
259
260                 case SSL3_ST_SW_HELLO_REQ_A:
261                 case SSL3_ST_SW_HELLO_REQ_B:
262
263                         s->shutdown=0;
264                         ret=ssl3_send_hello_request(s);
265                         if (ret <= 0) goto end;
266                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
267                         s->state=SSL3_ST_SW_FLUSH;
268                         s->init_num=0;
269
270                         ssl3_init_finished_mac(s);
271                         break;
272
273                 case SSL3_ST_SW_HELLO_REQ_C:
274                         s->state=SSL_ST_OK;
275                         break;
276
277                 case SSL3_ST_SR_CLNT_HELLO_A:
278                 case SSL3_ST_SR_CLNT_HELLO_B:
279                 case SSL3_ST_SR_CLNT_HELLO_C:
280
281                         s->shutdown=0;
282                         ret=ssl3_get_client_hello(s);
283                         if (ret <= 0) goto end;
284 #ifndef OPENSSL_NO_TLSEXT
285                         {
286                                 int al,warn;
287                                 warn = ssl_check_tlsext(s,&al);
288                                 if (warn == 0)
289                                         ssl3_send_alert(s,SSL3_AL_WARNING,al); 
290                                 else if (warn < 0) {
291                                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
292                                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLS_EXT);
293                                         ret = -1;
294                                         goto end;
295                                 }
296                         }
297 #endif
298                         s->new_session = 2;
299                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
300                         s->init_num=0;
301                         break;
302
303                 case SSL3_ST_SW_SRVR_HELLO_A:
304                 case SSL3_ST_SW_SRVR_HELLO_B:
305                         ret=ssl3_send_server_hello(s);
306                         if (ret <= 0) goto end;
307
308                         if (s->hit)
309                                 s->state=SSL3_ST_SW_CHANGE_A;
310                         else
311                                 s->state=SSL3_ST_SW_CERT_A;
312                         s->init_num=0;
313                         break;
314
315                 case SSL3_ST_SW_CERT_A:
316                 case SSL3_ST_SW_CERT_B:
317                         /* Check if it is anon DH or anon ECDH */
318                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
319                                 {
320                                 ret=ssl3_send_server_certificate(s);
321                                 if (ret <= 0) goto end;
322                                 }
323                         else
324                                 skip=1;
325                         s->state=SSL3_ST_SW_KEY_EXCH_A;
326                         s->init_num=0;
327                         break;
328
329                 case SSL3_ST_SW_KEY_EXCH_A:
330                 case SSL3_ST_SW_KEY_EXCH_B:
331                         l=s->s3->tmp.new_cipher->algorithms;
332
333                         /* clear this, it may get reset by
334                          * send_server_key_exchange */
335                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
336 #ifndef OPENSSL_NO_KRB5
337                                 && !(l & SSL_KRB5)
338 #endif /* OPENSSL_NO_KRB5 */
339                                 )
340                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
341                                  * even when forbidden by protocol specs
342                                  * (handshake may fail as clients are not required to
343                                  * be able to handle this) */
344                                 s->s3->tmp.use_rsa_tmp=1;
345                         else
346                                 s->s3->tmp.use_rsa_tmp=0;
347
348
349                         /* only send if a DH key exchange, fortezza or
350                          * RSA but we have a sign only certificate
351                          *
352                          * For ECC ciphersuites, we send a serverKeyExchange
353                          * message only if the cipher suite is either
354                          * ECDH-anon or ECDHE. In other cases, the
355                          * server certificate contains the server's 
356                          * public key for key exchange.
357                          */
358                         if (s->s3->tmp.use_rsa_tmp
359                             || (l & SSL_kECDHE)
360                             || (l & (SSL_DH|SSL_kFZA))
361                             || ((l & SSL_kRSA)
362                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
363                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
364                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
365                                         )
366                                     )
367                                 )
368                             )
369                                 {
370                                 ret=ssl3_send_server_key_exchange(s);
371                                 if (ret <= 0) goto end;
372                                 }
373                         else
374                                 skip=1;
375
376                         s->state=SSL3_ST_SW_CERT_REQ_A;
377                         s->init_num=0;
378                         break;
379
380                 case SSL3_ST_SW_CERT_REQ_A:
381                 case SSL3_ST_SW_CERT_REQ_B:
382                         if (/* don't request cert unless asked for it: */
383                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
384                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
385                                  * don't request cert during re-negotiation: */
386                                 ((s->session->peer != NULL) &&
387                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
388                                 /* never request cert in anonymous ciphersuites
389                                  * (see section "Certificate request" in SSL 3 drafts
390                                  * and in RFC 2246): */
391                                 ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
392                                  /* ... except when the application insists on verification
393                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
394                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
395                                  /* never request cert in Kerberos ciphersuites */
396                                 (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
397                                 {
398                                 /* no cert request */
399                                 skip=1;
400                                 s->s3->tmp.cert_request=0;
401                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
402                                 }
403                         else
404                                 {
405                                 s->s3->tmp.cert_request=1;
406                                 ret=ssl3_send_certificate_request(s);
407                                 if (ret <= 0) goto end;
408 #ifndef NETSCAPE_HANG_BUG
409                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
410 #else
411                                 s->state=SSL3_ST_SW_FLUSH;
412                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
413 #endif
414                                 s->init_num=0;
415                                 }
416                         break;
417
418                 case SSL3_ST_SW_SRVR_DONE_A:
419                 case SSL3_ST_SW_SRVR_DONE_B:
420                         ret=ssl3_send_server_done(s);
421                         if (ret <= 0) goto end;
422                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
423                         s->state=SSL3_ST_SW_FLUSH;
424                         s->init_num=0;
425                         break;
426                 
427                 case SSL3_ST_SW_FLUSH:
428                         /* number of bytes to be flushed */
429                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
430                         if (num1 > 0)
431                                 {
432                                 s->rwstate=SSL_WRITING;
433                                 num1=BIO_flush(s->wbio);
434                                 if (num1 <= 0) { ret= -1; goto end; }
435                                 s->rwstate=SSL_NOTHING;
436                                 }
437
438                         s->state=s->s3->tmp.next_state;
439                         break;
440
441                 case SSL3_ST_SR_CERT_A:
442                 case SSL3_ST_SR_CERT_B:
443                         /* Check for second client hello (MS SGC) */
444                         ret = ssl3_check_client_hello(s);
445                         if (ret <= 0)
446                                 goto end;
447                         if (ret == 2)
448                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
449                         else {
450                                 if (s->s3->tmp.cert_request)
451                                         {
452                                         ret=ssl3_get_client_certificate(s);
453                                         if (ret <= 0) goto end;
454                                         }
455                                 s->init_num=0;
456                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
457                         }
458                         break;
459
460                 case SSL3_ST_SR_KEY_EXCH_A:
461                 case SSL3_ST_SR_KEY_EXCH_B:
462                         ret=ssl3_get_client_key_exchange(s);
463                         if (ret <= 0) 
464                                 goto end;
465                         if (ret == 2)
466                                 {
467                                 /* For the ECDH ciphersuites when
468                                  * the client sends its ECDH pub key in
469                                  * a certificate, the CertificateVerify
470                                  * message is not sent.
471                                  */
472                                 s->state=SSL3_ST_SR_FINISHED_A;
473                                 s->init_num = 0;
474                                 }
475                         else   
476                                 {
477                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
478                                 s->init_num=0;
479
480                                 /* We need to get hashes here so if there is
481                                  * a client cert, it can be verified
482                                  */ 
483                                 s->method->ssl3_enc->cert_verify_mac(s,
484                                     &(s->s3->finish_dgst1),
485                                     &(s->s3->tmp.cert_verify_md[0]));
486                                 s->method->ssl3_enc->cert_verify_mac(s,
487                                     &(s->s3->finish_dgst2),
488                                     &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));
489                                 }
490                         break;
491
492                 case SSL3_ST_SR_CERT_VRFY_A:
493                 case SSL3_ST_SR_CERT_VRFY_B:
494
495                         /* we should decide if we expected this one */
496                         ret=ssl3_get_cert_verify(s);
497                         if (ret <= 0) goto end;
498
499                         s->state=SSL3_ST_SR_FINISHED_A;
500                         s->init_num=0;
501                         break;
502
503                 case SSL3_ST_SR_FINISHED_A:
504                 case SSL3_ST_SR_FINISHED_B:
505                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
506                                 SSL3_ST_SR_FINISHED_B);
507                         if (ret <= 0) goto end;
508                         if (s->hit)
509                                 s->state=SSL_ST_OK;
510                         else
511                                 s->state=SSL3_ST_SW_CHANGE_A;
512                         s->init_num=0;
513                         break;
514
515                 case SSL3_ST_SW_CHANGE_A:
516                 case SSL3_ST_SW_CHANGE_B:
517
518                         s->session->cipher=s->s3->tmp.new_cipher;
519                         if (!s->method->ssl3_enc->setup_key_block(s))
520                                 { ret= -1; goto end; }
521
522                         ret=ssl3_send_change_cipher_spec(s,
523                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
524
525                         if (ret <= 0) goto end;
526                         s->state=SSL3_ST_SW_FINISHED_A;
527                         s->init_num=0;
528
529                         if (!s->method->ssl3_enc->change_cipher_state(s,
530                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
531                                 {
532                                 ret= -1;
533                                 goto end;
534                                 }
535
536                         break;
537
538                 case SSL3_ST_SW_FINISHED_A:
539                 case SSL3_ST_SW_FINISHED_B:
540                         ret=ssl3_send_finished(s,
541                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
542                                 s->method->ssl3_enc->server_finished_label,
543                                 s->method->ssl3_enc->server_finished_label_len);
544                         if (ret <= 0) goto end;
545                         s->state=SSL3_ST_SW_FLUSH;
546                         if (s->hit)
547                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
548                         else
549                                 s->s3->tmp.next_state=SSL_ST_OK;
550                         s->init_num=0;
551                         break;
552
553                 case SSL_ST_OK:
554                         /* clean a few things up */
555                         ssl3_cleanup_key_block(s);
556
557                         BUF_MEM_free(s->init_buf);
558                         s->init_buf=NULL;
559
560                         /* remove buffering on output */
561                         ssl_free_wbio_buffer(s);
562
563                         s->init_num=0;
564
565                         if (s->new_session == 2) /* skipped if we just sent a HelloRequest */
566                                 {
567                                 /* actually not necessarily a 'new' session unless
568                                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
569                                 
570                                 s->new_session=0;
571                                 
572                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
573                                 
574                                 s->ctx->stats.sess_accept_good++;
575                                 /* s->server=1; */
576                                 s->handshake_func=ssl3_accept;
577
578                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
579                                 }
580                         
581                         ret = 1;
582                         goto end;
583                         /* break; */
584
585                 default:
586                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
587                         ret= -1;
588                         goto end;
589                         /* break; */
590                         }
591                 
592                 if (!s->s3->tmp.reuse_message && !skip)
593                         {
594                         if (s->debug)
595                                 {
596                                 if ((ret=BIO_flush(s->wbio)) <= 0)
597                                         goto end;
598                                 }
599
600
601                         if ((cb != NULL) && (s->state != state))
602                                 {
603                                 new_state=s->state;
604                                 s->state=state;
605                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
606                                 s->state=new_state;
607                                 }
608                         }
609                 skip=0;
610                 }
611 end:
612         /* BIO_flush(s->wbio); */
613
614         s->in_handshake--;
615         if (cb != NULL)
616                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
617         return(ret);
618         }
619
620 int ssl3_send_hello_request(SSL *s)
621         {
622         unsigned char *p;
623
624         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
625                 {
626                 p=(unsigned char *)s->init_buf->data;
627                 *(p++)=SSL3_MT_HELLO_REQUEST;
628                 *(p++)=0;
629                 *(p++)=0;
630                 *(p++)=0;
631
632                 s->state=SSL3_ST_SW_HELLO_REQ_B;
633                 /* number of bytes to write */
634                 s->init_num=4;
635                 s->init_off=0;
636                 }
637
638         /* SSL3_ST_SW_HELLO_REQ_B */
639         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
640         }
641
642 int ssl3_check_client_hello(SSL *s)
643         {
644         int ok;
645         long n;
646
647         /* this function is called when we really expect a Certificate message,
648          * so permit appropriate message length */
649         n=s->method->ssl_get_message(s,
650                 SSL3_ST_SR_CERT_A,
651                 SSL3_ST_SR_CERT_B,
652                 -1,
653                 s->max_cert_list,
654                 &ok);
655         if (!ok) return((int)n);
656         s->s3->tmp.reuse_message = 1;
657         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
658                 {
659                 /* Throw away what we have done so far in the current handshake,
660                  * which will now be aborted. (A full SSL_clear would be too much.)
661                  * I hope that tmp.dh is the only thing that may need to be cleared
662                  * when a handshake is not completed ... */
663 #ifndef OPENSSL_NO_DH
664                 if (s->s3->tmp.dh != NULL)
665                         {
666                         DH_free(s->s3->tmp.dh);
667                         s->s3->tmp.dh = NULL;
668                         }
669 #endif
670                 return 2;
671                 }
672         return 1;
673 }
674
675 int ssl3_get_client_hello(SSL *s)
676         {
677         int i,j,ok,al,ret= -1;
678         unsigned int cookie_len;
679         long n;
680         unsigned long id;
681         unsigned char *p,*d,*q;
682         SSL_CIPHER *c;
683 #ifndef OPENSSL_NO_COMP
684         SSL_COMP *comp=NULL;
685 #endif
686         STACK_OF(SSL_CIPHER) *ciphers=NULL;
687
688         /* We do this so that we will respond with our native type.
689          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
690          * This down switching should be handled by a different method.
691          * If we are SSLv3, we will respond with SSLv3, even if prompted with
692          * TLSv1.
693          */
694         if (s->state == SSL3_ST_SR_CLNT_HELLO_A)
695                 {
696                 s->first_packet=1;
697                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
698                 }
699         n=s->method->ssl_get_message(s,
700                 SSL3_ST_SR_CLNT_HELLO_B,
701                 SSL3_ST_SR_CLNT_HELLO_C,
702                 SSL3_MT_CLIENT_HELLO,
703                 SSL3_RT_MAX_PLAIN_LENGTH,
704                 &ok);
705
706         if (!ok) return((int)n);
707         d=p=(unsigned char *)s->init_msg;
708
709         /* use version from inside client hello, not from record header
710          * (may differ: see RFC 2246, Appendix E, second paragraph) */
711         s->client_version=(((int)p[0])<<8)|(int)p[1];
712         p+=2;
713
714         if (s->client_version < s->version)
715                 {
716                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
717                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR) 
718                         {
719                         /* similar to ssl3_get_record, send alert using remote version number */
720                         s->version = s->client_version;
721                         }
722                 al = SSL_AD_PROTOCOL_VERSION;
723                 goto f_err;
724                 }
725
726         /* load the client random */
727         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
728         p+=SSL3_RANDOM_SIZE;
729
730         /* get the session-id */
731         j= *(p++);
732
733         s->hit=0;
734         /* Versions before 0.9.7 always allow session reuse during renegotiation
735          * (i.e. when s->new_session is true), option
736          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7.
737          * Maybe this optional behaviour should always have been the default,
738          * but we cannot safely change the default behaviour (or new applications
739          * might be written that become totally unsecure when compiled with
740          * an earlier library version)
741          */
742         if (j == 0 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
743                 {
744                 if (!ssl_get_new_session(s,1))
745                         goto err;
746                 }
747         else
748                 {
749                 i=ssl_get_prev_session(s,p,j);
750                 if (i == 1)
751                         { /* previous session */
752                         s->hit=1;
753                         }
754                 else if (i == -1)
755                         goto err;
756                 else /* i == 0 */
757                         {
758                         if (!ssl_get_new_session(s,1))
759                                 goto err;
760                         }
761                 }
762
763         p+=j;
764
765         if (SSL_version(s) == DTLS1_VERSION)
766                 {
767                 /* cookie stuff */
768                 cookie_len = *(p++);
769
770                 if ( (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
771                         s->d1->send_cookie == 0)
772                         {
773                         /* HelloVerifyMessage has already been sent */
774                         if ( cookie_len != s->d1->cookie_len)
775                                 {
776                                 al = SSL_AD_HANDSHAKE_FAILURE;
777                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
778                                 goto f_err;
779                                 }
780                         }
781
782                 /* 
783                  * The ClientHello may contain a cookie even if the
784                  * HelloVerify message has not been sent--make sure that it
785                  * does not cause an overflow.
786                  */
787                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
788                         {
789                         /* too much data */
790                         al = SSL_AD_DECODE_ERROR;
791                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
792                         goto f_err;
793                         }
794
795                 /* verify the cookie if appropriate option is set. */
796                 if ( (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
797                         cookie_len > 0)
798                         {
799                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
800
801                         if ( s->ctx->app_verify_cookie_cb != NULL)
802                                 {
803                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
804                                         cookie_len) == 0)
805                                         {
806                                         al=SSL_AD_HANDSHAKE_FAILURE;
807                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
808                                                 SSL_R_COOKIE_MISMATCH);
809                                         goto f_err;
810                                         }
811                                 /* else cookie verification succeeded */
812                                 }
813                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
814                                                   s->d1->cookie_len) != 0) /* default verification */
815                                 {
816                                         al=SSL_AD_HANDSHAKE_FAILURE;
817                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
818                                                 SSL_R_COOKIE_MISMATCH);
819                                         goto f_err;
820                                 }
821                         }
822
823                 p += cookie_len;
824                 }
825
826         n2s(p,i);
827         if ((i == 0) && (j != 0))
828                 {
829                 /* we need a cipher if we are not resuming a session */
830                 al=SSL_AD_ILLEGAL_PARAMETER;
831                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
832                 goto f_err;
833                 }
834         if ((p+i) >= (d+n))
835                 {
836                 /* not enough data */
837                 al=SSL_AD_DECODE_ERROR;
838                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
839                 goto f_err;
840                 }
841         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
842                 == NULL))
843                 {
844                 goto err;
845                 }
846         p+=i;
847
848         /* If it is a hit, check that the cipher is in the list */
849         if ((s->hit) && (i > 0))
850                 {
851                 j=0;
852                 id=s->session->cipher->id;
853
854 #ifdef CIPHER_DEBUG
855                 printf("client sent %d ciphers\n",sk_num(ciphers));
856 #endif
857                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
858                         {
859                         c=sk_SSL_CIPHER_value(ciphers,i);
860 #ifdef CIPHER_DEBUG
861                         printf("client [%2d of %2d]:%s\n",
862                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
863 #endif
864                         if (c->id == id)
865                                 {
866                                 j=1;
867                                 break;
868                                 }
869                         }
870                 if (j == 0)
871                         {
872                         if ((s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
873                                 {
874                                 /* Very bad for multi-threading.... */
875                                 s->session->cipher=sk_SSL_CIPHER_value(ciphers, 0);
876                                 }
877                         else
878                                 {
879                                 /* we need to have the cipher in the cipher
880                                  * list if we are asked to reuse it */
881                                 al=SSL_AD_ILLEGAL_PARAMETER;
882                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
883                                 goto f_err;
884                                 }
885                         }
886                 }
887
888         /* compression */
889         i= *(p++);
890         if ((p+i) > (d+n))
891                 {
892                 /* not enough data */
893                 al=SSL_AD_DECODE_ERROR;
894                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
895                 goto f_err;
896                 }
897         q=p;
898         for (j=0; j<i; j++)
899                 {
900                 if (p[j] == 0) break;
901                 }
902
903         p+=i;
904         if (j >= i)
905                 {
906                 /* no compress */
907                 al=SSL_AD_DECODE_ERROR;
908                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
909                 goto f_err;
910                 }
911
912         /* Worst case, we will use the NULL compression, but if we have other
913          * options, we will now look for them.  We have i-1 compression
914          * algorithms from the client, starting at q. */
915         s->s3->tmp.new_compression=NULL;
916 #ifndef OPENSSL_NO_COMP
917         if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
918                 { /* See if we have a match */
919                 int m,nn,o,v,done=0;
920
921                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
922                 for (m=0; m<nn; m++)
923                         {
924                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
925                         v=comp->id;
926                         for (o=0; o<i; o++)
927                                 {
928                                 if (v == q[o])
929                                         {
930                                         done=1;
931                                         break;
932                                         }
933                                 }
934                         if (done) break;
935                         }
936                 if (done)
937                         s->s3->tmp.new_compression=comp;
938                 else
939                         comp=NULL;
940                 }
941 #endif
942
943 #ifndef OPENSSL_NO_TLSEXT
944         /* TLS extensions*/
945         if (s->version > SSL3_VERSION)
946                 {
947                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
948                         {
949                         /* 'al' set by ssl_parse_clienthello_tlsext */
950                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLS_EXT);
951                         goto f_err;
952                         }
953                 }
954 #endif
955
956         /* Given s->session->ciphers and SSL_get_ciphers, we must
957          * pick a cipher */
958
959         if (!s->hit)
960                 {
961 #ifdef OPENSSL_NO_COMP
962                 s->session->compress_meth=0;
963 #else
964                 s->session->compress_meth=(comp == NULL)?0:comp->id;
965 #endif
966                 if (s->session->ciphers != NULL)
967                         sk_SSL_CIPHER_free(s->session->ciphers);
968                 s->session->ciphers=ciphers;
969                 if (ciphers == NULL)
970                         {
971                         al=SSL_AD_ILLEGAL_PARAMETER;
972                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
973                         goto f_err;
974                         }
975                 ciphers=NULL;
976                 c=ssl3_choose_cipher(s,s->session->ciphers,
977                                      SSL_get_ciphers(s));
978
979                 if (c == NULL)
980                         {
981                         al=SSL_AD_HANDSHAKE_FAILURE;
982                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
983                         goto f_err;
984                         }
985                 s->s3->tmp.new_cipher=c;
986                 }
987         else
988                 {
989                 /* Session-id reuse */
990 #ifdef REUSE_CIPHER_BUG
991                 STACK_OF(SSL_CIPHER) *sk;
992                 SSL_CIPHER *nc=NULL;
993                 SSL_CIPHER *ec=NULL;
994
995                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
996                         {
997                         sk=s->session->ciphers;
998                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
999                                 {
1000                                 c=sk_SSL_CIPHER_value(sk,i);
1001                                 if (c->algorithms & SSL_eNULL)
1002                                         nc=c;
1003                                 if (SSL_C_IS_EXPORT(c))
1004                                         ec=c;
1005                                 }
1006                         if (nc != NULL)
1007                                 s->s3->tmp.new_cipher=nc;
1008                         else if (ec != NULL)
1009                                 s->s3->tmp.new_cipher=ec;
1010                         else
1011                                 s->s3->tmp.new_cipher=s->session->cipher;
1012                         }
1013                 else
1014 #endif
1015                 s->s3->tmp.new_cipher=s->session->cipher;
1016                 }
1017         
1018         /* we now have the following setup. 
1019          * client_random
1020          * cipher_list          - our prefered list of ciphers
1021          * ciphers              - the clients prefered list of ciphers
1022          * compression          - basically ignored right now
1023          * ssl version is set   - sslv3
1024          * s->session           - The ssl session has been setup.
1025          * s->hit               - session reuse flag
1026          * s->tmp.new_cipher    - the new cipher to use.
1027          */
1028
1029         ret=1;
1030         if (0)
1031                 {
1032 f_err:
1033                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1034                 }
1035 err:
1036         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1037         return(ret);
1038         }
1039
1040 int ssl3_send_server_hello(SSL *s)
1041         {
1042         unsigned char *buf;
1043         unsigned char *p,*d;
1044         int i,sl;
1045         unsigned long l,Time;
1046
1047         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1048                 {
1049                 buf=(unsigned char *)s->init_buf->data;
1050                 p=s->s3->server_random;
1051                 Time=(unsigned long)time(NULL);                 /* Time */
1052                 l2n(Time,p);
1053                 if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
1054                         return -1;
1055                 /* Do the message type and length last */
1056                 d=p= &(buf[4]);
1057
1058                 *(p++)=s->version>>8;
1059                 *(p++)=s->version&0xff;
1060
1061                 /* Random stuff */
1062                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1063                 p+=SSL3_RANDOM_SIZE;
1064
1065                 /* now in theory we have 3 options to sending back the
1066                  * session id.  If it is a re-use, we send back the
1067                  * old session-id, if it is a new session, we send
1068                  * back the new session-id or we send back a 0 length
1069                  * session-id if we want it to be single use.
1070                  * Currently I will not implement the '0' length session-id
1071                  * 12-Jan-98 - I'll now support the '0' length stuff.
1072                  */
1073                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER))
1074                         s->session->session_id_length=0;
1075
1076                 sl=s->session->session_id_length;
1077                 if (sl > (int)sizeof(s->session->session_id))
1078                         {
1079                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1080                         return -1;
1081                         }
1082                 *(p++)=sl;
1083                 memcpy(p,s->session->session_id,sl);
1084                 p+=sl;
1085
1086                 /* put the cipher */
1087                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1088                 p+=i;
1089
1090                 /* put the compression method */
1091 #ifdef OPENSSL_NO_COMP
1092                         *(p++)=0;
1093 #else
1094                 if (s->s3->tmp.new_compression == NULL)
1095                         *(p++)=0;
1096                 else
1097                         *(p++)=s->s3->tmp.new_compression->id;
1098 #endif
1099 #ifndef OPENSSL_NO_TLSEXT
1100                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1101                         {
1102                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1103                         return -1;
1104                         }
1105 #endif
1106
1107                 /* do the header */
1108                 l=(p-d);
1109                 d=buf;
1110                 *(d++)=SSL3_MT_SERVER_HELLO;
1111                 l2n3(l,d);
1112
1113                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
1114                 /* number of bytes to write */
1115                 s->init_num=p-buf;
1116                 s->init_off=0;
1117                 }
1118
1119         /* SSL3_ST_CW_CLNT_HELLO_B */
1120         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1121         }
1122
1123 int ssl3_send_server_done(SSL *s)
1124         {
1125         unsigned char *p;
1126
1127         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1128                 {
1129                 p=(unsigned char *)s->init_buf->data;
1130
1131                 /* do the header */
1132                 *(p++)=SSL3_MT_SERVER_DONE;
1133                 *(p++)=0;
1134                 *(p++)=0;
1135                 *(p++)=0;
1136
1137                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1138                 /* number of bytes to write */
1139                 s->init_num=4;
1140                 s->init_off=0;
1141                 }
1142
1143         /* SSL3_ST_CW_CLNT_HELLO_B */
1144         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1145         }
1146
1147 int ssl3_send_server_key_exchange(SSL *s)
1148         {
1149 #ifndef OPENSSL_NO_RSA
1150         unsigned char *q;
1151         int j,num;
1152         RSA *rsa;
1153         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1154         unsigned int u;
1155 #endif
1156 #ifndef OPENSSL_NO_DH
1157         DH *dh=NULL,*dhp;
1158 #endif
1159 #ifndef OPENSSL_NO_ECDH
1160         EC_KEY *ecdh=NULL, *ecdhp;
1161         unsigned char *encodedPoint = NULL;
1162         int encodedlen = 0;
1163         int curve_id = 0;
1164         BN_CTX *bn_ctx = NULL; 
1165 #endif
1166         EVP_PKEY *pkey;
1167         unsigned char *p,*d;
1168         int al,i;
1169         unsigned long type;
1170         int n;
1171         CERT *cert;
1172         BIGNUM *r[4];
1173         int nr[4],kn;
1174         BUF_MEM *buf;
1175         EVP_MD_CTX md_ctx;
1176
1177         EVP_MD_CTX_init(&md_ctx);
1178         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1179                 {
1180                 type=s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1181                 cert=s->cert;
1182
1183                 buf=s->init_buf;
1184
1185                 r[0]=r[1]=r[2]=r[3]=NULL;
1186                 n=0;
1187 #ifndef OPENSSL_NO_RSA
1188                 if (type & SSL_kRSA)
1189                         {
1190                         rsa=cert->rsa_tmp;
1191                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1192                                 {
1193                                 rsa=s->cert->rsa_tmp_cb(s,
1194                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1195                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1196                                 if(rsa == NULL)
1197                                 {
1198                                         al=SSL_AD_HANDSHAKE_FAILURE;
1199                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1200                                         goto f_err;
1201                                 }
1202                                 RSA_up_ref(rsa);
1203                                 cert->rsa_tmp=rsa;
1204                                 }
1205                         if (rsa == NULL)
1206                                 {
1207                                 al=SSL_AD_HANDSHAKE_FAILURE;
1208                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1209                                 goto f_err;
1210                                 }
1211                         r[0]=rsa->n;
1212                         r[1]=rsa->e;
1213                         s->s3->tmp.use_rsa_tmp=1;
1214                         }
1215                 else
1216 #endif
1217 #ifndef OPENSSL_NO_DH
1218                         if (type & SSL_kEDH)
1219                         {
1220                         dhp=cert->dh_tmp;
1221                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1222                                 dhp=s->cert->dh_tmp_cb(s,
1223                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1224                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1225                         if (dhp == NULL)
1226                                 {
1227                                 al=SSL_AD_HANDSHAKE_FAILURE;
1228                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1229                                 goto f_err;
1230                                 }
1231
1232                         if (s->s3->tmp.dh != NULL)
1233                                 {
1234                                 DH_free(dh);
1235                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1236                                 goto err;
1237                                 }
1238
1239                         if ((dh=DHparams_dup(dhp)) == NULL)
1240                                 {
1241                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1242                                 goto err;
1243                                 }
1244
1245                         s->s3->tmp.dh=dh;
1246                         if ((dhp->pub_key == NULL ||
1247                              dhp->priv_key == NULL ||
1248                              (s->options & SSL_OP_SINGLE_DH_USE)))
1249                                 {
1250                                 if(!DH_generate_key(dh))
1251                                     {
1252                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1253                                            ERR_R_DH_LIB);
1254                                     goto err;
1255                                     }
1256                                 }
1257                         else
1258                                 {
1259                                 dh->pub_key=BN_dup(dhp->pub_key);
1260                                 dh->priv_key=BN_dup(dhp->priv_key);
1261                                 if ((dh->pub_key == NULL) ||
1262                                         (dh->priv_key == NULL))
1263                                         {
1264                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1265                                         goto err;
1266                                         }
1267                                 }
1268                         r[0]=dh->p;
1269                         r[1]=dh->g;
1270                         r[2]=dh->pub_key;
1271                         }
1272                 else 
1273 #endif
1274 #ifndef OPENSSL_NO_ECDH
1275                         if (type & SSL_kECDHE)
1276                         {
1277                         const EC_GROUP *group;
1278
1279                         ecdhp=cert->ecdh_tmp;
1280                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1281                                 {
1282                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1283                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1284                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1285                                 }
1286                         if (ecdhp == NULL)
1287                                 {
1288                                 al=SSL_AD_HANDSHAKE_FAILURE;
1289                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1290                                 goto f_err;
1291                                 }
1292
1293                         if (s->s3->tmp.ecdh != NULL)
1294                                 {
1295                                 EC_KEY_free(s->s3->tmp.ecdh); 
1296                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1297                                 goto err;
1298                                 }
1299
1300                         /* Duplicate the ECDH structure. */
1301                         if (ecdhp == NULL)
1302                                 {
1303                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1304                                 goto err;
1305                                 }
1306                         if (!EC_KEY_up_ref(ecdhp))
1307                                 {
1308                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1309                                 goto err;
1310                                 }
1311                         ecdh = ecdhp;
1312
1313                         s->s3->tmp.ecdh=ecdh;
1314                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1315                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1316                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1317                                 {
1318                                 if(!EC_KEY_generate_key(ecdh))
1319                                     {
1320                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1321                                     goto err;
1322                                     }
1323                                 }
1324
1325                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1326                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1327                             (EC_KEY_get0_private_key(ecdh) == NULL))
1328                                 {
1329                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1330                                 goto err;
1331                                 }
1332
1333                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1334                             (EC_GROUP_get_degree(group) > 163)) 
1335                                 {
1336                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1337                                 goto err;
1338                                 }
1339
1340                         /* XXX: For now, we only support ephemeral ECDH
1341                          * keys over named (not generic) curves. For 
1342                          * supported named curves, curve_id is non-zero.
1343                          */
1344                         if ((curve_id = 
1345                             nid2curve_id(EC_GROUP_get_curve_name(group)))
1346                             == 0)
1347                                 {
1348                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1349                                 goto err;
1350                                 }
1351
1352                         /* Encode the public key.
1353                          * First check the size of encoding and
1354                          * allocate memory accordingly.
1355                          */
1356                         encodedlen = EC_POINT_point2oct(group, 
1357                             EC_KEY_get0_public_key(ecdh),
1358                             POINT_CONVERSION_UNCOMPRESSED, 
1359                             NULL, 0, NULL);
1360
1361                         encodedPoint = (unsigned char *) 
1362                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1363                         bn_ctx = BN_CTX_new();
1364                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1365                                 {
1366                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1367                                 goto err;
1368                                 }
1369
1370
1371                         encodedlen = EC_POINT_point2oct(group, 
1372                             EC_KEY_get0_public_key(ecdh), 
1373                             POINT_CONVERSION_UNCOMPRESSED, 
1374                             encodedPoint, encodedlen, bn_ctx);
1375
1376                         if (encodedlen == 0) 
1377                                 {
1378                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1379                                 goto err;
1380                                 }
1381
1382                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1383
1384                         /* XXX: For now, we only support named (not 
1385                          * generic) curves in ECDH ephemeral key exchanges.
1386                          * In this situation, we need four additional bytes
1387                          * to encode the entire ServerECDHParams
1388                          * structure. 
1389                          */
1390                         n = 4 + encodedlen;
1391
1392                         /* We'll generate the serverKeyExchange message
1393                          * explicitly so we can set these to NULLs
1394                          */
1395                         r[0]=NULL;
1396                         r[1]=NULL;
1397                         r[2]=NULL;
1398                         r[3]=NULL;
1399                         }
1400                 else 
1401 #endif /* !OPENSSL_NO_ECDH */
1402                         {
1403                         al=SSL_AD_HANDSHAKE_FAILURE;
1404                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1405                         goto f_err;
1406                         }
1407                 for (i=0; r[i] != NULL; i++)
1408                         {
1409                         nr[i]=BN_num_bytes(r[i]);
1410                         n+=2+nr[i];
1411                         }
1412
1413                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1414                         {
1415                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1416                                 == NULL)
1417                                 {
1418                                 al=SSL_AD_DECODE_ERROR;
1419                                 goto f_err;
1420                                 }
1421                         kn=EVP_PKEY_size(pkey);
1422                         }
1423                 else
1424                         {
1425                         pkey=NULL;
1426                         kn=0;
1427                         }
1428
1429                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1430                         {
1431                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1432                         goto err;
1433                         }
1434                 d=(unsigned char *)s->init_buf->data;
1435                 p= &(d[4]);
1436
1437                 for (i=0; r[i] != NULL; i++)
1438                         {
1439                         s2n(nr[i],p);
1440                         BN_bn2bin(r[i],p);
1441                         p+=nr[i];
1442                         }
1443
1444 #ifndef OPENSSL_NO_ECDH
1445                 if (type & SSL_kECDHE) 
1446                         {
1447                         /* XXX: For now, we only support named (not generic) curves.
1448                          * In this situation, the serverKeyExchange message has:
1449                          * [1 byte CurveType], [2 byte CurveName]
1450                          * [1 byte length of encoded point], followed by
1451                          * the actual encoded point itself
1452                          */
1453                         *p = NAMED_CURVE_TYPE;
1454                         p += 1;
1455                         *p = 0;
1456                         p += 1;
1457                         *p = curve_id;
1458                         p += 1;
1459                         *p = encodedlen;
1460                         p += 1;
1461                         memcpy((unsigned char*)p, 
1462                             (unsigned char *)encodedPoint, 
1463                             encodedlen);
1464                         OPENSSL_free(encodedPoint);
1465                         p += encodedlen;
1466                         }
1467 #endif
1468
1469                 /* not anonymous */
1470                 if (pkey != NULL)
1471                         {
1472                         /* n is the length of the params, they start at &(d[4])
1473                          * and p points to the space at the end. */
1474 #ifndef OPENSSL_NO_RSA
1475                         if (pkey->type == EVP_PKEY_RSA)
1476                                 {
1477                                 q=md_buf;
1478                                 j=0;
1479                                 for (num=2; num > 0; num--)
1480                                         {
1481                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1482                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1483                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1484                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1485                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1486                                         EVP_DigestFinal_ex(&md_ctx,q,
1487                                                 (unsigned int *)&i);
1488                                         q+=i;
1489                                         j+=i;
1490                                         }
1491                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1492                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1493                                         {
1494                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1495                                         goto err;
1496                                         }
1497                                 s2n(u,p);
1498                                 n+=u+2;
1499                                 }
1500                         else
1501 #endif
1502 #if !defined(OPENSSL_NO_DSA)
1503                                 if (pkey->type == EVP_PKEY_DSA)
1504                                 {
1505                                 /* lets do DSS */
1506                                 EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL);
1507                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1508                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1509                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1510                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1511                                         (unsigned int *)&i,pkey))
1512                                         {
1513                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1514                                         goto err;
1515                                         }
1516                                 s2n(i,p);
1517                                 n+=i+2;
1518                                 }
1519                         else
1520 #endif
1521 #if !defined(OPENSSL_NO_ECDSA)
1522                                 if (pkey->type == EVP_PKEY_EC)
1523                                 {
1524                                 /* let's do ECDSA */
1525                                 EVP_SignInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1526                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1527                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1528                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1529                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1530                                         (unsigned int *)&i,pkey))
1531                                         {
1532                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_ECDSA);
1533                                         goto err;
1534                                         }
1535                                 s2n(i,p);
1536                                 n+=i+2;
1537                                 }
1538                         else
1539 #endif
1540                                 {
1541                                 /* Is this error check actually needed? */
1542                                 al=SSL_AD_HANDSHAKE_FAILURE;
1543                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1544                                 goto f_err;
1545                                 }
1546                         }
1547
1548                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1549                 l2n3(n,d);
1550
1551                 /* we should now have things packed up, so lets send
1552                  * it off */
1553                 s->init_num=n+4;
1554                 s->init_off=0;
1555                 }
1556
1557         s->state = SSL3_ST_SW_KEY_EXCH_B;
1558         EVP_MD_CTX_cleanup(&md_ctx);
1559         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1560 f_err:
1561         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1562 err:
1563 #ifndef OPENSSL_NO_ECDH
1564         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1565         BN_CTX_free(bn_ctx);
1566 #endif
1567         EVP_MD_CTX_cleanup(&md_ctx);
1568         return(-1);
1569         }
1570
1571 int ssl3_send_certificate_request(SSL *s)
1572         {
1573         unsigned char *p,*d;
1574         int i,j,nl,off,n;
1575         STACK_OF(X509_NAME) *sk=NULL;
1576         X509_NAME *name;
1577         BUF_MEM *buf;
1578
1579         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1580                 {
1581                 buf=s->init_buf;
1582
1583                 d=p=(unsigned char *)&(buf->data[4]);
1584
1585                 /* get the list of acceptable cert types */
1586                 p++;
1587                 n=ssl3_get_req_cert_type(s,p);
1588                 d[0]=n;
1589                 p+=n;
1590                 n++;
1591
1592                 off=n;
1593                 p+=2;
1594                 n+=2;
1595
1596                 sk=SSL_get_client_CA_list(s);
1597                 nl=0;
1598                 if (sk != NULL)
1599                         {
1600                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1601                                 {
1602                                 name=sk_X509_NAME_value(sk,i);
1603                                 j=i2d_X509_NAME(name,NULL);
1604                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
1605                                         {
1606                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1607                                         goto err;
1608                                         }
1609                                 p=(unsigned char *)&(buf->data[4+n]);
1610                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1611                                         {
1612                                         s2n(j,p);
1613                                         i2d_X509_NAME(name,&p);
1614                                         n+=2+j;
1615                                         nl+=2+j;
1616                                         }
1617                                 else
1618                                         {
1619                                         d=p;
1620                                         i2d_X509_NAME(name,&p);
1621                                         j-=2; s2n(j,d); j+=2;
1622                                         n+=j;
1623                                         nl+=j;
1624                                         }
1625                                 }
1626                         }
1627                 /* else no CA names */
1628                 p=(unsigned char *)&(buf->data[4+off]);
1629                 s2n(nl,p);
1630
1631                 d=(unsigned char *)buf->data;
1632                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1633                 l2n3(n,d);
1634
1635                 /* we should now have things packed up, so lets send
1636                  * it off */
1637
1638                 s->init_num=n+4;
1639                 s->init_off=0;
1640 #ifdef NETSCAPE_HANG_BUG
1641                 p=(unsigned char *)s->init_buf->data + s->init_num;
1642
1643                 /* do the header */
1644                 *(p++)=SSL3_MT_SERVER_DONE;
1645                 *(p++)=0;
1646                 *(p++)=0;
1647                 *(p++)=0;
1648                 s->init_num += 4;
1649 #endif
1650
1651                 s->state = SSL3_ST_SW_CERT_REQ_B;
1652                 }
1653
1654         /* SSL3_ST_SW_CERT_REQ_B */
1655         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1656 err:
1657         return(-1);
1658         }
1659
1660 int ssl3_get_client_key_exchange(SSL *s)
1661         {
1662         int i,al,ok;
1663         long n;
1664         unsigned long l;
1665         unsigned char *p;
1666 #ifndef OPENSSL_NO_RSA
1667         RSA *rsa=NULL;
1668         EVP_PKEY *pkey=NULL;
1669 #endif
1670 #ifndef OPENSSL_NO_DH
1671         BIGNUM *pub=NULL;
1672         DH *dh_srvr;
1673 #endif
1674 #ifndef OPENSSL_NO_KRB5
1675         KSSL_ERR kssl_err;
1676 #endif /* OPENSSL_NO_KRB5 */
1677
1678 #ifndef OPENSSL_NO_ECDH
1679         EC_KEY *srvr_ecdh = NULL;
1680         EVP_PKEY *clnt_pub_pkey = NULL;
1681         EC_POINT *clnt_ecpoint = NULL;
1682         BN_CTX *bn_ctx = NULL; 
1683 #endif
1684
1685         n=s->method->ssl_get_message(s,
1686                 SSL3_ST_SR_KEY_EXCH_A,
1687                 SSL3_ST_SR_KEY_EXCH_B,
1688                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1689                 2048, /* ??? */
1690                 &ok);
1691
1692         if (!ok) return((int)n);
1693         p=(unsigned char *)s->init_msg;
1694
1695         l=s->s3->tmp.new_cipher->algorithms;
1696
1697 #ifndef OPENSSL_NO_RSA
1698         if (l & SSL_kRSA)
1699                 {
1700                 /* FIX THIS UP EAY EAY EAY EAY */
1701                 if (s->s3->tmp.use_rsa_tmp)
1702                         {
1703                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1704                                 rsa=s->cert->rsa_tmp;
1705                         /* Don't do a callback because rsa_tmp should
1706                          * be sent already */
1707                         if (rsa == NULL)
1708                                 {
1709                                 al=SSL_AD_HANDSHAKE_FAILURE;
1710                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1711                                 goto f_err;
1712
1713                                 }
1714                         }
1715                 else
1716                         {
1717                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1718                         if (    (pkey == NULL) ||
1719                                 (pkey->type != EVP_PKEY_RSA) ||
1720                                 (pkey->pkey.rsa == NULL))
1721                                 {
1722                                 al=SSL_AD_HANDSHAKE_FAILURE;
1723                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1724                                 goto f_err;
1725                                 }
1726                         rsa=pkey->pkey.rsa;
1727                         }
1728
1729                 /* TLS */
1730                 if (s->version > SSL3_VERSION)
1731                         {
1732                         n2s(p,i);
1733                         if (n != i+2)
1734                                 {
1735                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1736                                         {
1737                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1738                                         goto err;
1739                                         }
1740                                 else
1741                                         p-=2;
1742                                 }
1743                         else
1744                                 n=i;
1745                         }
1746
1747                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1748
1749                 al = -1;
1750                 
1751                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1752                         {
1753                         al=SSL_AD_DECODE_ERROR;
1754                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
1755                         }
1756
1757                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1758                         {
1759                         /* The premaster secret must contain the same version number as the
1760                          * ClientHello to detect version rollback attacks (strangely, the
1761                          * protocol does not offer such protection for DH ciphersuites).
1762                          * However, buggy clients exist that send the negotiated protocol
1763                          * version instead if the server does not support the requested
1764                          * protocol version.
1765                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1766                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1767                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1768                                 {
1769                                 al=SSL_AD_DECODE_ERROR;
1770                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1771
1772                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1773                                  * (http://eprint.iacr.org/2003/052/) exploits the version
1774                                  * number check as a "bad version oracle" -- an alert would
1775                                  * reveal that the plaintext corresponding to some ciphertext
1776                                  * made up by the adversary is properly formatted except
1777                                  * that the version number is wrong.  To avoid such attacks,
1778                                  * we should treat this just like any other decryption error. */
1779                                 }
1780                         }
1781
1782                 if (al != -1)
1783                         {
1784                         /* Some decryption failure -- use random value instead as countermeasure
1785                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
1786                          * (see RFC 2246, section 7.4.7.1). */
1787                         ERR_clear_error();
1788                         i = SSL_MAX_MASTER_KEY_LENGTH;
1789                         p[0] = s->client_version >> 8;
1790                         p[1] = s->client_version & 0xff;
1791                         if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */
1792                                 goto err;
1793                         }
1794         
1795                 s->session->master_key_length=
1796                         s->method->ssl3_enc->generate_master_secret(s,
1797                                 s->session->master_key,
1798                                 p,i);
1799                 OPENSSL_cleanse(p,i);
1800                 }
1801         else
1802 #endif
1803 #ifndef OPENSSL_NO_DH
1804                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1805                 {
1806                 n2s(p,i);
1807                 if (n != i+2)
1808                         {
1809                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1810                                 {
1811                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1812                                 goto err;
1813                                 }
1814                         else
1815                                 {
1816                                 p-=2;
1817                                 i=(int)n;
1818                                 }
1819                         }
1820
1821                 if (n == 0L) /* the parameters are in the cert */
1822                         {
1823                         al=SSL_AD_HANDSHAKE_FAILURE;
1824                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1825                         goto f_err;
1826                         }
1827                 else
1828                         {
1829                         if (s->s3->tmp.dh == NULL)
1830                                 {
1831                                 al=SSL_AD_HANDSHAKE_FAILURE;
1832                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1833                                 goto f_err;
1834                                 }
1835                         else
1836                                 dh_srvr=s->s3->tmp.dh;
1837                         }
1838
1839                 pub=BN_bin2bn(p,i,NULL);
1840                 if (pub == NULL)
1841                         {
1842                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1843                         goto err;
1844                         }
1845
1846                 i=DH_compute_key(p,pub,dh_srvr);
1847
1848                 if (i <= 0)
1849                         {
1850                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1851                         goto err;
1852                         }
1853
1854                 DH_free(s->s3->tmp.dh);
1855                 s->s3->tmp.dh=NULL;
1856
1857                 BN_clear_free(pub);
1858                 pub=NULL;
1859                 s->session->master_key_length=
1860                         s->method->ssl3_enc->generate_master_secret(s,
1861                                 s->session->master_key,p,i);
1862                 OPENSSL_cleanse(p,i);
1863                 }
1864         else
1865 #endif
1866 #ifndef OPENSSL_NO_KRB5
1867         if (l & SSL_kKRB5)
1868                 {
1869                 krb5_error_code         krb5rc;
1870                 krb5_data               enc_ticket;
1871                 krb5_data               authenticator;
1872                 krb5_data               enc_pms;
1873                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
1874                 EVP_CIPHER_CTX          ciph_ctx;
1875                 EVP_CIPHER              *enc = NULL;
1876                 unsigned char           iv[EVP_MAX_IV_LENGTH];
1877                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
1878                                                + EVP_MAX_BLOCK_LENGTH];
1879                 int                     padl, outl;
1880                 krb5_timestamp          authtime = 0;
1881                 krb5_ticket_times       ttimes;
1882
1883                 EVP_CIPHER_CTX_init(&ciph_ctx);
1884
1885                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
1886
1887                 n2s(p,i);
1888                 enc_ticket.length = i;
1889
1890                 if (n < enc_ticket.length + 6)
1891                         {
1892                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1893                                 SSL_R_DATA_LENGTH_TOO_LONG);
1894                         goto err;
1895                         }
1896
1897                 enc_ticket.data = (char *)p;
1898                 p+=enc_ticket.length;
1899
1900                 n2s(p,i);
1901                 authenticator.length = i;
1902
1903                 if (n < enc_ticket.length + authenticator.length + 6)
1904                         {
1905                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1906                                 SSL_R_DATA_LENGTH_TOO_LONG);
1907                         goto err;
1908                         }
1909
1910                 authenticator.data = (char *)p;
1911                 p+=authenticator.length;
1912
1913                 n2s(p,i);
1914                 enc_pms.length = i;
1915                 enc_pms.data = (char *)p;
1916                 p+=enc_pms.length;
1917
1918                 /* Note that the length is checked again below,
1919                 ** after decryption
1920                 */
1921                 if(enc_pms.length > sizeof pms)
1922                         {
1923                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1924                                SSL_R_DATA_LENGTH_TOO_LONG);
1925                         goto err;
1926                         }
1927
1928                 if (n != (long)(enc_ticket.length + authenticator.length +
1929                                                 enc_pms.length + 6))
1930                         {
1931                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1932                                 SSL_R_DATA_LENGTH_TOO_LONG);
1933                         goto err;
1934                         }
1935
1936                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
1937                                         &kssl_err)) != 0)
1938                         {
1939 #ifdef KSSL_DEBUG
1940                         printf("kssl_sget_tkt rtn %d [%d]\n",
1941                                 krb5rc, kssl_err.reason);
1942                         if (kssl_err.text)
1943                                 printf("kssl_err text= %s\n", kssl_err.text);
1944 #endif  /* KSSL_DEBUG */
1945                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1946                                 kssl_err.reason);
1947                         goto err;
1948                         }
1949
1950                 /*  Note: no authenticator is not considered an error,
1951                 **  but will return authtime == 0.
1952                 */
1953                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
1954                                         &authtime, &kssl_err)) != 0)
1955                         {
1956 #ifdef KSSL_DEBUG
1957                         printf("kssl_check_authent rtn %d [%d]\n",
1958                                 krb5rc, kssl_err.reason);
1959                         if (kssl_err.text)
1960                                 printf("kssl_err text= %s\n", kssl_err.text);
1961 #endif  /* KSSL_DEBUG */
1962                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1963                                 kssl_err.reason);
1964                         goto err;
1965                         }
1966
1967                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
1968                         {
1969                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
1970                         goto err;
1971                         }
1972
1973 #ifdef KSSL_DEBUG
1974                 kssl_ctx_show(kssl_ctx);
1975 #endif  /* KSSL_DEBUG */
1976
1977                 enc = kssl_map_enc(kssl_ctx->enctype);
1978                 if (enc == NULL)
1979                     goto err;
1980
1981                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
1982
1983                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
1984                         {
1985                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1986                                 SSL_R_DECRYPTION_FAILED);
1987                         goto err;
1988                         }
1989                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
1990                                         (unsigned char *)enc_pms.data, enc_pms.length))
1991                         {
1992                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1993                                 SSL_R_DECRYPTION_FAILED);
1994                         goto err;
1995                         }
1996                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1997                         {
1998                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1999                                 SSL_R_DATA_LENGTH_TOO_LONG);
2000                         goto err;
2001                         }
2002                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2003                         {
2004                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2005                                 SSL_R_DECRYPTION_FAILED);
2006                         goto err;
2007                         }
2008                 outl += padl;
2009                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2010                         {
2011                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2012                                 SSL_R_DATA_LENGTH_TOO_LONG);
2013                         goto err;
2014                         }
2015                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2016
2017                 s->session->master_key_length=
2018                         s->method->ssl3_enc->generate_master_secret(s,
2019                                 s->session->master_key, pms, outl);
2020
2021                 if (kssl_ctx->client_princ)
2022                         {
2023                         int len = strlen(kssl_ctx->client_princ);
2024                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2025                                 {
2026                                 s->session->krb5_client_princ_len = len;
2027                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2028                                 }
2029                         }
2030
2031
2032                 /*  Was doing kssl_ctx_free() here,
2033                 **  but it caused problems for apache.
2034                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2035                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2036                 */
2037                 }
2038         else
2039 #endif  /* OPENSSL_NO_KRB5 */
2040
2041 #ifndef OPENSSL_NO_ECDH
2042                 if ((l & SSL_kECDH) || (l & SSL_kECDHE))
2043                 {
2044                 int ret = 1;
2045                 int field_size = 0;
2046                 const EC_KEY   *tkey;
2047                 const EC_GROUP *group;
2048                 const BIGNUM *priv_key;
2049
2050                 /* initialize structures for server's ECDH key pair */
2051                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2052                         {
2053                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2054                             ERR_R_MALLOC_FAILURE);
2055                         goto err;
2056                         }
2057
2058                 /* Let's get server private key and group information */
2059                 if (l & SSL_kECDH) 
2060                         { 
2061                         /* use the certificate */
2062                         tkey = s->cert->key->privatekey->pkey.ec;
2063                         }
2064                 else
2065                         {
2066                         /* use the ephermeral values we saved when
2067                          * generating the ServerKeyExchange msg.
2068                          */
2069                         tkey = s->s3->tmp.ecdh;
2070                         }
2071
2072                 group    = EC_KEY_get0_group(tkey);
2073                 priv_key = EC_KEY_get0_private_key(tkey);
2074
2075                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2076                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2077                         {
2078                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2079                                ERR_R_EC_LIB);
2080                         goto err;
2081                         }
2082
2083                 /* Let's get client's public key */
2084                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2085                         {
2086                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2087                             ERR_R_MALLOC_FAILURE);
2088                         goto err;
2089                         }
2090
2091                 if (n == 0L) 
2092                         {
2093                         /* Client Publickey was in Client Certificate */
2094
2095                          if (l & SSL_kECDHE) 
2096                                  {
2097                                  al=SSL_AD_HANDSHAKE_FAILURE;
2098                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2099                                  goto f_err;
2100                                  }
2101                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2102                             == NULL) || 
2103                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2104                                 {
2105                                 /* XXX: For now, we do not support client
2106                                  * authentication using ECDH certificates
2107                                  * so this branch (n == 0L) of the code is
2108                                  * never executed. When that support is
2109                                  * added, we ought to ensure the key 
2110                                  * received in the certificate is 
2111                                  * authorized for key agreement.
2112                                  * ECDH_compute_key implicitly checks that
2113                                  * the two ECDH shares are for the same
2114                                  * group.
2115                                  */
2116                                 al=SSL_AD_HANDSHAKE_FAILURE;
2117                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2118                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2119                                 goto f_err;
2120                                 }
2121
2122                         EC_POINT_copy(clnt_ecpoint,
2123                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec));
2124                         ret = 2; /* Skip certificate verify processing */
2125                         }
2126                 else
2127                         {
2128                         /* Get client's public key from encoded point
2129                          * in the ClientKeyExchange message.
2130                          */
2131                         if ((bn_ctx = BN_CTX_new()) == NULL)
2132                                 {
2133                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2134                                     ERR_R_MALLOC_FAILURE);
2135                                 goto err;
2136                                 }
2137
2138                         /* Get encoded point length */
2139                         i = *p; 
2140                         p += 1;
2141                         if (EC_POINT_oct2point(group, 
2142                             clnt_ecpoint, p, i, bn_ctx) == 0)
2143                                 {
2144                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2145                                     ERR_R_EC_LIB);
2146                                 goto err;
2147                                 }
2148                         /* p is pointing to somewhere in the buffer
2149                          * currently, so set it to the start 
2150                          */ 
2151                         p=(unsigned char *)s->init_buf->data;
2152                         }
2153
2154                 /* Compute the shared pre-master secret */
2155                 field_size = EC_GROUP_get_degree(group);
2156                 if (field_size <= 0)
2157                         {
2158                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2159                                ERR_R_ECDH_LIB);
2160                         goto err;
2161                         }
2162                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2163                 if (i <= 0)
2164                         {
2165                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2166                             ERR_R_ECDH_LIB);
2167                         goto err;
2168                         }
2169
2170                 EVP_PKEY_free(clnt_pub_pkey);
2171                 EC_POINT_free(clnt_ecpoint);
2172                 if (srvr_ecdh != NULL) 
2173                         EC_KEY_free(srvr_ecdh);
2174                 BN_CTX_free(bn_ctx);
2175
2176                 /* Compute the master secret */
2177                 s->session->master_key_length = s->method->ssl3_enc-> \
2178                     generate_master_secret(s, s->session->master_key, p, i);
2179                 
2180                 OPENSSL_cleanse(p, i);
2181                 return (ret);
2182                 }
2183         else
2184 #endif
2185                 {
2186                 al=SSL_AD_HANDSHAKE_FAILURE;
2187                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2188                                 SSL_R_UNKNOWN_CIPHER_TYPE);
2189                 goto f_err;
2190                 }
2191
2192         return(1);
2193 f_err:
2194         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2195 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH)
2196 err:
2197 #endif
2198 #ifndef OPENSSL_NO_ECDH
2199         EVP_PKEY_free(clnt_pub_pkey);
2200         EC_POINT_free(clnt_ecpoint);
2201         if (srvr_ecdh != NULL) 
2202                 EC_KEY_free(srvr_ecdh);
2203         BN_CTX_free(bn_ctx);
2204 #endif
2205         return(-1);
2206         }
2207
2208 int ssl3_get_cert_verify(SSL *s)
2209         {
2210         EVP_PKEY *pkey=NULL;
2211         unsigned char *p;
2212         int al,ok,ret=0;
2213         long n;
2214         int type=0,i,j;
2215         X509 *peer;
2216
2217         n=s->method->ssl_get_message(s,
2218                 SSL3_ST_SR_CERT_VRFY_A,
2219                 SSL3_ST_SR_CERT_VRFY_B,
2220                 -1,
2221                 514, /* 514? */
2222                 &ok);
2223
2224         if (!ok) return((int)n);
2225
2226         if (s->session->peer != NULL)
2227                 {
2228                 peer=s->session->peer;
2229                 pkey=X509_get_pubkey(peer);
2230                 type=X509_certificate_type(peer,pkey);
2231                 }
2232         else
2233                 {
2234                 peer=NULL;
2235                 pkey=NULL;
2236                 }
2237
2238         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
2239                 {
2240                 s->s3->tmp.reuse_message=1;
2241                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
2242                         {
2243                         al=SSL_AD_UNEXPECTED_MESSAGE;
2244                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
2245                         goto f_err;
2246                         }
2247                 ret=1;
2248                 goto end;
2249                 }
2250
2251         if (peer == NULL)
2252                 {
2253                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
2254                 al=SSL_AD_UNEXPECTED_MESSAGE;
2255                 goto f_err;
2256                 }
2257
2258         if (!(type & EVP_PKT_SIGN))
2259                 {
2260                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2261                 al=SSL_AD_ILLEGAL_PARAMETER;
2262                 goto f_err;
2263                 }
2264
2265         if (s->s3->change_cipher_spec)
2266                 {
2267                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
2268                 al=SSL_AD_UNEXPECTED_MESSAGE;
2269                 goto f_err;
2270                 }
2271
2272         /* we now have a signature that we need to verify */
2273         p=(unsigned char *)s->init_msg;
2274         n2s(p,i);
2275         n-=2;
2276         if (i > n)
2277                 {
2278                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
2279                 al=SSL_AD_DECODE_ERROR;
2280                 goto f_err;
2281                 }
2282
2283         j=EVP_PKEY_size(pkey);
2284         if ((i > j) || (n > j) || (n <= 0))
2285                 {
2286                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
2287                 al=SSL_AD_DECODE_ERROR;
2288                 goto f_err;
2289                 }
2290
2291 #ifndef OPENSSL_NO_RSA 
2292         if (pkey->type == EVP_PKEY_RSA)
2293                 {
2294                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2295                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
2296                                                         pkey->pkey.rsa);
2297                 if (i < 0)
2298                         {
2299                         al=SSL_AD_DECRYPT_ERROR;
2300                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
2301                         goto f_err;
2302                         }
2303                 if (i == 0)
2304                         {
2305                         al=SSL_AD_DECRYPT_ERROR;
2306                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
2307                         goto f_err;
2308                         }
2309                 }
2310         else
2311 #endif
2312 #ifndef OPENSSL_NO_DSA
2313                 if (pkey->type == EVP_PKEY_DSA)
2314                 {
2315                 j=DSA_verify(pkey->save_type,
2316                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2317                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
2318                 if (j <= 0)
2319                         {
2320                         /* bad signature */
2321                         al=SSL_AD_DECRYPT_ERROR;
2322                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
2323                         goto f_err;
2324                         }
2325                 }
2326         else
2327 #endif
2328 #ifndef OPENSSL_NO_ECDSA
2329                 if (pkey->type == EVP_PKEY_EC)
2330                 {
2331                 j=ECDSA_verify(pkey->save_type,
2332                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2333                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
2334                 if (j <= 0)
2335                         {
2336                         /* bad signature */
2337                         al=SSL_AD_DECRYPT_ERROR;
2338                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2339                             SSL_R_BAD_ECDSA_SIGNATURE);
2340                         goto f_err;
2341                         }
2342                 }
2343         else
2344 #endif
2345                 {
2346                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
2347                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
2348                 goto f_err;
2349                 }
2350
2351
2352         ret=1;
2353         if (0)
2354                 {
2355 f_err:
2356                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2357                 }
2358 end:
2359         EVP_PKEY_free(pkey);
2360         return(ret);
2361         }
2362
2363 int ssl3_get_client_certificate(SSL *s)
2364         {
2365         int i,ok,al,ret= -1;
2366         X509 *x=NULL;
2367         unsigned long l,nc,llen,n;
2368         const unsigned char *p,*q;
2369         unsigned char *d;
2370         STACK_OF(X509) *sk=NULL;
2371
2372         n=s->method->ssl_get_message(s,
2373                 SSL3_ST_SR_CERT_A,
2374                 SSL3_ST_SR_CERT_B,
2375                 -1,
2376                 s->max_cert_list,
2377                 &ok);
2378
2379         if (!ok) return((int)n);
2380
2381         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2382                 {
2383                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
2384                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2385                         {
2386                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2387                         al=SSL_AD_HANDSHAKE_FAILURE;
2388                         goto f_err;
2389                         }
2390                 /* If tls asked for a client cert, the client must return a 0 list */
2391                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2392                         {
2393                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2394                         al=SSL_AD_UNEXPECTED_MESSAGE;
2395                         goto f_err;
2396                         }
2397                 s->s3->tmp.reuse_message=1;
2398                 return(1);
2399                 }
2400
2401         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2402                 {
2403                 al=SSL_AD_UNEXPECTED_MESSAGE;
2404                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
2405                 goto f_err;
2406                 }
2407         p=d=(unsigned char *)s->init_msg;
2408
2409         if ((sk=sk_X509_new_null()) == NULL)
2410                 {
2411                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2412                 goto err;
2413                 }
2414
2415         n2l3(p,llen);
2416         if (llen+3 != n)
2417                 {
2418                 al=SSL_AD_DECODE_ERROR;
2419                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
2420                 goto f_err;
2421                 }
2422         for (nc=0; nc<llen; )
2423                 {
2424                 n2l3(p,l);
2425                 if ((l+nc+3) > llen)
2426                         {
2427                         al=SSL_AD_DECODE_ERROR;
2428                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2429                         goto f_err;
2430                         }
2431
2432                 q=p;
2433                 x=d2i_X509(NULL,&p,l);
2434                 if (x == NULL)
2435                         {
2436                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
2437                         goto err;
2438                         }
2439                 if (p != (q+l))
2440                         {
2441                         al=SSL_AD_DECODE_ERROR;
2442                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2443                         goto f_err;
2444                         }
2445                 if (!sk_X509_push(sk,x))
2446                         {
2447                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2448                         goto err;
2449                         }
2450                 x=NULL;
2451                 nc+=l+3;
2452                 }
2453
2454         if (sk_X509_num(sk) <= 0)
2455                 {
2456                 /* TLS does not mind 0 certs returned */
2457                 if (s->version == SSL3_VERSION)
2458                         {
2459                         al=SSL_AD_HANDSHAKE_FAILURE;
2460                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
2461                         goto f_err;
2462                         }
2463                 /* Fail for TLS only if we required a certificate */
2464                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2465                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2466                         {
2467                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2468                         al=SSL_AD_HANDSHAKE_FAILURE;
2469                         goto f_err;
2470                         }
2471                 }
2472         else
2473                 {
2474                 i=ssl_verify_cert_chain(s,sk);
2475                 if (!i)
2476                         {
2477                         al=ssl_verify_alarm_type(s->verify_result);
2478                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
2479                         goto f_err;
2480                         }
2481                 }
2482
2483         if (s->session->peer != NULL) /* This should not be needed */
2484                 X509_free(s->session->peer);
2485         s->session->peer=sk_X509_shift(sk);
2486         s->session->verify_result = s->verify_result;
2487
2488         /* With the current implementation, sess_cert will always be NULL
2489          * when we arrive here. */
2490         if (s->session->sess_cert == NULL)
2491                 {
2492                 s->session->sess_cert = ssl_sess_cert_new();
2493                 if (s->session->sess_cert == NULL)
2494                         {
2495                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2496                         goto err;
2497                         }
2498                 }
2499         if (s->session->sess_cert->cert_chain != NULL)
2500                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2501         s->session->sess_cert->cert_chain=sk;
2502         /* Inconsistency alert: cert_chain does *not* include the
2503          * peer's own certificate, while we do include it in s3_clnt.c */
2504
2505         sk=NULL;
2506
2507         ret=1;
2508         if (0)
2509                 {
2510 f_err:
2511                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2512                 }
2513 err:
2514         if (x != NULL) X509_free(x);
2515         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2516         return(ret);
2517         }
2518
2519 int ssl3_send_server_certificate(SSL *s)
2520         {
2521         unsigned long l;
2522         X509 *x;
2523
2524         if (s->state == SSL3_ST_SW_CERT_A)
2525                 {
2526                 x=ssl_get_server_send_cert(s);
2527                 if (x == NULL &&
2528                         /* VRS: allow null cert if auth == KRB5 */
2529                         (s->s3->tmp.new_cipher->algorithms
2530                                 & (SSL_MKEY_MASK|SSL_AUTH_MASK))
2531                         != (SSL_aKRB5|SSL_kKRB5))
2532                         {
2533                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
2534                         return(0);
2535                         }
2536
2537                 l=ssl3_output_cert_chain(s,x);
2538                 s->state=SSL3_ST_SW_CERT_B;
2539                 s->init_num=(int)l;
2540                 s->init_off=0;
2541                 }
2542
2543         /* SSL3_ST_SW_CERT_B */
2544         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2545         }
2546
2547
2548 #ifndef OPENSSL_NO_ECDH
2549 /* This is the complement of curve_id2nid in s3_clnt.c. */
2550 static int nid2curve_id(int nid)
2551 {
2552         /* ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001)
2553          * (no changes in draft-ietf-tls-ecc-03.txt [June 2003]) */
2554         switch (nid) {
2555         case NID_sect163k1: /* sect163k1 (1) */
2556                 return 1;
2557         case NID_sect163r1: /* sect163r1 (2) */
2558                 return 2;
2559         case NID_sect163r2: /* sect163r2 (3) */
2560                 return 3;
2561         case NID_sect193r1: /* sect193r1 (4) */ 
2562                 return 4;
2563         case NID_sect193r2: /* sect193r2 (5) */ 
2564                 return 5;
2565         case NID_sect233k1: /* sect233k1 (6) */
2566                 return 6;
2567         case NID_sect233r1: /* sect233r1 (7) */ 
2568                 return 7;
2569         case NID_sect239k1: /* sect239k1 (8) */ 
2570                 return 8;
2571         case NID_sect283k1: /* sect283k1 (9) */
2572                 return 9;
2573         case NID_sect283r1: /* sect283r1 (10) */ 
2574                 return 10;
2575         case NID_sect409k1: /* sect409k1 (11) */ 
2576                 return 11;
2577         case NID_sect409r1: /* sect409r1 (12) */
2578                 return 12;
2579         case NID_sect571k1: /* sect571k1 (13) */ 
2580                 return 13;
2581         case NID_sect571r1: /* sect571r1 (14) */ 
2582                 return 14;
2583         case NID_secp160k1: /* secp160k1 (15) */
2584                 return 15;
2585         case NID_secp160r1: /* secp160r1 (16) */ 
2586                 return 16;
2587         case NID_secp160r2: /* secp160r2 (17) */ 
2588                 return 17;
2589         case NID_secp192k1: /* secp192k1 (18) */
2590                 return 18;
2591         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
2592                 return 19;
2593         case NID_secp224k1: /* secp224k1 (20) */ 
2594                 return 20;
2595         case NID_secp224r1: /* secp224r1 (21) */
2596                 return 21;
2597         case NID_secp256k1: /* secp256k1 (22) */ 
2598                 return 22;
2599         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
2600                 return 23;
2601         case NID_secp384r1: /* secp384r1 (24) */
2602                 return 24;
2603         case NID_secp521r1:  /* secp521r1 (25) */       
2604                 return 25;
2605         default:
2606                 return 0;
2607         }
2608 }
2609 #endif