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