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