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