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