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