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