There have been a number of complaints from a number of sources that names
[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                                 if(rsa == NULL)
959                                 {
960                                         al=SSL_AD_HANDSHAKE_FAILURE;
961                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
962                                         goto f_err;
963                                 }
964                                 CRYPTO_add(&rsa->references,1,CRYPTO_LOCK_RSA);
965                                 cert->rsa_tmp=rsa;
966                                 }
967                         if (rsa == NULL)
968                                 {
969                                 al=SSL_AD_HANDSHAKE_FAILURE;
970                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
971                                 goto f_err;
972                                 }
973                         r[0]=rsa->n;
974                         r[1]=rsa->e;
975                         s->s3->tmp.use_rsa_tmp=1;
976                         }
977                 else
978 #endif
979 #ifndef NO_DH
980                         if (type & SSL_kEDH)
981                         {
982                         dhp=cert->dh_tmp;
983                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
984                                 dhp=s->cert->dh_tmp_cb(s,
985                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
986                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
987                         if (dhp == NULL)
988                                 {
989                                 al=SSL_AD_HANDSHAKE_FAILURE;
990                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
991                                 goto f_err;
992                                 }
993
994                         if (s->s3->tmp.dh != NULL)
995                                 {
996                                 DH_free(dh);
997                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_INTERNAL_ERROR);
998                                 goto err;
999                                 }
1000
1001                         if ((dh=DHparams_dup(dhp)) == NULL)
1002                                 {
1003                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1004                                 goto err;
1005                                 }
1006
1007                         s->s3->tmp.dh=dh;
1008                         if ((dhp->pub_key == NULL ||
1009                              dhp->priv_key == NULL ||
1010                              (s->options & SSL_OP_SINGLE_DH_USE)))
1011                                 {
1012                                 if(!DH_generate_key(dh))
1013                                     {
1014                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1015                                            ERR_R_DH_LIB);
1016                                     goto err;
1017                                     }
1018                                 }
1019                         else
1020                                 {
1021                                 dh->pub_key=BN_dup(dhp->pub_key);
1022                                 dh->priv_key=BN_dup(dhp->priv_key);
1023                                 if ((dh->pub_key == NULL) ||
1024                                         (dh->priv_key == NULL))
1025                                         {
1026                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1027                                         goto err;
1028                                         }
1029                                 }
1030                         r[0]=dh->p;
1031                         r[1]=dh->g;
1032                         r[2]=dh->pub_key;
1033                         }
1034                 else 
1035 #endif
1036                         {
1037                         al=SSL_AD_HANDSHAKE_FAILURE;
1038                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1039                         goto f_err;
1040                         }
1041                 for (i=0; r[i] != NULL; i++)
1042                         {
1043                         nr[i]=BN_num_bytes(r[i]);
1044                         n+=2+nr[i];
1045                         }
1046
1047                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1048                         {
1049                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1050                                 == NULL)
1051                                 {
1052                                 al=SSL_AD_DECODE_ERROR;
1053                                 goto f_err;
1054                                 }
1055                         kn=EVP_PKEY_size(pkey);
1056                         }
1057                 else
1058                         {
1059                         pkey=NULL;
1060                         kn=0;
1061                         }
1062
1063                 if (!BUF_MEM_grow(buf,n+4+kn))
1064                         {
1065                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1066                         goto err;
1067                         }
1068                 d=(unsigned char *)s->init_buf->data;
1069                 p= &(d[4]);
1070
1071                 for (i=0; r[i] != NULL; i++)
1072                         {
1073                         s2n(nr[i],p);
1074                         BN_bn2bin(r[i],p);
1075                         p+=nr[i];
1076                         }
1077
1078                 /* not anonymous */
1079                 if (pkey != NULL)
1080                         {
1081                         /* n is the length of the params, they start at &(d[4])
1082                          * and p points to the space at the end. */
1083 #ifndef NO_RSA
1084                         if (pkey->type == EVP_PKEY_RSA)
1085                                 {
1086                                 q=md_buf;
1087                                 j=0;
1088                                 for (num=2; num > 0; num--)
1089                                         {
1090                                         EVP_DigestInit(&md_ctx,(num == 2)
1091                                                 ?s->ctx->md5:s->ctx->sha1);
1092                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1093                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1094                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1095                                         EVP_DigestFinal(&md_ctx,q,
1096                                                 (unsigned int *)&i);
1097                                         q+=i;
1098                                         j+=i;
1099                                         }
1100                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1101                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1102                                         {
1103                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1104                                         goto err;
1105                                         }
1106                                 s2n(u,p);
1107                                 n+=u+2;
1108                                 }
1109                         else
1110 #endif
1111 #if !defined(NO_DSA)
1112                                 if (pkey->type == EVP_PKEY_DSA)
1113                                 {
1114                                 /* lets do DSS */
1115                                 EVP_SignInit(&md_ctx,EVP_dss1());
1116                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1117                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1118                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1119                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1120                                         (unsigned int *)&i,pkey))
1121                                         {
1122                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1123                                         goto err;
1124                                         }
1125                                 s2n(i,p);
1126                                 n+=i+2;
1127                                 }
1128                         else
1129 #endif
1130                                 {
1131                                 /* Is this error check actually needed? */
1132                                 al=SSL_AD_HANDSHAKE_FAILURE;
1133                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1134                                 goto f_err;
1135                                 }
1136                         }
1137
1138                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1139                 l2n3(n,d);
1140
1141                 /* we should now have things packed up, so lets send
1142                  * it off */
1143                 s->init_num=n+4;
1144                 s->init_off=0;
1145                 }
1146
1147         s->state = SSL3_ST_SW_KEY_EXCH_B;
1148         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1149 f_err:
1150         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1151 err:
1152         return(-1);
1153         }
1154
1155 static int ssl3_send_certificate_request(SSL *s)
1156         {
1157         unsigned char *p,*d;
1158         int i,j,nl,off,n;
1159         STACK_OF(X509_NAME) *sk=NULL;
1160         X509_NAME *name;
1161         BUF_MEM *buf;
1162
1163         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1164                 {
1165                 buf=s->init_buf;
1166
1167                 d=p=(unsigned char *)&(buf->data[4]);
1168
1169                 /* get the list of acceptable cert types */
1170                 p++;
1171                 n=ssl3_get_req_cert_type(s,p);
1172                 d[0]=n;
1173                 p+=n;
1174                 n++;
1175
1176                 off=n;
1177                 p+=2;
1178                 n+=2;
1179
1180                 sk=SSL_get_client_CA_list(s);
1181                 nl=0;
1182                 if (sk != NULL)
1183                         {
1184                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1185                                 {
1186                                 name=sk_X509_NAME_value(sk,i);
1187                                 j=i2d_X509_NAME(name,NULL);
1188                                 if (!BUF_MEM_grow(buf,4+n+j+2))
1189                                         {
1190                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1191                                         goto err;
1192                                         }
1193                                 p=(unsigned char *)&(buf->data[4+n]);
1194                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1195                                         {
1196                                         s2n(j,p);
1197                                         i2d_X509_NAME(name,&p);
1198                                         n+=2+j;
1199                                         nl+=2+j;
1200                                         }
1201                                 else
1202                                         {
1203                                         d=p;
1204                                         i2d_X509_NAME(name,&p);
1205                                         j-=2; s2n(j,d); j+=2;
1206                                         n+=j;
1207                                         nl+=j;
1208                                         }
1209                                 }
1210                         }
1211                 /* else no CA names */
1212                 p=(unsigned char *)&(buf->data[4+off]);
1213                 s2n(nl,p);
1214
1215                 d=(unsigned char *)buf->data;
1216                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1217                 l2n3(n,d);
1218
1219                 /* we should now have things packed up, so lets send
1220                  * it off */
1221
1222                 s->init_num=n+4;
1223                 s->init_off=0;
1224 #ifdef NETSCAPE_HANG_BUG
1225                 p=(unsigned char *)s->init_buf->data + s->init_num;
1226
1227                 /* do the header */
1228                 *(p++)=SSL3_MT_SERVER_DONE;
1229                 *(p++)=0;
1230                 *(p++)=0;
1231                 *(p++)=0;
1232                 s->init_num += 4;
1233 #endif
1234
1235                 }
1236
1237         /* SSL3_ST_SW_CERT_REQ_B */
1238         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1239 err:
1240         return(-1);
1241         }
1242
1243 static int ssl3_get_client_key_exchange(SSL *s)
1244         {
1245         int i,al,ok;
1246         long n;
1247         unsigned long l;
1248         unsigned char *p;
1249 #ifndef NO_RSA
1250         RSA *rsa=NULL;
1251         EVP_PKEY *pkey=NULL;
1252 #endif
1253 #ifndef NO_DH
1254         BIGNUM *pub=NULL;
1255         DH *dh_srvr;
1256 #endif
1257
1258         n=ssl3_get_message(s,
1259                 SSL3_ST_SR_KEY_EXCH_A,
1260                 SSL3_ST_SR_KEY_EXCH_B,
1261                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1262                 400, /* ???? */
1263                 &ok);
1264
1265         if (!ok) return((int)n);
1266         p=(unsigned char *)s->init_buf->data;
1267
1268         l=s->s3->tmp.new_cipher->algorithms;
1269
1270 #ifndef NO_RSA
1271         if (l & SSL_kRSA)
1272                 {
1273                 /* FIX THIS UP EAY EAY EAY EAY */
1274                 if (s->s3->tmp.use_rsa_tmp)
1275                         {
1276                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1277                                 rsa=s->cert->rsa_tmp;
1278                         /* Don't do a callback because rsa_tmp should
1279                          * be sent already */
1280                         if (rsa == NULL)
1281                                 {
1282                                 al=SSL_AD_HANDSHAKE_FAILURE;
1283                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1284                                 goto f_err;
1285
1286                                 }
1287                         }
1288                 else
1289                         {
1290                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1291                         if (    (pkey == NULL) ||
1292                                 (pkey->type != EVP_PKEY_RSA) ||
1293                                 (pkey->pkey.rsa == NULL))
1294                                 {
1295                                 al=SSL_AD_HANDSHAKE_FAILURE;
1296                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1297                                 goto f_err;
1298                                 }
1299                         rsa=pkey->pkey.rsa;
1300                         }
1301
1302                 /* TLS */
1303                 if (s->version > SSL3_VERSION)
1304                         {
1305                         n2s(p,i);
1306                         if (n != i+2)
1307                                 {
1308                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1309                                         {
1310                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1311                                         goto err;
1312                                         }
1313                                 else
1314                                         p-=2;
1315                                 }
1316                         else
1317                                 n=i;
1318                         }
1319
1320                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1321
1322                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1323                         {
1324                         al=SSL_AD_DECODE_ERROR;
1325                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1326                         goto f_err;
1327                         }
1328
1329                 if (!((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1330                         {
1331                         /* The premaster secret must contain the same version number as the
1332                          * ClientHello to detect version rollback attacks (strangely, the
1333                          * protocol does not offer such protection for DH ciphersuites).
1334                          * However, buggy clients exist that send the negotiated protocol
1335                          * version instead if the server does not support the requested
1336                          * protocol version.
1337                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1338                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1339                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1340                                 {
1341                                 al=SSL_AD_DECODE_ERROR;
1342                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
1343                                 goto f_err;
1344                                 }
1345                         }
1346
1347                 s->session->master_key_length=
1348                         s->method->ssl3_enc->generate_master_secret(s,
1349                                 s->session->master_key,
1350                                 p,i);
1351                 memset(p,0,i);
1352                 }
1353         else
1354 #endif
1355 #ifndef NO_DH
1356                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1357                 {
1358                 n2s(p,i);
1359                 if (n != i+2)
1360                         {
1361                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1362                                 {
1363                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1364                                 goto err;
1365                                 }
1366                         else
1367                                 {
1368                                 p-=2;
1369                                 i=(int)n;
1370                                 }
1371                         }
1372
1373                 if (n == 0L) /* the parameters are in the cert */
1374                         {
1375                         al=SSL_AD_HANDSHAKE_FAILURE;
1376                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1377                         goto f_err;
1378                         }
1379                 else
1380                         {
1381                         if (s->s3->tmp.dh == NULL)
1382                                 {
1383                                 al=SSL_AD_HANDSHAKE_FAILURE;
1384                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1385                                 goto f_err;
1386                                 }
1387                         else
1388                                 dh_srvr=s->s3->tmp.dh;
1389                         }
1390
1391                 pub=BN_bin2bn(p,i,NULL);
1392                 if (pub == NULL)
1393                         {
1394                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1395                         goto err;
1396                         }
1397
1398                 i=DH_compute_key(p,pub,dh_srvr);
1399
1400                 if (i <= 0)
1401                         {
1402                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1403                         goto err;
1404                         }
1405
1406                 DH_free(s->s3->tmp.dh);
1407                 s->s3->tmp.dh=NULL;
1408
1409                 BN_clear_free(pub);
1410                 pub=NULL;
1411                 s->session->master_key_length=
1412                         s->method->ssl3_enc->generate_master_secret(s,
1413                                 s->session->master_key,p,i);
1414                 }
1415         else
1416 #endif
1417                 {
1418                 al=SSL_AD_HANDSHAKE_FAILURE;
1419                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNKNOWN_CIPHER_TYPE);
1420                 goto f_err;
1421                 }
1422
1423         return(1);
1424 f_err:
1425         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1426 #if !defined(NO_DH) || !defined(NO_RSA)
1427 err:
1428 #endif
1429         return(-1);
1430         }
1431
1432 static int ssl3_get_cert_verify(SSL *s)
1433         {
1434         EVP_PKEY *pkey=NULL;
1435         unsigned char *p;
1436         int al,ok,ret=0;
1437         long n;
1438         int type=0,i,j;
1439         X509 *peer;
1440
1441         n=ssl3_get_message(s,
1442                 SSL3_ST_SR_CERT_VRFY_A,
1443                 SSL3_ST_SR_CERT_VRFY_B,
1444                 -1,
1445                 512, /* 512? */
1446                 &ok);
1447
1448         if (!ok) return((int)n);
1449
1450         if (s->session->peer != NULL)
1451                 {
1452                 peer=s->session->peer;
1453                 pkey=X509_get_pubkey(peer);
1454                 type=X509_certificate_type(peer,pkey);
1455                 }
1456         else
1457                 {
1458                 peer=NULL;
1459                 pkey=NULL;
1460                 }
1461
1462         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
1463                 {
1464                 s->s3->tmp.reuse_message=1;
1465                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
1466                         {
1467                         al=SSL_AD_UNEXPECTED_MESSAGE;
1468                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
1469                         goto f_err;
1470                         }
1471                 ret=1;
1472                 goto end;
1473                 }
1474
1475         if (peer == NULL)
1476                 {
1477                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
1478                 al=SSL_AD_UNEXPECTED_MESSAGE;
1479                 goto f_err;
1480                 }
1481
1482         if (!(type & EVP_PKT_SIGN))
1483                 {
1484                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1485                 al=SSL_AD_ILLEGAL_PARAMETER;
1486                 goto f_err;
1487                 }
1488
1489         if (s->s3->change_cipher_spec)
1490                 {
1491                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
1492                 al=SSL_AD_UNEXPECTED_MESSAGE;
1493                 goto f_err;
1494                 }
1495
1496         /* we now have a signature that we need to verify */
1497         p=(unsigned char *)s->init_buf->data;
1498         n2s(p,i);
1499         n-=2;
1500         if (i > n)
1501                 {
1502                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
1503                 al=SSL_AD_DECODE_ERROR;
1504                 goto f_err;
1505                 }
1506
1507         j=EVP_PKEY_size(pkey);
1508         if ((i > j) || (n > j) || (n <= 0))
1509                 {
1510                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
1511                 al=SSL_AD_DECODE_ERROR;
1512                 goto f_err;
1513                 }
1514
1515 #ifndef NO_RSA 
1516         if (pkey->type == EVP_PKEY_RSA)
1517                 {
1518                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
1519                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
1520                                                         pkey->pkey.rsa);
1521                 if (i < 0)
1522                         {
1523                         al=SSL_AD_DECRYPT_ERROR;
1524                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
1525                         goto f_err;
1526                         }
1527                 if (i == 0)
1528                         {
1529                         al=SSL_AD_DECRYPT_ERROR;
1530                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
1531                         goto f_err;
1532                         }
1533                 }
1534         else
1535 #endif
1536 #ifndef NO_DSA
1537                 if (pkey->type == EVP_PKEY_DSA)
1538                 {
1539                 j=DSA_verify(pkey->save_type,
1540                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
1541                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
1542                 if (j <= 0)
1543                         {
1544                         /* bad signature */
1545                         al=SSL_AD_DECRYPT_ERROR;
1546                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
1547                         goto f_err;
1548                         }
1549                 }
1550         else
1551 #endif
1552                 {
1553                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_INTERNAL_ERROR);
1554                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
1555                 goto f_err;
1556                 }
1557
1558
1559         ret=1;
1560         if (0)
1561                 {
1562 f_err:
1563                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1564                 }
1565 end:
1566         EVP_PKEY_free(pkey);
1567         return(ret);
1568         }
1569
1570 static int ssl3_get_client_certificate(SSL *s)
1571         {
1572         int i,ok,al,ret= -1;
1573         X509 *x=NULL;
1574         unsigned long l,nc,llen,n;
1575         unsigned char *p,*d,*q;
1576         STACK_OF(X509) *sk=NULL;
1577
1578         n=ssl3_get_message(s,
1579                 SSL3_ST_SR_CERT_A,
1580                 SSL3_ST_SR_CERT_B,
1581                 -1,
1582 #if defined(MSDOS) && !defined(WIN32)
1583                 1024*30, /* 30k max cert list :-) */
1584 #else
1585                 1024*100, /* 100k max cert list :-) */
1586 #endif
1587                 &ok);
1588
1589         if (!ok) return((int)n);
1590
1591         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
1592                 {
1593                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
1594                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1595                         {
1596                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1597                         al=SSL_AD_HANDSHAKE_FAILURE;
1598                         goto f_err;
1599                         }
1600                 /* If tls asked for a client cert, the client must return a 0 list */
1601                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
1602                         {
1603                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
1604                         al=SSL_AD_UNEXPECTED_MESSAGE;
1605                         goto f_err;
1606                         }
1607                 s->s3->tmp.reuse_message=1;
1608                 return(1);
1609                 }
1610
1611         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1612                 {
1613                 al=SSL_AD_UNEXPECTED_MESSAGE;
1614                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
1615                 goto f_err;
1616                 }
1617         d=p=(unsigned char *)s->init_buf->data;
1618
1619         if ((sk=sk_X509_new_null()) == NULL)
1620                 {
1621                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1622                 goto err;
1623                 }
1624
1625         n2l3(p,llen);
1626         if (llen+3 != n)
1627                 {
1628                 al=SSL_AD_DECODE_ERROR;
1629                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1630                 goto f_err;
1631                 }
1632         for (nc=0; nc<llen; )
1633                 {
1634                 n2l3(p,l);
1635                 if ((l+nc+3) > llen)
1636                         {
1637                         al=SSL_AD_DECODE_ERROR;
1638                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1639                         goto f_err;
1640                         }
1641
1642                 q=p;
1643                 x=d2i_X509(NULL,&p,l);
1644                 if (x == NULL)
1645                         {
1646                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
1647                         goto err;
1648                         }
1649                 if (p != (q+l))
1650                         {
1651                         al=SSL_AD_DECODE_ERROR;
1652                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1653                         goto f_err;
1654                         }
1655                 if (!sk_X509_push(sk,x))
1656                         {
1657                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1658                         goto err;
1659                         }
1660                 x=NULL;
1661                 nc+=l+3;
1662                 }
1663
1664         if (sk_X509_num(sk) <= 0)
1665                 {
1666                 /* TLS does not mind 0 certs returned */
1667                 if (s->version == SSL3_VERSION)
1668                         {
1669                         al=SSL_AD_HANDSHAKE_FAILURE;
1670                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
1671                         goto f_err;
1672                         }
1673                 /* Fail for TLS only if we required a certificate */
1674                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
1675                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1676                         {
1677                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1678                         al=SSL_AD_HANDSHAKE_FAILURE;
1679                         goto f_err;
1680                         }
1681                 }
1682         else
1683                 {
1684                 i=ssl_verify_cert_chain(s,sk);
1685                 if (!i)
1686                         {
1687                         al=ssl_verify_alarm_type(s->verify_result);
1688                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
1689                         goto f_err;
1690                         }
1691                 }
1692
1693         if (s->session->peer != NULL) /* This should not be needed */
1694                 X509_free(s->session->peer);
1695         s->session->peer=sk_X509_shift(sk);
1696         s->session->verify_result = s->verify_result;
1697
1698         /* With the current implementation, sess_cert will always be NULL
1699          * when we arrive here. */
1700         if (s->session->sess_cert == NULL)
1701                 {
1702                 s->session->sess_cert = ssl_sess_cert_new();
1703                 if (s->session->sess_cert == NULL)
1704                         {
1705                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1706                         goto err;
1707                         }
1708                 }
1709         if (s->session->sess_cert->cert_chain != NULL)
1710                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
1711         s->session->sess_cert->cert_chain=sk;
1712         /* Inconsistency alert: cert_chain does *not* include the
1713          * peer's own certificate, while we do include it in s3_clnt.c */
1714
1715         sk=NULL;
1716
1717         ret=1;
1718         if (0)
1719                 {
1720 f_err:
1721                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1722                 }
1723 err:
1724         if (x != NULL) X509_free(x);
1725         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
1726         return(ret);
1727         }
1728
1729 int ssl3_send_server_certificate(SSL *s)
1730         {
1731         unsigned long l;
1732         X509 *x;
1733
1734         if (s->state == SSL3_ST_SW_CERT_A)
1735                 {
1736                 x=ssl_get_server_send_cert(s);
1737                 if (x == NULL)
1738                         {
1739                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,SSL_R_INTERNAL_ERROR);
1740                         return(0);
1741                         }
1742
1743                 l=ssl3_output_cert_chain(s,x);
1744                 s->state=SSL3_ST_SW_CERT_B;
1745                 s->init_num=(int)l;
1746                 s->init_off=0;
1747                 }
1748
1749         /* SSL3_ST_SW_CERT_B */
1750         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1751         }