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