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