PR: 2115
[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  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by 
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124
125 #define REUSE_CIPHER_BUG
126 #define NETSCAPE_HANG_BUG
127
128 #include <stdio.h>
129 #include "ssl_locl.h"
130 #include "kssl_lcl.h"
131 #include <openssl/buffer.h>
132 #include <openssl/rand.h>
133 #include <openssl/objects.h>
134 #include <openssl/evp.h>
135 #include <openssl/hmac.h>
136 #include <openssl/x509.h>
137 #ifndef OPENSSL_NO_DH
138 #include <openssl/dh.h>
139 #endif
140 #include <openssl/bn.h>
141 #ifndef OPENSSL_NO_KRB5
142 #include <openssl/krb5_asn.h>
143 #endif
144 #include <openssl/md5.h>
145
146 static SSL_METHOD *ssl3_get_server_method(int ver);
147 #ifndef OPENSSL_NO_ECDH
148 static int nid2curve_id(int nid);
149 #endif
150
151 static SSL_METHOD *ssl3_get_server_method(int ver)
152         {
153         if (ver == SSL3_VERSION)
154                 return(SSLv3_server_method());
155         else
156                 return(NULL);
157         }
158
159 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
160                         ssl3_accept,
161                         ssl_undefined_function,
162                         ssl3_get_server_method)
163
164 int ssl3_accept(SSL *s)
165         {
166         BUF_MEM *buf;
167         unsigned long l,Time=(unsigned long)time(NULL);
168         void (*cb)(const SSL *ssl,int type,int val)=NULL;
169         long num1;
170         int ret= -1;
171         int new_state,state,skip=0;
172
173         RAND_add(&Time,sizeof(Time),0);
174         ERR_clear_error();
175         clear_sys_error();
176
177         if (s->info_callback != NULL)
178                 cb=s->info_callback;
179         else if (s->ctx->info_callback != NULL)
180                 cb=s->ctx->info_callback;
181
182         /* init things to blank */
183         s->in_handshake++;
184         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
185
186         if (s->cert == NULL)
187                 {
188                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
189                 return(-1);
190                 }
191
192         for (;;)
193                 {
194                 state=s->state;
195
196                 switch (s->state)
197                         {
198                 case SSL_ST_RENEGOTIATE:
199                         s->new_session=1;
200                         /* s->state=SSL_ST_ACCEPT; */
201
202                 case SSL_ST_BEFORE:
203                 case SSL_ST_ACCEPT:
204                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
205                 case SSL_ST_OK|SSL_ST_ACCEPT:
206
207                         s->server=1;
208                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
209
210                         if ((s->version>>8) != 3)
211                                 {
212                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
213                                 return -1;
214                                 }
215                         s->type=SSL_ST_ACCEPT;
216
217                         if (s->init_buf == NULL)
218                                 {
219                                 if ((buf=BUF_MEM_new()) == NULL)
220                                         {
221                                         ret= -1;
222                                         goto end;
223                                         }
224                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
225                                         {
226                                         ret= -1;
227                                         goto end;
228                                         }
229                                 s->init_buf=buf;
230                                 }
231
232                         if (!ssl3_setup_buffers(s))
233                                 {
234                                 ret= -1;
235                                 goto end;
236                                 }
237
238                         s->init_num=0;
239
240                         if (s->state != SSL_ST_RENEGOTIATE)
241                                 {
242                                 /* Ok, we now need to push on a buffering BIO so that
243                                  * the output is sent in a way that TCP likes :-)
244                                  */
245                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
246                                 
247                                 ssl3_init_finished_mac(s);
248                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
249                                 s->ctx->stats.sess_accept++;
250                                 }
251                         else
252                                 {
253                                 /* s->state == SSL_ST_RENEGOTIATE,
254                                  * we will just send a HelloRequest */
255                                 s->ctx->stats.sess_accept_renegotiate++;
256                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
257                                 }
258                         break;
259
260                 case SSL3_ST_SW_HELLO_REQ_A:
261                 case SSL3_ST_SW_HELLO_REQ_B:
262
263                         s->shutdown=0;
264                         ret=ssl3_send_hello_request(s);
265                         if (ret <= 0) goto end;
266                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
267                         s->state=SSL3_ST_SW_FLUSH;
268                         s->init_num=0;
269
270                         ssl3_init_finished_mac(s);
271                         break;
272
273                 case SSL3_ST_SW_HELLO_REQ_C:
274                         s->state=SSL_ST_OK;
275                         break;
276
277                 case SSL3_ST_SR_CLNT_HELLO_A:
278                 case SSL3_ST_SR_CLNT_HELLO_B:
279                 case SSL3_ST_SR_CLNT_HELLO_C:
280
281                         s->shutdown=0;
282                         ret=ssl3_get_client_hello(s);
283                         if (ret <= 0) goto end;
284                         s->new_session = 2;
285                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
286                         s->init_num=0;
287                         break;
288
289                 case SSL3_ST_SW_SRVR_HELLO_A:
290                 case SSL3_ST_SW_SRVR_HELLO_B:
291                         ret=ssl3_send_server_hello(s);
292                         if (ret <= 0) goto end;
293 #ifndef OPENSSL_NO_TLSEXT
294                         if (s->hit)
295                                 {
296                                 if (s->tlsext_ticket_expected)
297                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
298                                 else
299                                         s->state=SSL3_ST_SW_CHANGE_A;
300                                 }
301 #else
302                         if (s->hit)
303                                         s->state=SSL3_ST_SW_CHANGE_A;
304 #endif
305                         else
306                                 s->state=SSL3_ST_SW_CERT_A;
307                         s->init_num=0;
308                         break;
309
310                 case SSL3_ST_SW_CERT_A:
311                 case SSL3_ST_SW_CERT_B:
312                         /* Check if it is anon DH or anon ECDH or KRB5 */
313                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL)
314                                 && !(s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
315                                 {
316                                 ret=ssl3_send_server_certificate(s);
317                                 if (ret <= 0) goto end;
318 #ifndef OPENSSL_NO_TLSEXT
319                                 if (s->tlsext_status_expected)
320                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
321                                 else
322                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
323                                 }
324                         else
325                                 {
326                                 skip = 1;
327                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
328                                 }
329 #else
330                                 }
331                         else
332                                 skip=1;
333
334                         s->state=SSL3_ST_SW_KEY_EXCH_A;
335 #endif
336                         s->init_num=0;
337                         break;
338
339                 case SSL3_ST_SW_KEY_EXCH_A:
340                 case SSL3_ST_SW_KEY_EXCH_B:
341                         l=s->s3->tmp.new_cipher->algorithms;
342
343                         /* clear this, it may get reset by
344                          * send_server_key_exchange */
345                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
346 #ifndef OPENSSL_NO_KRB5
347                                 && !(l & SSL_KRB5)
348 #endif /* OPENSSL_NO_KRB5 */
349                                 )
350                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
351                                  * even when forbidden by protocol specs
352                                  * (handshake may fail as clients are not required to
353                                  * be able to handle this) */
354                                 s->s3->tmp.use_rsa_tmp=1;
355                         else
356                                 s->s3->tmp.use_rsa_tmp=0;
357
358
359                         /* only send if a DH key exchange, fortezza or
360                          * RSA but we have a sign only certificate
361                          *
362                          * For ECC ciphersuites, we send a serverKeyExchange
363                          * message only if the cipher suite is either
364                          * ECDH-anon or ECDHE. In other cases, the
365                          * server certificate contains the server's 
366                          * public key for key exchange.
367                          */
368                         if (s->s3->tmp.use_rsa_tmp
369                             || (l & SSL_kECDHE)
370                             || (l & (SSL_DH|SSL_kFZA))
371                             || ((l & SSL_kRSA)
372                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
373                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
374                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
375                                         )
376                                     )
377                                 )
378                             )
379                                 {
380                                 ret=ssl3_send_server_key_exchange(s);
381                                 if (ret <= 0) goto end;
382                                 }
383                         else
384                                 skip=1;
385
386                         s->state=SSL3_ST_SW_CERT_REQ_A;
387                         s->init_num=0;
388                         break;
389
390                 case SSL3_ST_SW_CERT_REQ_A:
391                 case SSL3_ST_SW_CERT_REQ_B:
392                         if (/* don't request cert unless asked for it: */
393                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
394                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
395                                  * don't request cert during re-negotiation: */
396                                 ((s->session->peer != NULL) &&
397                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
398                                 /* never request cert in anonymous ciphersuites
399                                  * (see section "Certificate request" in SSL 3 drafts
400                                  * and in RFC 2246): */
401                                 ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
402                                  /* ... except when the application insists on verification
403                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
404                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
405                                  /* never request cert in Kerberos ciphersuites */
406                                 (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
407                                 {
408                                 /* no cert request */
409                                 skip=1;
410                                 s->s3->tmp.cert_request=0;
411                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
412                                 }
413                         else
414                                 {
415                                 s->s3->tmp.cert_request=1;
416                                 ret=ssl3_send_certificate_request(s);
417                                 if (ret <= 0) goto end;
418 #ifndef NETSCAPE_HANG_BUG
419                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
420 #else
421                                 s->state=SSL3_ST_SW_FLUSH;
422                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
423 #endif
424                                 s->init_num=0;
425                                 }
426                         break;
427
428                 case SSL3_ST_SW_SRVR_DONE_A:
429                 case SSL3_ST_SW_SRVR_DONE_B:
430                         ret=ssl3_send_server_done(s);
431                         if (ret <= 0) goto end;
432                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
433                         s->state=SSL3_ST_SW_FLUSH;
434                         s->init_num=0;
435                         break;
436                 
437                 case SSL3_ST_SW_FLUSH:
438                         /* number of bytes to be flushed */
439                         num1=BIO_ctrl(s->wbio,BIO_CTRL_WPENDING,0,NULL);
440                         if (num1 > 0)
441                                 {
442                                 s->rwstate=SSL_WRITING;
443                                 num1=BIO_flush(s->wbio);
444                                 if (num1 <= 0) { ret= -1; goto end; }
445                                 s->rwstate=SSL_NOTHING;
446                                 }
447
448                         s->state=s->s3->tmp.next_state;
449                         break;
450
451                 case SSL3_ST_SR_CERT_A:
452                 case SSL3_ST_SR_CERT_B:
453                         /* Check for second client hello (MS SGC) */
454                         ret = ssl3_check_client_hello(s);
455                         if (ret <= 0)
456                                 goto end;
457                         if (ret == 2)
458                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
459                         else {
460                                 if (s->s3->tmp.cert_request)
461                                         {
462                                         ret=ssl3_get_client_certificate(s);
463                                         if (ret <= 0) goto end;
464                                         }
465                                 s->init_num=0;
466                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
467                         }
468                         break;
469
470                 case SSL3_ST_SR_KEY_EXCH_A:
471                 case SSL3_ST_SR_KEY_EXCH_B:
472                         ret=ssl3_get_client_key_exchange(s);
473                         if (ret <= 0) 
474                                 goto end;
475                         if (ret == 2)
476                                 {
477                                 /* For the ECDH ciphersuites when
478                                  * the client sends its ECDH pub key in
479                                  * a certificate, the CertificateVerify
480                                  * message is not sent.
481                                  */
482                                 s->state=SSL3_ST_SR_FINISHED_A;
483                                 s->init_num = 0;
484                                 }
485                         else   
486                                 {
487                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
488                                 s->init_num=0;
489
490                                 /* We need to get hashes here so if there is
491                                  * a client cert, it can be verified
492                                  */ 
493                                 s->method->ssl3_enc->cert_verify_mac(s,
494                                     &(s->s3->finish_dgst1),
495                                     &(s->s3->tmp.cert_verify_md[0]));
496                                 s->method->ssl3_enc->cert_verify_mac(s,
497                                     &(s->s3->finish_dgst2),
498                                     &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));
499                                 }
500                         break;
501
502                 case SSL3_ST_SR_CERT_VRFY_A:
503                 case SSL3_ST_SR_CERT_VRFY_B:
504
505                         /* we should decide if we expected this one */
506                         ret=ssl3_get_cert_verify(s);
507                         if (ret <= 0) goto end;
508
509                         s->state=SSL3_ST_SR_FINISHED_A;
510                         s->init_num=0;
511                         break;
512
513                 case SSL3_ST_SR_FINISHED_A:
514                 case SSL3_ST_SR_FINISHED_B:
515                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
516                                 SSL3_ST_SR_FINISHED_B);
517                         if (ret <= 0) goto end;
518                         if (s->hit)
519                                 s->state=SSL_ST_OK;
520 #ifndef OPENSSL_NO_TLSEXT
521                         else if (s->tlsext_ticket_expected)
522                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
523 #endif
524                         else
525                                 s->state=SSL3_ST_SW_CHANGE_A;
526                         s->init_num=0;
527                         break;
528
529 #ifndef OPENSSL_NO_TLSEXT
530                 case SSL3_ST_SW_SESSION_TICKET_A:
531                 case SSL3_ST_SW_SESSION_TICKET_B:
532                         ret=ssl3_send_newsession_ticket(s);
533                         if (ret <= 0) goto end;
534                         s->state=SSL3_ST_SW_CHANGE_A;
535                         s->init_num=0;
536                         break;
537
538                 case SSL3_ST_SW_CERT_STATUS_A:
539                 case SSL3_ST_SW_CERT_STATUS_B:
540                         ret=ssl3_send_cert_status(s);
541                         if (ret <= 0) goto end;
542                         s->state=SSL3_ST_SW_KEY_EXCH_A;
543                         s->init_num=0;
544                         break;
545
546 #endif
547
548                 case SSL3_ST_SW_CHANGE_A:
549                 case SSL3_ST_SW_CHANGE_B:
550
551                         s->session->cipher=s->s3->tmp.new_cipher;
552                         if (!s->method->ssl3_enc->setup_key_block(s))
553                                 { ret= -1; goto end; }
554
555                         ret=ssl3_send_change_cipher_spec(s,
556                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
557
558                         if (ret <= 0) goto end;
559                         s->state=SSL3_ST_SW_FINISHED_A;
560                         s->init_num=0;
561
562                         if (!s->method->ssl3_enc->change_cipher_state(s,
563                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
564                                 {
565                                 ret= -1;
566                                 goto end;
567                                 }
568
569                         break;
570
571                 case SSL3_ST_SW_FINISHED_A:
572                 case SSL3_ST_SW_FINISHED_B:
573                         ret=ssl3_send_finished(s,
574                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
575                                 s->method->ssl3_enc->server_finished_label,
576                                 s->method->ssl3_enc->server_finished_label_len);
577                         if (ret <= 0) goto end;
578                         s->state=SSL3_ST_SW_FLUSH;
579                         if (s->hit)
580                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
581                         else
582                                 s->s3->tmp.next_state=SSL_ST_OK;
583                         s->init_num=0;
584                         break;
585
586                 case SSL_ST_OK:
587                         /* clean a few things up */
588                         ssl3_cleanup_key_block(s);
589
590                         BUF_MEM_free(s->init_buf);
591                         s->init_buf=NULL;
592
593                         /* remove buffering on output */
594                         ssl_free_wbio_buffer(s);
595
596                         s->init_num=0;
597
598                         if (s->new_session == 2) /* skipped if we just sent a HelloRequest */
599                                 {
600                                 /* actually not necessarily a 'new' session unless
601                                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
602                                 
603                                 s->new_session=0;
604                                 
605                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
606                                 
607                                 s->ctx->stats.sess_accept_good++;
608                                 /* s->server=1; */
609                                 s->handshake_func=ssl3_accept;
610
611                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
612                                 }
613                         
614                         ret = 1;
615                         goto end;
616                         /* break; */
617
618                 default:
619                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
620                         ret= -1;
621                         goto end;
622                         /* break; */
623                         }
624                 
625                 if (!s->s3->tmp.reuse_message && !skip)
626                         {
627                         if (s->debug)
628                                 {
629                                 if ((ret=BIO_flush(s->wbio)) <= 0)
630                                         goto end;
631                                 }
632
633
634                         if ((cb != NULL) && (s->state != state))
635                                 {
636                                 new_state=s->state;
637                                 s->state=state;
638                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
639                                 s->state=new_state;
640                                 }
641                         }
642                 skip=0;
643                 }
644 end:
645         /* BIO_flush(s->wbio); */
646
647         s->in_handshake--;
648         if (cb != NULL)
649                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
650         return(ret);
651         }
652
653 int ssl3_send_hello_request(SSL *s)
654         {
655         unsigned char *p;
656
657         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
658                 {
659                 p=(unsigned char *)s->init_buf->data;
660                 *(p++)=SSL3_MT_HELLO_REQUEST;
661                 *(p++)=0;
662                 *(p++)=0;
663                 *(p++)=0;
664
665                 s->state=SSL3_ST_SW_HELLO_REQ_B;
666                 /* number of bytes to write */
667                 s->init_num=4;
668                 s->init_off=0;
669                 }
670
671         /* SSL3_ST_SW_HELLO_REQ_B */
672         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
673         }
674
675 int ssl3_check_client_hello(SSL *s)
676         {
677         int ok;
678         long n;
679
680         /* this function is called when we really expect a Certificate message,
681          * so permit appropriate message length */
682         n=s->method->ssl_get_message(s,
683                 SSL3_ST_SR_CERT_A,
684                 SSL3_ST_SR_CERT_B,
685                 -1,
686                 s->max_cert_list,
687                 &ok);
688         if (!ok) return((int)n);
689         s->s3->tmp.reuse_message = 1;
690         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
691                 {
692                 /* Throw away what we have done so far in the current handshake,
693                  * which will now be aborted. (A full SSL_clear would be too much.)
694                  * I hope that tmp.dh is the only thing that may need to be cleared
695                  * when a handshake is not completed ... */
696 #ifndef OPENSSL_NO_DH
697                 if (s->s3->tmp.dh != NULL)
698                         {
699                         DH_free(s->s3->tmp.dh);
700                         s->s3->tmp.dh = NULL;
701                         }
702 #endif
703                 return 2;
704                 }
705         return 1;
706 }
707
708 int ssl3_get_client_hello(SSL *s)
709         {
710         int i,j,ok,al,ret= -1;
711         unsigned int cookie_len;
712         long n;
713         unsigned long id;
714         unsigned char *p,*d,*q;
715         SSL_CIPHER *c;
716 #ifndef OPENSSL_NO_COMP
717         SSL_COMP *comp=NULL;
718 #endif
719         STACK_OF(SSL_CIPHER) *ciphers=NULL;
720
721         /* We do this so that we will respond with our native type.
722          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
723          * This down switching should be handled by a different method.
724          * If we are SSLv3, we will respond with SSLv3, even if prompted with
725          * TLSv1.
726          */
727         if (s->state == SSL3_ST_SR_CLNT_HELLO_A)
728                 {
729                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
730                 }
731         s->first_packet=1;
732         n=s->method->ssl_get_message(s,
733                 SSL3_ST_SR_CLNT_HELLO_B,
734                 SSL3_ST_SR_CLNT_HELLO_C,
735                 SSL3_MT_CLIENT_HELLO,
736                 SSL3_RT_MAX_PLAIN_LENGTH,
737                 &ok);
738
739         if (!ok) return((int)n);
740         s->first_packet=0;
741         d=p=(unsigned char *)s->init_msg;
742
743         /* use version from inside client hello, not from record header
744          * (may differ: see RFC 2246, Appendix E, second paragraph) */
745         s->client_version=(((int)p[0])<<8)|(int)p[1];
746         p+=2;
747
748         if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
749             (s->version != DTLS1_VERSION && s->client_version < s->version))
750                 {
751                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
752                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR) 
753                         {
754                         /* similar to ssl3_get_record, send alert using remote version number */
755                         s->version = s->client_version;
756                         }
757                 al = SSL_AD_PROTOCOL_VERSION;
758                 goto f_err;
759                 }
760
761         /* If we require cookies and this ClientHello doesn't
762          * contain one, just return since we do not want to
763          * allocate any memory yet. So check cookie length...
764          */
765         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
766                 {
767                 unsigned int session_length, cookie_length;
768                 
769                 session_length = *(p + SSL3_RANDOM_SIZE);
770                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
771
772                 if (cookie_length == 0)
773                         return 1;
774                 }
775
776         /* load the client random */
777         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
778         p+=SSL3_RANDOM_SIZE;
779
780         /* get the session-id */
781         j= *(p++);
782
783         s->hit=0;
784         /* Versions before 0.9.7 always allow session reuse during renegotiation
785          * (i.e. when s->new_session is true), option
786          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7.
787          * Maybe this optional behaviour should always have been the default,
788          * but we cannot safely change the default behaviour (or new applications
789          * might be written that become totally unsecure when compiled with
790          * an earlier library version)
791          */
792         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
793                 {
794                 if (!ssl_get_new_session(s,1))
795                         goto err;
796                 }
797         else
798                 {
799                 i=ssl_get_prev_session(s, p, j, d + n);
800                 if (i == 1)
801                         { /* previous session */
802                         s->hit=1;
803                         }
804                 else if (i == -1)
805                         goto err;
806                 else /* i == 0 */
807                         {
808                         if (!ssl_get_new_session(s,1))
809                                 goto err;
810                         }
811                 }
812
813         p+=j;
814
815         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
816                 {
817                 /* cookie stuff */
818                 cookie_len = *(p++);
819
820                 /* 
821                  * The ClientHello may contain a cookie even if the
822                  * HelloVerify message has not been sent--make sure that it
823                  * does not cause an overflow.
824                  */
825                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
826                         {
827                         /* too much data */
828                         al = SSL_AD_DECODE_ERROR;
829                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
830                         goto f_err;
831                         }
832
833                 /* verify the cookie if appropriate option is set. */
834                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
835                         cookie_len > 0)
836                         {
837                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
838
839                         if ( s->ctx->app_verify_cookie_cb != NULL)
840                                 {
841                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
842                                         cookie_len) == 0)
843                                         {
844                                         al=SSL_AD_HANDSHAKE_FAILURE;
845                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
846                                                 SSL_R_COOKIE_MISMATCH);
847                                         goto f_err;
848                                         }
849                                 /* else cookie verification succeeded */
850                                 }
851                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
852                                                   s->d1->cookie_len) != 0) /* default verification */
853                                 {
854                                         al=SSL_AD_HANDSHAKE_FAILURE;
855                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
856                                                 SSL_R_COOKIE_MISMATCH);
857                                         goto f_err;
858                                 }
859
860                         ret = 2;
861                         }
862
863                 p += cookie_len;
864                 }
865
866         n2s(p,i);
867         if ((i == 0) && (j != 0))
868                 {
869                 /* we need a cipher if we are not resuming a session */
870                 al=SSL_AD_ILLEGAL_PARAMETER;
871                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
872                 goto f_err;
873                 }
874         if ((p+i) >= (d+n))
875                 {
876                 /* not enough data */
877                 al=SSL_AD_DECODE_ERROR;
878                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
879                 goto f_err;
880                 }
881         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
882                 == NULL))
883                 {
884                 goto err;
885                 }
886         p+=i;
887
888         /* If it is a hit, check that the cipher is in the list */
889         if ((s->hit) && (i > 0))
890                 {
891                 j=0;
892                 id=s->session->cipher->id;
893
894 #ifdef CIPHER_DEBUG
895                 printf("client sent %d ciphers\n",sk_num(ciphers));
896 #endif
897                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
898                         {
899                         c=sk_SSL_CIPHER_value(ciphers,i);
900 #ifdef CIPHER_DEBUG
901                         printf("client [%2d of %2d]:%s\n",
902                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
903 #endif
904                         if (c->id == id)
905                                 {
906                                 j=1;
907                                 break;
908                                 }
909                         }
910                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
911                         {
912                         /* Special case as client bug workaround: the previously used cipher may
913                          * not be in the current list, the client instead might be trying to
914                          * continue using a cipher that before wasn't chosen due to server
915                          * preferences.  We'll have to reject the connection if the cipher is not
916                          * enabled, though. */
917                         c = sk_SSL_CIPHER_value(ciphers, 0);
918                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
919                                 {
920                                 s->session->cipher = c;
921                                 j = 1;
922                                 }
923                         }
924                 if (j == 0)
925                         {
926                         /* we need to have the cipher in the cipher
927                          * list if we are asked to reuse it */
928                         al=SSL_AD_ILLEGAL_PARAMETER;
929                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
930                         goto f_err;
931                         }
932                 }
933
934         /* compression */
935         i= *(p++);
936         if ((p+i) > (d+n))
937                 {
938                 /* not enough data */
939                 al=SSL_AD_DECODE_ERROR;
940                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
941                 goto f_err;
942                 }
943         q=p;
944         for (j=0; j<i; j++)
945                 {
946                 if (p[j] == 0) break;
947                 }
948
949         p+=i;
950         if (j >= i)
951                 {
952                 /* no compress */
953                 al=SSL_AD_DECODE_ERROR;
954                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
955                 goto f_err;
956                 }
957
958 #ifndef OPENSSL_NO_TLSEXT
959         /* TLS extensions*/
960         if (s->version > SSL3_VERSION && s->version != DTLS1_VERSION && s->version != DTLS1_BAD_VER)
961                 {
962                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
963                         {
964                         /* 'al' set by ssl_parse_clienthello_tlsext */
965                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
966                         goto f_err;
967                         }
968                 }
969                 if (ssl_check_clienthello_tlsext(s) <= 0) {
970                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
971                         goto err;
972                 }
973
974         /* DTLS extensions */
975         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
976                 {
977                 if (!ssl_parse_clienthello_dtlsext(s,&p,d,n, &al))
978                         {
979                                 /* 'al' set by ssl_parse_clienthello_dtlsext */
980                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
981                                 goto f_err;
982                         }
983                 }
984 #endif
985         /* Worst case, we will use the NULL compression, but if we have other
986          * options, we will now look for them.  We have i-1 compression
987          * algorithms from the client, starting at q. */
988         s->s3->tmp.new_compression=NULL;
989 #ifndef OPENSSL_NO_COMP
990         if (s->ctx->comp_methods != NULL)
991                 { /* See if we have a match */
992                 int m,nn,o,v,done=0;
993
994                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
995                 for (m=0; m<nn; m++)
996                         {
997                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
998                         v=comp->id;
999                         for (o=0; o<i; o++)
1000                                 {
1001                                 if (v == q[o])
1002                                         {
1003                                         done=1;
1004                                         break;
1005                                         }
1006                                 }
1007                         if (done) break;
1008                         }
1009                 if (done)
1010                         s->s3->tmp.new_compression=comp;
1011                 else
1012                         comp=NULL;
1013                 }
1014 #endif
1015
1016         /* TLS does not mind if there is extra stuff */
1017 #if 0   /* SSL 3.0 does not mind either, so we should disable this test
1018          * (was enabled in 0.9.6d through 0.9.6j and 0.9.7 through 0.9.7b,
1019          * in earlier SSLeay/OpenSSL releases this test existed but was buggy) */
1020         if (s->version == SSL3_VERSION)
1021                 {
1022                 if (p < (d+n))
1023                         {
1024                         /* wrong number of bytes,
1025                          * there could be more to follow */
1026                         al=SSL_AD_DECODE_ERROR;
1027                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1028                         goto f_err;
1029                         }
1030                 }
1031 #endif
1032
1033         /* Given s->session->ciphers and SSL_get_ciphers, we must
1034          * pick a cipher */
1035
1036         if (!s->hit)
1037                 {
1038 #ifdef OPENSSL_NO_COMP
1039                 s->session->compress_meth=0;
1040 #else
1041                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1042 #endif
1043                 if (s->session->ciphers != NULL)
1044                         sk_SSL_CIPHER_free(s->session->ciphers);
1045                 s->session->ciphers=ciphers;
1046                 if (ciphers == NULL)
1047                         {
1048                         al=SSL_AD_ILLEGAL_PARAMETER;
1049                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1050                         goto f_err;
1051                         }
1052                 ciphers=NULL;
1053                 c=ssl3_choose_cipher(s,s->session->ciphers,
1054                                      SSL_get_ciphers(s));
1055
1056                 if (c == NULL)
1057                         {
1058                         al=SSL_AD_HANDSHAKE_FAILURE;
1059                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1060                         goto f_err;
1061                         }
1062                 s->s3->tmp.new_cipher=c;
1063                 }
1064         else
1065                 {
1066                 /* Session-id reuse */
1067 #ifdef REUSE_CIPHER_BUG
1068                 STACK_OF(SSL_CIPHER) *sk;
1069                 SSL_CIPHER *nc=NULL;
1070                 SSL_CIPHER *ec=NULL;
1071
1072                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1073                         {
1074                         sk=s->session->ciphers;
1075                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1076                                 {
1077                                 c=sk_SSL_CIPHER_value(sk,i);
1078                                 if (c->algorithms & SSL_eNULL)
1079                                         nc=c;
1080                                 if (SSL_C_IS_EXPORT(c))
1081                                         ec=c;
1082                                 }
1083                         if (nc != NULL)
1084                                 s->s3->tmp.new_cipher=nc;
1085                         else if (ec != NULL)
1086                                 s->s3->tmp.new_cipher=ec;
1087                         else
1088                                 s->s3->tmp.new_cipher=s->session->cipher;
1089                         }
1090                 else
1091 #endif
1092                 s->s3->tmp.new_cipher=s->session->cipher;
1093                 }
1094         
1095         /* we now have the following setup. 
1096          * client_random
1097          * cipher_list          - our prefered list of ciphers
1098          * ciphers              - the clients prefered list of ciphers
1099          * compression          - basically ignored right now
1100          * ssl version is set   - sslv3
1101          * s->session           - The ssl session has been setup.
1102          * s->hit               - session reuse flag
1103          * s->tmp.new_cipher    - the new cipher to use.
1104          */
1105
1106         if (ret < 0) ret=1;
1107         if (0)
1108                 {
1109 f_err:
1110                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1111                 }
1112 err:
1113         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1114         return(ret);
1115         }
1116
1117 int ssl3_send_server_hello(SSL *s)
1118         {
1119         unsigned char *buf;
1120         unsigned char *p,*d;
1121         int i,sl;
1122         unsigned long l,Time;
1123
1124         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1125                 {
1126                 buf=(unsigned char *)s->init_buf->data;
1127                 p=s->s3->server_random;
1128                 Time=(unsigned long)time(NULL);                 /* Time */
1129                 l2n(Time,p);
1130                 if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
1131                         return -1;
1132                 /* Do the message type and length last */
1133                 d=p= &(buf[4]);
1134
1135                 *(p++)=s->version>>8;
1136                 *(p++)=s->version&0xff;
1137
1138                 /* Random stuff */
1139                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1140                 p+=SSL3_RANDOM_SIZE;
1141
1142                 /* now in theory we have 3 options to sending back the
1143                  * session id.  If it is a re-use, we send back the
1144                  * old session-id, if it is a new session, we send
1145                  * back the new session-id or we send back a 0 length
1146                  * session-id if we want it to be single use.
1147                  * Currently I will not implement the '0' length session-id
1148                  * 12-Jan-98 - I'll now support the '0' length stuff.
1149                  *
1150                  * We also have an additional case where stateless session
1151                  * resumption is successful: we always send back the old
1152                  * session id. In this case s->hit is non zero: this can
1153                  * only happen if stateless session resumption is succesful
1154                  * if session caching is disabled so existing functionality
1155                  * is unaffected.
1156                  */
1157                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1158                         && !s->hit)
1159                         s->session->session_id_length=0;
1160
1161                 sl=s->session->session_id_length;
1162                 if (sl > (int)sizeof(s->session->session_id))
1163                         {
1164                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1165                         return -1;
1166                         }
1167                 *(p++)=sl;
1168                 memcpy(p,s->session->session_id,sl);
1169                 p+=sl;
1170
1171                 /* put the cipher */
1172                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1173                 p+=i;
1174
1175                 /* put the compression method */
1176 #ifdef OPENSSL_NO_COMP
1177                         *(p++)=0;
1178 #else
1179                 if (s->s3->tmp.new_compression == NULL)
1180                         *(p++)=0;
1181                 else
1182                         *(p++)=s->s3->tmp.new_compression->id;
1183 #endif
1184 #ifndef OPENSSL_NO_TLSEXT
1185                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1186                         {
1187                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1188                         return -1;
1189                         }
1190 #endif
1191                 /* do the header */
1192                 l=(p-d);
1193                 d=buf;
1194                 *(d++)=SSL3_MT_SERVER_HELLO;
1195                 l2n3(l,d);
1196
1197                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1198                 /* number of bytes to write */
1199                 s->init_num=p-buf;
1200                 s->init_off=0;
1201                 }
1202
1203         /* SSL3_ST_SW_SRVR_HELLO_B */
1204         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1205         }
1206
1207 int ssl3_send_server_done(SSL *s)
1208         {
1209         unsigned char *p;
1210
1211         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1212                 {
1213                 p=(unsigned char *)s->init_buf->data;
1214
1215                 /* do the header */
1216                 *(p++)=SSL3_MT_SERVER_DONE;
1217                 *(p++)=0;
1218                 *(p++)=0;
1219                 *(p++)=0;
1220
1221                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1222                 /* number of bytes to write */
1223                 s->init_num=4;
1224                 s->init_off=0;
1225                 }
1226
1227         /* SSL3_ST_SW_SRVR_DONE_B */
1228         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1229         }
1230
1231 int ssl3_send_server_key_exchange(SSL *s)
1232         {
1233 #ifndef OPENSSL_NO_RSA
1234         unsigned char *q;
1235         int j,num;
1236         RSA *rsa;
1237         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1238         unsigned int u;
1239 #endif
1240 #ifndef OPENSSL_NO_DH
1241         DH *dh=NULL,*dhp;
1242 #endif
1243 #ifndef OPENSSL_NO_ECDH
1244         EC_KEY *ecdh=NULL, *ecdhp;
1245         unsigned char *encodedPoint = NULL;
1246         int encodedlen = 0;
1247         int curve_id = 0;
1248         BN_CTX *bn_ctx = NULL; 
1249 #endif
1250         EVP_PKEY *pkey;
1251         unsigned char *p,*d;
1252         int al,i;
1253         unsigned long type;
1254         int n;
1255         CERT *cert;
1256         BIGNUM *r[4];
1257         int nr[4],kn;
1258         BUF_MEM *buf;
1259         EVP_MD_CTX md_ctx;
1260
1261         EVP_MD_CTX_init(&md_ctx);
1262         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1263                 {
1264                 type=s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1265                 cert=s->cert;
1266
1267                 buf=s->init_buf;
1268
1269                 r[0]=r[1]=r[2]=r[3]=NULL;
1270                 n=0;
1271 #ifndef OPENSSL_NO_RSA
1272                 if (type & SSL_kRSA)
1273                         {
1274                         rsa=cert->rsa_tmp;
1275                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1276                                 {
1277                                 rsa=s->cert->rsa_tmp_cb(s,
1278                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1279                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1280                                 if(rsa == NULL)
1281                                 {
1282                                         al=SSL_AD_HANDSHAKE_FAILURE;
1283                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1284                                         goto f_err;
1285                                 }
1286                                 RSA_up_ref(rsa);
1287                                 cert->rsa_tmp=rsa;
1288                                 }
1289                         if (rsa == NULL)
1290                                 {
1291                                 al=SSL_AD_HANDSHAKE_FAILURE;
1292                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1293                                 goto f_err;
1294                                 }
1295                         r[0]=rsa->n;
1296                         r[1]=rsa->e;
1297                         s->s3->tmp.use_rsa_tmp=1;
1298                         }
1299                 else
1300 #endif
1301 #ifndef OPENSSL_NO_DH
1302                         if (type & SSL_kEDH)
1303                         {
1304                         dhp=cert->dh_tmp;
1305                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1306                                 dhp=s->cert->dh_tmp_cb(s,
1307                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1308                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1309                         if (dhp == NULL)
1310                                 {
1311                                 al=SSL_AD_HANDSHAKE_FAILURE;
1312                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1313                                 goto f_err;
1314                                 }
1315
1316                         if (s->s3->tmp.dh != NULL)
1317                                 {
1318                                 DH_free(dh);
1319                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1320                                 goto err;
1321                                 }
1322
1323                         if ((dh=DHparams_dup(dhp)) == NULL)
1324                                 {
1325                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1326                                 goto err;
1327                                 }
1328
1329                         s->s3->tmp.dh=dh;
1330                         if ((dhp->pub_key == NULL ||
1331                              dhp->priv_key == NULL ||
1332                              (s->options & SSL_OP_SINGLE_DH_USE)))
1333                                 {
1334                                 if(!DH_generate_key(dh))
1335                                     {
1336                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1337                                            ERR_R_DH_LIB);
1338                                     goto err;
1339                                     }
1340                                 }
1341                         else
1342                                 {
1343                                 dh->pub_key=BN_dup(dhp->pub_key);
1344                                 dh->priv_key=BN_dup(dhp->priv_key);
1345                                 if ((dh->pub_key == NULL) ||
1346                                         (dh->priv_key == NULL))
1347                                         {
1348                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1349                                         goto err;
1350                                         }
1351                                 }
1352                         r[0]=dh->p;
1353                         r[1]=dh->g;
1354                         r[2]=dh->pub_key;
1355                         }
1356                 else 
1357 #endif
1358 #ifndef OPENSSL_NO_ECDH
1359                         if (type & SSL_kECDHE)
1360                         {
1361                         const EC_GROUP *group;
1362
1363                         ecdhp=cert->ecdh_tmp;
1364                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1365                                 {
1366                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1367                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1368                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1369                                 }
1370                         if (ecdhp == NULL)
1371                                 {
1372                                 al=SSL_AD_HANDSHAKE_FAILURE;
1373                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1374                                 goto f_err;
1375                                 }
1376
1377                         if (s->s3->tmp.ecdh != NULL)
1378                                 {
1379                                 EC_KEY_free(s->s3->tmp.ecdh); 
1380                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1381                                 goto err;
1382                                 }
1383
1384                         /* Duplicate the ECDH structure. */
1385                         if (ecdhp == NULL)
1386                                 {
1387                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1388                                 goto err;
1389                                 }
1390                         if (!EC_KEY_up_ref(ecdhp))
1391                                 {
1392                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1393                                 goto err;
1394                                 }
1395                         ecdh = ecdhp;
1396
1397                         s->s3->tmp.ecdh=ecdh;
1398                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1399                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1400                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1401                                 {
1402                                 if(!EC_KEY_generate_key(ecdh))
1403                                     {
1404                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1405                                     goto err;
1406                                     }
1407                                 }
1408
1409                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1410                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1411                             (EC_KEY_get0_private_key(ecdh) == NULL))
1412                                 {
1413                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1414                                 goto err;
1415                                 }
1416
1417                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1418                             (EC_GROUP_get_degree(group) > 163)) 
1419                                 {
1420                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1421                                 goto err;
1422                                 }
1423
1424                         /* XXX: For now, we only support ephemeral ECDH
1425                          * keys over named (not generic) curves. For 
1426                          * supported named curves, curve_id is non-zero.
1427                          */
1428                         if ((curve_id = 
1429                             nid2curve_id(EC_GROUP_get_curve_name(group)))
1430                             == 0)
1431                                 {
1432                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1433                                 goto err;
1434                                 }
1435
1436                         /* Encode the public key.
1437                          * First check the size of encoding and
1438                          * allocate memory accordingly.
1439                          */
1440                         encodedlen = EC_POINT_point2oct(group, 
1441                             EC_KEY_get0_public_key(ecdh),
1442                             POINT_CONVERSION_UNCOMPRESSED, 
1443                             NULL, 0, NULL);
1444
1445                         encodedPoint = (unsigned char *) 
1446                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1447                         bn_ctx = BN_CTX_new();
1448                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1449                                 {
1450                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1451                                 goto err;
1452                                 }
1453
1454
1455                         encodedlen = EC_POINT_point2oct(group, 
1456                             EC_KEY_get0_public_key(ecdh), 
1457                             POINT_CONVERSION_UNCOMPRESSED, 
1458                             encodedPoint, encodedlen, bn_ctx);
1459
1460                         if (encodedlen == 0) 
1461                                 {
1462                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1463                                 goto err;
1464                                 }
1465
1466                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1467
1468                         /* XXX: For now, we only support named (not 
1469                          * generic) curves in ECDH ephemeral key exchanges.
1470                          * In this situation, we need four additional bytes
1471                          * to encode the entire ServerECDHParams
1472                          * structure. 
1473                          */
1474                         n = 4 + encodedlen;
1475
1476                         /* We'll generate the serverKeyExchange message
1477                          * explicitly so we can set these to NULLs
1478                          */
1479                         r[0]=NULL;
1480                         r[1]=NULL;
1481                         r[2]=NULL;
1482                         r[3]=NULL;
1483                         }
1484                 else 
1485 #endif /* !OPENSSL_NO_ECDH */
1486                         {
1487                         al=SSL_AD_HANDSHAKE_FAILURE;
1488                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1489                         goto f_err;
1490                         }
1491                 for (i=0; r[i] != NULL; i++)
1492                         {
1493                         nr[i]=BN_num_bytes(r[i]);
1494                         n+=2+nr[i];
1495                         }
1496
1497                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1498                         {
1499                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1500                                 == NULL)
1501                                 {
1502                                 al=SSL_AD_DECODE_ERROR;
1503                                 goto f_err;
1504                                 }
1505                         kn=EVP_PKEY_size(pkey);
1506                         }
1507                 else
1508                         {
1509                         pkey=NULL;
1510                         kn=0;
1511                         }
1512
1513                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1514                         {
1515                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1516                         goto err;
1517                         }
1518                 d=(unsigned char *)s->init_buf->data;
1519                 p= &(d[4]);
1520
1521                 for (i=0; r[i] != NULL; i++)
1522                         {
1523                         s2n(nr[i],p);
1524                         BN_bn2bin(r[i],p);
1525                         p+=nr[i];
1526                         }
1527
1528 #ifndef OPENSSL_NO_ECDH
1529                 if (type & SSL_kECDHE) 
1530                         {
1531                         /* XXX: For now, we only support named (not generic) curves.
1532                          * In this situation, the serverKeyExchange message has:
1533                          * [1 byte CurveType], [2 byte CurveName]
1534                          * [1 byte length of encoded point], followed by
1535                          * the actual encoded point itself
1536                          */
1537                         *p = NAMED_CURVE_TYPE;
1538                         p += 1;
1539                         *p = 0;
1540                         p += 1;
1541                         *p = curve_id;
1542                         p += 1;
1543                         *p = encodedlen;
1544                         p += 1;
1545                         memcpy((unsigned char*)p, 
1546                             (unsigned char *)encodedPoint, 
1547                             encodedlen);
1548                         OPENSSL_free(encodedPoint);
1549                         p += encodedlen;
1550                         }
1551 #endif
1552
1553                 /* not anonymous */
1554                 if (pkey != NULL)
1555                         {
1556                         /* n is the length of the params, they start at &(d[4])
1557                          * and p points to the space at the end. */
1558 #ifndef OPENSSL_NO_RSA
1559                         if (pkey->type == EVP_PKEY_RSA)
1560                                 {
1561                                 q=md_buf;
1562                                 j=0;
1563                                 for (num=2; num > 0; num--)
1564                                         {
1565                                         EVP_MD_CTX_set_flags(&md_ctx,
1566                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1567                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1568                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1569                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1570                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1571                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1572                                         EVP_DigestFinal_ex(&md_ctx,q,
1573                                                 (unsigned int *)&i);
1574                                         q+=i;
1575                                         j+=i;
1576                                         }
1577                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1578                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1579                                         {
1580                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1581                                         goto err;
1582                                         }
1583                                 s2n(u,p);
1584                                 n+=u+2;
1585                                 }
1586                         else
1587 #endif
1588 #if !defined(OPENSSL_NO_DSA)
1589                                 if (pkey->type == EVP_PKEY_DSA)
1590                                 {
1591                                 /* lets do DSS */
1592                                 EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL);
1593                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1594                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1595                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1596                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1597                                         (unsigned int *)&i,pkey))
1598                                         {
1599                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1600                                         goto err;
1601                                         }
1602                                 s2n(i,p);
1603                                 n+=i+2;
1604                                 }
1605                         else
1606 #endif
1607 #if !defined(OPENSSL_NO_ECDSA)
1608                                 if (pkey->type == EVP_PKEY_EC)
1609                                 {
1610                                 /* let's do ECDSA */
1611                                 EVP_SignInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1612                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1613                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1614                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1615                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1616                                         (unsigned int *)&i,pkey))
1617                                         {
1618                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_ECDSA);
1619                                         goto err;
1620                                         }
1621                                 s2n(i,p);
1622                                 n+=i+2;
1623                                 }
1624                         else
1625 #endif
1626                                 {
1627                                 /* Is this error check actually needed? */
1628                                 al=SSL_AD_HANDSHAKE_FAILURE;
1629                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1630                                 goto f_err;
1631                                 }
1632                         }
1633
1634                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1635                 l2n3(n,d);
1636
1637                 /* we should now have things packed up, so lets send
1638                  * it off */
1639                 s->init_num=n+4;
1640                 s->init_off=0;
1641                 }
1642
1643         s->state = SSL3_ST_SW_KEY_EXCH_B;
1644         EVP_MD_CTX_cleanup(&md_ctx);
1645         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1646 f_err:
1647         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1648 err:
1649 #ifndef OPENSSL_NO_ECDH
1650         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1651         BN_CTX_free(bn_ctx);
1652 #endif
1653         EVP_MD_CTX_cleanup(&md_ctx);
1654         return(-1);
1655         }
1656
1657 int ssl3_send_certificate_request(SSL *s)
1658         {
1659         unsigned char *p,*d;
1660         int i,j,nl,off,n;
1661         STACK_OF(X509_NAME) *sk=NULL;
1662         X509_NAME *name;
1663         BUF_MEM *buf;
1664
1665         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1666                 {
1667                 buf=s->init_buf;
1668
1669                 d=p=(unsigned char *)&(buf->data[4]);
1670
1671                 /* get the list of acceptable cert types */
1672                 p++;
1673                 n=ssl3_get_req_cert_type(s,p);
1674                 d[0]=n;
1675                 p+=n;
1676                 n++;
1677
1678                 off=n;
1679                 p+=2;
1680                 n+=2;
1681
1682                 sk=SSL_get_client_CA_list(s);
1683                 nl=0;
1684                 if (sk != NULL)
1685                         {
1686                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1687                                 {
1688                                 name=sk_X509_NAME_value(sk,i);
1689                                 j=i2d_X509_NAME(name,NULL);
1690                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
1691                                         {
1692                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1693                                         goto err;
1694                                         }
1695                                 p=(unsigned char *)&(buf->data[4+n]);
1696                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1697                                         {
1698                                         s2n(j,p);
1699                                         i2d_X509_NAME(name,&p);
1700                                         n+=2+j;
1701                                         nl+=2+j;
1702                                         }
1703                                 else
1704                                         {
1705                                         d=p;
1706                                         i2d_X509_NAME(name,&p);
1707                                         j-=2; s2n(j,d); j+=2;
1708                                         n+=j;
1709                                         nl+=j;
1710                                         }
1711                                 }
1712                         }
1713                 /* else no CA names */
1714                 p=(unsigned char *)&(buf->data[4+off]);
1715                 s2n(nl,p);
1716
1717                 d=(unsigned char *)buf->data;
1718                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1719                 l2n3(n,d);
1720
1721                 /* we should now have things packed up, so lets send
1722                  * it off */
1723
1724                 s->init_num=n+4;
1725                 s->init_off=0;
1726 #ifdef NETSCAPE_HANG_BUG
1727                 p=(unsigned char *)s->init_buf->data + s->init_num;
1728
1729                 /* do the header */
1730                 *(p++)=SSL3_MT_SERVER_DONE;
1731                 *(p++)=0;
1732                 *(p++)=0;
1733                 *(p++)=0;
1734                 s->init_num += 4;
1735 #endif
1736
1737                 s->state = SSL3_ST_SW_CERT_REQ_B;
1738                 }
1739
1740         /* SSL3_ST_SW_CERT_REQ_B */
1741         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1742 err:
1743         return(-1);
1744         }
1745
1746 int ssl3_get_client_key_exchange(SSL *s)
1747         {
1748         int i,al,ok;
1749         long n;
1750         unsigned long l;
1751         unsigned char *p;
1752 #ifndef OPENSSL_NO_RSA
1753         RSA *rsa=NULL;
1754         EVP_PKEY *pkey=NULL;
1755 #endif
1756 #ifndef OPENSSL_NO_DH
1757         BIGNUM *pub=NULL;
1758         DH *dh_srvr;
1759 #endif
1760 #ifndef OPENSSL_NO_KRB5
1761         KSSL_ERR kssl_err;
1762 #endif /* OPENSSL_NO_KRB5 */
1763
1764 #ifndef OPENSSL_NO_ECDH
1765         EC_KEY *srvr_ecdh = NULL;
1766         EVP_PKEY *clnt_pub_pkey = NULL;
1767         EC_POINT *clnt_ecpoint = NULL;
1768         BN_CTX *bn_ctx = NULL; 
1769 #endif
1770
1771         n=s->method->ssl_get_message(s,
1772                 SSL3_ST_SR_KEY_EXCH_A,
1773                 SSL3_ST_SR_KEY_EXCH_B,
1774                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1775                 2048, /* ??? */
1776                 &ok);
1777
1778         if (!ok) return((int)n);
1779         p=(unsigned char *)s->init_msg;
1780
1781         l=s->s3->tmp.new_cipher->algorithms;
1782
1783 #ifndef OPENSSL_NO_RSA
1784         if (l & SSL_kRSA)
1785                 {
1786                 /* FIX THIS UP EAY EAY EAY EAY */
1787                 if (s->s3->tmp.use_rsa_tmp)
1788                         {
1789                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1790                                 rsa=s->cert->rsa_tmp;
1791                         /* Don't do a callback because rsa_tmp should
1792                          * be sent already */
1793                         if (rsa == NULL)
1794                                 {
1795                                 al=SSL_AD_HANDSHAKE_FAILURE;
1796                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1797                                 goto f_err;
1798
1799                                 }
1800                         }
1801                 else
1802                         {
1803                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1804                         if (    (pkey == NULL) ||
1805                                 (pkey->type != EVP_PKEY_RSA) ||
1806                                 (pkey->pkey.rsa == NULL))
1807                                 {
1808                                 al=SSL_AD_HANDSHAKE_FAILURE;
1809                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1810                                 goto f_err;
1811                                 }
1812                         rsa=pkey->pkey.rsa;
1813                         }
1814
1815                 /* TLS and [incidentally] DTLS, including pre-0.9.8f */
1816                 if (s->version > SSL3_VERSION &&
1817                     s->client_version != DTLS1_BAD_VER)
1818                         {
1819                         n2s(p,i);
1820                         if (n != i+2)
1821                                 {
1822                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1823                                         {
1824                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1825                                         goto err;
1826                                         }
1827                                 else
1828                                         p-=2;
1829                                 }
1830                         else
1831                                 n=i;
1832                         }
1833
1834                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1835
1836                 al = -1;
1837                 
1838                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1839                         {
1840                         al=SSL_AD_DECODE_ERROR;
1841                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
1842                         }
1843
1844                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1845                         {
1846                         /* The premaster secret must contain the same version number as the
1847                          * ClientHello to detect version rollback attacks (strangely, the
1848                          * protocol does not offer such protection for DH ciphersuites).
1849                          * However, buggy clients exist that send the negotiated protocol
1850                          * version instead if the server does not support the requested
1851                          * protocol version.
1852                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1853                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1854                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1855                                 {
1856                                 al=SSL_AD_DECODE_ERROR;
1857                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1858
1859                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1860                                  * (http://eprint.iacr.org/2003/052/) exploits the version
1861                                  * number check as a "bad version oracle" -- an alert would
1862                                  * reveal that the plaintext corresponding to some ciphertext
1863                                  * made up by the adversary is properly formatted except
1864                                  * that the version number is wrong.  To avoid such attacks,
1865                                  * we should treat this just like any other decryption error. */
1866                                 }
1867                         }
1868
1869                 if (al != -1)
1870                         {
1871                         /* Some decryption failure -- use random value instead as countermeasure
1872                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
1873                          * (see RFC 2246, section 7.4.7.1). */
1874                         ERR_clear_error();
1875                         i = SSL_MAX_MASTER_KEY_LENGTH;
1876                         p[0] = s->client_version >> 8;
1877                         p[1] = s->client_version & 0xff;
1878                         if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */
1879                                 goto err;
1880                         }
1881         
1882                 s->session->master_key_length=
1883                         s->method->ssl3_enc->generate_master_secret(s,
1884                                 s->session->master_key,
1885                                 p,i);
1886                 OPENSSL_cleanse(p,i);
1887                 }
1888         else
1889 #endif
1890 #ifndef OPENSSL_NO_DH
1891                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1892                 {
1893                 n2s(p,i);
1894                 if (n != i+2)
1895                         {
1896                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1897                                 {
1898                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1899                                 goto err;
1900                                 }
1901                         else
1902                                 {
1903                                 p-=2;
1904                                 i=(int)n;
1905                                 }
1906                         }
1907
1908                 if (n == 0L) /* the parameters are in the cert */
1909                         {
1910                         al=SSL_AD_HANDSHAKE_FAILURE;
1911                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1912                         goto f_err;
1913                         }
1914                 else
1915                         {
1916                         if (s->s3->tmp.dh == NULL)
1917                                 {
1918                                 al=SSL_AD_HANDSHAKE_FAILURE;
1919                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1920                                 goto f_err;
1921                                 }
1922                         else
1923                                 dh_srvr=s->s3->tmp.dh;
1924                         }
1925
1926                 pub=BN_bin2bn(p,i,NULL);
1927                 if (pub == NULL)
1928                         {
1929                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1930                         goto err;
1931                         }
1932
1933                 i=DH_compute_key(p,pub,dh_srvr);
1934
1935                 if (i <= 0)
1936                         {
1937                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1938                         goto err;
1939                         }
1940
1941                 DH_free(s->s3->tmp.dh);
1942                 s->s3->tmp.dh=NULL;
1943
1944                 BN_clear_free(pub);
1945                 pub=NULL;
1946                 s->session->master_key_length=
1947                         s->method->ssl3_enc->generate_master_secret(s,
1948                                 s->session->master_key,p,i);
1949                 OPENSSL_cleanse(p,i);
1950                 }
1951         else
1952 #endif
1953 #ifndef OPENSSL_NO_KRB5
1954         if (l & SSL_kKRB5)
1955                 {
1956                 krb5_error_code         krb5rc;
1957                 krb5_data               enc_ticket;
1958                 krb5_data               authenticator;
1959                 krb5_data               enc_pms;
1960                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
1961                 EVP_CIPHER_CTX          ciph_ctx;
1962                 EVP_CIPHER              *enc = NULL;
1963                 unsigned char           iv[EVP_MAX_IV_LENGTH];
1964                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
1965                                                + EVP_MAX_BLOCK_LENGTH];
1966                 int                     padl, outl;
1967                 krb5_timestamp          authtime = 0;
1968                 krb5_ticket_times       ttimes;
1969
1970                 EVP_CIPHER_CTX_init(&ciph_ctx);
1971
1972                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
1973
1974                 n2s(p,i);
1975                 enc_ticket.length = i;
1976
1977                 if (n < (int)enc_ticket.length + 6)
1978                         {
1979                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1980                                 SSL_R_DATA_LENGTH_TOO_LONG);
1981                         goto err;
1982                         }
1983
1984                 enc_ticket.data = (char *)p;
1985                 p+=enc_ticket.length;
1986
1987                 n2s(p,i);
1988                 authenticator.length = i;
1989
1990                 if (n < (int)(enc_ticket.length + authenticator.length) + 6)
1991                         {
1992                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1993                                 SSL_R_DATA_LENGTH_TOO_LONG);
1994                         goto err;
1995                         }
1996
1997                 authenticator.data = (char *)p;
1998                 p+=authenticator.length;
1999
2000                 n2s(p,i);
2001                 enc_pms.length = i;
2002                 enc_pms.data = (char *)p;
2003                 p+=enc_pms.length;
2004
2005                 /* Note that the length is checked again below,
2006                 ** after decryption
2007                 */
2008                 if(enc_pms.length > sizeof pms)
2009                         {
2010                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2011                                SSL_R_DATA_LENGTH_TOO_LONG);
2012                         goto err;
2013                         }
2014
2015                 if (n != (long)(enc_ticket.length + authenticator.length +
2016                                                 enc_pms.length + 6))
2017                         {
2018                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2019                                 SSL_R_DATA_LENGTH_TOO_LONG);
2020                         goto err;
2021                         }
2022
2023                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2024                                         &kssl_err)) != 0)
2025                         {
2026 #ifdef KSSL_DEBUG
2027                         printf("kssl_sget_tkt rtn %d [%d]\n",
2028                                 krb5rc, kssl_err.reason);
2029                         if (kssl_err.text)
2030                                 printf("kssl_err text= %s\n", kssl_err.text);
2031 #endif  /* KSSL_DEBUG */
2032                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2033                                 kssl_err.reason);
2034                         goto err;
2035                         }
2036
2037                 /*  Note: no authenticator is not considered an error,
2038                 **  but will return authtime == 0.
2039                 */
2040                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2041                                         &authtime, &kssl_err)) != 0)
2042                         {
2043 #ifdef KSSL_DEBUG
2044                         printf("kssl_check_authent rtn %d [%d]\n",
2045                                 krb5rc, kssl_err.reason);
2046                         if (kssl_err.text)
2047                                 printf("kssl_err text= %s\n", kssl_err.text);
2048 #endif  /* KSSL_DEBUG */
2049                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2050                                 kssl_err.reason);
2051                         goto err;
2052                         }
2053
2054                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2055                         {
2056                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2057                         goto err;
2058                         }
2059
2060 #ifdef KSSL_DEBUG
2061                 kssl_ctx_show(kssl_ctx);
2062 #endif  /* KSSL_DEBUG */
2063
2064                 enc = kssl_map_enc(kssl_ctx->enctype);
2065                 if (enc == NULL)
2066                     goto err;
2067
2068                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2069
2070                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2071                         {
2072                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2073                                 SSL_R_DECRYPTION_FAILED);
2074                         goto err;
2075                         }
2076                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2077                                         (unsigned char *)enc_pms.data, enc_pms.length))
2078                         {
2079                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2080                                 SSL_R_DECRYPTION_FAILED);
2081                         goto err;
2082                         }
2083                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2084                         {
2085                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2086                                 SSL_R_DATA_LENGTH_TOO_LONG);
2087                         goto err;
2088                         }
2089                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2090                         {
2091                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2092                                 SSL_R_DECRYPTION_FAILED);
2093                         goto err;
2094                         }
2095                 outl += padl;
2096                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2097                         {
2098                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2099                                 SSL_R_DATA_LENGTH_TOO_LONG);
2100                         goto err;
2101                         }
2102                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2103                     {
2104                     /* The premaster secret must contain the same version number as the
2105                      * ClientHello to detect version rollback attacks (strangely, the
2106                      * protocol does not offer such protection for DH ciphersuites).
2107                      * However, buggy clients exist that send random bytes instead of
2108                      * the protocol version.
2109                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2110                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2111                      */
2112                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2113                         {
2114                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2115                                SSL_AD_DECODE_ERROR);
2116                         goto err;
2117                         }
2118                     }
2119
2120                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2121
2122                 s->session->master_key_length=
2123                         s->method->ssl3_enc->generate_master_secret(s,
2124                                 s->session->master_key, pms, outl);
2125
2126                 if (kssl_ctx->client_princ)
2127                         {
2128                         size_t len = strlen(kssl_ctx->client_princ);
2129                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2130                                 {
2131                                 s->session->krb5_client_princ_len = len;
2132                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2133                                 }
2134                         }
2135
2136
2137                 /*  Was doing kssl_ctx_free() here,
2138                 **  but it caused problems for apache.
2139                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2140                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2141                 */
2142                 }
2143         else
2144 #endif  /* OPENSSL_NO_KRB5 */
2145
2146 #ifndef OPENSSL_NO_ECDH
2147                 if ((l & SSL_kECDH) || (l & SSL_kECDHE))
2148                 {
2149                 int ret = 1;
2150                 int field_size = 0;
2151                 const EC_KEY   *tkey;
2152                 const EC_GROUP *group;
2153                 const BIGNUM *priv_key;
2154
2155                 /* initialize structures for server's ECDH key pair */
2156                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2157                         {
2158                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2159                             ERR_R_MALLOC_FAILURE);
2160                         goto err;
2161                         }
2162
2163                 /* Let's get server private key and group information */
2164                 if (l & SSL_kECDH) 
2165                         { 
2166                         /* use the certificate */
2167                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2168                         }
2169                 else
2170                         {
2171                         /* use the ephermeral values we saved when
2172                          * generating the ServerKeyExchange msg.
2173                          */
2174                         tkey = s->s3->tmp.ecdh;
2175                         }
2176
2177                 group    = EC_KEY_get0_group(tkey);
2178                 priv_key = EC_KEY_get0_private_key(tkey);
2179
2180                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2181                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2182                         {
2183                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2184                                ERR_R_EC_LIB);
2185                         goto err;
2186                         }
2187
2188                 /* Let's get client's public key */
2189                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2190                         {
2191                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2192                             ERR_R_MALLOC_FAILURE);
2193                         goto err;
2194                         }
2195
2196                 if (n == 0L) 
2197                         {
2198                         /* Client Publickey was in Client Certificate */
2199
2200                          if (l & SSL_kECDHE) 
2201                                  {
2202                                  al=SSL_AD_HANDSHAKE_FAILURE;
2203                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2204                                  goto f_err;
2205                                  }
2206                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2207                             == NULL) || 
2208                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2209                                 {
2210                                 /* XXX: For now, we do not support client
2211                                  * authentication using ECDH certificates
2212                                  * so this branch (n == 0L) of the code is
2213                                  * never executed. When that support is
2214                                  * added, we ought to ensure the key 
2215                                  * received in the certificate is 
2216                                  * authorized for key agreement.
2217                                  * ECDH_compute_key implicitly checks that
2218                                  * the two ECDH shares are for the same
2219                                  * group.
2220                                  */
2221                                 al=SSL_AD_HANDSHAKE_FAILURE;
2222                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2223                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2224                                 goto f_err;
2225                                 }
2226
2227                         if (EC_POINT_copy(clnt_ecpoint,
2228                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2229                                 {
2230                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2231                                         ERR_R_EC_LIB);
2232                                 goto err;
2233                                 }
2234                         ret = 2; /* Skip certificate verify processing */
2235                         }
2236                 else
2237                         {
2238                         /* Get client's public key from encoded point
2239                          * in the ClientKeyExchange message.
2240                          */
2241                         if ((bn_ctx = BN_CTX_new()) == NULL)
2242                                 {
2243                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2244                                     ERR_R_MALLOC_FAILURE);
2245                                 goto err;
2246                                 }
2247
2248                         /* Get encoded point length */
2249                         i = *p; 
2250                         p += 1;
2251                         if (EC_POINT_oct2point(group, 
2252                             clnt_ecpoint, p, i, bn_ctx) == 0)
2253                                 {
2254                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2255                                     ERR_R_EC_LIB);
2256                                 goto err;
2257                                 }
2258                         /* p is pointing to somewhere in the buffer
2259                          * currently, so set it to the start 
2260                          */ 
2261                         p=(unsigned char *)s->init_buf->data;
2262                         }
2263
2264                 /* Compute the shared pre-master secret */
2265                 field_size = EC_GROUP_get_degree(group);
2266                 if (field_size <= 0)
2267                         {
2268                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2269                                ERR_R_ECDH_LIB);
2270                         goto err;
2271                         }
2272                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2273                 if (i <= 0)
2274                         {
2275                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2276                             ERR_R_ECDH_LIB);
2277                         goto err;
2278                         }
2279
2280                 EVP_PKEY_free(clnt_pub_pkey);
2281                 EC_POINT_free(clnt_ecpoint);
2282                 if (srvr_ecdh != NULL) 
2283                         EC_KEY_free(srvr_ecdh);
2284                 BN_CTX_free(bn_ctx);
2285
2286                 /* Compute the master secret */
2287                 s->session->master_key_length = s->method->ssl3_enc-> \
2288                     generate_master_secret(s, s->session->master_key, p, i);
2289                 
2290                 OPENSSL_cleanse(p, i);
2291                 return (ret);
2292                 }
2293         else
2294 #endif
2295                 {
2296                 al=SSL_AD_HANDSHAKE_FAILURE;
2297                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2298                                 SSL_R_UNKNOWN_CIPHER_TYPE);
2299                 goto f_err;
2300                 }
2301
2302         return(1);
2303 f_err:
2304         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2305 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH)
2306 err:
2307 #endif
2308 #ifndef OPENSSL_NO_ECDH
2309         EVP_PKEY_free(clnt_pub_pkey);
2310         EC_POINT_free(clnt_ecpoint);
2311         if (srvr_ecdh != NULL) 
2312                 EC_KEY_free(srvr_ecdh);
2313         BN_CTX_free(bn_ctx);
2314 #endif
2315         return(-1);
2316         }
2317
2318 int ssl3_get_cert_verify(SSL *s)
2319         {
2320         EVP_PKEY *pkey=NULL;
2321         unsigned char *p;
2322         int al,ok,ret=0;
2323         long n;
2324         int type=0,i,j;
2325         X509 *peer;
2326
2327         n=s->method->ssl_get_message(s,
2328                 SSL3_ST_SR_CERT_VRFY_A,
2329                 SSL3_ST_SR_CERT_VRFY_B,
2330                 -1,
2331                 514, /* 514? */
2332                 &ok);
2333
2334         if (!ok) return((int)n);
2335
2336         if (s->session->peer != NULL)
2337                 {
2338                 peer=s->session->peer;
2339                 pkey=X509_get_pubkey(peer);
2340                 type=X509_certificate_type(peer,pkey);
2341                 }
2342         else
2343                 {
2344                 peer=NULL;
2345                 pkey=NULL;
2346                 }
2347
2348         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
2349                 {
2350                 s->s3->tmp.reuse_message=1;
2351                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
2352                         {
2353                         al=SSL_AD_UNEXPECTED_MESSAGE;
2354                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
2355                         goto f_err;
2356                         }
2357                 ret=1;
2358                 goto end;
2359                 }
2360
2361         if (peer == NULL)
2362                 {
2363                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
2364                 al=SSL_AD_UNEXPECTED_MESSAGE;
2365                 goto f_err;
2366                 }
2367
2368         if (!(type & EVP_PKT_SIGN))
2369                 {
2370                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2371                 al=SSL_AD_ILLEGAL_PARAMETER;
2372                 goto f_err;
2373                 }
2374
2375         if (s->s3->change_cipher_spec)
2376                 {
2377                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
2378                 al=SSL_AD_UNEXPECTED_MESSAGE;
2379                 goto f_err;
2380                 }
2381
2382         /* we now have a signature that we need to verify */
2383         p=(unsigned char *)s->init_msg;
2384         n2s(p,i);
2385         n-=2;
2386         if (i > n)
2387                 {
2388                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
2389                 al=SSL_AD_DECODE_ERROR;
2390                 goto f_err;
2391                 }
2392
2393         j=EVP_PKEY_size(pkey);
2394         if ((i > j) || (n > j) || (n <= 0))
2395                 {
2396                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
2397                 al=SSL_AD_DECODE_ERROR;
2398                 goto f_err;
2399                 }
2400
2401 #ifndef OPENSSL_NO_RSA 
2402         if (pkey->type == EVP_PKEY_RSA)
2403                 {
2404                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2405                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
2406                                                         pkey->pkey.rsa);
2407                 if (i < 0)
2408                         {
2409                         al=SSL_AD_DECRYPT_ERROR;
2410                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
2411                         goto f_err;
2412                         }
2413                 if (i == 0)
2414                         {
2415                         al=SSL_AD_DECRYPT_ERROR;
2416                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
2417                         goto f_err;
2418                         }
2419                 }
2420         else
2421 #endif
2422 #ifndef OPENSSL_NO_DSA
2423                 if (pkey->type == EVP_PKEY_DSA)
2424                 {
2425                 j=DSA_verify(pkey->save_type,
2426                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2427                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
2428                 if (j <= 0)
2429                         {
2430                         /* bad signature */
2431                         al=SSL_AD_DECRYPT_ERROR;
2432                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
2433                         goto f_err;
2434                         }
2435                 }
2436         else
2437 #endif
2438 #ifndef OPENSSL_NO_ECDSA
2439                 if (pkey->type == EVP_PKEY_EC)
2440                 {
2441                 j=ECDSA_verify(pkey->save_type,
2442                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2443                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
2444                 if (j <= 0)
2445                         {
2446                         /* bad signature */
2447                         al=SSL_AD_DECRYPT_ERROR;
2448                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2449                             SSL_R_BAD_ECDSA_SIGNATURE);
2450                         goto f_err;
2451                         }
2452                 }
2453         else
2454 #endif
2455                 {
2456                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
2457                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
2458                 goto f_err;
2459                 }
2460
2461
2462         ret=1;
2463         if (0)
2464                 {
2465 f_err:
2466                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2467                 }
2468 end:
2469         EVP_PKEY_free(pkey);
2470         return(ret);
2471         }
2472
2473 int ssl3_get_client_certificate(SSL *s)
2474         {
2475         int i,ok,al,ret= -1;
2476         X509 *x=NULL;
2477         unsigned long l,nc,llen,n;
2478         const unsigned char *p,*q;
2479         unsigned char *d;
2480         STACK_OF(X509) *sk=NULL;
2481
2482         n=s->method->ssl_get_message(s,
2483                 SSL3_ST_SR_CERT_A,
2484                 SSL3_ST_SR_CERT_B,
2485                 -1,
2486                 s->max_cert_list,
2487                 &ok);
2488
2489         if (!ok) return((int)n);
2490
2491         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2492                 {
2493                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
2494                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2495                         {
2496                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2497                         al=SSL_AD_HANDSHAKE_FAILURE;
2498                         goto f_err;
2499                         }
2500                 /* If tls asked for a client cert, the client must return a 0 list */
2501                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2502                         {
2503                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2504                         al=SSL_AD_UNEXPECTED_MESSAGE;
2505                         goto f_err;
2506                         }
2507                 s->s3->tmp.reuse_message=1;
2508                 return(1);
2509                 }
2510
2511         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2512                 {
2513                 al=SSL_AD_UNEXPECTED_MESSAGE;
2514                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
2515                 goto f_err;
2516                 }
2517         p=d=(unsigned char *)s->init_msg;
2518
2519         if ((sk=sk_X509_new_null()) == NULL)
2520                 {
2521                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2522                 goto err;
2523                 }
2524
2525         n2l3(p,llen);
2526         if (llen+3 != n)
2527                 {
2528                 al=SSL_AD_DECODE_ERROR;
2529                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
2530                 goto f_err;
2531                 }
2532         for (nc=0; nc<llen; )
2533                 {
2534                 n2l3(p,l);
2535                 if ((l+nc+3) > llen)
2536                         {
2537                         al=SSL_AD_DECODE_ERROR;
2538                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2539                         goto f_err;
2540                         }
2541
2542                 q=p;
2543                 x=d2i_X509(NULL,&p,l);
2544                 if (x == NULL)
2545                         {
2546                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
2547                         goto err;
2548                         }
2549                 if (p != (q+l))
2550                         {
2551                         al=SSL_AD_DECODE_ERROR;
2552                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2553                         goto f_err;
2554                         }
2555                 if (!sk_X509_push(sk,x))
2556                         {
2557                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2558                         goto err;
2559                         }
2560                 x=NULL;
2561                 nc+=l+3;
2562                 }
2563
2564         if (sk_X509_num(sk) <= 0)
2565                 {
2566                 /* TLS does not mind 0 certs returned */
2567                 if (s->version == SSL3_VERSION)
2568                         {
2569                         al=SSL_AD_HANDSHAKE_FAILURE;
2570                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
2571                         goto f_err;
2572                         }
2573                 /* Fail for TLS only if we required a certificate */
2574                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2575                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2576                         {
2577                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2578                         al=SSL_AD_HANDSHAKE_FAILURE;
2579                         goto f_err;
2580                         }
2581                 }
2582         else
2583                 {
2584                 i=ssl_verify_cert_chain(s,sk);
2585                 if (i <= 0)
2586                         {
2587                         al=ssl_verify_alarm_type(s->verify_result);
2588                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
2589                         goto f_err;
2590                         }
2591                 }
2592
2593         if (s->session->peer != NULL) /* This should not be needed */
2594                 X509_free(s->session->peer);
2595         s->session->peer=sk_X509_shift(sk);
2596         s->session->verify_result = s->verify_result;
2597
2598         /* With the current implementation, sess_cert will always be NULL
2599          * when we arrive here. */
2600         if (s->session->sess_cert == NULL)
2601                 {
2602                 s->session->sess_cert = ssl_sess_cert_new();
2603                 if (s->session->sess_cert == NULL)
2604                         {
2605                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2606                         goto err;
2607                         }
2608                 }
2609         if (s->session->sess_cert->cert_chain != NULL)
2610                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2611         s->session->sess_cert->cert_chain=sk;
2612         /* Inconsistency alert: cert_chain does *not* include the
2613          * peer's own certificate, while we do include it in s3_clnt.c */
2614
2615         sk=NULL;
2616
2617         ret=1;
2618         if (0)
2619                 {
2620 f_err:
2621                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2622                 }
2623 err:
2624         if (x != NULL) X509_free(x);
2625         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2626         return(ret);
2627         }
2628
2629 int ssl3_send_server_certificate(SSL *s)
2630         {
2631         unsigned long l;
2632         X509 *x;
2633
2634         if (s->state == SSL3_ST_SW_CERT_A)
2635                 {
2636                 x=ssl_get_server_send_cert(s);
2637                 if (x == NULL &&
2638                         /* VRS: allow null cert if auth == KRB5 */
2639                         (s->s3->tmp.new_cipher->algorithms
2640                                 & (SSL_MKEY_MASK|SSL_AUTH_MASK))
2641                         != (SSL_aKRB5|SSL_kKRB5))
2642                         {
2643                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
2644                         return(0);
2645                         }
2646
2647                 l=ssl3_output_cert_chain(s,x);
2648                 s->state=SSL3_ST_SW_CERT_B;
2649                 s->init_num=(int)l;
2650                 s->init_off=0;
2651                 }
2652
2653         /* SSL3_ST_SW_CERT_B */
2654         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2655         }
2656
2657
2658 #ifndef OPENSSL_NO_ECDH
2659 /* This is the complement of curve_id2nid in s3_clnt.c. */
2660 static int nid2curve_id(int nid)
2661 {
2662         /* ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001)
2663          * (no changes in draft-ietf-tls-ecc-03.txt [June 2003]) */
2664         switch (nid) {
2665         case NID_sect163k1: /* sect163k1 (1) */
2666                 return 1;
2667         case NID_sect163r1: /* sect163r1 (2) */
2668                 return 2;
2669         case NID_sect163r2: /* sect163r2 (3) */
2670                 return 3;
2671         case NID_sect193r1: /* sect193r1 (4) */ 
2672                 return 4;
2673         case NID_sect193r2: /* sect193r2 (5) */ 
2674                 return 5;
2675         case NID_sect233k1: /* sect233k1 (6) */
2676                 return 6;
2677         case NID_sect233r1: /* sect233r1 (7) */ 
2678                 return 7;
2679         case NID_sect239k1: /* sect239k1 (8) */ 
2680                 return 8;
2681         case NID_sect283k1: /* sect283k1 (9) */
2682                 return 9;
2683         case NID_sect283r1: /* sect283r1 (10) */ 
2684                 return 10;
2685         case NID_sect409k1: /* sect409k1 (11) */ 
2686                 return 11;
2687         case NID_sect409r1: /* sect409r1 (12) */
2688                 return 12;
2689         case NID_sect571k1: /* sect571k1 (13) */ 
2690                 return 13;
2691         case NID_sect571r1: /* sect571r1 (14) */ 
2692                 return 14;
2693         case NID_secp160k1: /* secp160k1 (15) */
2694                 return 15;
2695         case NID_secp160r1: /* secp160r1 (16) */ 
2696                 return 16;
2697         case NID_secp160r2: /* secp160r2 (17) */ 
2698                 return 17;
2699         case NID_secp192k1: /* secp192k1 (18) */
2700                 return 18;
2701         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
2702                 return 19;
2703         case NID_secp224k1: /* secp224k1 (20) */ 
2704                 return 20;
2705         case NID_secp224r1: /* secp224r1 (21) */
2706                 return 21;
2707         case NID_secp256k1: /* secp256k1 (22) */ 
2708                 return 22;
2709         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
2710                 return 23;
2711         case NID_secp384r1: /* secp384r1 (24) */
2712                 return 24;
2713         case NID_secp521r1:  /* secp521r1 (25) */       
2714                 return 25;
2715         default:
2716                 return 0;
2717         }
2718 }
2719 #endif
2720 #ifndef OPENSSL_NO_TLSEXT
2721 int ssl3_send_newsession_ticket(SSL *s)
2722         {
2723         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
2724                 {
2725                 unsigned char *p, *senc, *macstart;
2726                 int len, slen;
2727                 unsigned int hlen;
2728                 EVP_CIPHER_CTX ctx;
2729                 HMAC_CTX hctx;
2730                 SSL_CTX *tctx = s->initial_ctx;
2731                 unsigned char iv[EVP_MAX_IV_LENGTH];
2732                 unsigned char key_name[16];
2733
2734                 /* get session encoding length */
2735                 slen = i2d_SSL_SESSION(s->session, NULL);
2736                 /* Some length values are 16 bits, so forget it if session is
2737                  * too long
2738                  */
2739                 if (slen > 0xFF00)
2740                         return -1;
2741                 /* Grow buffer if need be: the length calculation is as
2742                  * follows 1 (size of message name) + 3 (message length
2743                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2744                  * 16 (key name) + max_iv_len (iv length) +
2745                  * session_length + max_enc_block_size (max encrypted session
2746                  * length) + max_md_size (HMAC).
2747                  */
2748                 if (!BUF_MEM_grow(s->init_buf,
2749                         26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2750                         EVP_MAX_MD_SIZE + slen))
2751                         return -1;
2752                 senc = OPENSSL_malloc(slen);
2753                 if (!senc)
2754                         return -1;
2755                 p = senc;
2756                 i2d_SSL_SESSION(s->session, &p);
2757
2758                 p=(unsigned char *)s->init_buf->data;
2759                 /* do the header */
2760                 *(p++)=SSL3_MT_NEWSESSION_TICKET;
2761                 /* Skip message length for now */
2762                 p += 3;
2763                 EVP_CIPHER_CTX_init(&ctx);
2764                 HMAC_CTX_init(&hctx);
2765                 /* Initialize HMAC and cipher contexts. If callback present
2766                  * it does all the work otherwise use generated values
2767                  * from parent ctx.
2768                  */
2769                 if (tctx->tlsext_ticket_key_cb)
2770                         {
2771                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2772                                                          &hctx, 1) < 0)
2773                                 {
2774                                 OPENSSL_free(senc);
2775                                 return -1;
2776                                 }
2777                         }
2778                 else
2779                         {
2780                         RAND_pseudo_bytes(iv, 16);
2781                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2782                                         tctx->tlsext_tick_aes_key, iv);
2783                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2784                                         tlsext_tick_md(), NULL);
2785                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2786                         }
2787                 l2n(s->session->tlsext_tick_lifetime_hint, p);
2788                 /* Skip ticket length for now */
2789                 p += 2;
2790                 /* Output key name */
2791                 macstart = p;
2792                 memcpy(p, key_name, 16);
2793                 p += 16;
2794                 /* output IV */
2795                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2796                 p += EVP_CIPHER_CTX_iv_length(&ctx);
2797                 /* Encrypt session data */
2798                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2799                 p += len;
2800                 EVP_EncryptFinal(&ctx, p, &len);
2801                 p += len;
2802                 EVP_CIPHER_CTX_cleanup(&ctx);
2803
2804                 HMAC_Update(&hctx, macstart, p - macstart);
2805                 HMAC_Final(&hctx, p, &hlen);
2806                 HMAC_CTX_cleanup(&hctx);
2807
2808                 p += hlen;
2809                 /* Now write out lengths: p points to end of data written */
2810                 /* Total length */
2811                 len = p - (unsigned char *)s->init_buf->data;
2812                 p=(unsigned char *)s->init_buf->data + 1;
2813                 l2n3(len - 4, p); /* Message length */
2814                 p += 4;
2815                 s2n(len - 10, p);  /* Ticket length */
2816
2817                 /* number of bytes to write */
2818                 s->init_num= len;
2819                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
2820                 s->init_off=0;
2821                 OPENSSL_free(senc);
2822                 }
2823
2824         /* SSL3_ST_SW_SESSION_TICKET_B */
2825         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2826         }
2827
2828 int ssl3_send_cert_status(SSL *s)
2829         {
2830         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
2831                 {
2832                 unsigned char *p;
2833                 /* Grow buffer if need be: the length calculation is as
2834                  * follows 1 (message type) + 3 (message length) +
2835                  * 1 (ocsp response type) + 3 (ocsp response length)
2836                  * + (ocsp response)
2837                  */
2838                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
2839                         return -1;
2840
2841                 p=(unsigned char *)s->init_buf->data;
2842
2843                 /* do the header */
2844                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
2845                 /* message length */
2846                 l2n3(s->tlsext_ocsp_resplen + 4, p);
2847                 /* status type */
2848                 *(p++)= s->tlsext_status_type;
2849                 /* length of OCSP response */
2850                 l2n3(s->tlsext_ocsp_resplen, p);
2851                 /* actual response */
2852                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2853                 /* number of bytes to write */
2854                 s->init_num = 8 + s->tlsext_ocsp_resplen;
2855                 s->state=SSL3_ST_SW_CERT_STATUS_B;
2856                 s->init_off = 0;
2857                 }
2858
2859         /* SSL3_ST_SW_CERT_STATUS_B */
2860         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2861         }
2862 #endif