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