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