If FDIRS is to be treated like SDIRS, let's not forget to initialize
[oweals/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-2002 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 #define REUSE_CIPHER_BUG
113 #define NETSCAPE_HANG_BUG
114
115
116 #include <stdio.h>
117 #include "ssl_locl.h"
118 #include "kssl_lcl.h"
119 #include <openssl/buffer.h>
120 #include <openssl/rand.h>
121 #include <openssl/objects.h>
122 #include <openssl/evp.h>
123 #include <openssl/x509.h>
124 #include <openssl/krb5_asn.h>
125 #include <openssl/md5.h>
126 #include "cryptlib.h"
127
128 static SSL_METHOD *ssl3_get_server_method(int ver);
129 static int ssl3_get_client_hello(SSL *s);
130 static int ssl3_check_client_hello(SSL *s);
131 static int ssl3_send_server_hello(SSL *s);
132 static int ssl3_send_server_key_exchange(SSL *s);
133 static int ssl3_send_certificate_request(SSL *s);
134 static int ssl3_send_server_done(SSL *s);
135 static int ssl3_get_client_key_exchange(SSL *s);
136 static int ssl3_get_client_certificate(SSL *s);
137 static int ssl3_get_cert_verify(SSL *s);
138 static int ssl3_send_hello_request(SSL *s);
139
140 static SSL_METHOD *ssl3_get_server_method(int ver)
141         {
142         if (ver == SSL3_VERSION)
143                 return(SSLv3_server_method());
144         else
145                 return(NULL);
146         }
147
148 SSL_METHOD *SSLv3_server_method(void)
149         {
150         static int init=1;
151         static SSL_METHOD SSLv3_server_data;
152
153         if (init)
154                 {
155                 CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);
156
157                 if (init)
158                         {
159                         memcpy((char *)&SSLv3_server_data,(char *)sslv3_base_method(),
160                                 sizeof(SSL_METHOD));
161                         SSLv3_server_data.ssl_accept=ssl3_accept;
162                         SSLv3_server_data.get_ssl_method=ssl3_get_server_method;
163                         init=0;
164                         }
165                         
166                 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
167                 }
168         return(&SSLv3_server_data);
169         }
170
171 int ssl3_accept(SSL *s)
172         {
173         BUF_MEM *buf;
174         unsigned long l,Time=time(NULL);
175         void (*cb)(const SSL *ssl,int type,int val)=NULL;
176         long num1;
177         int ret= -1;
178         int new_state,state,skip=0;
179
180         RAND_add(&Time,sizeof(Time),0);
181         ERR_clear_error();
182         clear_sys_error();
183
184         if (s->info_callback != NULL)
185                 cb=s->info_callback;
186         else if (s->ctx->info_callback != NULL)
187                 cb=s->ctx->info_callback;
188
189         /* init things to blank */
190         s->in_handshake++;
191         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
192
193         if (s->cert == NULL)
194                 {
195                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
196                 return(-1);
197                 }
198
199         for (;;)
200                 {
201                 state=s->state;
202
203                 switch (s->state)
204                         {
205                 case SSL_ST_RENEGOTIATE:
206                         s->new_session=1;
207                         /* s->state=SSL_ST_ACCEPT; */
208
209                 case SSL_ST_BEFORE:
210                 case SSL_ST_ACCEPT:
211                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
212                 case SSL_ST_OK|SSL_ST_ACCEPT:
213
214                         s->server=1;
215                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
216
217                         if ((s->version>>8) != 3)
218                                 {
219                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
220                                 return -1;
221                                 }
222                         s->type=SSL_ST_ACCEPT;
223
224                         if (s->init_buf == NULL)
225                                 {
226                                 if ((buf=BUF_MEM_new()) == NULL)
227                                         {
228                                         ret= -1;
229                                         goto end;
230                                         }
231                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
232                                         {
233                                         ret= -1;
234                                         goto end;
235                                         }
236                                 s->init_buf=buf;
237                                 }
238
239                         if (!ssl3_setup_buffers(s))
240                                 {
241                                 ret= -1;
242                                 goto end;
243                                 }
244
245                         s->init_num=0;
246
247                         if (s->state != SSL_ST_RENEGOTIATE)
248                                 {
249                                 /* Ok, we now need to push on a buffering BIO so that
250                                  * the output is sent in a way that TCP likes :-)
251                                  */
252                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
253                                 
254                                 ssl3_init_finished_mac(s);
255                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
256                                 s->ctx->stats.sess_accept++;
257                                 }
258                         else
259                                 {
260                                 /* s->state == SSL_ST_RENEGOTIATE,
261                                  * we will just send a HelloRequest */
262                                 s->ctx->stats.sess_accept_renegotiate++;
263                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
264                                 }
265                         break;
266
267                 case SSL3_ST_SW_HELLO_REQ_A:
268                 case SSL3_ST_SW_HELLO_REQ_B:
269
270                         s->shutdown=0;
271                         ret=ssl3_send_hello_request(s);
272                         if (ret <= 0) goto end;
273                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
274                         s->state=SSL3_ST_SW_FLUSH;
275                         s->init_num=0;
276
277                         ssl3_init_finished_mac(s);
278                         break;
279
280                 case SSL3_ST_SW_HELLO_REQ_C:
281                         s->state=SSL_ST_OK;
282                         break;
283
284                 case SSL3_ST_SR_CLNT_HELLO_A:
285                 case SSL3_ST_SR_CLNT_HELLO_B:
286                 case SSL3_ST_SR_CLNT_HELLO_C:
287
288                         s->shutdown=0;
289                         ret=ssl3_get_client_hello(s);
290                         if (ret <= 0) goto end;
291                         s->new_session = 2;
292                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
293                         s->init_num=0;
294                         break;
295
296                 case SSL3_ST_SW_SRVR_HELLO_A:
297                 case SSL3_ST_SW_SRVR_HELLO_B:
298                         ret=ssl3_send_server_hello(s);
299                         if (ret <= 0) goto end;
300
301                         if (s->hit)
302                                 s->state=SSL3_ST_SW_CHANGE_A;
303                         else
304                                 s->state=SSL3_ST_SW_CERT_A;
305                         s->init_num=0;
306                         break;
307
308                 case SSL3_ST_SW_CERT_A:
309                 case SSL3_ST_SW_CERT_B:
310                         /* Check if it is anon DH */
311                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
312                                 {
313                                 ret=ssl3_send_server_certificate(s);
314                                 if (ret <= 0) goto end;
315                                 }
316                         else
317                                 skip=1;
318                         s->state=SSL3_ST_SW_KEY_EXCH_A;
319                         s->init_num=0;
320                         break;
321
322                 case SSL3_ST_SW_KEY_EXCH_A:
323                 case SSL3_ST_SW_KEY_EXCH_B:
324                         l=s->s3->tmp.new_cipher->algorithms;
325
326                         /* clear this, it may get reset by
327                          * send_server_key_exchange */
328                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
329 #ifndef OPENSSL_NO_KRB5
330                                 && !(l & SSL_KRB5)
331 #endif /* OPENSSL_NO_KRB5 */
332                                 )
333                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
334                                  * even when forbidden by protocol specs
335                                  * (handshake may fail as clients are not required to
336                                  * be able to handle this) */
337                                 s->s3->tmp.use_rsa_tmp=1;
338                         else
339                                 s->s3->tmp.use_rsa_tmp=0;
340
341                         /* only send if a DH key exchange, fortezza or
342                          * RSA but we have a sign only certificate */
343                         if (s->s3->tmp.use_rsa_tmp
344                             || (l & (SSL_DH|SSL_kFZA))
345                             || ((l & SSL_kRSA)
346                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
347                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
348                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
349                                         )
350                                     )
351                                 )
352                             )
353                                 {
354                                 ret=ssl3_send_server_key_exchange(s);
355                                 if (ret <= 0) goto end;
356                                 }
357                         else
358                                 skip=1;
359
360                         s->state=SSL3_ST_SW_CERT_REQ_A;
361                         s->init_num=0;
362                         break;
363
364                 case SSL3_ST_SW_CERT_REQ_A:
365                 case SSL3_ST_SW_CERT_REQ_B:
366                         if (/* don't request cert unless asked for it: */
367                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
368                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
369                                  * don't request cert during re-negotiation: */
370                                 ((s->session->peer != NULL) &&
371                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
372                                 /* never request cert in anonymous ciphersuites
373                                  * (see section "Certificate request" in SSL 3 drafts
374                                  * and in RFC 2246): */
375                                 ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
376                                  /* ... except when the application insists on verification
377                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
378                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
379                                  /* never request cert in Kerberos ciphersuites */
380                                 (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
381                                 {
382                                 /* no cert request */
383                                 skip=1;
384                                 s->s3->tmp.cert_request=0;
385                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
386                                 }
387                         else
388                                 {
389                                 s->s3->tmp.cert_request=1;
390                                 ret=ssl3_send_certificate_request(s);
391                                 if (ret <= 0) goto end;
392 #ifndef NETSCAPE_HANG_BUG
393                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
394 #else
395                                 s->state=SSL3_ST_SW_FLUSH;
396                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
397 #endif
398                                 s->init_num=0;
399                                 }
400                         break;
401
402                 case SSL3_ST_SW_SRVR_DONE_A:
403                 case SSL3_ST_SW_SRVR_DONE_B:
404                         ret=ssl3_send_server_done(s);
405                         if (ret <= 0) goto end;
406                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
407                         s->state=SSL3_ST_SW_FLUSH;
408                         s->init_num=0;
409                         break;
410                 
411                 case SSL3_ST_SW_FLUSH:
412                         /* number of bytes to be flushed */
413                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
414                         if (num1 > 0)
415                                 {
416                                 s->rwstate=SSL_WRITING;
417                                 num1=BIO_flush(s->wbio);
418                                 if (num1 <= 0) { ret= -1; goto end; }
419                                 s->rwstate=SSL_NOTHING;
420                                 }
421
422                         s->state=s->s3->tmp.next_state;
423                         break;
424
425                 case SSL3_ST_SR_CERT_A:
426                 case SSL3_ST_SR_CERT_B:
427                         /* Check for second client hello (MS SGC) */
428                         ret = ssl3_check_client_hello(s);
429                         if (ret <= 0)
430                                 goto end;
431                         if (ret == 2)
432                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
433                         else {
434                                 /* could be sent for a DH cert, even if we
435                                  * have not asked for it :-) */
436                                 ret=ssl3_get_client_certificate(s);
437                                 if (ret <= 0) goto end;
438                                 s->init_num=0;
439                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
440                         }
441                         break;
442
443                 case SSL3_ST_SR_KEY_EXCH_A:
444                 case SSL3_ST_SR_KEY_EXCH_B:
445                         ret=ssl3_get_client_key_exchange(s);
446                         if (ret <= 0) goto end;
447                         s->state=SSL3_ST_SR_CERT_VRFY_A;
448                         s->init_num=0;
449
450                         /* We need to get hashes here so if there is
451                          * a client cert, it can be verified */ 
452                         s->method->ssl3_enc->cert_verify_mac(s,
453                                 &(s->s3->finish_dgst1),
454                                 &(s->s3->tmp.cert_verify_md[0]));
455                         s->method->ssl3_enc->cert_verify_mac(s,
456                                 &(s->s3->finish_dgst2),
457                                 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));
458
459                         break;
460
461                 case SSL3_ST_SR_CERT_VRFY_A:
462                 case SSL3_ST_SR_CERT_VRFY_B:
463
464                         /* we should decide if we expected this one */
465                         ret=ssl3_get_cert_verify(s);
466                         if (ret <= 0) goto end;
467
468                         s->state=SSL3_ST_SR_FINISHED_A;
469                         s->init_num=0;
470                         break;
471
472                 case SSL3_ST_SR_FINISHED_A:
473                 case SSL3_ST_SR_FINISHED_B:
474                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
475                                 SSL3_ST_SR_FINISHED_B);
476                         if (ret <= 0) goto end;
477                         if (s->hit)
478                                 s->state=SSL_ST_OK;
479                         else
480                                 s->state=SSL3_ST_SW_CHANGE_A;
481                         s->init_num=0;
482                         break;
483
484                 case SSL3_ST_SW_CHANGE_A:
485                 case SSL3_ST_SW_CHANGE_B:
486
487                         s->session->cipher=s->s3->tmp.new_cipher;
488                         if (!s->method->ssl3_enc->setup_key_block(s))
489                                 { ret= -1; goto end; }
490
491                         ret=ssl3_send_change_cipher_spec(s,
492                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
493
494                         if (ret <= 0) goto end;
495                         s->state=SSL3_ST_SW_FINISHED_A;
496                         s->init_num=0;
497
498                         if (!s->method->ssl3_enc->change_cipher_state(s,
499                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
500                                 {
501                                 ret= -1;
502                                 goto end;
503                                 }
504
505                         break;
506
507                 case SSL3_ST_SW_FINISHED_A:
508                 case SSL3_ST_SW_FINISHED_B:
509                         ret=ssl3_send_finished(s,
510                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
511                                 s->method->ssl3_enc->server_finished_label,
512                                 s->method->ssl3_enc->server_finished_label_len);
513                         if (ret <= 0) goto end;
514                         s->state=SSL3_ST_SW_FLUSH;
515                         if (s->hit)
516                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
517                         else
518                                 s->s3->tmp.next_state=SSL_ST_OK;
519                         s->init_num=0;
520                         break;
521
522                 case SSL_ST_OK:
523                         /* clean a few things up */
524                         ssl3_cleanup_key_block(s);
525
526                         BUF_MEM_free(s->init_buf);
527                         s->init_buf=NULL;
528
529                         /* remove buffering on output */
530                         ssl_free_wbio_buffer(s);
531
532                         s->init_num=0;
533
534                         if (s->new_session == 2) /* skipped if we just sent a HelloRequest */
535                                 {
536                                 /* actually not necessarily a 'new' session unless
537                                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
538                                 
539                                 s->new_session=0;
540                                 
541                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
542                                 
543                                 s->ctx->stats.sess_accept_good++;
544                                 /* s->server=1; */
545                                 s->handshake_func=ssl3_accept;
546
547                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
548                                 }
549                         
550                         ret = 1;
551                         goto end;
552                         /* break; */
553
554                 default:
555                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
556                         ret= -1;
557                         goto end;
558                         /* break; */
559                         }
560                 
561                 if (!s->s3->tmp.reuse_message && !skip)
562                         {
563                         if (s->debug)
564                                 {
565                                 if ((ret=BIO_flush(s->wbio)) <= 0)
566                                         goto end;
567                                 }
568
569
570                         if ((cb != NULL) && (s->state != state))
571                                 {
572                                 new_state=s->state;
573                                 s->state=state;
574                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
575                                 s->state=new_state;
576                                 }
577                         }
578                 skip=0;
579                 }
580 end:
581         /* BIO_flush(s->wbio); */
582
583         s->in_handshake--;
584         if (cb != NULL)
585                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
586         return(ret);
587         }
588
589 static int ssl3_send_hello_request(SSL *s)
590         {
591         unsigned char *p;
592
593         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
594                 {
595                 p=(unsigned char *)s->init_buf->data;
596                 *(p++)=SSL3_MT_HELLO_REQUEST;
597                 *(p++)=0;
598                 *(p++)=0;
599                 *(p++)=0;
600
601                 s->state=SSL3_ST_SW_HELLO_REQ_B;
602                 /* number of bytes to write */
603                 s->init_num=4;
604                 s->init_off=0;
605                 }
606
607         /* SSL3_ST_SW_HELLO_REQ_B */
608         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
609         }
610
611 static int ssl3_check_client_hello(SSL *s)
612         {
613         int ok;
614         long n;
615
616         /* this function is called when we really expect a Certificate message,
617          * so permit appropriate message length */
618         n=ssl3_get_message(s,
619                 SSL3_ST_SR_CERT_A,
620                 SSL3_ST_SR_CERT_B,
621                 -1,
622                 s->max_cert_list,
623                 &ok);
624         if (!ok) return((int)n);
625         s->s3->tmp.reuse_message = 1;
626         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
627                 {
628                 /* Throw away what we have done so far in the current handshake,
629                  * which will now be aborted. (A full SSL_clear would be too much.)
630                  * I hope that tmp.dh is the only thing that may need to be cleared
631                  * when a handshake is not completed ... */
632 #ifndef OPENSSL_NO_DH
633                 if (s->s3->tmp.dh != NULL)
634                         {
635                         DH_free(s->s3->tmp.dh);
636                         s->s3->tmp.dh = NULL;
637                         }
638 #endif
639                 return 2;
640                 }
641         return 1;
642 }
643
644 static int ssl3_get_client_hello(SSL *s)
645         {
646         int i,j,ok,al,ret= -1;
647         long n;
648         unsigned long id;
649         unsigned char *p,*d,*q;
650         SSL_CIPHER *c;
651         SSL_COMP *comp=NULL;
652         STACK_OF(SSL_CIPHER) *ciphers=NULL;
653
654         /* We do this so that we will respond with our native type.
655          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
656          * This down switching should be handled by a different method.
657          * If we are SSLv3, we will respond with SSLv3, even if prompted with
658          * TLSv1.
659          */
660         if (s->state == SSL3_ST_SR_CLNT_HELLO_A)
661                 {
662                 s->first_packet=1;
663                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
664                 }
665         n=ssl3_get_message(s,
666                 SSL3_ST_SR_CLNT_HELLO_B,
667                 SSL3_ST_SR_CLNT_HELLO_C,
668                 SSL3_MT_CLIENT_HELLO,
669                 SSL3_RT_MAX_PLAIN_LENGTH,
670                 &ok);
671
672         if (!ok) return((int)n);
673         d=p=(unsigned char *)s->init_msg;
674
675         /* use version from inside client hello, not from record header
676          * (may differ: see RFC 2246, Appendix E, second paragraph) */
677         s->client_version=(((int)p[0])<<8)|(int)p[1];
678         p+=2;
679
680         if (s->client_version < s->version)
681                 {
682                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
683                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR) 
684                         {
685                         /* similar to ssl3_get_record, send alert using remote version number */
686                         s->version = s->client_version;
687                         }
688                 al = SSL_AD_PROTOCOL_VERSION;
689                 goto f_err;
690                 }
691
692         /* load the client random */
693         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
694         p+=SSL3_RANDOM_SIZE;
695
696         /* get the session-id */
697         j= *(p++);
698
699         s->hit=0;
700         /* Versions before 0.9.7 always allow session reuse during renegotiation
701          * (i.e. when s->new_session is true), option
702          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7.
703          * Maybe this optional behaviour should always have been the default,
704          * but we cannot safely change the default behaviour (or new applications
705          * might be written that become totally unsecure when compiled with
706          * an earlier library version)
707          */
708         if (j == 0 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
709                 {
710                 if (!ssl_get_new_session(s,1))
711                         goto err;
712                 }
713         else
714                 {
715                 i=ssl_get_prev_session(s,p,j);
716                 if (i == 1)
717                         { /* previous session */
718                         s->hit=1;
719                         }
720                 else if (i == -1)
721                         goto err;
722                 else /* i == 0 */
723                         {
724                         if (!ssl_get_new_session(s,1))
725                                 goto err;
726                         }
727                 }
728
729         p+=j;
730         n2s(p,i);
731         if ((i == 0) && (j != 0))
732                 {
733                 /* we need a cipher if we are not resuming a session */
734                 al=SSL_AD_ILLEGAL_PARAMETER;
735                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
736                 goto f_err;
737                 }
738         if ((p+i) >= (d+n))
739                 {
740                 /* not enough data */
741                 al=SSL_AD_DECODE_ERROR;
742                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
743                 goto f_err;
744                 }
745         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
746                 == NULL))
747                 {
748                 goto err;
749                 }
750         p+=i;
751
752         /* If it is a hit, check that the cipher is in the list */
753         if ((s->hit) && (i > 0))
754                 {
755                 j=0;
756                 id=s->session->cipher->id;
757
758 #ifdef CIPHER_DEBUG
759                 printf("client sent %d ciphers\n",sk_num(ciphers));
760 #endif
761                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
762                         {
763                         c=sk_SSL_CIPHER_value(ciphers,i);
764 #ifdef CIPHER_DEBUG
765                         printf("client [%2d of %2d]:%s\n",
766                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
767 #endif
768                         if (c->id == id)
769                                 {
770                                 j=1;
771                                 break;
772                                 }
773                         }
774                 if (j == 0)
775                         {
776                         if ((s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
777                                 {
778                                 /* Very bad for multi-threading.... */
779                                 s->session->cipher=sk_SSL_CIPHER_value(ciphers,
780                                                                        0);
781                                 }
782                         else
783                                 {
784                                 /* we need to have the cipher in the cipher
785                                  * list if we are asked to reuse it */
786                                 al=SSL_AD_ILLEGAL_PARAMETER;
787                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
788                                 goto f_err;
789                                 }
790                         }
791                 }
792
793         /* compression */
794         i= *(p++);
795         if ((p+i) > (d+n))
796                 {
797                 /* not enough data */
798                 al=SSL_AD_DECODE_ERROR;
799                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
800                 goto f_err;
801                 }
802         q=p;
803         for (j=0; j<i; j++)
804                 {
805                 if (p[j] == 0) break;
806                 }
807
808         p+=i;
809         if (j >= i)
810                 {
811                 /* no compress */
812                 al=SSL_AD_DECODE_ERROR;
813                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
814                 goto f_err;
815                 }
816
817         /* Worst case, we will use the NULL compression, but if we have other
818          * options, we will now look for them.  We have i-1 compression
819          * algorithms from the client, starting at q. */
820         s->s3->tmp.new_compression=NULL;
821         if (s->ctx->comp_methods != NULL)
822                 { /* See if we have a match */
823                 int m,nn,o,v,done=0;
824
825                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
826                 for (m=0; m<nn; m++)
827                         {
828                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
829                         v=comp->id;
830                         for (o=0; o<i; o++)
831                                 {
832                                 if (v == q[o])
833                                         {
834                                         done=1;
835                                         break;
836                                         }
837                                 }
838                         if (done) break;
839                         }
840                 if (done)
841                         s->s3->tmp.new_compression=comp;
842                 else
843                         comp=NULL;
844                 }
845
846         /* TLS does not mind if there is extra stuff */
847 #if 0   /* SSL 3.0 does not mind either, so we should disable this test
848          * (was enabled in 0.9.6d through 0.9.6j and 0.9.7 through 0.9.7b,
849          * in earlier SSLeay/OpenSSL releases this test existed but was buggy) */
850         if (s->version == SSL3_VERSION)
851                 {
852                 if (p < (d+n))
853                         {
854                         /* wrong number of bytes,
855                          * there could be more to follow */
856                         al=SSL_AD_DECODE_ERROR;
857                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
858                         goto f_err;
859                         }
860                 }
861 #endif
862
863         /* Given s->session->ciphers and SSL_get_ciphers, we must
864          * pick a cipher */
865
866         if (!s->hit)
867                 {
868                 s->session->compress_meth=(comp == NULL)?0:comp->id;
869                 if (s->session->ciphers != NULL)
870                         sk_SSL_CIPHER_free(s->session->ciphers);
871                 s->session->ciphers=ciphers;
872                 if (ciphers == NULL)
873                         {
874                         al=SSL_AD_ILLEGAL_PARAMETER;
875                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
876                         goto f_err;
877                         }
878                 ciphers=NULL;
879                 c=ssl3_choose_cipher(s,s->session->ciphers,
880                                      SSL_get_ciphers(s));
881
882                 if (c == NULL)
883                         {
884                         al=SSL_AD_HANDSHAKE_FAILURE;
885                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
886                         goto f_err;
887                         }
888                 s->s3->tmp.new_cipher=c;
889                 }
890         else
891                 {
892                 /* Session-id reuse */
893 #ifdef REUSE_CIPHER_BUG
894                 STACK_OF(SSL_CIPHER) *sk;
895                 SSL_CIPHER *nc=NULL;
896                 SSL_CIPHER *ec=NULL;
897
898                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
899                         {
900                         sk=s->session->ciphers;
901                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
902                                 {
903                                 c=sk_SSL_CIPHER_value(sk,i);
904                                 if (c->algorithms & SSL_eNULL)
905                                         nc=c;
906                                 if (SSL_C_IS_EXPORT(c))
907                                         ec=c;
908                                 }
909                         if (nc != NULL)
910                                 s->s3->tmp.new_cipher=nc;
911                         else if (ec != NULL)
912                                 s->s3->tmp.new_cipher=ec;
913                         else
914                                 s->s3->tmp.new_cipher=s->session->cipher;
915                         }
916                 else
917 #endif
918                 s->s3->tmp.new_cipher=s->session->cipher;
919                 }
920         
921         /* we now have the following setup. 
922          * client_random
923          * cipher_list          - our prefered list of ciphers
924          * ciphers              - the clients prefered list of ciphers
925          * compression          - basically ignored right now
926          * ssl version is set   - sslv3
927          * s->session           - The ssl session has been setup.
928          * s->hit               - session reuse flag
929          * s->tmp.new_cipher    - the new cipher to use.
930          */
931
932         ret=1;
933         if (0)
934                 {
935 f_err:
936                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
937                 }
938 err:
939         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
940         return(ret);
941         }
942
943 static int ssl3_send_server_hello(SSL *s)
944         {
945         unsigned char *buf;
946         unsigned char *p,*d;
947         int i,sl;
948         unsigned long l,Time;
949
950         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
951                 {
952                 buf=(unsigned char *)s->init_buf->data;
953                 p=s->s3->server_random;
954                 Time=time(NULL);                        /* Time */
955                 l2n(Time,p);
956                 RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
957                 /* Do the message type and length last */
958                 d=p= &(buf[4]);
959
960                 *(p++)=s->version>>8;
961                 *(p++)=s->version&0xff;
962
963                 /* Random stuff */
964                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
965                 p+=SSL3_RANDOM_SIZE;
966
967                 /* now in theory we have 3 options to sending back the
968                  * session id.  If it is a re-use, we send back the
969                  * old session-id, if it is a new session, we send
970                  * back the new session-id or we send back a 0 length
971                  * session-id if we want it to be single use.
972                  * Currently I will not implement the '0' length session-id
973                  * 12-Jan-98 - I'll now support the '0' length stuff.
974                  */
975                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER))
976                         s->session->session_id_length=0;
977
978                 sl=s->session->session_id_length;
979                 if (sl > sizeof s->session->session_id)
980                         {
981                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
982                         return -1;
983                         }
984                 *(p++)=sl;
985                 memcpy(p,s->session->session_id,sl);
986                 p+=sl;
987
988                 /* put the cipher */
989                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
990                 p+=i;
991
992                 /* put the compression method */
993                 if (s->s3->tmp.new_compression == NULL)
994                         *(p++)=0;
995                 else
996                         *(p++)=s->s3->tmp.new_compression->id;
997
998                 /* do the header */
999                 l=(p-d);
1000                 d=buf;
1001                 *(d++)=SSL3_MT_SERVER_HELLO;
1002                 l2n3(l,d);
1003
1004                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
1005                 /* number of bytes to write */
1006                 s->init_num=p-buf;
1007                 s->init_off=0;
1008                 }
1009
1010         /* SSL3_ST_CW_CLNT_HELLO_B */
1011         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1012         }
1013
1014 static int ssl3_send_server_done(SSL *s)
1015         {
1016         unsigned char *p;
1017
1018         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1019                 {
1020                 p=(unsigned char *)s->init_buf->data;
1021
1022                 /* do the header */
1023                 *(p++)=SSL3_MT_SERVER_DONE;
1024                 *(p++)=0;
1025                 *(p++)=0;
1026                 *(p++)=0;
1027
1028                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1029                 /* number of bytes to write */
1030                 s->init_num=4;
1031                 s->init_off=0;
1032                 }
1033
1034         /* SSL3_ST_CW_CLNT_HELLO_B */
1035         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1036         }
1037
1038 static int ssl3_send_server_key_exchange(SSL *s)
1039         {
1040 #ifndef OPENSSL_NO_RSA
1041         unsigned char *q;
1042         int j,num;
1043         RSA *rsa;
1044         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1045         unsigned int u;
1046 #endif
1047 #ifndef OPENSSL_NO_DH
1048         DH *dh=NULL,*dhp;
1049 #endif
1050         EVP_PKEY *pkey;
1051         unsigned char *p,*d;
1052         int al,i;
1053         unsigned long type;
1054         int n;
1055         CERT *cert;
1056         BIGNUM *r[4];
1057         int nr[4],kn;
1058         BUF_MEM *buf;
1059         EVP_MD_CTX md_ctx;
1060
1061         EVP_MD_CTX_init(&md_ctx);
1062         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1063                 {
1064                 type=s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1065                 cert=s->cert;
1066
1067                 buf=s->init_buf;
1068
1069                 r[0]=r[1]=r[2]=r[3]=NULL;
1070                 n=0;
1071 #ifndef OPENSSL_NO_RSA
1072                 if (type & SSL_kRSA)
1073                         {
1074                         rsa=cert->rsa_tmp;
1075                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1076                                 {
1077                                 rsa=s->cert->rsa_tmp_cb(s,
1078                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1079                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1080                                 if(rsa == NULL)
1081                                 {
1082                                         al=SSL_AD_HANDSHAKE_FAILURE;
1083                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1084                                         goto f_err;
1085                                 }
1086                                 RSA_up_ref(rsa);
1087                                 cert->rsa_tmp=rsa;
1088                                 }
1089                         if (rsa == NULL)
1090                                 {
1091                                 al=SSL_AD_HANDSHAKE_FAILURE;
1092                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1093                                 goto f_err;
1094                                 }
1095                         r[0]=rsa->n;
1096                         r[1]=rsa->e;
1097                         s->s3->tmp.use_rsa_tmp=1;
1098                         }
1099                 else
1100 #endif
1101 #ifndef OPENSSL_NO_DH
1102                         if (type & SSL_kEDH)
1103                         {
1104                         dhp=cert->dh_tmp;
1105                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1106                                 dhp=s->cert->dh_tmp_cb(s,
1107                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1108                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1109                         if (dhp == NULL)
1110                                 {
1111                                 al=SSL_AD_HANDSHAKE_FAILURE;
1112                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1113                                 goto f_err;
1114                                 }
1115
1116                         if (s->s3->tmp.dh != NULL)
1117                                 {
1118                                 DH_free(dh);
1119                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1120                                 goto err;
1121                                 }
1122
1123                         if ((dh=DHparams_dup(dhp)) == NULL)
1124                                 {
1125                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1126                                 goto err;
1127                                 }
1128
1129                         s->s3->tmp.dh=dh;
1130                         if ((dhp->pub_key == NULL ||
1131                              dhp->priv_key == NULL ||
1132                              (s->options & SSL_OP_SINGLE_DH_USE)))
1133                                 {
1134                                 if(!DH_generate_key(dh))
1135                                     {
1136                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1137                                            ERR_R_DH_LIB);
1138                                     goto err;
1139                                     }
1140                                 }
1141                         else
1142                                 {
1143                                 dh->pub_key=BN_dup(dhp->pub_key);
1144                                 dh->priv_key=BN_dup(dhp->priv_key);
1145                                 if ((dh->pub_key == NULL) ||
1146                                         (dh->priv_key == NULL))
1147                                         {
1148                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1149                                         goto err;
1150                                         }
1151                                 }
1152                         r[0]=dh->p;
1153                         r[1]=dh->g;
1154                         r[2]=dh->pub_key;
1155                         }
1156                 else 
1157 #endif
1158                         {
1159                         al=SSL_AD_HANDSHAKE_FAILURE;
1160                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1161                         goto f_err;
1162                         }
1163                 for (i=0; r[i] != NULL; i++)
1164                         {
1165                         nr[i]=BN_num_bytes(r[i]);
1166                         n+=2+nr[i];
1167                         }
1168
1169                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1170                         {
1171                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1172                                 == NULL)
1173                                 {
1174                                 al=SSL_AD_DECODE_ERROR;
1175                                 goto f_err;
1176                                 }
1177                         kn=EVP_PKEY_size(pkey);
1178                         }
1179                 else
1180                         {
1181                         pkey=NULL;
1182                         kn=0;
1183                         }
1184
1185                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1186                         {
1187                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1188                         goto err;
1189                         }
1190                 d=(unsigned char *)s->init_buf->data;
1191                 p= &(d[4]);
1192
1193                 for (i=0; r[i] != NULL; i++)
1194                         {
1195                         s2n(nr[i],p);
1196                         BN_bn2bin(r[i],p);
1197                         p+=nr[i];
1198                         }
1199
1200                 /* not anonymous */
1201                 if (pkey != NULL)
1202                         {
1203                         /* n is the length of the params, they start at &(d[4])
1204                          * and p points to the space at the end. */
1205 #ifndef OPENSSL_NO_RSA
1206                         if (pkey->type == EVP_PKEY_RSA)
1207                                 {
1208                                 q=md_buf;
1209                                 j=0;
1210                                 for (num=2; num > 0; num--)
1211                                         {
1212                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1213                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1214                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1215                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1216                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1217                                         EVP_DigestFinal_ex(&md_ctx,q,
1218                                                 (unsigned int *)&i);
1219                                         q+=i;
1220                                         j+=i;
1221                                         }
1222                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1223                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1224                                         {
1225                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1226                                         goto err;
1227                                         }
1228                                 s2n(u,p);
1229                                 n+=u+2;
1230                                 }
1231                         else
1232 #endif
1233 #if !defined(OPENSSL_NO_DSA)
1234                                 if (pkey->type == EVP_PKEY_DSA)
1235                                 {
1236                                 /* lets do DSS */
1237                                 EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL);
1238                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1239                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1240                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1241                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1242                                         (unsigned int *)&i,pkey))
1243                                         {
1244                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1245                                         goto err;
1246                                         }
1247                                 s2n(i,p);
1248                                 n+=i+2;
1249                                 }
1250                         else
1251 #endif
1252                                 {
1253                                 /* Is this error check actually needed? */
1254                                 al=SSL_AD_HANDSHAKE_FAILURE;
1255                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1256                                 goto f_err;
1257                                 }
1258                         }
1259
1260                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1261                 l2n3(n,d);
1262
1263                 /* we should now have things packed up, so lets send
1264                  * it off */
1265                 s->init_num=n+4;
1266                 s->init_off=0;
1267                 }
1268
1269         s->state = SSL3_ST_SW_KEY_EXCH_B;
1270         EVP_MD_CTX_cleanup(&md_ctx);
1271         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1272 f_err:
1273         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1274 err:
1275         EVP_MD_CTX_cleanup(&md_ctx);
1276         return(-1);
1277         }
1278
1279 static int ssl3_send_certificate_request(SSL *s)
1280         {
1281         unsigned char *p,*d;
1282         int i,j,nl,off,n;
1283         STACK_OF(X509_NAME) *sk=NULL;
1284         X509_NAME *name;
1285         BUF_MEM *buf;
1286
1287         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1288                 {
1289                 buf=s->init_buf;
1290
1291                 d=p=(unsigned char *)&(buf->data[4]);
1292
1293                 /* get the list of acceptable cert types */
1294                 p++;
1295                 n=ssl3_get_req_cert_type(s,p);
1296                 d[0]=n;
1297                 p+=n;
1298                 n++;
1299
1300                 off=n;
1301                 p+=2;
1302                 n+=2;
1303
1304                 sk=SSL_get_client_CA_list(s);
1305                 nl=0;
1306                 if (sk != NULL)
1307                         {
1308                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1309                                 {
1310                                 name=sk_X509_NAME_value(sk,i);
1311                                 j=i2d_X509_NAME(name,NULL);
1312                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
1313                                         {
1314                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1315                                         goto err;
1316                                         }
1317                                 p=(unsigned char *)&(buf->data[4+n]);
1318                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1319                                         {
1320                                         s2n(j,p);
1321                                         i2d_X509_NAME(name,&p);
1322                                         n+=2+j;
1323                                         nl+=2+j;
1324                                         }
1325                                 else
1326                                         {
1327                                         d=p;
1328                                         i2d_X509_NAME(name,&p);
1329                                         j-=2; s2n(j,d); j+=2;
1330                                         n+=j;
1331                                         nl+=j;
1332                                         }
1333                                 }
1334                         }
1335                 /* else no CA names */
1336                 p=(unsigned char *)&(buf->data[4+off]);
1337                 s2n(nl,p);
1338
1339                 d=(unsigned char *)buf->data;
1340                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1341                 l2n3(n,d);
1342
1343                 /* we should now have things packed up, so lets send
1344                  * it off */
1345
1346                 s->init_num=n+4;
1347                 s->init_off=0;
1348 #ifdef NETSCAPE_HANG_BUG
1349                 p=(unsigned char *)s->init_buf->data + s->init_num;
1350
1351                 /* do the header */
1352                 *(p++)=SSL3_MT_SERVER_DONE;
1353                 *(p++)=0;
1354                 *(p++)=0;
1355                 *(p++)=0;
1356                 s->init_num += 4;
1357 #endif
1358
1359                 }
1360
1361         /* SSL3_ST_SW_CERT_REQ_B */
1362         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1363 err:
1364         return(-1);
1365         }
1366
1367 static int ssl3_get_client_key_exchange(SSL *s)
1368         {
1369         int i,al,ok;
1370         long n;
1371         unsigned long l;
1372         unsigned char *p;
1373 #ifndef OPENSSL_NO_RSA
1374         RSA *rsa=NULL;
1375         EVP_PKEY *pkey=NULL;
1376 #endif
1377 #ifndef OPENSSL_NO_DH
1378         BIGNUM *pub=NULL;
1379         DH *dh_srvr;
1380 #endif
1381 #ifndef OPENSSL_NO_KRB5
1382         KSSL_ERR kssl_err;
1383 #endif /* OPENSSL_NO_KRB5 */
1384
1385         n=ssl3_get_message(s,
1386                 SSL3_ST_SR_KEY_EXCH_A,
1387                 SSL3_ST_SR_KEY_EXCH_B,
1388                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1389                 2048, /* ??? */
1390                 &ok);
1391
1392         if (!ok) return((int)n);
1393         p=(unsigned char *)s->init_msg;
1394
1395         l=s->s3->tmp.new_cipher->algorithms;
1396
1397 #ifndef OPENSSL_NO_RSA
1398         if (l & SSL_kRSA)
1399                 {
1400                 /* FIX THIS UP EAY EAY EAY EAY */
1401                 if (s->s3->tmp.use_rsa_tmp)
1402                         {
1403                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1404                                 rsa=s->cert->rsa_tmp;
1405                         /* Don't do a callback because rsa_tmp should
1406                          * be sent already */
1407                         if (rsa == NULL)
1408                                 {
1409                                 al=SSL_AD_HANDSHAKE_FAILURE;
1410                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1411                                 goto f_err;
1412
1413                                 }
1414                         }
1415                 else
1416                         {
1417                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1418                         if (    (pkey == NULL) ||
1419                                 (pkey->type != EVP_PKEY_RSA) ||
1420                                 (pkey->pkey.rsa == NULL))
1421                                 {
1422                                 al=SSL_AD_HANDSHAKE_FAILURE;
1423                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1424                                 goto f_err;
1425                                 }
1426                         rsa=pkey->pkey.rsa;
1427                         }
1428
1429                 /* TLS */
1430                 if (s->version > SSL3_VERSION)
1431                         {
1432                         n2s(p,i);
1433                         if (n != i+2)
1434                                 {
1435                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1436                                         {
1437                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1438                                         goto err;
1439                                         }
1440                                 else
1441                                         p-=2;
1442                                 }
1443                         else
1444                                 n=i;
1445                         }
1446
1447                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1448
1449                 al = -1;
1450                 
1451                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1452                         {
1453                         al=SSL_AD_DECODE_ERROR;
1454                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
1455                         }
1456
1457                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1458                         {
1459                         /* The premaster secret must contain the same version number as the
1460                          * ClientHello to detect version rollback attacks (strangely, the
1461                          * protocol does not offer such protection for DH ciphersuites).
1462                          * However, buggy clients exist that send the negotiated protocol
1463                          * version instead if the server does not support the requested
1464                          * protocol version.
1465                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1466                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1467                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1468                                 {
1469                                 al=SSL_AD_DECODE_ERROR;
1470                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1471
1472                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1473                                  * (http://eprint.iacr.org/2003/052/) exploits the version
1474                                  * number check as a "bad version oracle" -- an alert would
1475                                  * reveal that the plaintext corresponding to some ciphertext
1476                                  * made up by the adversary is properly formatted except
1477                                  * that the version number is wrong.  To avoid such attacks,
1478                                  * we should treat this just like any other decryption error. */
1479                                 }
1480                         }
1481
1482                 if (al != -1)
1483                         {
1484                         /* Some decryption failure -- use random value instead as countermeasure
1485                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
1486                          * (see RFC 2246, section 7.4.7.1). */
1487                         ERR_clear_error();
1488                         i = SSL_MAX_MASTER_KEY_LENGTH;
1489                         p[0] = s->client_version >> 8;
1490                         p[1] = s->client_version & 0xff;
1491                         RAND_pseudo_bytes(p+2, i-2); /* should be RAND_bytes, but we cannot work around a failure */
1492                         }
1493         
1494                 s->session->master_key_length=
1495                         s->method->ssl3_enc->generate_master_secret(s,
1496                                 s->session->master_key,
1497                                 p,i);
1498                 OPENSSL_cleanse(p,i);
1499                 }
1500         else
1501 #endif
1502 #ifndef OPENSSL_NO_DH
1503                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1504                 {
1505                 n2s(p,i);
1506                 if (n != i+2)
1507                         {
1508                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1509                                 {
1510                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1511                                 goto err;
1512                                 }
1513                         else
1514                                 {
1515                                 p-=2;
1516                                 i=(int)n;
1517                                 }
1518                         }
1519
1520                 if (n == 0L) /* the parameters are in the cert */
1521                         {
1522                         al=SSL_AD_HANDSHAKE_FAILURE;
1523                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1524                         goto f_err;
1525                         }
1526                 else
1527                         {
1528                         if (s->s3->tmp.dh == NULL)
1529                                 {
1530                                 al=SSL_AD_HANDSHAKE_FAILURE;
1531                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1532                                 goto f_err;
1533                                 }
1534                         else
1535                                 dh_srvr=s->s3->tmp.dh;
1536                         }
1537
1538                 pub=BN_bin2bn(p,i,NULL);
1539                 if (pub == NULL)
1540                         {
1541                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1542                         goto err;
1543                         }
1544
1545                 i=DH_compute_key(p,pub,dh_srvr);
1546
1547                 if (i <= 0)
1548                         {
1549                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1550                         goto err;
1551                         }
1552
1553                 DH_free(s->s3->tmp.dh);
1554                 s->s3->tmp.dh=NULL;
1555
1556                 BN_clear_free(pub);
1557                 pub=NULL;
1558                 s->session->master_key_length=
1559                         s->method->ssl3_enc->generate_master_secret(s,
1560                                 s->session->master_key,p,i);
1561                 OPENSSL_cleanse(p,i);
1562                 }
1563         else
1564 #endif
1565 #ifndef OPENSSL_NO_KRB5
1566         if (l & SSL_kKRB5)
1567                 {
1568                 krb5_error_code         krb5rc;
1569                 krb5_data               enc_ticket;
1570                 krb5_data               authenticator;
1571                 krb5_data               enc_pms;
1572                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
1573                 EVP_CIPHER_CTX          ciph_ctx;
1574                 EVP_CIPHER              *enc = NULL;
1575                 unsigned char           iv[EVP_MAX_IV_LENGTH];
1576                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
1577                                                + EVP_MAX_BLOCK_LENGTH];
1578                 int                     padl, outl;
1579                 krb5_timestamp          authtime = 0;
1580                 krb5_ticket_times       ttimes;
1581
1582                 EVP_CIPHER_CTX_init(&ciph_ctx);
1583
1584                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
1585
1586                 n2s(p,i);
1587                 enc_ticket.length = i;
1588                 enc_ticket.data = (char *)p;
1589                 p+=enc_ticket.length;
1590
1591                 n2s(p,i);
1592                 authenticator.length = i;
1593                 authenticator.data = (char *)p;
1594                 p+=authenticator.length;
1595
1596                 n2s(p,i);
1597                 enc_pms.length = i;
1598                 enc_pms.data = (char *)p;
1599                 p+=enc_pms.length;
1600
1601                 /* Note that the length is checked again below,
1602                 ** after decryption
1603                 */
1604                 if(enc_pms.length > sizeof pms)
1605                         {
1606                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1607                                SSL_R_DATA_LENGTH_TOO_LONG);
1608                         goto err;
1609                         }
1610
1611                 if (n != enc_ticket.length + authenticator.length +
1612                                                 enc_pms.length + 6)
1613                         {
1614                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1615                                 SSL_R_DATA_LENGTH_TOO_LONG);
1616                         goto err;
1617                         }
1618
1619                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
1620                                         &kssl_err)) != 0)
1621                         {
1622 #ifdef KSSL_DEBUG
1623                         printf("kssl_sget_tkt rtn %d [%d]\n",
1624                                 krb5rc, kssl_err.reason);
1625                         if (kssl_err.text)
1626                                 printf("kssl_err text= %s\n", kssl_err.text);
1627 #endif  /* KSSL_DEBUG */
1628                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1629                                 kssl_err.reason);
1630                         goto err;
1631                         }
1632
1633                 /*  Note: no authenticator is not considered an error,
1634                 **  but will return authtime == 0.
1635                 */
1636                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
1637                                         &authtime, &kssl_err)) != 0)
1638                         {
1639 #ifdef KSSL_DEBUG
1640                         printf("kssl_check_authent rtn %d [%d]\n",
1641                                 krb5rc, kssl_err.reason);
1642                         if (kssl_err.text)
1643                                 printf("kssl_err text= %s\n", kssl_err.text);
1644 #endif  /* KSSL_DEBUG */
1645                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1646                                 kssl_err.reason);
1647                         goto err;
1648                         }
1649
1650                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
1651                         {
1652                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, krb5rc);
1653                         goto err;
1654                         }
1655
1656 #ifdef KSSL_DEBUG
1657                 kssl_ctx_show(kssl_ctx);
1658 #endif  /* KSSL_DEBUG */
1659
1660                 enc = kssl_map_enc(kssl_ctx->enctype);
1661                 if (enc == NULL)
1662                     goto err;
1663
1664                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
1665
1666                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
1667                         {
1668                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1669                                 SSL_R_DECRYPTION_FAILED);
1670                         goto err;
1671                         }
1672                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
1673                                         (unsigned char *)enc_pms.data, enc_pms.length))
1674                         {
1675                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1676                                 SSL_R_DECRYPTION_FAILED);
1677                         goto err;
1678                         }
1679                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1680                         {
1681                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1682                                 SSL_R_DATA_LENGTH_TOO_LONG);
1683                         goto err;
1684                         }
1685                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
1686                         {
1687                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1688                                 SSL_R_DECRYPTION_FAILED);
1689                         goto err;
1690                         }
1691                 outl += padl;
1692                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1693                         {
1694                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1695                                 SSL_R_DATA_LENGTH_TOO_LONG);
1696                         goto err;
1697                         }
1698                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1699
1700                 s->session->master_key_length=
1701                         s->method->ssl3_enc->generate_master_secret(s,
1702                                 s->session->master_key, pms, outl);
1703
1704                 if (kssl_ctx->client_princ)
1705                         {
1706                         int len = strlen(kssl_ctx->client_princ);
1707                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
1708                                 {
1709                                 s->session->krb5_client_princ_len = len;
1710                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
1711                                 }
1712                         }
1713
1714
1715                 /*  Was doing kssl_ctx_free() here,
1716                 **  but it caused problems for apache.
1717                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
1718                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
1719                 */
1720                 }
1721         else
1722 #endif  /* OPENSSL_NO_KRB5 */
1723                 {
1724                 al=SSL_AD_HANDSHAKE_FAILURE;
1725                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1726                                 SSL_R_UNKNOWN_CIPHER_TYPE);
1727                 goto f_err;
1728                 }
1729
1730         return(1);
1731 f_err:
1732         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1733 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA)
1734 err:
1735 #endif
1736         return(-1);
1737         }
1738
1739 static int ssl3_get_cert_verify(SSL *s)
1740         {
1741         EVP_PKEY *pkey=NULL;
1742         unsigned char *p;
1743         int al,ok,ret=0;
1744         long n;
1745         int type=0,i,j;
1746         X509 *peer;
1747
1748         n=ssl3_get_message(s,
1749                 SSL3_ST_SR_CERT_VRFY_A,
1750                 SSL3_ST_SR_CERT_VRFY_B,
1751                 -1,
1752                 514, /* 514? */
1753                 &ok);
1754
1755         if (!ok) return((int)n);
1756
1757         if (s->session->peer != NULL)
1758                 {
1759                 peer=s->session->peer;
1760                 pkey=X509_get_pubkey(peer);
1761                 type=X509_certificate_type(peer,pkey);
1762                 }
1763         else
1764                 {
1765                 peer=NULL;
1766                 pkey=NULL;
1767                 }
1768
1769         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
1770                 {
1771                 s->s3->tmp.reuse_message=1;
1772                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
1773                         {
1774                         al=SSL_AD_UNEXPECTED_MESSAGE;
1775                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
1776                         goto f_err;
1777                         }
1778                 ret=1;
1779                 goto end;
1780                 }
1781
1782         if (peer == NULL)
1783                 {
1784                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
1785                 al=SSL_AD_UNEXPECTED_MESSAGE;
1786                 goto f_err;
1787                 }
1788
1789         if (!(type & EVP_PKT_SIGN))
1790                 {
1791                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1792                 al=SSL_AD_ILLEGAL_PARAMETER;
1793                 goto f_err;
1794                 }
1795
1796         if (s->s3->change_cipher_spec)
1797                 {
1798                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
1799                 al=SSL_AD_UNEXPECTED_MESSAGE;
1800                 goto f_err;
1801                 }
1802
1803         /* we now have a signature that we need to verify */
1804         p=(unsigned char *)s->init_msg;
1805         n2s(p,i);
1806         n-=2;
1807         if (i > n)
1808                 {
1809                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
1810                 al=SSL_AD_DECODE_ERROR;
1811                 goto f_err;
1812                 }
1813
1814         j=EVP_PKEY_size(pkey);
1815         if ((i > j) || (n > j) || (n <= 0))
1816                 {
1817                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
1818                 al=SSL_AD_DECODE_ERROR;
1819                 goto f_err;
1820                 }
1821
1822 #ifndef OPENSSL_NO_RSA 
1823         if (pkey->type == EVP_PKEY_RSA)
1824                 {
1825                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
1826                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
1827                                                         pkey->pkey.rsa);
1828                 if (i < 0)
1829                         {
1830                         al=SSL_AD_DECRYPT_ERROR;
1831                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
1832                         goto f_err;
1833                         }
1834                 if (i == 0)
1835                         {
1836                         al=SSL_AD_DECRYPT_ERROR;
1837                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
1838                         goto f_err;
1839                         }
1840                 }
1841         else
1842 #endif
1843 #ifndef OPENSSL_NO_DSA
1844                 if (pkey->type == EVP_PKEY_DSA)
1845                 {
1846                 j=DSA_verify(pkey->save_type,
1847                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
1848                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
1849                 if (j <= 0)
1850                         {
1851                         /* bad signature */
1852                         al=SSL_AD_DECRYPT_ERROR;
1853                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
1854                         goto f_err;
1855                         }
1856                 }
1857         else
1858 #endif
1859                 {
1860                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
1861                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
1862                 goto f_err;
1863                 }
1864
1865
1866         ret=1;
1867         if (0)
1868                 {
1869 f_err:
1870                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1871                 }
1872 end:
1873         EVP_PKEY_free(pkey);
1874         return(ret);
1875         }
1876
1877 static int ssl3_get_client_certificate(SSL *s)
1878         {
1879         int i,ok,al,ret= -1;
1880         X509 *x=NULL;
1881         unsigned long l,nc,llen,n;
1882         unsigned char *p,*d,*q;
1883         STACK_OF(X509) *sk=NULL;
1884
1885         n=ssl3_get_message(s,
1886                 SSL3_ST_SR_CERT_A,
1887                 SSL3_ST_SR_CERT_B,
1888                 -1,
1889                 s->max_cert_list,
1890                 &ok);
1891
1892         if (!ok) return((int)n);
1893
1894         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
1895                 {
1896                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
1897                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1898                         {
1899                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1900                         al=SSL_AD_HANDSHAKE_FAILURE;
1901                         goto f_err;
1902                         }
1903                 /* If tls asked for a client cert, the client must return a 0 list */
1904                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
1905                         {
1906                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
1907                         al=SSL_AD_UNEXPECTED_MESSAGE;
1908                         goto f_err;
1909                         }
1910                 s->s3->tmp.reuse_message=1;
1911                 return(1);
1912                 }
1913
1914         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1915                 {
1916                 al=SSL_AD_UNEXPECTED_MESSAGE;
1917                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
1918                 goto f_err;
1919                 }
1920         d=p=(unsigned char *)s->init_msg;
1921
1922         if ((sk=sk_X509_new_null()) == NULL)
1923                 {
1924                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1925                 goto err;
1926                 }
1927
1928         n2l3(p,llen);
1929         if (llen+3 != n)
1930                 {
1931                 al=SSL_AD_DECODE_ERROR;
1932                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1933                 goto f_err;
1934                 }
1935         for (nc=0; nc<llen; )
1936                 {
1937                 n2l3(p,l);
1938                 if ((l+nc+3) > llen)
1939                         {
1940                         al=SSL_AD_DECODE_ERROR;
1941                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1942                         goto f_err;
1943                         }
1944
1945                 q=p;
1946                 x=d2i_X509(NULL,&p,l);
1947                 if (x == NULL)
1948                         {
1949                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
1950                         goto err;
1951                         }
1952                 if (p != (q+l))
1953                         {
1954                         al=SSL_AD_DECODE_ERROR;
1955                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1956                         goto f_err;
1957                         }
1958                 if (!sk_X509_push(sk,x))
1959                         {
1960                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1961                         goto err;
1962                         }
1963                 x=NULL;
1964                 nc+=l+3;
1965                 }
1966
1967         if (sk_X509_num(sk) <= 0)
1968                 {
1969                 /* TLS does not mind 0 certs returned */
1970                 if (s->version == SSL3_VERSION)
1971                         {
1972                         al=SSL_AD_HANDSHAKE_FAILURE;
1973                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
1974                         goto f_err;
1975                         }
1976                 /* Fail for TLS only if we required a certificate */
1977                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
1978                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1979                         {
1980                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1981                         al=SSL_AD_HANDSHAKE_FAILURE;
1982                         goto f_err;
1983                         }
1984                 }
1985         else
1986                 {
1987                 i=ssl_verify_cert_chain(s,sk);
1988                 if (!i)
1989                         {
1990                         al=ssl_verify_alarm_type(s->verify_result);
1991                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
1992                         goto f_err;
1993                         }
1994                 }
1995
1996         if (s->session->peer != NULL) /* This should not be needed */
1997                 X509_free(s->session->peer);
1998         s->session->peer=sk_X509_shift(sk);
1999         s->session->verify_result = s->verify_result;
2000
2001         /* With the current implementation, sess_cert will always be NULL
2002          * when we arrive here. */
2003         if (s->session->sess_cert == NULL)
2004                 {
2005                 s->session->sess_cert = ssl_sess_cert_new();
2006                 if (s->session->sess_cert == NULL)
2007                         {
2008                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2009                         goto err;
2010                         }
2011                 }
2012         if (s->session->sess_cert->cert_chain != NULL)
2013                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2014         s->session->sess_cert->cert_chain=sk;
2015         /* Inconsistency alert: cert_chain does *not* include the
2016          * peer's own certificate, while we do include it in s3_clnt.c */
2017
2018         sk=NULL;
2019
2020         ret=1;
2021         if (0)
2022                 {
2023 f_err:
2024                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2025                 }
2026 err:
2027         if (x != NULL) X509_free(x);
2028         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2029         return(ret);
2030         }
2031
2032 int ssl3_send_server_certificate(SSL *s)
2033         {
2034         unsigned long l;
2035         X509 *x;
2036
2037         if (s->state == SSL3_ST_SW_CERT_A)
2038                 {
2039                 x=ssl_get_server_send_cert(s);
2040                 if (x == NULL &&
2041                         /* VRS: allow null cert if auth == KRB5 */
2042                         (s->s3->tmp.new_cipher->algorithms
2043                                 & (SSL_MKEY_MASK|SSL_AUTH_MASK))
2044                         != (SSL_aKRB5|SSL_kKRB5))
2045                         {
2046                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
2047                         return(0);
2048                         }
2049
2050                 l=ssl3_output_cert_chain(s,x);
2051                 s->state=SSL3_ST_SW_CERT_B;
2052                 s->init_num=(int)l;
2053                 s->init_off=0;
2054                 }
2055
2056         /* SSL3_ST_SW_CERT_B */
2057         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2058         }