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