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