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