Disable session related stuff in SSL_ST_OK case of ssl3_accept if we
[oweals/openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-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         int got_new_session=0;
174
175         RAND_add(&Time,sizeof(Time),0);
176         ERR_clear_error();
177         clear_sys_error();
178
179         if (s->info_callback != NULL)
180                 cb=s->info_callback;
181         else if (s->ctx->info_callback != NULL)
182                 cb=s->ctx->info_callback;
183
184         /* init things to blank */
185         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
186         s->in_handshake++;
187
188         if (s->cert == NULL)
189                 {
190                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
191                 return(-1);
192                 }
193
194         for (;;)
195                 {
196                 state=s->state;
197
198                 switch (s->state)
199                         {
200                 case SSL_ST_RENEGOTIATE:
201                         s->new_session=1;
202                         /* s->state=SSL_ST_ACCEPT; */
203
204                 case SSL_ST_BEFORE:
205                 case SSL_ST_ACCEPT:
206                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
207                 case SSL_ST_OK|SSL_ST_ACCEPT:
208
209                         s->server=1;
210                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
211
212                         if ((s->version>>8) != 3)
213                                 {
214                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
215                                 return -1;
216                                 }
217                         s->type=SSL_ST_ACCEPT;
218
219                         if (s->init_buf == NULL)
220                                 {
221                                 if ((buf=BUF_MEM_new()) == NULL)
222                                         {
223                                         ret= -1;
224                                         goto end;
225                                         }
226                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
227                                         {
228                                         ret= -1;
229                                         goto end;
230                                         }
231                                 s->init_buf=buf;
232                                 }
233
234                         if (!ssl3_setup_buffers(s))
235                                 {
236                                 ret= -1;
237                                 goto end;
238                                 }
239
240                         s->init_num=0;
241
242                         if (s->state != SSL_ST_RENEGOTIATE)
243                                 {
244                                 /* Ok, we now need to push on a buffering BIO so that
245                                  * the output is sent in a way that TCP likes :-)
246                                  */
247                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
248                                 
249                                 ssl3_init_finished_mac(s);
250                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
251                                 s->ctx->stats.sess_accept++;
252                                 }
253                         else
254                                 {
255                                 /* s->state == SSL_ST_RENEGOTIATE,
256                                  * we will just send a HelloRequest */
257                                 s->ctx->stats.sess_accept_renegotiate++;
258                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
259                                 }
260                         break;
261
262                 case SSL3_ST_SW_HELLO_REQ_A:
263                 case SSL3_ST_SW_HELLO_REQ_B:
264
265                         s->shutdown=0;
266                         ret=ssl3_send_hello_request(s);
267                         if (ret <= 0) goto end;
268                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
269                         s->state=SSL3_ST_SW_FLUSH;
270                         s->init_num=0;
271
272                         ssl3_init_finished_mac(s);
273                         break;
274
275                 case SSL3_ST_SW_HELLO_REQ_C:
276                         s->state=SSL_ST_OK;
277                         break;
278
279                 case SSL3_ST_SR_CLNT_HELLO_A:
280                 case SSL3_ST_SR_CLNT_HELLO_B:
281                 case SSL3_ST_SR_CLNT_HELLO_C:
282
283                         s->shutdown=0;
284                         ret=ssl3_get_client_hello(s);
285                         if (ret <= 0) goto end;
286                         got_new_session=1;
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                         s->init_num=0;
528
529                         if (got_new_session) /* skipped if we just sent a HelloRequest */
530                                 {
531                                 /* actually not necessarily a 'new' session unless
532                                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
533                                 
534                                 s->new_session=0;
535                                 
536                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
537                                 
538                                 s->ctx->stats.sess_accept_good++;
539                                 /* s->server=1; */
540                                 s->handshake_func=ssl3_accept;
541
542                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
543                                 }
544                         
545                         goto end;
546                         /* break; */
547
548                 default:
549                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
550                         ret= -1;
551                         goto end;
552                         /* break; */
553                         }
554                 
555                 if (!s->s3->tmp.reuse_message && !skip)
556                         {
557                         if (s->debug)
558                                 {
559                                 if ((ret=BIO_flush(s->wbio)) <= 0)
560                                         goto end;
561                                 }
562
563
564                         if ((cb != NULL) && (s->state != state))
565                                 {
566                                 new_state=s->state;
567                                 s->state=state;
568                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
569                                 s->state=new_state;
570                                 }
571                         }
572                 skip=0;
573                 }
574 end:
575         /* BIO_flush(s->wbio); */
576
577         if (cb != NULL)
578                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
579         s->in_handshake--;
580         return(ret);
581         }
582
583 static int ssl3_send_hello_request(SSL *s)
584         {
585         unsigned char *p;
586
587         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
588                 {
589                 p=(unsigned char *)s->init_buf->data;
590                 *(p++)=SSL3_MT_HELLO_REQUEST;
591                 *(p++)=0;
592                 *(p++)=0;
593                 *(p++)=0;
594
595                 s->state=SSL3_ST_SW_HELLO_REQ_B;
596                 /* number of bytes to write */
597                 s->init_num=4;
598                 s->init_off=0;
599                 }
600
601         /* SSL3_ST_SW_HELLO_REQ_B */
602         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
603         }
604
605 static int ssl3_check_client_hello(SSL *s)
606         {
607         int ok;
608         long n;
609
610         /* this function is called when we really expect a Certificate message,
611          * so permit appropriate message length */
612         n=ssl3_get_message(s,
613                 SSL3_ST_SR_CERT_A,
614                 SSL3_ST_SR_CERT_B,
615                 -1,
616                 s->max_cert_list,
617                 &ok);
618         if (!ok) return((int)n);
619         s->s3->tmp.reuse_message = 1;
620         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
621                 {
622                 /* Throw away what we have done so far in the current handshake,
623                  * which will now be aborted. (A full SSL_clear would be too much.)
624                  * I hope that tmp.dh is the only thing that may need to be cleared
625                  * when a handshake is not completed ... */
626 #ifndef OPENSSL_NO_DH
627                 if (s->s3->tmp.dh != NULL)
628                         {
629                         DH_free(s->s3->tmp.dh);
630                         s->s3->tmp.dh = NULL;
631                         }
632 #endif
633                 return 2;
634                 }
635         return 1;
636 }
637
638 static int ssl3_get_client_hello(SSL *s)
639         {
640         int i,j,ok,al,ret= -1;
641         long n;
642         unsigned long id;
643         unsigned char *p,*d,*q;
644         SSL_CIPHER *c;
645         SSL_COMP *comp=NULL;
646         STACK_OF(SSL_CIPHER) *ciphers=NULL;
647
648         /* We do this so that we will respond with our native type.
649          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
650          * This down switching should be handled by a different method.
651          * If we are SSLv3, we will respond with SSLv3, even if prompted with
652          * TLSv1.
653          */
654         if (s->state == SSL3_ST_SR_CLNT_HELLO_A)
655                 {
656                 s->first_packet=1;
657                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
658                 }
659         n=ssl3_get_message(s,
660                 SSL3_ST_SR_CLNT_HELLO_B,
661                 SSL3_ST_SR_CLNT_HELLO_C,
662                 SSL3_MT_CLIENT_HELLO,
663                 SSL3_RT_MAX_PLAIN_LENGTH,
664                 &ok);
665
666         if (!ok) return((int)n);
667         d=p=(unsigned char *)s->init_buf->data;
668
669         /* use version from inside client hello, not from record header
670          * (may differ: see RFC 2246, Appendix E, second paragraph) */
671         s->client_version=(((int)p[0])<<8)|(int)p[1];
672         p+=2;
673
674         /* load the client random */
675         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
676         p+=SSL3_RANDOM_SIZE;
677
678         /* get the session-id */
679         j= *(p++);
680
681         s->hit=0;
682         /* Versions before 0.9.7 always allow session reuse during renegotiation
683          * (i.e. when s->new_session is true), option
684          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7.
685          * Maybe this optional behaviour should always have been the default,
686          * but we cannot safely change the default behaviour (or new applications
687          * might be written that become totally unsecure when compiled with
688          * an earlier library version)
689          */
690         if (j == 0 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
691                 {
692                 if (!ssl_get_new_session(s,1))
693                         goto err;
694                 }
695         else
696                 {
697                 i=ssl_get_prev_session(s,p,j);
698                 if (i == 1)
699                         { /* previous session */
700                         s->hit=1;
701                         }
702                 else if (i == -1)
703                         goto err;
704                 else /* i == 0 */
705                         {
706                         if (!ssl_get_new_session(s,1))
707                                 goto err;
708                         }
709                 }
710
711         p+=j;
712         n2s(p,i);
713         if ((i == 0) && (j != 0))
714                 {
715                 /* we need a cipher if we are not resuming a session */
716                 al=SSL_AD_ILLEGAL_PARAMETER;
717                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
718                 goto f_err;
719                 }
720         if ((i+p) > (d+n))
721                 {
722                 /* not enough data */
723                 al=SSL_AD_DECODE_ERROR;
724                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
725                 goto f_err;
726                 }
727         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
728                 == NULL))
729                 {
730                 goto err;
731                 }
732         p+=i;
733
734         /* If it is a hit, check that the cipher is in the list */
735         if ((s->hit) && (i > 0))
736                 {
737                 j=0;
738                 id=s->session->cipher->id;
739
740 #ifdef CIPHER_DEBUG
741                 printf("client sent %d ciphers\n",sk_num(ciphers));
742 #endif
743                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
744                         {
745                         c=sk_SSL_CIPHER_value(ciphers,i);
746 #ifdef CIPHER_DEBUG
747                         printf("client [%2d of %2d]:%s\n",
748                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
749 #endif
750                         if (c->id == id)
751                                 {
752                                 j=1;
753                                 break;
754                                 }
755                         }
756                 if (j == 0)
757                         {
758                         if ((s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
759                                 {
760                                 /* Very bad for multi-threading.... */
761                                 s->session->cipher=sk_SSL_CIPHER_value(ciphers,
762                                                                        0);
763                                 }
764                         else
765                                 {
766                                 /* we need to have the cipher in the cipher
767                                  * list if we are asked to reuse it */
768                                 al=SSL_AD_ILLEGAL_PARAMETER;
769                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
770                                 goto f_err;
771                                 }
772                         }
773                 }
774
775         /* compression */
776         i= *(p++);
777         q=p;
778         for (j=0; j<i; j++)
779                 {
780                 if (p[j] == 0) break;
781                 }
782
783         p+=i;
784         if (j >= i)
785                 {
786                 /* no compress */
787                 al=SSL_AD_DECODE_ERROR;
788                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
789                 goto f_err;
790                 }
791
792         /* Worst case, we will use the NULL compression, but if we have other
793          * options, we will now look for them.  We have i-1 compression
794          * algorithms from the client, starting at q. */
795         s->s3->tmp.new_compression=NULL;
796         if (s->ctx->comp_methods != NULL)
797                 { /* See if we have a match */
798                 int m,nn,o,v,done=0;
799
800                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
801                 for (m=0; m<nn; m++)
802                         {
803                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
804                         v=comp->id;
805                         for (o=0; o<i; o++)
806                                 {
807                                 if (v == q[o])
808                                         {
809                                         done=1;
810                                         break;
811                                         }
812                                 }
813                         if (done) break;
814                         }
815                 if (done)
816                         s->s3->tmp.new_compression=comp;
817                 else
818                         comp=NULL;
819                 }
820
821         /* TLS does not mind if there is extra stuff */
822         if (s->version == SSL3_VERSION)
823                 {
824                 if (p > (d+n))
825                         {
826                         /* wrong number of bytes,
827                          * there could be more to follow */
828                         al=SSL_AD_DECODE_ERROR;
829                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
830                         goto f_err;
831                         }
832                 }
833
834         /* Given s->session->ciphers and SSL_get_ciphers, we must
835          * pick a cipher */
836
837         if (!s->hit)
838                 {
839                 s->session->compress_meth=(comp == NULL)?0:comp->id;
840                 if (s->session->ciphers != NULL)
841                         sk_SSL_CIPHER_free(s->session->ciphers);
842                 s->session->ciphers=ciphers;
843                 if (ciphers == NULL)
844                         {
845                         al=SSL_AD_ILLEGAL_PARAMETER;
846                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
847                         goto f_err;
848                         }
849                 ciphers=NULL;
850                 c=ssl3_choose_cipher(s,s->session->ciphers,
851                                      SSL_get_ciphers(s));
852
853                 if (c == NULL)
854                         {
855                         al=SSL_AD_HANDSHAKE_FAILURE;
856                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
857                         goto f_err;
858                         }
859                 s->s3->tmp.new_cipher=c;
860                 }
861         else
862                 {
863                 /* Session-id reuse */
864 #ifdef REUSE_CIPHER_BUG
865                 STACK_OF(SSL_CIPHER) *sk;
866                 SSL_CIPHER *nc=NULL;
867                 SSL_CIPHER *ec=NULL;
868
869                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
870                         {
871                         sk=s->session->ciphers;
872                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
873                                 {
874                                 c=sk_SSL_CIPHER_value(sk,i);
875                                 if (c->algorithms & SSL_eNULL)
876                                         nc=c;
877                                 if (SSL_C_IS_EXPORT(c))
878                                         ec=c;
879                                 }
880                         if (nc != NULL)
881                                 s->s3->tmp.new_cipher=nc;
882                         else if (ec != NULL)
883                                 s->s3->tmp.new_cipher=ec;
884                         else
885                                 s->s3->tmp.new_cipher=s->session->cipher;
886                         }
887                 else
888 #endif
889                 s->s3->tmp.new_cipher=s->session->cipher;
890                 }
891         
892         /* we now have the following setup. 
893          * client_random
894          * cipher_list          - our prefered list of ciphers
895          * ciphers              - the clients prefered list of ciphers
896          * compression          - basically ignored right now
897          * ssl version is set   - sslv3
898          * s->session           - The ssl session has been setup.
899          * s->hit               - session reuse flag
900          * s->tmp.new_cipher    - the new cipher to use.
901          */
902
903         ret=1;
904         if (0)
905                 {
906 f_err:
907                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
908                 }
909 err:
910         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
911         return(ret);
912         }
913
914 static int ssl3_send_server_hello(SSL *s)
915         {
916         unsigned char *buf;
917         unsigned char *p,*d;
918         int i,sl;
919         unsigned long l,Time;
920
921         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
922                 {
923                 buf=(unsigned char *)s->init_buf->data;
924                 p=s->s3->server_random;
925                 Time=time(NULL);                        /* Time */
926                 l2n(Time,p);
927                 RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
928                 /* Do the message type and length last */
929                 d=p= &(buf[4]);
930
931                 *(p++)=s->version>>8;
932                 *(p++)=s->version&0xff;
933
934                 /* Random stuff */
935                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
936                 p+=SSL3_RANDOM_SIZE;
937
938                 /* now in theory we have 3 options to sending back the
939                  * session id.  If it is a re-use, we send back the
940                  * old session-id, if it is a new session, we send
941                  * back the new session-id or we send back a 0 length
942                  * session-id if we want it to be single use.
943                  * Currently I will not implement the '0' length session-id
944                  * 12-Jan-98 - I'll now support the '0' length stuff.
945                  */
946                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER))
947                         s->session->session_id_length=0;
948
949                 sl=s->session->session_id_length;
950                 *(p++)=sl;
951                 memcpy(p,s->session->session_id,sl);
952                 p+=sl;
953
954                 /* put the cipher */
955                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
956                 p+=i;
957
958                 /* put the compression method */
959                 if (s->s3->tmp.new_compression == NULL)
960                         *(p++)=0;
961                 else
962                         *(p++)=s->s3->tmp.new_compression->id;
963
964                 /* do the header */
965                 l=(p-d);
966                 d=buf;
967                 *(d++)=SSL3_MT_SERVER_HELLO;
968                 l2n3(l,d);
969
970                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
971                 /* number of bytes to write */
972                 s->init_num=p-buf;
973                 s->init_off=0;
974                 }
975
976         /* SSL3_ST_CW_CLNT_HELLO_B */
977         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
978         }
979
980 static int ssl3_send_server_done(SSL *s)
981         {
982         unsigned char *p;
983
984         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
985                 {
986                 p=(unsigned char *)s->init_buf->data;
987
988                 /* do the header */
989                 *(p++)=SSL3_MT_SERVER_DONE;
990                 *(p++)=0;
991                 *(p++)=0;
992                 *(p++)=0;
993
994                 s->state=SSL3_ST_SW_SRVR_DONE_B;
995                 /* number of bytes to write */
996                 s->init_num=4;
997                 s->init_off=0;
998                 }
999
1000         /* SSL3_ST_CW_CLNT_HELLO_B */
1001         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1002         }
1003
1004 static int ssl3_send_server_key_exchange(SSL *s)
1005         {
1006 #ifndef OPENSSL_NO_RSA
1007         unsigned char *q;
1008         int j,num;
1009         RSA *rsa;
1010         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1011         unsigned int u;
1012 #endif
1013 #ifndef OPENSSL_NO_DH
1014         DH *dh=NULL,*dhp;
1015 #endif
1016         EVP_PKEY *pkey;
1017         unsigned char *p,*d;
1018         int al,i;
1019         unsigned long type;
1020         int n;
1021         CERT *cert;
1022         BIGNUM *r[4];
1023         int nr[4],kn;
1024         BUF_MEM *buf;
1025         EVP_MD_CTX md_ctx;
1026
1027         EVP_MD_CTX_init(&md_ctx);
1028         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1029                 {
1030                 type=s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1031                 cert=s->cert;
1032
1033                 buf=s->init_buf;
1034
1035                 r[0]=r[1]=r[2]=r[3]=NULL;
1036                 n=0;
1037 #ifndef OPENSSL_NO_RSA
1038                 if (type & SSL_kRSA)
1039                         {
1040                         rsa=cert->rsa_tmp;
1041                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1042                                 {
1043                                 rsa=s->cert->rsa_tmp_cb(s,
1044                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1045                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1046                                 if(rsa == NULL)
1047                                 {
1048                                         al=SSL_AD_HANDSHAKE_FAILURE;
1049                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1050                                         goto f_err;
1051                                 }
1052                                 RSA_up_ref(rsa);
1053                                 cert->rsa_tmp=rsa;
1054                                 }
1055                         if (rsa == NULL)
1056                                 {
1057                                 al=SSL_AD_HANDSHAKE_FAILURE;
1058                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1059                                 goto f_err;
1060                                 }
1061                         r[0]=rsa->n;
1062                         r[1]=rsa->e;
1063                         s->s3->tmp.use_rsa_tmp=1;
1064                         }
1065                 else
1066 #endif
1067 #ifndef OPENSSL_NO_DH
1068                         if (type & SSL_kEDH)
1069                         {
1070                         dhp=cert->dh_tmp;
1071                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1072                                 dhp=s->cert->dh_tmp_cb(s,
1073                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1074                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1075                         if (dhp == NULL)
1076                                 {
1077                                 al=SSL_AD_HANDSHAKE_FAILURE;
1078                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1079                                 goto f_err;
1080                                 }
1081
1082                         if (s->s3->tmp.dh != NULL)
1083                                 {
1084                                 DH_free(dh);
1085                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1086                                 goto err;
1087                                 }
1088
1089                         if ((dh=DHparams_dup(dhp)) == NULL)
1090                                 {
1091                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1092                                 goto err;
1093                                 }
1094
1095                         s->s3->tmp.dh=dh;
1096                         if ((dhp->pub_key == NULL ||
1097                              dhp->priv_key == NULL ||
1098                              (s->options & SSL_OP_SINGLE_DH_USE)))
1099                                 {
1100                                 if(!DH_generate_key(dh))
1101                                     {
1102                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1103                                            ERR_R_DH_LIB);
1104                                     goto err;
1105                                     }
1106                                 }
1107                         else
1108                                 {
1109                                 dh->pub_key=BN_dup(dhp->pub_key);
1110                                 dh->priv_key=BN_dup(dhp->priv_key);
1111                                 if ((dh->pub_key == NULL) ||
1112                                         (dh->priv_key == NULL))
1113                                         {
1114                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1115                                         goto err;
1116                                         }
1117                                 }
1118                         r[0]=dh->p;
1119                         r[1]=dh->g;
1120                         r[2]=dh->pub_key;
1121                         }
1122                 else 
1123 #endif
1124                         {
1125                         al=SSL_AD_HANDSHAKE_FAILURE;
1126                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1127                         goto f_err;
1128                         }
1129                 for (i=0; r[i] != NULL; i++)
1130                         {
1131                         nr[i]=BN_num_bytes(r[i]);
1132                         n+=2+nr[i];
1133                         }
1134
1135                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1136                         {
1137                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1138                                 == NULL)
1139                                 {
1140                                 al=SSL_AD_DECODE_ERROR;
1141                                 goto f_err;
1142                                 }
1143                         kn=EVP_PKEY_size(pkey);
1144                         }
1145                 else
1146                         {
1147                         pkey=NULL;
1148                         kn=0;
1149                         }
1150
1151                 if (!BUF_MEM_grow(buf,n+4+kn))
1152                         {
1153                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1154                         goto err;
1155                         }
1156                 d=(unsigned char *)s->init_buf->data;
1157                 p= &(d[4]);
1158
1159                 for (i=0; r[i] != NULL; i++)
1160                         {
1161                         s2n(nr[i],p);
1162                         BN_bn2bin(r[i],p);
1163                         p+=nr[i];
1164                         }
1165
1166                 /* not anonymous */
1167                 if (pkey != NULL)
1168                         {
1169                         /* n is the length of the params, they start at &(d[4])
1170                          * and p points to the space at the end. */
1171 #ifndef OPENSSL_NO_RSA
1172                         if (pkey->type == EVP_PKEY_RSA)
1173                                 {
1174                                 q=md_buf;
1175                                 j=0;
1176                                 for (num=2; num > 0; num--)
1177                                         {
1178                                         EVP_DigestInit(&md_ctx,(num == 2)
1179                                                 ?s->ctx->md5:s->ctx->sha1);
1180                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1181                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1182                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1183                                         EVP_DigestFinal(&md_ctx,q,
1184                                                 (unsigned int *)&i);
1185                                         q+=i;
1186                                         j+=i;
1187                                         }
1188                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1189                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1190                                         {
1191                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1192                                         goto err;
1193                                         }
1194                                 s2n(u,p);
1195                                 n+=u+2;
1196                                 }
1197                         else
1198 #endif
1199 #if !defined(OPENSSL_NO_DSA)
1200                                 if (pkey->type == EVP_PKEY_DSA)
1201                                 {
1202                                 /* lets do DSS */
1203                                 EVP_SignInit(&md_ctx,EVP_dss1());
1204                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1205                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1206                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1207                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1208                                         (unsigned int *)&i,pkey))
1209                                         {
1210                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1211                                         goto err;
1212                                         }
1213                                 s2n(i,p);
1214                                 n+=i+2;
1215                                 }
1216                         else
1217 #endif
1218                                 {
1219                                 /* Is this error check actually needed? */
1220                                 al=SSL_AD_HANDSHAKE_FAILURE;
1221                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1222                                 goto f_err;
1223                                 }
1224                         }
1225
1226                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1227                 l2n3(n,d);
1228
1229                 /* we should now have things packed up, so lets send
1230                  * it off */
1231                 s->init_num=n+4;
1232                 s->init_off=0;
1233                 }
1234
1235         s->state = SSL3_ST_SW_KEY_EXCH_B;
1236         EVP_MD_CTX_cleanup(&md_ctx);
1237         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1238 f_err:
1239         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1240 err:
1241         EVP_MD_CTX_cleanup(&md_ctx);
1242         return(-1);
1243         }
1244
1245 static int ssl3_send_certificate_request(SSL *s)
1246         {
1247         unsigned char *p,*d;
1248         int i,j,nl,off,n;
1249         STACK_OF(X509_NAME) *sk=NULL;
1250         X509_NAME *name;
1251         BUF_MEM *buf;
1252
1253         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1254                 {
1255                 buf=s->init_buf;
1256
1257                 d=p=(unsigned char *)&(buf->data[4]);
1258
1259                 /* get the list of acceptable cert types */
1260                 p++;
1261                 n=ssl3_get_req_cert_type(s,p);
1262                 d[0]=n;
1263                 p+=n;
1264                 n++;
1265
1266                 off=n;
1267                 p+=2;
1268                 n+=2;
1269
1270                 sk=SSL_get_client_CA_list(s);
1271                 nl=0;
1272                 if (sk != NULL)
1273                         {
1274                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1275                                 {
1276                                 name=sk_X509_NAME_value(sk,i);
1277                                 j=i2d_X509_NAME(name,NULL);
1278                                 if (!BUF_MEM_grow(buf,4+n+j+2))
1279                                         {
1280                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1281                                         goto err;
1282                                         }
1283                                 p=(unsigned char *)&(buf->data[4+n]);
1284                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1285                                         {
1286                                         s2n(j,p);
1287                                         i2d_X509_NAME(name,&p);
1288                                         n+=2+j;
1289                                         nl+=2+j;
1290                                         }
1291                                 else
1292                                         {
1293                                         d=p;
1294                                         i2d_X509_NAME(name,&p);
1295                                         j-=2; s2n(j,d); j+=2;
1296                                         n+=j;
1297                                         nl+=j;
1298                                         }
1299                                 }
1300                         }
1301                 /* else no CA names */
1302                 p=(unsigned char *)&(buf->data[4+off]);
1303                 s2n(nl,p);
1304
1305                 d=(unsigned char *)buf->data;
1306                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1307                 l2n3(n,d);
1308
1309                 /* we should now have things packed up, so lets send
1310                  * it off */
1311
1312                 s->init_num=n+4;
1313                 s->init_off=0;
1314 #ifdef NETSCAPE_HANG_BUG
1315                 p=(unsigned char *)s->init_buf->data + s->init_num;
1316
1317                 /* do the header */
1318                 *(p++)=SSL3_MT_SERVER_DONE;
1319                 *(p++)=0;
1320                 *(p++)=0;
1321                 *(p++)=0;
1322                 s->init_num += 4;
1323 #endif
1324
1325                 }
1326
1327         /* SSL3_ST_SW_CERT_REQ_B */
1328         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1329 err:
1330         return(-1);
1331         }
1332
1333 static int ssl3_get_client_key_exchange(SSL *s)
1334         {
1335         int i,al,ok;
1336         long n;
1337         unsigned long l;
1338         unsigned char *p;
1339 #ifndef OPENSSL_NO_RSA
1340         RSA *rsa=NULL;
1341         EVP_PKEY *pkey=NULL;
1342 #endif
1343 #ifndef OPENSSL_NO_DH
1344         BIGNUM *pub=NULL;
1345         DH *dh_srvr;
1346 #endif
1347 #ifndef OPENSSL_NO_KRB5
1348         KSSL_ERR kssl_err;
1349 #endif /* OPENSSL_NO_KRB5 */
1350
1351         n=ssl3_get_message(s,
1352                 SSL3_ST_SR_KEY_EXCH_A,
1353                 SSL3_ST_SR_KEY_EXCH_B,
1354                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1355                 2048, /* ??? */
1356                 &ok);
1357
1358         if (!ok) return((int)n);
1359         p=(unsigned char *)s->init_buf->data;
1360
1361         l=s->s3->tmp.new_cipher->algorithms;
1362
1363 #ifndef OPENSSL_NO_RSA
1364         if (l & SSL_kRSA)
1365                 {
1366                 /* FIX THIS UP EAY EAY EAY EAY */
1367                 if (s->s3->tmp.use_rsa_tmp)
1368                         {
1369                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1370                                 rsa=s->cert->rsa_tmp;
1371                         /* Don't do a callback because rsa_tmp should
1372                          * be sent already */
1373                         if (rsa == NULL)
1374                                 {
1375                                 al=SSL_AD_HANDSHAKE_FAILURE;
1376                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1377                                 goto f_err;
1378
1379                                 }
1380                         }
1381                 else
1382                         {
1383                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1384                         if (    (pkey == NULL) ||
1385                                 (pkey->type != EVP_PKEY_RSA) ||
1386                                 (pkey->pkey.rsa == NULL))
1387                                 {
1388                                 al=SSL_AD_HANDSHAKE_FAILURE;
1389                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1390                                 goto f_err;
1391                                 }
1392                         rsa=pkey->pkey.rsa;
1393                         }
1394
1395                 /* TLS */
1396                 if (s->version > SSL3_VERSION)
1397                         {
1398                         n2s(p,i);
1399                         if (n != i+2)
1400                                 {
1401                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1402                                         {
1403                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1404                                         goto err;
1405                                         }
1406                                 else
1407                                         p-=2;
1408                                 }
1409                         else
1410                                 n=i;
1411                         }
1412
1413                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1414
1415                 al = -1;
1416                 
1417                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1418                         {
1419                         al=SSL_AD_DECODE_ERROR;
1420                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1421                         }
1422
1423                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1424                         {
1425                         /* The premaster secret must contain the same version number as the
1426                          * ClientHello to detect version rollback attacks (strangely, the
1427                          * protocol does not offer such protection for DH ciphersuites).
1428                          * However, buggy clients exist that send the negotiated protocol
1429                          * version instead if the server does not support the requested
1430                          * protocol version.
1431                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1432                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1433                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1434                                 {
1435                                 al=SSL_AD_DECODE_ERROR;
1436                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
1437                                 goto f_err;
1438                                 }
1439                         }
1440
1441                 if (al != -1)
1442                         {
1443 #if 0
1444                         goto f_err;
1445 #else
1446                         /* Some decryption failure -- use random value instead as countermeasure
1447                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
1448                          * (see RFC 2246, section 7.4.7.1).
1449                          * But note that due to length and protocol version checking, the
1450                          * attack is impractical anyway (see section 5 in D. Bleichenbacher:
1451                          * "Chosen Ciphertext Attacks Against Protocols Based on the RSA
1452                          * Encryption Standard PKCS #1", CRYPTO '98, LNCS 1462, pp. 1-12).
1453                          */
1454                         ERR_clear_error();
1455                         i = SSL_MAX_MASTER_KEY_LENGTH;
1456                         p[0] = s->client_version >> 8;
1457                         p[1] = s->client_version & 0xff;
1458                         RAND_pseudo_bytes(p+2, i-2); /* should be RAND_bytes, but we cannot work around a failure */
1459 #endif
1460                         }
1461         
1462                 s->session->master_key_length=
1463                         s->method->ssl3_enc->generate_master_secret(s,
1464                                 s->session->master_key,
1465                                 p,i);
1466                 memset(p,0,i);
1467                 }
1468         else
1469 #endif
1470 #ifndef OPENSSL_NO_DH
1471                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1472                 {
1473                 n2s(p,i);
1474                 if (n != i+2)
1475                         {
1476                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1477                                 {
1478                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1479                                 goto err;
1480                                 }
1481                         else
1482                                 {
1483                                 p-=2;
1484                                 i=(int)n;
1485                                 }
1486                         }
1487
1488                 if (n == 0L) /* the parameters are in the cert */
1489                         {
1490                         al=SSL_AD_HANDSHAKE_FAILURE;
1491                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1492                         goto f_err;
1493                         }
1494                 else
1495                         {
1496                         if (s->s3->tmp.dh == NULL)
1497                                 {
1498                                 al=SSL_AD_HANDSHAKE_FAILURE;
1499                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1500                                 goto f_err;
1501                                 }
1502                         else
1503                                 dh_srvr=s->s3->tmp.dh;
1504                         }
1505
1506                 pub=BN_bin2bn(p,i,NULL);
1507                 if (pub == NULL)
1508                         {
1509                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1510                         goto err;
1511                         }
1512
1513                 i=DH_compute_key(p,pub,dh_srvr);
1514
1515                 if (i <= 0)
1516                         {
1517                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1518                         goto err;
1519                         }
1520
1521                 DH_free(s->s3->tmp.dh);
1522                 s->s3->tmp.dh=NULL;
1523
1524                 BN_clear_free(pub);
1525                 pub=NULL;
1526                 s->session->master_key_length=
1527                         s->method->ssl3_enc->generate_master_secret(s,
1528                                 s->session->master_key,p,i);
1529                 memset(p,0,i);
1530                 }
1531         else
1532 #endif
1533 #ifndef OPENSSL_NO_KRB5
1534         if (l & SSL_kKRB5)
1535                 {
1536                 krb5_error_code         krb5rc;
1537                 krb5_data               enc_ticket;
1538                 krb5_data               authenticator;
1539                 krb5_data               enc_pms;
1540                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
1541                 EVP_CIPHER_CTX          ciph_ctx;
1542                 EVP_CIPHER              *enc = NULL;
1543                 unsigned char           iv[EVP_MAX_IV_LENGTH];
1544                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
1545                                                 + EVP_MAX_IV_LENGTH + 1];
1546                 int                     padl, outl = sizeof(pms);
1547                 krb5_timestamp          authtime = 0;
1548                 krb5_ticket_times       ttimes;
1549
1550                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
1551
1552                 n2s(p,i);
1553                 enc_ticket.length = i;
1554                 enc_ticket.data = p;
1555                 p+=enc_ticket.length;
1556
1557                 n2s(p,i);
1558                 authenticator.length = i;
1559                 authenticator.data = p;
1560                 p+=authenticator.length;
1561
1562                 n2s(p,i);
1563                 enc_pms.length = i;
1564                 enc_pms.data = p;
1565                 p+=enc_pms.length;
1566
1567                 if ((unsigned long)n != enc_ticket.length + authenticator.length +
1568                                                 enc_pms.length + 6)
1569                         {
1570                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1571                                 SSL_R_DATA_LENGTH_TOO_LONG);
1572                         goto err;
1573                         }
1574
1575                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
1576                                         &kssl_err)) != 0)
1577                         {
1578 #ifdef KSSL_DEBUG
1579                         printf("kssl_sget_tkt rtn %d [%d]\n",
1580                                 krb5rc, kssl_err.reason);
1581                         if (kssl_err.text)
1582                                 printf("kssl_err text= %s\n", kssl_err.text);
1583 #endif  /* KSSL_DEBUG */
1584                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1585                                 kssl_err.reason);
1586                         goto err;
1587                         }
1588
1589                 /*  Note: no authenticator is not considered an error,
1590                 **  but will return authtime == 0.
1591                 */
1592                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
1593                                         &authtime, &kssl_err)) != 0)
1594                         {
1595 #ifdef KSSL_DEBUG
1596                         printf("kssl_check_authent rtn %d [%d]\n",
1597                                 krb5rc, kssl_err.reason);
1598                         if (kssl_err.text)
1599                                 printf("kssl_err text= %s\n", kssl_err.text);
1600 #endif  /* KSSL_DEBUG */
1601                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1602                                 kssl_err.reason);
1603                         goto err;
1604                         }
1605
1606                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
1607                         {
1608                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, krb5rc);
1609                         goto err;
1610                         }
1611
1612 #ifdef KSSL_DEBUG
1613                 kssl_ctx_show(kssl_ctx);
1614 #endif  /* KSSL_DEBUG */
1615
1616                 enc = kssl_map_enc(kssl_ctx->enctype);
1617                 if (enc == NULL)
1618                     goto err;
1619
1620                 memset(iv, 0, EVP_MAX_IV_LENGTH);       /* per RFC 1510 */
1621
1622                 if (!EVP_DecryptInit(&ciph_ctx,enc,kssl_ctx->key,iv))
1623                         {
1624                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1625                                 SSL_R_DECRYPTION_FAILED);
1626                         goto err;
1627                         }
1628                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
1629                                         enc_pms.data, enc_pms.length))
1630                         {
1631                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1632                                 SSL_R_DECRYPTION_FAILED);
1633                         goto err;
1634                         }
1635                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1636                         {
1637                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1638                                 SSL_R_DATA_LENGTH_TOO_LONG);
1639                         goto err;
1640                         }
1641                 if (!EVP_DecryptFinal(&ciph_ctx,&(pms[outl]),&padl))
1642                         {
1643                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1644                                 SSL_R_DECRYPTION_FAILED);
1645                         goto err;
1646                         }
1647                 outl += padl;
1648                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1649                         {
1650                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1651                                 SSL_R_DATA_LENGTH_TOO_LONG);
1652                         goto err;
1653                         }
1654                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1655
1656                 s->session->master_key_length=
1657                         s->method->ssl3_enc->generate_master_secret(s,
1658                                 s->session->master_key, pms, outl);
1659
1660                 if (kssl_ctx->client_princ)
1661                         {
1662                         int len = strlen(kssl_ctx->client_princ);
1663                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
1664                                 {
1665                                 s->session->krb5_client_princ_len = len;
1666                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
1667                                 }
1668                         }
1669
1670
1671                 /*  Was doing kssl_ctx_free() here,
1672                 **  but it caused problems for apache.
1673                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
1674                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
1675                 */
1676                 }
1677         else
1678 #endif  /* OPENSSL_NO_KRB5 */
1679                 {
1680                 al=SSL_AD_HANDSHAKE_FAILURE;
1681                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1682                                 SSL_R_UNKNOWN_CIPHER_TYPE);
1683                 goto f_err;
1684                 }
1685
1686         return(1);
1687 f_err:
1688         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1689 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA)
1690 err:
1691 #endif
1692         return(-1);
1693         }
1694
1695 static int ssl3_get_cert_verify(SSL *s)
1696         {
1697         EVP_PKEY *pkey=NULL;
1698         unsigned char *p;
1699         int al,ok,ret=0;
1700         long n;
1701         int type=0,i,j;
1702         X509 *peer;
1703
1704         n=ssl3_get_message(s,
1705                 SSL3_ST_SR_CERT_VRFY_A,
1706                 SSL3_ST_SR_CERT_VRFY_B,
1707                 -1,
1708                 512, /* 512? */
1709                 &ok);
1710
1711         if (!ok) return((int)n);
1712
1713         if (s->session->peer != NULL)
1714                 {
1715                 peer=s->session->peer;
1716                 pkey=X509_get_pubkey(peer);
1717                 type=X509_certificate_type(peer,pkey);
1718                 }
1719         else
1720                 {
1721                 peer=NULL;
1722                 pkey=NULL;
1723                 }
1724
1725         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
1726                 {
1727                 s->s3->tmp.reuse_message=1;
1728                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
1729                         {
1730                         al=SSL_AD_UNEXPECTED_MESSAGE;
1731                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
1732                         goto f_err;
1733                         }
1734                 ret=1;
1735                 goto end;
1736                 }
1737
1738         if (peer == NULL)
1739                 {
1740                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
1741                 al=SSL_AD_UNEXPECTED_MESSAGE;
1742                 goto f_err;
1743                 }
1744
1745         if (!(type & EVP_PKT_SIGN))
1746                 {
1747                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1748                 al=SSL_AD_ILLEGAL_PARAMETER;
1749                 goto f_err;
1750                 }
1751
1752         if (s->s3->change_cipher_spec)
1753                 {
1754                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
1755                 al=SSL_AD_UNEXPECTED_MESSAGE;
1756                 goto f_err;
1757                 }
1758
1759         /* we now have a signature that we need to verify */
1760         p=(unsigned char *)s->init_buf->data;
1761         n2s(p,i);
1762         n-=2;
1763         if (i > n)
1764                 {
1765                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
1766                 al=SSL_AD_DECODE_ERROR;
1767                 goto f_err;
1768                 }
1769
1770         j=EVP_PKEY_size(pkey);
1771         if ((i > j) || (n > j) || (n <= 0))
1772                 {
1773                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
1774                 al=SSL_AD_DECODE_ERROR;
1775                 goto f_err;
1776                 }
1777
1778 #ifndef OPENSSL_NO_RSA 
1779         if (pkey->type == EVP_PKEY_RSA)
1780                 {
1781                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
1782                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
1783                                                         pkey->pkey.rsa);
1784                 if (i < 0)
1785                         {
1786                         al=SSL_AD_DECRYPT_ERROR;
1787                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
1788                         goto f_err;
1789                         }
1790                 if (i == 0)
1791                         {
1792                         al=SSL_AD_DECRYPT_ERROR;
1793                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
1794                         goto f_err;
1795                         }
1796                 }
1797         else
1798 #endif
1799 #ifndef OPENSSL_NO_DSA
1800                 if (pkey->type == EVP_PKEY_DSA)
1801                 {
1802                 j=DSA_verify(pkey->save_type,
1803                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
1804                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
1805                 if (j <= 0)
1806                         {
1807                         /* bad signature */
1808                         al=SSL_AD_DECRYPT_ERROR;
1809                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
1810                         goto f_err;
1811                         }
1812                 }
1813         else
1814 #endif
1815                 {
1816                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
1817                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
1818                 goto f_err;
1819                 }
1820
1821
1822         ret=1;
1823         if (0)
1824                 {
1825 f_err:
1826                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1827                 }
1828 end:
1829         EVP_PKEY_free(pkey);
1830         return(ret);
1831         }
1832
1833 static int ssl3_get_client_certificate(SSL *s)
1834         {
1835         int i,ok,al,ret= -1;
1836         X509 *x=NULL;
1837         unsigned long l,nc,llen,n;
1838         unsigned char *p,*d,*q;
1839         STACK_OF(X509) *sk=NULL;
1840
1841         n=ssl3_get_message(s,
1842                 SSL3_ST_SR_CERT_A,
1843                 SSL3_ST_SR_CERT_B,
1844                 -1,
1845                 s->max_cert_list,
1846                 &ok);
1847
1848         if (!ok) return((int)n);
1849
1850         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
1851                 {
1852                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
1853                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1854                         {
1855                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1856                         al=SSL_AD_HANDSHAKE_FAILURE;
1857                         goto f_err;
1858                         }
1859                 /* If tls asked for a client cert, the client must return a 0 list */
1860                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
1861                         {
1862                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
1863                         al=SSL_AD_UNEXPECTED_MESSAGE;
1864                         goto f_err;
1865                         }
1866                 s->s3->tmp.reuse_message=1;
1867                 return(1);
1868                 }
1869
1870         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1871                 {
1872                 al=SSL_AD_UNEXPECTED_MESSAGE;
1873                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
1874                 goto f_err;
1875                 }
1876         d=p=(unsigned char *)s->init_buf->data;
1877
1878         if ((sk=sk_X509_new_null()) == NULL)
1879                 {
1880                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1881                 goto err;
1882                 }
1883
1884         n2l3(p,llen);
1885         if (llen+3 != n)
1886                 {
1887                 al=SSL_AD_DECODE_ERROR;
1888                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1889                 goto f_err;
1890                 }
1891         for (nc=0; nc<llen; )
1892                 {
1893                 n2l3(p,l);
1894                 if ((l+nc+3) > llen)
1895                         {
1896                         al=SSL_AD_DECODE_ERROR;
1897                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1898                         goto f_err;
1899                         }
1900
1901                 q=p;
1902                 x=d2i_X509(NULL,&p,l);
1903                 if (x == NULL)
1904                         {
1905                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
1906                         goto err;
1907                         }
1908                 if (p != (q+l))
1909                         {
1910                         al=SSL_AD_DECODE_ERROR;
1911                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1912                         goto f_err;
1913                         }
1914                 if (!sk_X509_push(sk,x))
1915                         {
1916                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1917                         goto err;
1918                         }
1919                 x=NULL;
1920                 nc+=l+3;
1921                 }
1922
1923         if (sk_X509_num(sk) <= 0)
1924                 {
1925                 /* TLS does not mind 0 certs returned */
1926                 if (s->version == SSL3_VERSION)
1927                         {
1928                         al=SSL_AD_HANDSHAKE_FAILURE;
1929                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
1930                         goto f_err;
1931                         }
1932                 /* Fail for TLS only if we required a certificate */
1933                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
1934                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1935                         {
1936                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1937                         al=SSL_AD_HANDSHAKE_FAILURE;
1938                         goto f_err;
1939                         }
1940                 }
1941         else
1942                 {
1943                 i=ssl_verify_cert_chain(s,sk);
1944                 if (!i)
1945                         {
1946                         al=ssl_verify_alarm_type(s->verify_result);
1947                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
1948                         goto f_err;
1949                         }
1950                 }
1951
1952         if (s->session->peer != NULL) /* This should not be needed */
1953                 X509_free(s->session->peer);
1954         s->session->peer=sk_X509_shift(sk);
1955         s->session->verify_result = s->verify_result;
1956
1957         /* With the current implementation, sess_cert will always be NULL
1958          * when we arrive here. */
1959         if (s->session->sess_cert == NULL)
1960                 {
1961                 s->session->sess_cert = ssl_sess_cert_new();
1962                 if (s->session->sess_cert == NULL)
1963                         {
1964                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1965                         goto err;
1966                         }
1967                 }
1968         if (s->session->sess_cert->cert_chain != NULL)
1969                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
1970         s->session->sess_cert->cert_chain=sk;
1971         /* Inconsistency alert: cert_chain does *not* include the
1972          * peer's own certificate, while we do include it in s3_clnt.c */
1973
1974         sk=NULL;
1975
1976         ret=1;
1977         if (0)
1978                 {
1979 f_err:
1980                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1981                 }
1982 err:
1983         if (x != NULL) X509_free(x);
1984         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
1985         return(ret);
1986         }
1987
1988 int ssl3_send_server_certificate(SSL *s)
1989         {
1990         unsigned long l;
1991         X509 *x;
1992
1993         if (s->state == SSL3_ST_SW_CERT_A)
1994                 {
1995                 x=ssl_get_server_send_cert(s);
1996                 if (x == NULL &&
1997                         /* VRS: allow null cert if auth == KRB5 */
1998                         (s->s3->tmp.new_cipher->algorithms
1999                                 & (SSL_MKEY_MASK|SSL_AUTH_MASK))
2000                         != (SSL_aKRB5|SSL_kKRB5))
2001                         {
2002                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
2003                         return(0);
2004                         }
2005
2006                 l=ssl3_output_cert_chain(s,x);
2007                 s->state=SSL3_ST_SW_CERT_B;
2008                 s->init_num=(int)l;
2009                 s->init_off=0;
2010                 }
2011
2012         /* SSL3_ST_SW_CERT_B */
2013         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2014         }