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