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