Add TLS exporter.
[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 #ifndef OPENSSL_NO_SRP
183 static int SSL_check_srp_ext_ClientHello(SSL *s, int *ad)
184         {
185         int ret = SSL_ERROR_NONE;
186
187         *ad = SSL_AD_UNRECOGNIZED_NAME;
188
189         if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
190             (s->srp_ctx.TLS_ext_srp_username_callback != NULL))
191                 {
192                 if(s->srp_ctx.login == NULL)
193                         {
194                         /* There isn't any srp login extension !!! */
195                         ret = SSL3_AL_WARNING;
196                         *ad = SSL_AD_MISSING_SRP_USERNAME;
197                         }
198                 else
199                         {
200                         ret = SSL_srp_server_param_with_username(s,ad);
201                         }
202                 }
203         return ret;
204         }
205 #endif
206
207 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
208                         ssl3_accept,
209                         ssl_undefined_function,
210                         ssl3_get_server_method)
211
212 int ssl3_accept(SSL *s)
213         {
214         BUF_MEM *buf;
215         unsigned long alg_k,Time=(unsigned long)time(NULL);
216         void (*cb)(const SSL *ssl,int type,int val)=NULL;
217         int ret= -1;
218         int new_state,state,skip=0;
219 #ifndef OPENSSL_NO_SRP
220         int srp_no_username=0;
221         int extension_error,al;
222 #endif
223
224         RAND_add(&Time,sizeof(Time),0);
225         ERR_clear_error();
226         clear_sys_error();
227
228         if (s->info_callback != NULL)
229                 cb=s->info_callback;
230         else if (s->ctx->info_callback != NULL)
231                 cb=s->ctx->info_callback;
232
233         /* init things to blank */
234         s->in_handshake++;
235         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
236
237         if (s->cert == NULL)
238                 {
239                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
240                 return(-1);
241                 }
242
243         for (;;)
244                 {
245                 state=s->state;
246
247                 switch (s->state)
248                         {
249                 case SSL_ST_RENEGOTIATE:
250                         s->renegotiate=1;
251                         /* s->state=SSL_ST_ACCEPT; */
252
253                 case SSL_ST_BEFORE:
254                 case SSL_ST_ACCEPT:
255                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
256                 case SSL_ST_OK|SSL_ST_ACCEPT:
257
258                         s->server=1;
259                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
260
261                         if ((s->version>>8) != 3)
262                                 {
263                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
264                                 return -1;
265                                 }
266                         s->type=SSL_ST_ACCEPT;
267
268                         if (s->init_buf == NULL)
269                                 {
270                                 if ((buf=BUF_MEM_new()) == NULL)
271                                         {
272                                         ret= -1;
273                                         goto end;
274                                         }
275                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
276                                         {
277                                         ret= -1;
278                                         goto end;
279                                         }
280                                 s->init_buf=buf;
281                                 }
282
283                         if (!ssl3_setup_buffers(s))
284                                 {
285                                 ret= -1;
286                                 goto end;
287                                 }
288
289                         s->init_num=0;
290
291                         if (s->state != SSL_ST_RENEGOTIATE)
292                                 {
293                                 /* Ok, we now need to push on a buffering BIO so that
294                                  * the output is sent in a way that TCP likes :-)
295                                  */
296                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
297                                 
298                                 ssl3_init_finished_mac(s);
299                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
300                                 s->ctx->stats.sess_accept++;
301                                 }
302                         else if (!s->s3->send_connection_binding &&
303                                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
304                                 {
305                                 /* Server attempting to renegotiate with
306                                  * client that doesn't support secure
307                                  * renegotiation.
308                                  */
309                                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
310                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
311                                 ret = -1;
312                                 goto end;
313                                 }
314                         else
315                                 {
316                                 /* s->state == SSL_ST_RENEGOTIATE,
317                                  * we will just send a HelloRequest */
318                                 s->ctx->stats.sess_accept_renegotiate++;
319                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
320                                 }
321                         break;
322
323                 case SSL3_ST_SW_HELLO_REQ_A:
324                 case SSL3_ST_SW_HELLO_REQ_B:
325
326                         s->shutdown=0;
327                         ret=ssl3_send_hello_request(s);
328                         if (ret <= 0) goto end;
329                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
330                         s->state=SSL3_ST_SW_FLUSH;
331                         s->init_num=0;
332
333                         ssl3_init_finished_mac(s);
334                         break;
335
336                 case SSL3_ST_SW_HELLO_REQ_C:
337                         s->state=SSL_ST_OK;
338                         break;
339
340                 case SSL3_ST_SR_CLNT_HELLO_A:
341                 case SSL3_ST_SR_CLNT_HELLO_B:
342                 case SSL3_ST_SR_CLNT_HELLO_C:
343 #ifndef OPENSSL_NO_SRP
344                 case SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME:
345 #endif
346
347                         s->shutdown=0;
348                         ret=ssl3_get_client_hello(s);
349                         if (ret <= 0) goto end;
350 #ifndef OPENSSL_NO_SRP
351                         extension_error = 0;
352                         if ((al = SSL_check_srp_ext_ClientHello(s,&extension_error)) != SSL_ERROR_NONE)
353                                 {
354                                 ssl3_send_alert(s,al,extension_error);
355                                 if (extension_error == SSL_AD_MISSING_SRP_USERNAME)
356                                         {
357                                         if (srp_no_username) goto end;
358                                         ERR_clear_error();
359                                         srp_no_username = 1;
360                                         s->state=SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME;
361                                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
362                                         if ((ret=BIO_flush(s->wbio)) <= 0) goto end;
363                                         s->init_num=0;
364                                         break;
365                                         }
366                                 ret = -1;
367                                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
368                                 goto end;
369                                 }
370 #endif
371                         
372                         s->renegotiate = 2;
373                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
374                         s->init_num=0;
375                         break;
376
377                 case SSL3_ST_SW_SRVR_HELLO_A:
378                 case SSL3_ST_SW_SRVR_HELLO_B:
379                         ret=ssl3_send_server_hello(s);
380                         if (ret <= 0) goto end;
381 #ifndef OPENSSL_NO_TLSEXT
382                         if (s->hit)
383                                 {
384                                 if (s->tlsext_ticket_expected)
385                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
386                                 else
387                                         s->state=SSL3_ST_SW_CHANGE_A;
388                                 }
389 #else
390                         if (s->hit)
391                                         s->state=SSL3_ST_SW_CHANGE_A;
392 #endif
393                         else
394                                 s->state=SSL3_ST_SW_CERT_A;
395                         s->init_num=0;
396                         break;
397
398                 case SSL3_ST_SW_CERT_A:
399                 case SSL3_ST_SW_CERT_B:
400                         /* Check if it is anon DH or anon ECDH, */
401                         /* normal PSK or KRB5 or SRP */
402                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
403                                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
404                                 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
405                                 {
406                                 ret=ssl3_send_server_certificate(s);
407                                 if (ret <= 0) goto end;
408 #ifndef OPENSSL_NO_TLSEXT
409                                 if (s->tlsext_status_expected)
410                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
411                                 else
412                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
413                                 }
414                         else
415                                 {
416                                 skip = 1;
417                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
418                                 }
419 #else
420                                 }
421                         else
422                                 skip=1;
423
424                         s->state=SSL3_ST_SW_KEY_EXCH_A;
425 #endif
426                         s->init_num=0;
427                         break;
428
429                 case SSL3_ST_SW_KEY_EXCH_A:
430                 case SSL3_ST_SW_KEY_EXCH_B:
431                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
432
433                         /* clear this, it may get reset by
434                          * send_server_key_exchange */
435                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
436 #ifndef OPENSSL_NO_KRB5
437                                 && !(alg_k & SSL_kKRB5)
438 #endif /* OPENSSL_NO_KRB5 */
439                                 )
440                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
441                                  * even when forbidden by protocol specs
442                                  * (handshake may fail as clients are not required to
443                                  * be able to handle this) */
444                                 s->s3->tmp.use_rsa_tmp=1;
445                         else
446                                 s->s3->tmp.use_rsa_tmp=0;
447
448
449                         /* only send if a DH key exchange, fortezza or
450                          * RSA but we have a sign only certificate
451                          *
452                          * PSK: may send PSK identity hints
453                          *
454                          * For ECC ciphersuites, we send a serverKeyExchange
455                          * message only if the cipher suite is either
456                          * ECDH-anon or ECDHE. In other cases, the
457                          * server certificate contains the server's
458                          * public key for key exchange.
459                          */
460                         if (s->s3->tmp.use_rsa_tmp
461                         /* PSK: send ServerKeyExchange if PSK identity
462                          * hint if provided */
463 #ifndef OPENSSL_NO_PSK
464                             || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
465 #endif
466 #ifndef OPENSSL_NO_SRP
467                             /* SRP: send ServerKeyExchange */
468                             || (alg_k & SSL_kSRP)
469 #endif
470                             || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
471                             || (alg_k & SSL_kEECDH)
472                             || ((alg_k & SSL_kRSA)
473                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
474                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
475                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
476                                         )
477                                     )
478                                 )
479                             )
480                                 {
481                                 ret=ssl3_send_server_key_exchange(s);
482                                 if (ret <= 0) goto end;
483                                 }
484                         else
485                                 skip=1;
486
487                         s->state=SSL3_ST_SW_CERT_REQ_A;
488                         s->init_num=0;
489                         break;
490
491                 case SSL3_ST_SW_CERT_REQ_A:
492                 case SSL3_ST_SW_CERT_REQ_B:
493                         if (/* don't request cert unless asked for it: */
494                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
495                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
496                                  * don't request cert during re-negotiation: */
497                                 ((s->session->peer != NULL) &&
498                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
499                                 /* never request cert in anonymous ciphersuites
500                                  * (see section "Certificate request" in SSL 3 drafts
501                                  * and in RFC 2246): */
502                                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
503                                  /* ... except when the application insists on verification
504                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
505                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
506                                  /* never request cert in Kerberos ciphersuites */
507                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
508                                 /* With normal PSK Certificates and
509                                  * Certificate Requests are omitted */
510                                 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
511                                 {
512                                 /* no cert request */
513                                 skip=1;
514                                 s->s3->tmp.cert_request=0;
515                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
516                                 if (s->s3->handshake_buffer)
517                                         if (!ssl3_digest_cached_records(s))
518                                                 return -1;
519                                 }
520                         else
521                                 {
522                                 s->s3->tmp.cert_request=1;
523                                 ret=ssl3_send_certificate_request(s);
524                                 if (ret <= 0) goto end;
525 #ifndef NETSCAPE_HANG_BUG
526                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
527 #else
528                                 s->state=SSL3_ST_SW_FLUSH;
529                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
530 #endif
531                                 s->init_num=0;
532                                 }
533                         break;
534
535                 case SSL3_ST_SW_SRVR_DONE_A:
536                 case SSL3_ST_SW_SRVR_DONE_B:
537                         ret=ssl3_send_server_done(s);
538                         if (ret <= 0) goto end;
539                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
540                         s->state=SSL3_ST_SW_FLUSH;
541                         s->init_num=0;
542                         break;
543                 
544                 case SSL3_ST_SW_FLUSH:
545
546                         /* This code originally checked to see if
547                          * any data was pending using BIO_CTRL_INFO
548                          * and then flushed. This caused problems
549                          * as documented in PR#1939. The proposed
550                          * fix doesn't completely resolve this issue
551                          * as buggy implementations of BIO_CTRL_PENDING
552                          * still exist. So instead we just flush
553                          * unconditionally.
554                          */
555
556                         s->rwstate=SSL_WRITING;
557                         if (BIO_flush(s->wbio) <= 0)
558                                 {
559                                 ret= -1;
560                                 goto end;
561                                 }
562                         s->rwstate=SSL_NOTHING;
563
564                         s->state=s->s3->tmp.next_state;
565                         break;
566
567                 case SSL3_ST_SR_CERT_A:
568                 case SSL3_ST_SR_CERT_B:
569                         /* Check for second client hello (MS SGC) */
570                         ret = ssl3_check_client_hello(s);
571                         if (ret <= 0)
572                                 goto end;
573                         if (ret == 2)
574                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
575                         else {
576                                 if (s->s3->tmp.cert_request)
577                                         {
578                                         ret=ssl3_get_client_certificate(s);
579                                         if (ret <= 0) goto end;
580                                         }
581                                 s->init_num=0;
582                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
583                         }
584                         break;
585
586                 case SSL3_ST_SR_KEY_EXCH_A:
587                 case SSL3_ST_SR_KEY_EXCH_B:
588                         ret=ssl3_get_client_key_exchange(s);
589                         if (ret <= 0)
590                                 goto end;
591                         if (ret == 2)
592                                 {
593                                 /* For the ECDH ciphersuites when
594                                  * the client sends its ECDH pub key in
595                                  * a certificate, the CertificateVerify
596                                  * message is not sent.
597                                  * Also for GOST ciphersuites when
598                                  * the client uses its key from the certificate
599                                  * for key exchange.
600                                  */
601 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
602                                 s->state=SSL3_ST_SR_FINISHED_A;
603 #else
604                                 if (s->s3->next_proto_neg_seen)
605                                         s->state=SSL3_ST_SR_NEXT_PROTO_A;
606                                 else
607                                         s->state=SSL3_ST_SR_FINISHED_A;
608 #endif
609                                 s->init_num = 0;
610                                 }
611                         else if (TLS1_get_version(s) >= TLS1_2_VERSION)
612                                 {
613                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
614                                 s->init_num=0;
615                                 if (!s->session->peer)
616                                         break;
617                                 /* For TLS v1.2 freeze the handshake buffer
618                                  * at this point and digest cached records.
619                                  */
620                                 if (!s->s3->handshake_buffer)
621                                         {
622                                         SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
623                                         return -1;
624                                         }
625                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
626                                 if (!ssl3_digest_cached_records(s))
627                                         return -1;
628                                 }
629                         else
630                                 {
631                                 int offset=0;
632                                 int dgst_num;
633
634                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
635                                 s->init_num=0;
636
637                                 /* We need to get hashes here so if there is
638                                  * a client cert, it can be verified
639                                  * FIXME - digest processing for CertificateVerify
640                                  * should be generalized. But it is next step
641                                  */
642                                 if (s->s3->handshake_buffer)
643                                         if (!ssl3_digest_cached_records(s))
644                                                 return -1;
645                                 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
646                                         if (s->s3->handshake_dgst[dgst_num]) 
647                                                 {
648                                                 int dgst_size;
649
650                                                 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]));
651                                                 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
652                                                 if (dgst_size < 0)
653                                                         {
654                                                         ret = -1;
655                                                         goto end;
656                                                         }
657                                                 offset+=dgst_size;
658                                                 }               
659                                 }
660                         break;
661
662                 case SSL3_ST_SR_CERT_VRFY_A:
663                 case SSL3_ST_SR_CERT_VRFY_B:
664
665                         /* we should decide if we expected this one */
666                         ret=ssl3_get_cert_verify(s);
667                         if (ret <= 0) goto end;
668
669 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
670                         s->state=SSL3_ST_SR_FINISHED_A;
671 #else
672                         if (s->s3->next_proto_neg_seen)
673                                 s->state=SSL3_ST_SR_NEXT_PROTO_A;
674                         else
675                                 s->state=SSL3_ST_SR_FINISHED_A;
676 #endif
677                         s->init_num=0;
678                         break;
679
680 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
681                 case SSL3_ST_SR_NEXT_PROTO_A:
682                 case SSL3_ST_SR_NEXT_PROTO_B:
683                         ret=ssl3_get_next_proto(s);
684                         if (ret <= 0) goto end;
685                         s->init_num = 0;
686                         s->state=SSL3_ST_SR_FINISHED_A;
687                         break;
688 #endif
689
690                 case SSL3_ST_SR_FINISHED_A:
691                 case SSL3_ST_SR_FINISHED_B:
692                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
693                                 SSL3_ST_SR_FINISHED_B);
694                         if (ret <= 0) goto end;
695                         if (s->hit)
696                                 s->state=SSL_ST_OK;
697 #ifndef OPENSSL_NO_TLSEXT
698                         else if (s->tlsext_ticket_expected)
699                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
700 #endif
701                         else
702                                 s->state=SSL3_ST_SW_CHANGE_A;
703                         s->init_num=0;
704                         break;
705
706 #ifndef OPENSSL_NO_TLSEXT
707                 case SSL3_ST_SW_SESSION_TICKET_A:
708                 case SSL3_ST_SW_SESSION_TICKET_B:
709                         ret=ssl3_send_newsession_ticket(s);
710                         if (ret <= 0) goto end;
711                         s->state=SSL3_ST_SW_CHANGE_A;
712                         s->init_num=0;
713                         break;
714
715                 case SSL3_ST_SW_CERT_STATUS_A:
716                 case SSL3_ST_SW_CERT_STATUS_B:
717                         ret=ssl3_send_cert_status(s);
718                         if (ret <= 0) goto end;
719                         s->state=SSL3_ST_SW_KEY_EXCH_A;
720                         s->init_num=0;
721                         break;
722
723 #endif
724
725                 case SSL3_ST_SW_CHANGE_A:
726                 case SSL3_ST_SW_CHANGE_B:
727
728                         s->session->cipher=s->s3->tmp.new_cipher;
729                         if (!s->method->ssl3_enc->setup_key_block(s))
730                                 { ret= -1; goto end; }
731
732                         ret=ssl3_send_change_cipher_spec(s,
733                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
734
735                         if (ret <= 0) goto end;
736                         s->state=SSL3_ST_SW_FINISHED_A;
737                         s->init_num=0;
738
739                         if (!s->method->ssl3_enc->change_cipher_state(s,
740                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
741                                 {
742                                 ret= -1;
743                                 goto end;
744                                 }
745
746                         break;
747
748                 case SSL3_ST_SW_FINISHED_A:
749                 case SSL3_ST_SW_FINISHED_B:
750                         ret=ssl3_send_finished(s,
751                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
752                                 s->method->ssl3_enc->server_finished_label,
753                                 s->method->ssl3_enc->server_finished_label_len);
754                         if (ret <= 0) goto end;
755                         s->state=SSL3_ST_SW_FLUSH;
756                         if (s->hit)
757                                 {
758 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
759                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
760 #else
761                                 if (s->s3->next_proto_neg_seen)
762                                         s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
763                                 else
764                                         s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
765 #endif
766                                 }
767                         else
768                                 s->s3->tmp.next_state=SSL_ST_OK;
769                         s->init_num=0;
770                         break;
771
772                 case SSL_ST_OK:
773                         /* clean a few things up */
774                         ssl3_cleanup_key_block(s);
775
776                         BUF_MEM_free(s->init_buf);
777                         s->init_buf=NULL;
778
779                         /* remove buffering on output */
780                         ssl_free_wbio_buffer(s);
781
782                         s->init_num=0;
783
784                         if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
785                                 {
786                                 s->renegotiate=0;
787                                 s->new_session=0;
788                                 
789                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
790                                 
791                                 s->ctx->stats.sess_accept_good++;
792                                 /* s->server=1; */
793                                 s->handshake_func=ssl3_accept;
794
795                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
796                                 }
797                         
798                         ret = 1;
799                         goto end;
800                         /* break; */
801
802                 default:
803                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
804                         ret= -1;
805                         goto end;
806                         /* break; */
807                         }
808                 
809                 if (!s->s3->tmp.reuse_message && !skip)
810                         {
811                         if (s->debug)
812                                 {
813                                 if ((ret=BIO_flush(s->wbio)) <= 0)
814                                         goto end;
815                                 }
816
817
818                         if ((cb != NULL) && (s->state != state))
819                                 {
820                                 new_state=s->state;
821                                 s->state=state;
822                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
823                                 s->state=new_state;
824                                 }
825                         }
826                 skip=0;
827                 }
828 end:
829         /* BIO_flush(s->wbio); */
830
831         s->in_handshake--;
832         if (cb != NULL)
833                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
834         return(ret);
835         }
836
837 int ssl3_send_hello_request(SSL *s)
838         {
839         unsigned char *p;
840
841         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
842                 {
843                 p=(unsigned char *)s->init_buf->data;
844                 *(p++)=SSL3_MT_HELLO_REQUEST;
845                 *(p++)=0;
846                 *(p++)=0;
847                 *(p++)=0;
848
849                 s->state=SSL3_ST_SW_HELLO_REQ_B;
850                 /* number of bytes to write */
851                 s->init_num=4;
852                 s->init_off=0;
853                 }
854
855         /* SSL3_ST_SW_HELLO_REQ_B */
856         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
857         }
858
859 int ssl3_check_client_hello(SSL *s)
860         {
861         int ok;
862         long n;
863
864         /* this function is called when we really expect a Certificate message,
865          * so permit appropriate message length */
866         n=s->method->ssl_get_message(s,
867                 SSL3_ST_SR_CERT_A,
868                 SSL3_ST_SR_CERT_B,
869                 -1,
870                 s->max_cert_list,
871                 &ok);
872         if (!ok) return((int)n);
873         s->s3->tmp.reuse_message = 1;
874         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
875                 {
876                 /* Throw away what we have done so far in the current handshake,
877                  * which will now be aborted. (A full SSL_clear would be too much.) */
878 #ifndef OPENSSL_NO_DH
879                 if (s->s3->tmp.dh != NULL)
880                         {
881                         DH_free(s->s3->tmp.dh);
882                         s->s3->tmp.dh = NULL;
883                         }
884 #endif
885 #ifndef OPENSSL_NO_ECDH
886                 if (s->s3->tmp.ecdh != NULL)
887                         {
888                         EC_KEY_free(s->s3->tmp.ecdh);
889                         s->s3->tmp.ecdh = NULL;
890                         }
891 #endif
892                 return 2;
893                 }
894         return 1;
895 }
896
897 int ssl3_get_client_hello(SSL *s)
898         {
899         int i,j,ok,al,ret= -1;
900         unsigned int cookie_len;
901         long n;
902         unsigned long id;
903         unsigned char *p,*d,*q;
904         SSL_CIPHER *c;
905 #ifndef OPENSSL_NO_COMP
906         SSL_COMP *comp=NULL;
907 #endif
908         STACK_OF(SSL_CIPHER) *ciphers=NULL;
909
910         /* We do this so that we will respond with our native type.
911          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
912          * This down switching should be handled by a different method.
913          * If we are SSLv3, we will respond with SSLv3, even if prompted with
914          * TLSv1.
915          */
916         if (s->state == SSL3_ST_SR_CLNT_HELLO_A
917 #ifndef OPENSSL_NO_SRP
918                 || (s->state == SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME)
919 #endif
920                 )
921                 {
922                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
923                 }
924         s->first_packet=1;
925         n=s->method->ssl_get_message(s,
926                 SSL3_ST_SR_CLNT_HELLO_B,
927                 SSL3_ST_SR_CLNT_HELLO_C,
928                 SSL3_MT_CLIENT_HELLO,
929                 SSL3_RT_MAX_PLAIN_LENGTH,
930                 &ok);
931
932         if (!ok) return((int)n);
933         s->first_packet=0;
934         d=p=(unsigned char *)s->init_msg;
935
936         /* use version from inside client hello, not from record header
937          * (may differ: see RFC 2246, Appendix E, second paragraph) */
938         s->client_version=(((int)p[0])<<8)|(int)p[1];
939         p+=2;
940
941         if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
942             (s->version != DTLS1_VERSION && s->client_version < s->version))
943                 {
944                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
945                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR)
946                         {
947                         /* similar to ssl3_get_record, send alert using remote version number */
948                         s->version = s->client_version;
949                         }
950                 al = SSL_AD_PROTOCOL_VERSION;
951                 goto f_err;
952                 }
953
954         /* If we require cookies and this ClientHello doesn't
955          * contain one, just return since we do not want to
956          * allocate any memory yet. So check cookie length...
957          */
958         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
959                 {
960                 unsigned int session_length, cookie_length;
961                 
962                 session_length = *(p + SSL3_RANDOM_SIZE);
963                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
964
965                 if (cookie_length == 0)
966                         return 1;
967                 }
968
969         /* load the client random */
970         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
971         p+=SSL3_RANDOM_SIZE;
972
973         /* get the session-id */
974         j= *(p++);
975
976         s->hit=0;
977         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
978          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
979          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
980          * than a change to default behavior so that applications relying on this for security
981          * won't even compile against older library versions).
982          *
983          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
984          * renegotiation but not a new session (s->new_session remains unset): for servers,
985          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
986          * setting will be ignored.
987          */
988         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
989                 {
990                 if (!ssl_get_new_session(s,1))
991                         goto err;
992                 }
993         else
994                 {
995                 i=ssl_get_prev_session(s, p, j, d + n);
996                 if (i == 1)
997                         { /* previous session */
998                         s->hit=1;
999                         }
1000                 else if (i == -1)
1001                         goto err;
1002                 else /* i == 0 */
1003                         {
1004                         if (!ssl_get_new_session(s,1))
1005                                 goto err;
1006                         }
1007                 }
1008
1009         p+=j;
1010
1011         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1012                 {
1013                 /* cookie stuff */
1014                 cookie_len = *(p++);
1015
1016                 /* 
1017                  * The ClientHello may contain a cookie even if the
1018                  * HelloVerify message has not been sent--make sure that it
1019                  * does not cause an overflow.
1020                  */
1021                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1022                         {
1023                         /* too much data */
1024                         al = SSL_AD_DECODE_ERROR;
1025                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1026                         goto f_err;
1027                         }
1028
1029                 /* verify the cookie if appropriate option is set. */
1030                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1031                         cookie_len > 0)
1032                         {
1033                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
1034
1035                         if ( s->ctx->app_verify_cookie_cb != NULL)
1036                                 {
1037                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1038                                         cookie_len) == 0)
1039                                         {
1040                                         al=SSL_AD_HANDSHAKE_FAILURE;
1041                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1042                                                 SSL_R_COOKIE_MISMATCH);
1043                                         goto f_err;
1044                                         }
1045                                 /* else cookie verification succeeded */
1046                                 }
1047                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
1048                                                   s->d1->cookie_len) != 0) /* default verification */
1049                                 {
1050                                         al=SSL_AD_HANDSHAKE_FAILURE;
1051                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1052                                                 SSL_R_COOKIE_MISMATCH);
1053                                         goto f_err;
1054                                 }
1055
1056                         ret = 2;
1057                         }
1058
1059                 p += cookie_len;
1060                 }
1061
1062         n2s(p,i);
1063         if ((i == 0) && (j != 0))
1064                 {
1065                 /* we need a cipher if we are not resuming a session */
1066                 al=SSL_AD_ILLEGAL_PARAMETER;
1067                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1068                 goto f_err;
1069                 }
1070         if ((p+i) >= (d+n))
1071                 {
1072                 /* not enough data */
1073                 al=SSL_AD_DECODE_ERROR;
1074                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1075                 goto f_err;
1076                 }
1077         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1078                 == NULL))
1079                 {
1080                 goto err;
1081                 }
1082         p+=i;
1083
1084         /* If it is a hit, check that the cipher is in the list */
1085         if ((s->hit) && (i > 0))
1086                 {
1087                 j=0;
1088                 id=s->session->cipher->id;
1089
1090 #ifdef CIPHER_DEBUG
1091                 printf("client sent %d ciphers\n",sk_num(ciphers));
1092 #endif
1093                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1094                         {
1095                         c=sk_SSL_CIPHER_value(ciphers,i);
1096 #ifdef CIPHER_DEBUG
1097                         printf("client [%2d of %2d]:%s\n",
1098                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1099 #endif
1100                         if (c->id == id)
1101                                 {
1102                                 j=1;
1103                                 break;
1104                                 }
1105                         }
1106 /* Disabled because it can be used in a ciphersuite downgrade
1107  * attack: CVE-2010-4180.
1108  */
1109 #if 0
1110                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1111                         {
1112                         /* Special case as client bug workaround: the previously used cipher may
1113                          * not be in the current list, the client instead might be trying to
1114                          * continue using a cipher that before wasn't chosen due to server
1115                          * preferences.  We'll have to reject the connection if the cipher is not
1116                          * enabled, though. */
1117                         c = sk_SSL_CIPHER_value(ciphers, 0);
1118                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1119                                 {
1120                                 s->session->cipher = c;
1121                                 j = 1;
1122                                 }
1123                         }
1124 #endif
1125                 if (j == 0)
1126                         {
1127                         /* we need to have the cipher in the cipher
1128                          * list if we are asked to reuse it */
1129                         al=SSL_AD_ILLEGAL_PARAMETER;
1130                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1131                         goto f_err;
1132                         }
1133                 }
1134
1135         /* compression */
1136         i= *(p++);
1137         if ((p+i) > (d+n))
1138                 {
1139                 /* not enough data */
1140                 al=SSL_AD_DECODE_ERROR;
1141                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1142                 goto f_err;
1143                 }
1144         q=p;
1145         for (j=0; j<i; j++)
1146                 {
1147                 if (p[j] == 0) break;
1148                 }
1149
1150         p+=i;
1151         if (j >= i)
1152                 {
1153                 /* no compress */
1154                 al=SSL_AD_DECODE_ERROR;
1155                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1156                 goto f_err;
1157                 }
1158
1159 #ifndef OPENSSL_NO_TLSEXT
1160         /* TLS extensions*/
1161         if (s->version >= SSL3_VERSION)
1162                 {
1163                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
1164                         {
1165                         /* 'al' set by ssl_parse_clienthello_tlsext */
1166                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1167                         goto f_err;
1168                         }
1169                 }
1170                 if (ssl_check_clienthello_tlsext(s) <= 0) {
1171                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
1172                         goto err;
1173                 }
1174
1175         /* Check if we want to use external pre-shared secret for this
1176          * handshake for not reused session only. We need to generate
1177          * server_random before calling tls_session_secret_cb in order to allow
1178          * SessionTicket processing to use it in key derivation. */
1179         {
1180                 unsigned long Time;
1181                 unsigned char *pos;
1182                 Time=(unsigned long)time(NULL);                 /* Time */
1183                 pos=s->s3->server_random;
1184                 l2n(Time,pos);
1185                 if (RAND_pseudo_bytes(pos,SSL3_RANDOM_SIZE-4) <= 0)
1186                         {
1187                         al=SSL_AD_INTERNAL_ERROR;
1188                         goto f_err;
1189                         }
1190         }
1191
1192         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1193                 {
1194                 SSL_CIPHER *pref_cipher=NULL;
1195
1196                 s->session->master_key_length=sizeof(s->session->master_key);
1197                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1198                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1199                         {
1200                         s->hit=1;
1201                         s->session->ciphers=ciphers;
1202                         s->session->verify_result=X509_V_OK;
1203
1204                         ciphers=NULL;
1205
1206                         /* check if some cipher was preferred by call back */
1207                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1208                         if (pref_cipher == NULL)
1209                                 {
1210                                 al=SSL_AD_HANDSHAKE_FAILURE;
1211                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1212                                 goto f_err;
1213                                 }
1214
1215                         s->session->cipher=pref_cipher;
1216
1217                         if (s->cipher_list)
1218                                 sk_SSL_CIPHER_free(s->cipher_list);
1219
1220                         if (s->cipher_list_by_id)
1221                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1222
1223                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1224                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1225                         }
1226                 }
1227 #endif
1228
1229         /* Worst case, we will use the NULL compression, but if we have other
1230          * options, we will now look for them.  We have i-1 compression
1231          * algorithms from the client, starting at q. */
1232         s->s3->tmp.new_compression=NULL;
1233 #ifndef OPENSSL_NO_COMP
1234         /* This only happens if we have a cache hit */
1235         if (s->session->compress_meth != 0)
1236                 {
1237                 int m, comp_id = s->session->compress_meth;
1238                 /* Perform sanity checks on resumed compression algorithm */
1239                 /* Can't disable compression */
1240                 if (s->options & SSL_OP_NO_COMPRESSION)
1241                         {
1242                         al=SSL_AD_INTERNAL_ERROR;
1243                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1244                         goto f_err;
1245                         }
1246                 /* Look for resumed compression method */
1247                 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1248                         {
1249                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1250                         if (comp_id == comp->id)
1251                                 {
1252                                 s->s3->tmp.new_compression=comp;
1253                                 break;
1254                                 }
1255                         }
1256                 if (s->s3->tmp.new_compression == NULL)
1257                         {
1258                         al=SSL_AD_INTERNAL_ERROR;
1259                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1260                         goto f_err;
1261                         }
1262                 /* Look for resumed method in compression list */
1263                 for (m = 0; m < i; m++)
1264                         {
1265                         if (q[m] == comp_id)
1266                                 break;
1267                         }
1268                 if (m >= i)
1269                         {
1270                         al=SSL_AD_ILLEGAL_PARAMETER;
1271                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1272                         goto f_err;
1273                         }
1274                 }
1275         else if (s->hit)
1276                 comp = NULL;
1277         else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1278                 { /* See if we have a match */
1279                 int m,nn,o,v,done=0;
1280
1281                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1282                 for (m=0; m<nn; m++)
1283                         {
1284                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1285                         v=comp->id;
1286                         for (o=0; o<i; o++)
1287                                 {
1288                                 if (v == q[o])
1289                                         {
1290                                         done=1;
1291                                         break;
1292                                         }
1293                                 }
1294                         if (done) break;
1295                         }
1296                 if (done)
1297                         s->s3->tmp.new_compression=comp;
1298                 else
1299                         comp=NULL;
1300                 }
1301 #else
1302         /* If compression is disabled we'd better not try to resume a session
1303          * using compression.
1304          */
1305         if (s->session->compress_meth != 0)
1306                 {
1307                 al=SSL_AD_INTERNAL_ERROR;
1308                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1309                 goto f_err;
1310                 }
1311 #endif
1312
1313         /* Given s->session->ciphers and SSL_get_ciphers, we must
1314          * pick a cipher */
1315
1316         if (!s->hit)
1317                 {
1318 #ifdef OPENSSL_NO_COMP
1319                 s->session->compress_meth=0;
1320 #else
1321                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1322 #endif
1323                 if (s->session->ciphers != NULL)
1324                         sk_SSL_CIPHER_free(s->session->ciphers);
1325                 s->session->ciphers=ciphers;
1326                 if (ciphers == NULL)
1327                         {
1328                         al=SSL_AD_ILLEGAL_PARAMETER;
1329                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1330                         goto f_err;
1331                         }
1332                 ciphers=NULL;
1333                 c=ssl3_choose_cipher(s,s->session->ciphers,
1334                                      SSL_get_ciphers(s));
1335
1336                 if (c == NULL)
1337                         {
1338                         al=SSL_AD_HANDSHAKE_FAILURE;
1339                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1340                         goto f_err;
1341                         }
1342                 s->s3->tmp.new_cipher=c;
1343                 }
1344         else
1345                 {
1346                 /* Session-id reuse */
1347 #ifdef REUSE_CIPHER_BUG
1348                 STACK_OF(SSL_CIPHER) *sk;
1349                 SSL_CIPHER *nc=NULL;
1350                 SSL_CIPHER *ec=NULL;
1351
1352                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1353                         {
1354                         sk=s->session->ciphers;
1355                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1356                                 {
1357                                 c=sk_SSL_CIPHER_value(sk,i);
1358                                 if (c->algorithm_enc & SSL_eNULL)
1359                                         nc=c;
1360                                 if (SSL_C_IS_EXPORT(c))
1361                                         ec=c;
1362                                 }
1363                         if (nc != NULL)
1364                                 s->s3->tmp.new_cipher=nc;
1365                         else if (ec != NULL)
1366                                 s->s3->tmp.new_cipher=ec;
1367                         else
1368                                 s->s3->tmp.new_cipher=s->session->cipher;
1369                         }
1370                 else
1371 #endif
1372                 s->s3->tmp.new_cipher=s->session->cipher;
1373                 }
1374
1375         if (TLS1_get_version(s) < TLS1_2_VERSION || !(s->verify_mode & SSL_VERIFY_PEER))
1376                 {
1377                 if (!ssl3_digest_cached_records(s))
1378                         goto f_err;
1379                 }
1380         
1381         /* we now have the following setup. 
1382          * client_random
1383          * cipher_list          - our prefered list of ciphers
1384          * ciphers              - the clients prefered list of ciphers
1385          * compression          - basically ignored right now
1386          * ssl version is set   - sslv3
1387          * s->session           - The ssl session has been setup.
1388          * s->hit               - session reuse flag
1389          * s->tmp.new_cipher    - the new cipher to use.
1390          */
1391
1392         if (ret < 0) ret=1;
1393         if (0)
1394                 {
1395 f_err:
1396                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1397                 }
1398 err:
1399         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1400         return(ret);
1401         }
1402
1403 int ssl3_send_server_hello(SSL *s)
1404         {
1405         unsigned char *buf;
1406         unsigned char *p,*d;
1407         int i,sl;
1408         unsigned long l;
1409 #ifdef OPENSSL_NO_TLSEXT
1410         unsigned long Time;
1411 #endif
1412
1413         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1414                 {
1415                 buf=(unsigned char *)s->init_buf->data;
1416 #ifdef OPENSSL_NO_TLSEXT
1417                 p=s->s3->server_random;
1418                 /* Generate server_random if it was not needed previously */
1419                 Time=(unsigned long)time(NULL);                 /* Time */
1420                 l2n(Time,p);
1421                 if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
1422                         return -1;
1423 #endif
1424                 /* Do the message type and length last */
1425                 d=p= &(buf[4]);
1426
1427                 *(p++)=s->version>>8;
1428                 *(p++)=s->version&0xff;
1429
1430                 /* Random stuff */
1431                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1432                 p+=SSL3_RANDOM_SIZE;
1433
1434                 /* There are several cases for the session ID to send
1435                  * back in the server hello:
1436                  * - For session reuse from the session cache,
1437                  *   we send back the old session ID.
1438                  * - If stateless session reuse (using a session ticket)
1439                  *   is successful, we send back the client's "session ID"
1440                  *   (which doesn't actually identify the session).
1441                  * - If it is a new session, we send back the new
1442                  *   session ID.
1443                  * - However, if we want the new session to be single-use,
1444                  *   we send back a 0-length session ID.
1445                  * s->hit is non-zero in either case of session reuse,
1446                  * so the following won't overwrite an ID that we're supposed
1447                  * to send back.
1448                  */
1449                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1450                         && !s->hit)
1451                         s->session->session_id_length=0;
1452
1453                 sl=s->session->session_id_length;
1454                 if (sl > (int)sizeof(s->session->session_id))
1455                         {
1456                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1457                         return -1;
1458                         }
1459                 *(p++)=sl;
1460                 memcpy(p,s->session->session_id,sl);
1461                 p+=sl;
1462
1463                 /* put the cipher */
1464                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1465                 p+=i;
1466
1467                 /* put the compression method */
1468 #ifdef OPENSSL_NO_COMP
1469                         *(p++)=0;
1470 #else
1471                 if (s->s3->tmp.new_compression == NULL)
1472                         *(p++)=0;
1473                 else
1474                         *(p++)=s->s3->tmp.new_compression->id;
1475 #endif
1476 #ifndef OPENSSL_NO_TLSEXT
1477                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1478                         {
1479                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1480                         return -1;
1481                         }
1482                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1483                         {
1484                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1485                         return -1;
1486                         }
1487 #endif
1488                 /* do the header */
1489                 l=(p-d);
1490                 d=buf;
1491                 *(d++)=SSL3_MT_SERVER_HELLO;
1492                 l2n3(l,d);
1493
1494                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1495                 /* number of bytes to write */
1496                 s->init_num=p-buf;
1497                 s->init_off=0;
1498                 }
1499
1500         /* SSL3_ST_SW_SRVR_HELLO_B */
1501         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1502         }
1503
1504 int ssl3_send_server_done(SSL *s)
1505         {
1506         unsigned char *p;
1507
1508         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1509                 {
1510                 p=(unsigned char *)s->init_buf->data;
1511
1512                 /* do the header */
1513                 *(p++)=SSL3_MT_SERVER_DONE;
1514                 *(p++)=0;
1515                 *(p++)=0;
1516                 *(p++)=0;
1517
1518                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1519                 /* number of bytes to write */
1520                 s->init_num=4;
1521                 s->init_off=0;
1522                 }
1523
1524         /* SSL3_ST_SW_SRVR_DONE_B */
1525         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1526         }
1527
1528 int ssl3_send_server_key_exchange(SSL *s)
1529         {
1530 #ifndef OPENSSL_NO_RSA
1531         unsigned char *q;
1532         int j,num;
1533         RSA *rsa;
1534         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1535         unsigned int u;
1536 #endif
1537 #ifndef OPENSSL_NO_DH
1538         DH *dh=NULL,*dhp;
1539 #endif
1540 #ifndef OPENSSL_NO_ECDH
1541         EC_KEY *ecdh=NULL, *ecdhp;
1542         unsigned char *encodedPoint = NULL;
1543         int encodedlen = 0;
1544         int curve_id = 0;
1545         BN_CTX *bn_ctx = NULL; 
1546 #endif
1547         EVP_PKEY *pkey;
1548         const EVP_MD *md = NULL;
1549         unsigned char *p,*d;
1550         int al,i;
1551         unsigned long type;
1552         int n;
1553         CERT *cert;
1554         BIGNUM *r[4];
1555         int nr[4],kn;
1556         BUF_MEM *buf;
1557         EVP_MD_CTX md_ctx;
1558
1559         EVP_MD_CTX_init(&md_ctx);
1560         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1561                 {
1562                 type=s->s3->tmp.new_cipher->algorithm_mkey;
1563                 cert=s->cert;
1564
1565                 buf=s->init_buf;
1566
1567                 r[0]=r[1]=r[2]=r[3]=NULL;
1568                 n=0;
1569 #ifndef OPENSSL_NO_RSA
1570                 if (type & SSL_kRSA)
1571                         {
1572                         rsa=cert->rsa_tmp;
1573                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1574                                 {
1575                                 rsa=s->cert->rsa_tmp_cb(s,
1576                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1577                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1578                                 if(rsa == NULL)
1579                                 {
1580                                         al=SSL_AD_HANDSHAKE_FAILURE;
1581                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1582                                         goto f_err;
1583                                 }
1584                                 RSA_up_ref(rsa);
1585                                 cert->rsa_tmp=rsa;
1586                                 }
1587                         if (rsa == NULL)
1588                                 {
1589                                 al=SSL_AD_HANDSHAKE_FAILURE;
1590                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1591                                 goto f_err;
1592                                 }
1593                         r[0]=rsa->n;
1594                         r[1]=rsa->e;
1595                         s->s3->tmp.use_rsa_tmp=1;
1596                         }
1597                 else
1598 #endif
1599 #ifndef OPENSSL_NO_DH
1600                         if (type & SSL_kEDH)
1601                         {
1602                         dhp=cert->dh_tmp;
1603                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1604                                 dhp=s->cert->dh_tmp_cb(s,
1605                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1606                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1607                         if (dhp == NULL)
1608                                 {
1609                                 al=SSL_AD_HANDSHAKE_FAILURE;
1610                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1611                                 goto f_err;
1612                                 }
1613
1614                         if (s->s3->tmp.dh != NULL)
1615                                 {
1616                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1617                                 goto err;
1618                                 }
1619
1620                         if ((dh=DHparams_dup(dhp)) == NULL)
1621                                 {
1622                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1623                                 goto err;
1624                                 }
1625
1626                         s->s3->tmp.dh=dh;
1627                         if ((dhp->pub_key == NULL ||
1628                              dhp->priv_key == NULL ||
1629                              (s->options & SSL_OP_SINGLE_DH_USE)))
1630                                 {
1631                                 if(!DH_generate_key(dh))
1632                                     {
1633                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1634                                            ERR_R_DH_LIB);
1635                                     goto err;
1636                                     }
1637                                 }
1638                         else
1639                                 {
1640                                 dh->pub_key=BN_dup(dhp->pub_key);
1641                                 dh->priv_key=BN_dup(dhp->priv_key);
1642                                 if ((dh->pub_key == NULL) ||
1643                                         (dh->priv_key == NULL))
1644                                         {
1645                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1646                                         goto err;
1647                                         }
1648                                 }
1649                         r[0]=dh->p;
1650                         r[1]=dh->g;
1651                         r[2]=dh->pub_key;
1652                         }
1653                 else 
1654 #endif
1655 #ifndef OPENSSL_NO_ECDH
1656                         if (type & SSL_kEECDH)
1657                         {
1658                         const EC_GROUP *group;
1659
1660                         ecdhp=cert->ecdh_tmp;
1661                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1662                                 {
1663                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1664                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1665                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1666                                 }
1667                         if (ecdhp == NULL)
1668                                 {
1669                                 al=SSL_AD_HANDSHAKE_FAILURE;
1670                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1671                                 goto f_err;
1672                                 }
1673
1674                         if (s->s3->tmp.ecdh != NULL)
1675                                 {
1676                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1677                                 goto err;
1678                                 }
1679
1680                         /* Duplicate the ECDH structure. */
1681                         if (ecdhp == NULL)
1682                                 {
1683                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1684                                 goto err;
1685                                 }
1686                         if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1687                                 {
1688                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1689                                 goto err;
1690                                 }
1691
1692                         s->s3->tmp.ecdh=ecdh;
1693                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1694                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1695                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1696                                 {
1697                                 if(!EC_KEY_generate_key(ecdh))
1698                                     {
1699                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1700                                     goto err;
1701                                     }
1702                                 }
1703
1704                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1705                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1706                             (EC_KEY_get0_private_key(ecdh) == NULL))
1707                                 {
1708                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1709                                 goto err;
1710                                 }
1711
1712                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1713                             (EC_GROUP_get_degree(group) > 163)) 
1714                                 {
1715                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1716                                 goto err;
1717                                 }
1718
1719                         /* XXX: For now, we only support ephemeral ECDH
1720                          * keys over named (not generic) curves. For 
1721                          * supported named curves, curve_id is non-zero.
1722                          */
1723                         if ((curve_id = 
1724                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1725                             == 0)
1726                                 {
1727                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1728                                 goto err;
1729                                 }
1730
1731                         /* Encode the public key.
1732                          * First check the size of encoding and
1733                          * allocate memory accordingly.
1734                          */
1735                         encodedlen = EC_POINT_point2oct(group, 
1736                             EC_KEY_get0_public_key(ecdh),
1737                             POINT_CONVERSION_UNCOMPRESSED, 
1738                             NULL, 0, NULL);
1739
1740                         encodedPoint = (unsigned char *) 
1741                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1742                         bn_ctx = BN_CTX_new();
1743                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1744                                 {
1745                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1746                                 goto err;
1747                                 }
1748
1749
1750                         encodedlen = EC_POINT_point2oct(group, 
1751                             EC_KEY_get0_public_key(ecdh), 
1752                             POINT_CONVERSION_UNCOMPRESSED, 
1753                             encodedPoint, encodedlen, bn_ctx);
1754
1755                         if (encodedlen == 0) 
1756                                 {
1757                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1758                                 goto err;
1759                                 }
1760
1761                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1762
1763                         /* XXX: For now, we only support named (not 
1764                          * generic) curves in ECDH ephemeral key exchanges.
1765                          * In this situation, we need four additional bytes
1766                          * to encode the entire ServerECDHParams
1767                          * structure. 
1768                          */
1769                         n = 4 + encodedlen;
1770
1771                         /* We'll generate the serverKeyExchange message
1772                          * explicitly so we can set these to NULLs
1773                          */
1774                         r[0]=NULL;
1775                         r[1]=NULL;
1776                         r[2]=NULL;
1777                         r[3]=NULL;
1778                         }
1779                 else 
1780 #endif /* !OPENSSL_NO_ECDH */
1781 #ifndef OPENSSL_NO_PSK
1782                         if (type & SSL_kPSK)
1783                                 {
1784                                 /* reserve size for record length and PSK identity hint*/
1785                                 n+=2+strlen(s->ctx->psk_identity_hint);
1786                                 }
1787                         else
1788 #endif /* !OPENSSL_NO_PSK */
1789 #ifndef OPENSSL_NO_SRP
1790                 if (type & SSL_kSRP)
1791                         {
1792                         if ((s->srp_ctx.N == NULL) ||
1793                                 (s->srp_ctx.g == NULL) ||
1794                                 (s->srp_ctx.s == NULL) ||
1795                                 (s->srp_ctx.B == NULL))
1796                                 {
1797                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1798                                 goto err;
1799                                 }
1800                         r[0]=s->srp_ctx.N;
1801                         r[1]=s->srp_ctx.g;
1802                         r[2]=s->srp_ctx.s;
1803                         r[3]=s->srp_ctx.B;
1804                         }
1805                 else 
1806 #endif
1807                         {
1808                         al=SSL_AD_HANDSHAKE_FAILURE;
1809                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1810                         goto f_err;
1811                         }
1812                 for (i=0; r[i] != NULL && i<4; i++)
1813                         {
1814                         nr[i]=BN_num_bytes(r[i]);
1815 #ifndef OPENSSL_NO_SRP
1816                         if ((i == 2) && (type & SSL_kSRP))
1817                                 n+=1+nr[i];
1818                         else
1819 #endif
1820                         n+=2+nr[i];
1821                         }
1822
1823                 if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1824                         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1825                         {
1826                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1827                                 == NULL)
1828                                 {
1829                                 al=SSL_AD_DECODE_ERROR;
1830                                 goto f_err;
1831                                 }
1832                         kn=EVP_PKEY_size(pkey);
1833                         }
1834                 else
1835                         {
1836                         pkey=NULL;
1837                         kn=0;
1838                         }
1839
1840                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1841                         {
1842                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1843                         goto err;
1844                         }
1845                 d=(unsigned char *)s->init_buf->data;
1846                 p= &(d[4]);
1847
1848                 for (i=0; r[i] != NULL && i<4; i++)
1849                         {
1850 #ifndef OPENSSL_NO_SRP
1851                         if ((i == 2) && (type & SSL_kSRP))
1852                                 {
1853                                 *p = nr[i];
1854                                 p++;
1855                                 }
1856                         else
1857 #endif
1858                         s2n(nr[i],p);
1859                         BN_bn2bin(r[i],p);
1860                         p+=nr[i];
1861                         }
1862
1863 #ifndef OPENSSL_NO_ECDH
1864                 if (type & SSL_kEECDH) 
1865                         {
1866                         /* XXX: For now, we only support named (not generic) curves.
1867                          * In this situation, the serverKeyExchange message has:
1868                          * [1 byte CurveType], [2 byte CurveName]
1869                          * [1 byte length of encoded point], followed by
1870                          * the actual encoded point itself
1871                          */
1872                         *p = NAMED_CURVE_TYPE;
1873                         p += 1;
1874                         *p = 0;
1875                         p += 1;
1876                         *p = curve_id;
1877                         p += 1;
1878                         *p = encodedlen;
1879                         p += 1;
1880                         memcpy((unsigned char*)p, 
1881                             (unsigned char *)encodedPoint, 
1882                             encodedlen);
1883                         OPENSSL_free(encodedPoint);
1884                         encodedPoint = NULL;
1885                         p += encodedlen;
1886                         }
1887 #endif
1888
1889 #ifndef OPENSSL_NO_PSK
1890                 if (type & SSL_kPSK)
1891                         {
1892                         /* copy PSK identity hint */
1893                         s2n(strlen(s->ctx->psk_identity_hint), p); 
1894                         strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1895                         p+=strlen(s->ctx->psk_identity_hint);
1896                         }
1897 #endif
1898
1899                 /* not anonymous */
1900                 if (pkey != NULL)
1901                         {
1902                         /* n is the length of the params, they start at &(d[4])
1903                          * and p points to the space at the end. */
1904 #ifndef OPENSSL_NO_RSA
1905                         if (pkey->type == EVP_PKEY_RSA
1906                                         && TLS1_get_version(s) < TLS1_2_VERSION)
1907                                 {
1908                                 q=md_buf;
1909                                 j=0;
1910                                 for (num=2; num > 0; num--)
1911                                         {
1912                                         EVP_MD_CTX_set_flags(&md_ctx,
1913                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1914                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1915                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1916                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1917                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1918                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1919                                         EVP_DigestFinal_ex(&md_ctx,q,
1920                                                 (unsigned int *)&i);
1921                                         q+=i;
1922                                         j+=i;
1923                                         }
1924                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1925                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1926                                         {
1927                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1928                                         goto err;
1929                                         }
1930                                 s2n(u,p);
1931                                 n+=u+2;
1932                                 }
1933                         else
1934 #endif
1935                         if (md)
1936                                 {
1937                                 /* For TLS1.2 and later send signature
1938                                  * algorithm */
1939                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
1940                                         {
1941                                         if (!tls12_get_sigandhash(p, pkey, md))
1942                                                 {
1943                                                 /* Should never happen */
1944                                                 al=SSL_AD_INTERNAL_ERROR;
1945                                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1946                                                 goto f_err;
1947                                                 }
1948                                         p+=2;
1949                                         }
1950 #ifdef SSL_DEBUG
1951                                 fprintf(stderr, "Using hash %s\n",
1952                                                         EVP_MD_name(md));
1953 #endif
1954                                 EVP_SignInit_ex(&md_ctx, md, NULL);
1955                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1956                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1957                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1958                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1959                                         (unsigned int *)&i,pkey))
1960                                         {
1961                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
1962                                         goto err;
1963                                         }
1964                                 s2n(i,p);
1965                                 n+=i+2;
1966                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
1967                                         n+= 2;
1968                                 }
1969                         else
1970                                 {
1971                                 /* Is this error check actually needed? */
1972                                 al=SSL_AD_HANDSHAKE_FAILURE;
1973                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1974                                 goto f_err;
1975                                 }
1976                         }
1977
1978                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1979                 l2n3(n,d);
1980
1981                 /* we should now have things packed up, so lets send
1982                  * it off */
1983                 s->init_num=n+4;
1984                 s->init_off=0;
1985                 }
1986
1987         s->state = SSL3_ST_SW_KEY_EXCH_B;
1988         EVP_MD_CTX_cleanup(&md_ctx);
1989         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1990 f_err:
1991         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1992 err:
1993 #ifndef OPENSSL_NO_ECDH
1994         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1995         BN_CTX_free(bn_ctx);
1996 #endif
1997         EVP_MD_CTX_cleanup(&md_ctx);
1998         return(-1);
1999         }
2000
2001 int ssl3_send_certificate_request(SSL *s)
2002         {
2003         unsigned char *p,*d;
2004         int i,j,nl,off,n;
2005         STACK_OF(X509_NAME) *sk=NULL;
2006         X509_NAME *name;
2007         BUF_MEM *buf;
2008
2009         if (s->state == SSL3_ST_SW_CERT_REQ_A)
2010                 {
2011                 buf=s->init_buf;
2012
2013                 d=p=(unsigned char *)&(buf->data[4]);
2014
2015                 /* get the list of acceptable cert types */
2016                 p++;
2017                 n=ssl3_get_req_cert_type(s,p);
2018                 d[0]=n;
2019                 p+=n;
2020                 n++;
2021
2022                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2023                         {
2024                         nl = tls12_get_req_sig_algs(s, p + 2);
2025                         s2n(nl, p);
2026                         p += nl + 2;
2027                         n += nl + 2;
2028                         }
2029
2030                 off=n;
2031                 p+=2;
2032                 n+=2;
2033
2034                 sk=SSL_get_client_CA_list(s);
2035                 nl=0;
2036                 if (sk != NULL)
2037                         {
2038                         for (i=0; i<sk_X509_NAME_num(sk); i++)
2039                                 {
2040                                 name=sk_X509_NAME_value(sk,i);
2041                                 j=i2d_X509_NAME(name,NULL);
2042                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
2043                                         {
2044                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2045                                         goto err;
2046                                         }
2047                                 p=(unsigned char *)&(buf->data[4+n]);
2048                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2049                                         {
2050                                         s2n(j,p);
2051                                         i2d_X509_NAME(name,&p);
2052                                         n+=2+j;
2053                                         nl+=2+j;
2054                                         }
2055                                 else
2056                                         {
2057                                         d=p;
2058                                         i2d_X509_NAME(name,&p);
2059                                         j-=2; s2n(j,d); j+=2;
2060                                         n+=j;
2061                                         nl+=j;
2062                                         }
2063                                 }
2064                         }
2065                 /* else no CA names */
2066                 p=(unsigned char *)&(buf->data[4+off]);
2067                 s2n(nl,p);
2068
2069                 d=(unsigned char *)buf->data;
2070                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
2071                 l2n3(n,d);
2072
2073                 /* we should now have things packed up, so lets send
2074                  * it off */
2075
2076                 s->init_num=n+4;
2077                 s->init_off=0;
2078 #ifdef NETSCAPE_HANG_BUG
2079                 p=(unsigned char *)s->init_buf->data + s->init_num;
2080
2081                 /* do the header */
2082                 *(p++)=SSL3_MT_SERVER_DONE;
2083                 *(p++)=0;
2084                 *(p++)=0;
2085                 *(p++)=0;
2086                 s->init_num += 4;
2087 #endif
2088
2089                 s->state = SSL3_ST_SW_CERT_REQ_B;
2090                 }
2091
2092         /* SSL3_ST_SW_CERT_REQ_B */
2093         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2094 err:
2095         return(-1);
2096         }
2097
2098 int ssl3_get_client_key_exchange(SSL *s)
2099         {
2100         int i,al,ok;
2101         long n;
2102         unsigned long alg_k;
2103         unsigned char *p;
2104 #ifndef OPENSSL_NO_RSA
2105         RSA *rsa=NULL;
2106         EVP_PKEY *pkey=NULL;
2107 #endif
2108 #ifndef OPENSSL_NO_DH
2109         BIGNUM *pub=NULL;
2110         DH *dh_srvr;
2111 #endif
2112 #ifndef OPENSSL_NO_KRB5
2113         KSSL_ERR kssl_err;
2114 #endif /* OPENSSL_NO_KRB5 */
2115
2116 #ifndef OPENSSL_NO_ECDH
2117         EC_KEY *srvr_ecdh = NULL;
2118         EVP_PKEY *clnt_pub_pkey = NULL;
2119         EC_POINT *clnt_ecpoint = NULL;
2120         BN_CTX *bn_ctx = NULL; 
2121 #endif
2122
2123         n=s->method->ssl_get_message(s,
2124                 SSL3_ST_SR_KEY_EXCH_A,
2125                 SSL3_ST_SR_KEY_EXCH_B,
2126                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2127                 2048, /* ??? */
2128                 &ok);
2129
2130         if (!ok) return((int)n);
2131         p=(unsigned char *)s->init_msg;
2132
2133         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2134
2135 #ifndef OPENSSL_NO_RSA
2136         if (alg_k & SSL_kRSA)
2137                 {
2138                 /* FIX THIS UP EAY EAY EAY EAY */
2139                 if (s->s3->tmp.use_rsa_tmp)
2140                         {
2141                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2142                                 rsa=s->cert->rsa_tmp;
2143                         /* Don't do a callback because rsa_tmp should
2144                          * be sent already */
2145                         if (rsa == NULL)
2146                                 {
2147                                 al=SSL_AD_HANDSHAKE_FAILURE;
2148                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2149                                 goto f_err;
2150
2151                                 }
2152                         }
2153                 else
2154                         {
2155                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2156                         if (    (pkey == NULL) ||
2157                                 (pkey->type != EVP_PKEY_RSA) ||
2158                                 (pkey->pkey.rsa == NULL))
2159                                 {
2160                                 al=SSL_AD_HANDSHAKE_FAILURE;
2161                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2162                                 goto f_err;
2163                                 }
2164                         rsa=pkey->pkey.rsa;
2165                         }
2166
2167                 /* TLS and [incidentally] DTLS{0xFEFF} */
2168                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2169                         {
2170                         n2s(p,i);
2171                         if (n != i+2)
2172                                 {
2173                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2174                                         {
2175                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2176                                         goto err;
2177                                         }
2178                                 else
2179                                         p-=2;
2180                                 }
2181                         else
2182                                 n=i;
2183                         }
2184
2185                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2186
2187                 al = -1;
2188                 
2189                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
2190                         {
2191                         al=SSL_AD_DECODE_ERROR;
2192                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
2193                         }
2194
2195                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
2196                         {
2197                         /* The premaster secret must contain the same version number as the
2198                          * ClientHello to detect version rollback attacks (strangely, the
2199                          * protocol does not offer such protection for DH ciphersuites).
2200                          * However, buggy clients exist that send the negotiated protocol
2201                          * version instead if the server does not support the requested
2202                          * protocol version.
2203                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2204                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
2205                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
2206                                 {
2207                                 al=SSL_AD_DECODE_ERROR;
2208                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
2209
2210                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2211                                  * (http://eprint.iacr.org/2003/052/) exploits the version
2212                                  * number check as a "bad version oracle" -- an alert would
2213                                  * reveal that the plaintext corresponding to some ciphertext
2214                                  * made up by the adversary is properly formatted except
2215                                  * that the version number is wrong.  To avoid such attacks,
2216                                  * we should treat this just like any other decryption error. */
2217                                 }
2218                         }
2219
2220                 if (al != -1)
2221                         {
2222                         /* Some decryption failure -- use random value instead as countermeasure
2223                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
2224                          * (see RFC 2246, section 7.4.7.1). */
2225                         ERR_clear_error();
2226                         i = SSL_MAX_MASTER_KEY_LENGTH;
2227                         p[0] = s->client_version >> 8;
2228                         p[1] = s->client_version & 0xff;
2229                         if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */
2230                                 goto err;
2231                         }
2232         
2233                 s->session->master_key_length=
2234                         s->method->ssl3_enc->generate_master_secret(s,
2235                                 s->session->master_key,
2236                                 p,i);
2237                 OPENSSL_cleanse(p,i);
2238                 }
2239         else
2240 #endif
2241 #ifndef OPENSSL_NO_DH
2242                 if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2243                 {
2244                 n2s(p,i);
2245                 if (n != i+2)
2246                         {
2247                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2248                                 {
2249                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2250                                 goto err;
2251                                 }
2252                         else
2253                                 {
2254                                 p-=2;
2255                                 i=(int)n;
2256                                 }
2257                         }
2258
2259                 if (n == 0L) /* the parameters are in the cert */
2260                         {
2261                         al=SSL_AD_HANDSHAKE_FAILURE;
2262                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
2263                         goto f_err;
2264                         }
2265                 else
2266                         {
2267                         if (s->s3->tmp.dh == NULL)
2268                                 {
2269                                 al=SSL_AD_HANDSHAKE_FAILURE;
2270                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2271                                 goto f_err;
2272                                 }
2273                         else
2274                                 dh_srvr=s->s3->tmp.dh;
2275                         }
2276
2277                 pub=BN_bin2bn(p,i,NULL);
2278                 if (pub == NULL)
2279                         {
2280                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2281                         goto err;
2282                         }
2283
2284                 i=DH_compute_key(p,pub,dh_srvr);
2285
2286                 if (i <= 0)
2287                         {
2288                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2289                         goto err;
2290                         }
2291
2292                 DH_free(s->s3->tmp.dh);
2293                 s->s3->tmp.dh=NULL;
2294
2295                 BN_clear_free(pub);
2296                 pub=NULL;
2297                 s->session->master_key_length=
2298                         s->method->ssl3_enc->generate_master_secret(s,
2299                                 s->session->master_key,p,i);
2300                 OPENSSL_cleanse(p,i);
2301                 }
2302         else
2303 #endif
2304 #ifndef OPENSSL_NO_KRB5
2305         if (alg_k & SSL_kKRB5)
2306                 {
2307                 krb5_error_code         krb5rc;
2308                 krb5_data               enc_ticket;
2309                 krb5_data               authenticator;
2310                 krb5_data               enc_pms;
2311                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
2312                 EVP_CIPHER_CTX          ciph_ctx;
2313                 const EVP_CIPHER        *enc = NULL;
2314                 unsigned char           iv[EVP_MAX_IV_LENGTH];
2315                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
2316                                                + EVP_MAX_BLOCK_LENGTH];
2317                 int                  padl, outl;
2318                 krb5_timestamp          authtime = 0;
2319                 krb5_ticket_times       ttimes;
2320
2321                 EVP_CIPHER_CTX_init(&ciph_ctx);
2322
2323                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2324
2325                 n2s(p,i);
2326                 enc_ticket.length = i;
2327
2328                 if (n < (long)(enc_ticket.length + 6))
2329                         {
2330                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2331                                 SSL_R_DATA_LENGTH_TOO_LONG);
2332                         goto err;
2333                         }
2334
2335                 enc_ticket.data = (char *)p;
2336                 p+=enc_ticket.length;
2337
2338                 n2s(p,i);
2339                 authenticator.length = i;
2340
2341                 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2342                         {
2343                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2344                                 SSL_R_DATA_LENGTH_TOO_LONG);
2345                         goto err;
2346                         }
2347
2348                 authenticator.data = (char *)p;
2349                 p+=authenticator.length;
2350
2351                 n2s(p,i);
2352                 enc_pms.length = i;
2353                 enc_pms.data = (char *)p;
2354                 p+=enc_pms.length;
2355
2356                 /* Note that the length is checked again below,
2357                 ** after decryption
2358                 */
2359                 if(enc_pms.length > sizeof pms)
2360                         {
2361                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2362                                SSL_R_DATA_LENGTH_TOO_LONG);
2363                         goto err;
2364                         }
2365
2366                 if (n != (long)(enc_ticket.length + authenticator.length +
2367                                                 enc_pms.length + 6))
2368                         {
2369                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2370                                 SSL_R_DATA_LENGTH_TOO_LONG);
2371                         goto err;
2372                         }
2373
2374                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2375                                         &kssl_err)) != 0)
2376                         {
2377 #ifdef KSSL_DEBUG
2378                         printf("kssl_sget_tkt rtn %d [%d]\n",
2379                                 krb5rc, kssl_err.reason);
2380                         if (kssl_err.text)
2381                                 printf("kssl_err text= %s\n", kssl_err.text);
2382 #endif  /* KSSL_DEBUG */
2383                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2384                                 kssl_err.reason);
2385                         goto err;
2386                         }
2387
2388                 /*  Note: no authenticator is not considered an error,
2389                 **  but will return authtime == 0.
2390                 */
2391                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2392                                         &authtime, &kssl_err)) != 0)
2393                         {
2394 #ifdef KSSL_DEBUG
2395                         printf("kssl_check_authent rtn %d [%d]\n",
2396                                 krb5rc, kssl_err.reason);
2397                         if (kssl_err.text)
2398                                 printf("kssl_err text= %s\n", kssl_err.text);
2399 #endif  /* KSSL_DEBUG */
2400                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2401                                 kssl_err.reason);
2402                         goto err;
2403                         }
2404
2405                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2406                         {
2407                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2408                         goto err;
2409                         }
2410
2411 #ifdef KSSL_DEBUG
2412                 kssl_ctx_show(kssl_ctx);
2413 #endif  /* KSSL_DEBUG */
2414
2415                 enc = kssl_map_enc(kssl_ctx->enctype);
2416                 if (enc == NULL)
2417                     goto err;
2418
2419                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2420
2421                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2422                         {
2423                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2424                                 SSL_R_DECRYPTION_FAILED);
2425                         goto err;
2426                         }
2427                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2428                                         (unsigned char *)enc_pms.data, enc_pms.length))
2429                         {
2430                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2431                                 SSL_R_DECRYPTION_FAILED);
2432                         goto err;
2433                         }
2434                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2435                         {
2436                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2437                                 SSL_R_DATA_LENGTH_TOO_LONG);
2438                         goto err;
2439                         }
2440                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2441                         {
2442                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2443                                 SSL_R_DECRYPTION_FAILED);
2444                         goto err;
2445                         }
2446                 outl += padl;
2447                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2448                         {
2449                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2450                                 SSL_R_DATA_LENGTH_TOO_LONG);
2451                         goto err;
2452                         }
2453                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2454                     {
2455                     /* The premaster secret must contain the same version number as the
2456                      * ClientHello to detect version rollback attacks (strangely, the
2457                      * protocol does not offer such protection for DH ciphersuites).
2458                      * However, buggy clients exist that send random bytes instead of
2459                      * the protocol version.
2460                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2461                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2462                      */
2463                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2464                         {
2465                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2466                                SSL_AD_DECODE_ERROR);
2467                         goto err;
2468                         }
2469                     }
2470
2471                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2472
2473                 s->session->master_key_length=
2474                         s->method->ssl3_enc->generate_master_secret(s,
2475                                 s->session->master_key, pms, outl);
2476
2477                 if (kssl_ctx->client_princ)
2478                         {
2479                         size_t len = strlen(kssl_ctx->client_princ);
2480                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2481                                 {
2482                                 s->session->krb5_client_princ_len = len;
2483                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2484                                 }
2485                         }
2486
2487
2488                 /*  Was doing kssl_ctx_free() here,
2489                 **  but it caused problems for apache.
2490                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2491                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2492                 */
2493                 }
2494         else
2495 #endif  /* OPENSSL_NO_KRB5 */
2496
2497 #ifndef OPENSSL_NO_ECDH
2498                 if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2499                 {
2500                 int ret = 1;
2501                 int field_size = 0;
2502                 const EC_KEY   *tkey;
2503                 const EC_GROUP *group;
2504                 const BIGNUM *priv_key;
2505
2506                 /* initialize structures for server's ECDH key pair */
2507                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2508                         {
2509                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2510                             ERR_R_MALLOC_FAILURE);
2511                         goto err;
2512                         }
2513
2514                 /* Let's get server private key and group information */
2515                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2516                         { 
2517                         /* use the certificate */
2518                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2519                         }
2520                 else
2521                         {
2522                         /* use the ephermeral values we saved when
2523                          * generating the ServerKeyExchange msg.
2524                          */
2525                         tkey = s->s3->tmp.ecdh;
2526                         }
2527
2528                 group    = EC_KEY_get0_group(tkey);
2529                 priv_key = EC_KEY_get0_private_key(tkey);
2530
2531                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2532                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2533                         {
2534                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2535                                ERR_R_EC_LIB);
2536                         goto err;
2537                         }
2538
2539                 /* Let's get client's public key */
2540                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2541                         {
2542                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2543                             ERR_R_MALLOC_FAILURE);
2544                         goto err;
2545                         }
2546
2547                 if (n == 0L) 
2548                         {
2549                         /* Client Publickey was in Client Certificate */
2550
2551                          if (alg_k & SSL_kEECDH)
2552                                  {
2553                                  al=SSL_AD_HANDSHAKE_FAILURE;
2554                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2555                                  goto f_err;
2556                                  }
2557                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2558                             == NULL) || 
2559                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2560                                 {
2561                                 /* XXX: For now, we do not support client
2562                                  * authentication using ECDH certificates
2563                                  * so this branch (n == 0L) of the code is
2564                                  * never executed. When that support is
2565                                  * added, we ought to ensure the key 
2566                                  * received in the certificate is 
2567                                  * authorized for key agreement.
2568                                  * ECDH_compute_key implicitly checks that
2569                                  * the two ECDH shares are for the same
2570                                  * group.
2571                                  */
2572                                 al=SSL_AD_HANDSHAKE_FAILURE;
2573                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2574                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2575                                 goto f_err;
2576                                 }
2577
2578                         if (EC_POINT_copy(clnt_ecpoint,
2579                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2580                                 {
2581                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2582                                         ERR_R_EC_LIB);
2583                                 goto err;
2584                                 }
2585                         ret = 2; /* Skip certificate verify processing */
2586                         }
2587                 else
2588                         {
2589                         /* Get client's public key from encoded point
2590                          * in the ClientKeyExchange message.
2591                          */
2592                         if ((bn_ctx = BN_CTX_new()) == NULL)
2593                                 {
2594                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2595                                     ERR_R_MALLOC_FAILURE);
2596                                 goto err;
2597                                 }
2598
2599                         /* Get encoded point length */
2600                         i = *p; 
2601                         p += 1;
2602                         if (n != 1 + i)
2603                                 {
2604                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2605                                     ERR_R_EC_LIB);
2606                                 goto err;
2607                                 }
2608                         if (EC_POINT_oct2point(group, 
2609                             clnt_ecpoint, p, i, bn_ctx) == 0)
2610                                 {
2611                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2612                                     ERR_R_EC_LIB);
2613                                 goto err;
2614                                 }
2615                         /* p is pointing to somewhere in the buffer
2616                          * currently, so set it to the start 
2617                          */ 
2618                         p=(unsigned char *)s->init_buf->data;
2619                         }
2620
2621                 /* Compute the shared pre-master secret */
2622                 field_size = EC_GROUP_get_degree(group);
2623                 if (field_size <= 0)
2624                         {
2625                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2626                                ERR_R_ECDH_LIB);
2627                         goto err;
2628                         }
2629                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2630                 if (i <= 0)
2631                         {
2632                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2633                             ERR_R_ECDH_LIB);
2634                         goto err;
2635                         }
2636
2637                 EVP_PKEY_free(clnt_pub_pkey);
2638                 EC_POINT_free(clnt_ecpoint);
2639                 EC_KEY_free(srvr_ecdh);
2640                 BN_CTX_free(bn_ctx);
2641                 EC_KEY_free(s->s3->tmp.ecdh);
2642                 s->s3->tmp.ecdh = NULL; 
2643
2644                 /* Compute the master secret */
2645                 s->session->master_key_length = s->method->ssl3_enc-> \
2646                     generate_master_secret(s, s->session->master_key, p, i);
2647                 
2648                 OPENSSL_cleanse(p, i);
2649                 return (ret);
2650                 }
2651         else
2652 #endif
2653 #ifndef OPENSSL_NO_PSK
2654                 if (alg_k & SSL_kPSK)
2655                         {
2656                         unsigned char *t = NULL;
2657                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2658                         unsigned int pre_ms_len = 0, psk_len = 0;
2659                         int psk_err = 1;
2660                         char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2661
2662                         al=SSL_AD_HANDSHAKE_FAILURE;
2663
2664                         n2s(p,i);
2665                         if (n != i+2)
2666                                 {
2667                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2668                                         SSL_R_LENGTH_MISMATCH);
2669                                 goto psk_err;
2670                                 }
2671                         if (i > PSK_MAX_IDENTITY_LEN)
2672                                 {
2673                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2674                                         SSL_R_DATA_LENGTH_TOO_LONG);
2675                                 goto psk_err;
2676                                 }
2677                         if (s->psk_server_callback == NULL)
2678                                 {
2679                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2680                                        SSL_R_PSK_NO_SERVER_CB);
2681                                 goto psk_err;
2682                                 }
2683
2684                         /* Create guaranteed NULL-terminated identity
2685                          * string for the callback */
2686                         memcpy(tmp_id, p, i);
2687                         memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2688                         psk_len = s->psk_server_callback(s, tmp_id,
2689                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2690                         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2691
2692                         if (psk_len > PSK_MAX_PSK_LEN)
2693                                 {
2694                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2695                                         ERR_R_INTERNAL_ERROR);
2696                                 goto psk_err;
2697                                 }
2698                         else if (psk_len == 0)
2699                                 {
2700                                 /* PSK related to the given identity not found */
2701                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2702                                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2703                                 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2704                                 goto psk_err;
2705                                 }
2706
2707                         /* create PSK pre_master_secret */
2708                         pre_ms_len=2+psk_len+2+psk_len;
2709                         t = psk_or_pre_ms;
2710                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2711                         s2n(psk_len, t);
2712                         memset(t, 0, psk_len);
2713                         t+=psk_len;
2714                         s2n(psk_len, t);
2715
2716                         if (s->session->psk_identity != NULL)
2717                                 OPENSSL_free(s->session->psk_identity);
2718                         s->session->psk_identity = BUF_strdup((char *)p);
2719                         if (s->session->psk_identity == NULL)
2720                                 {
2721                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2722                                         ERR_R_MALLOC_FAILURE);
2723                                 goto psk_err;
2724                                 }
2725
2726                         if (s->session->psk_identity_hint != NULL)
2727                                 OPENSSL_free(s->session->psk_identity_hint);
2728                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2729                         if (s->ctx->psk_identity_hint != NULL &&
2730                                 s->session->psk_identity_hint == NULL)
2731                                 {
2732                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2733                                         ERR_R_MALLOC_FAILURE);
2734                                 goto psk_err;
2735                                 }
2736
2737                         s->session->master_key_length=
2738                                 s->method->ssl3_enc->generate_master_secret(s,
2739                                         s->session->master_key, psk_or_pre_ms, pre_ms_len);
2740                         psk_err = 0;
2741                 psk_err:
2742                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2743                         if (psk_err != 0)
2744                                 goto f_err;
2745                         }
2746                 else
2747 #endif
2748 #ifndef OPENSSL_NO_SRP
2749                 if (alg_k & SSL_kSRP)
2750                         {
2751                         int param_len;
2752
2753                         n2s(p,i);
2754                         param_len=i+2;
2755                         if (param_len > n)
2756                                 {
2757                                 al=SSL_AD_DECODE_ERROR;
2758                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2759                                 goto f_err;
2760                                 }
2761                         if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2762                                 {
2763                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2764                                 goto err;
2765                                 }
2766                         if (s->session->srp_username != NULL)
2767                                 OPENSSL_free(s->session->srp_username);
2768                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2769                         if (s->session->srp_username == NULL)
2770                                 {
2771                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2772                                         ERR_R_MALLOC_FAILURE);
2773                                 goto err;
2774                                 }
2775
2776                         if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2777                                 {
2778                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2779                                 goto err;
2780                                 }
2781
2782                         p+=i;
2783                         }
2784                 else
2785 #endif  /* OPENSSL_NO_SRP */
2786                 if (alg_k & SSL_kGOST) 
2787                         {
2788                         int ret = 0;
2789                         EVP_PKEY_CTX *pkey_ctx;
2790                         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2791                         unsigned char premaster_secret[32], *start;
2792                         size_t outlen=32, inlen;
2793                         unsigned long alg_a;
2794
2795                         /* Get our certificate private key*/
2796                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2797                         if (alg_a & SSL_aGOST94)
2798                                 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2799                         else if (alg_a & SSL_aGOST01)
2800                                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2801
2802                         pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2803                         EVP_PKEY_decrypt_init(pkey_ctx);
2804                         /* If client certificate is present and is of the same type, maybe
2805                          * use it for key exchange.  Don't mind errors from
2806                          * EVP_PKEY_derive_set_peer, because it is completely valid to use
2807                          * a client certificate for authorization only. */
2808                         client_pub_pkey = X509_get_pubkey(s->session->peer);
2809                         if (client_pub_pkey)
2810                                 {
2811                                 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2812                                         ERR_clear_error();
2813                                 }
2814                         /* Decrypt session key */
2815                         if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED))) 
2816                                 {
2817                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2818                                 goto gerr;
2819                                 }
2820                         if (p[1] == 0x81)
2821                                 {
2822                                 start = p+3;
2823                                 inlen = p[2];
2824                                 }
2825                         else if (p[1] < 0x80)
2826                                 {
2827                                 start = p+2;
2828                                 inlen = p[1];
2829                                 }
2830                         else
2831                                 {
2832                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2833                                 goto gerr;
2834                                 }
2835                         if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
2836
2837                                 {
2838                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2839                                 goto gerr;
2840                                 }
2841                         /* Generate master secret */
2842                         s->session->master_key_length=
2843                                 s->method->ssl3_enc->generate_master_secret(s,
2844                                         s->session->master_key,premaster_secret,32);
2845                         /* Check if pubkey from client certificate was used */
2846                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2847                                 ret = 2;
2848                         else
2849                                 ret = 1;
2850                 gerr:
2851                         EVP_PKEY_free(client_pub_pkey);
2852                         EVP_PKEY_CTX_free(pkey_ctx);
2853                         if (ret)
2854                                 return ret;
2855                         else
2856                                 goto err;
2857                         }
2858                 else
2859                 {
2860                 al=SSL_AD_HANDSHAKE_FAILURE;
2861                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2862                                 SSL_R_UNKNOWN_CIPHER_TYPE);
2863                 goto f_err;
2864                 }
2865
2866         return(1);
2867 f_err:
2868         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2869 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2870 err:
2871 #endif
2872 #ifndef OPENSSL_NO_ECDH
2873         EVP_PKEY_free(clnt_pub_pkey);
2874         EC_POINT_free(clnt_ecpoint);
2875         if (srvr_ecdh != NULL) 
2876                 EC_KEY_free(srvr_ecdh);
2877         BN_CTX_free(bn_ctx);
2878 #endif
2879         return(-1);
2880         }
2881
2882 int ssl3_get_cert_verify(SSL *s)
2883         {
2884         EVP_PKEY *pkey=NULL;
2885         unsigned char *p;
2886         int al,ok,ret=0;
2887         long n;
2888         int type=0,i,j;
2889         X509 *peer;
2890         const EVP_MD *md = NULL;
2891         EVP_MD_CTX mctx;
2892         EVP_MD_CTX_init(&mctx);
2893
2894         n=s->method->ssl_get_message(s,
2895                 SSL3_ST_SR_CERT_VRFY_A,
2896                 SSL3_ST_SR_CERT_VRFY_B,
2897                 -1,
2898                 514, /* 514? */
2899                 &ok);
2900
2901         if (!ok) return((int)n);
2902
2903         if (s->session->peer != NULL)
2904                 {
2905                 peer=s->session->peer;
2906                 pkey=X509_get_pubkey(peer);
2907                 type=X509_certificate_type(peer,pkey);
2908                 }
2909         else
2910                 {
2911                 peer=NULL;
2912                 pkey=NULL;
2913                 }
2914
2915         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
2916                 {
2917                 s->s3->tmp.reuse_message=1;
2918                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
2919                         {
2920                         al=SSL_AD_UNEXPECTED_MESSAGE;
2921                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
2922                         goto f_err;
2923                         }
2924                 ret=1;
2925                 goto end;
2926                 }
2927
2928         if (peer == NULL)
2929                 {
2930                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
2931                 al=SSL_AD_UNEXPECTED_MESSAGE;
2932                 goto f_err;
2933                 }
2934
2935         if (!(type & EVP_PKT_SIGN))
2936                 {
2937                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2938                 al=SSL_AD_ILLEGAL_PARAMETER;
2939                 goto f_err;
2940                 }
2941
2942         if (s->s3->change_cipher_spec)
2943                 {
2944                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
2945                 al=SSL_AD_UNEXPECTED_MESSAGE;
2946                 goto f_err;
2947                 }
2948
2949         /* we now have a signature that we need to verify */
2950         p=(unsigned char *)s->init_msg;
2951         /* Check for broken implementations of GOST ciphersuites */
2952         /* If key is GOST and n is exactly 64, it is bare
2953          * signature without length field */
2954         if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
2955                 pkey->type == NID_id_GostR3410_2001) )
2956                 {
2957                 i=64;
2958                 } 
2959         else 
2960                 {       
2961                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2962                         {
2963                         int sigalg = tls12_get_sigid(pkey);
2964                         /* Should never happen */
2965                         if (sigalg == -1)
2966                                 {
2967                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
2968                                 al=SSL_AD_INTERNAL_ERROR;
2969                                 goto f_err;
2970                                 }
2971                         /* Check key type is consistent with signature */
2972                         if (sigalg != (int)p[1])
2973                                 {
2974                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_TYPE);
2975                                 al=SSL_AD_DECODE_ERROR;
2976                                 goto f_err;
2977                                 }
2978                         md = tls12_get_hash(p[0]);
2979                         if (md == NULL)
2980                                 {
2981                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_UNKNOWN_DIGEST);
2982                                 al=SSL_AD_DECODE_ERROR;
2983                                 goto f_err;
2984                                 }
2985 #ifdef SSL_DEBUG
2986 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2987 #endif
2988                         p += 2;
2989                         n -= 2;
2990                         }
2991                 n2s(p,i);
2992                 n-=2;
2993                 if (i > n)
2994                         {
2995                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
2996                         al=SSL_AD_DECODE_ERROR;
2997                         goto f_err;
2998                         }
2999         }
3000         j=EVP_PKEY_size(pkey);
3001         if ((i > j) || (n > j) || (n <= 0))
3002                 {
3003                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3004                 al=SSL_AD_DECODE_ERROR;
3005                 goto f_err;
3006                 }
3007
3008         if (TLS1_get_version(s) >= TLS1_2_VERSION)
3009                 {
3010                 long hdatalen = 0;
3011                 void *hdata;
3012                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3013                 if (hdatalen <= 0)
3014                         {
3015                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3016                         al=SSL_AD_INTERNAL_ERROR;
3017                         goto f_err;
3018                         }
3019 #ifdef SSL_DEBUG
3020                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3021                                                         EVP_MD_name(md));
3022 #endif
3023                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3024                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3025                         {
3026                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3027                         al=SSL_AD_INTERNAL_ERROR;
3028                         goto f_err;
3029                         }
3030
3031                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3032                         {
3033                         al=SSL_AD_DECRYPT_ERROR;
3034                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3035                         goto f_err;
3036                         }
3037                 }
3038         else
3039 #ifndef OPENSSL_NO_RSA 
3040         if (pkey->type == EVP_PKEY_RSA)
3041                 {
3042                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3043                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3044                                                         pkey->pkey.rsa);
3045                 if (i < 0)
3046                         {
3047                         al=SSL_AD_DECRYPT_ERROR;
3048                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3049                         goto f_err;
3050                         }
3051                 if (i == 0)
3052                         {
3053                         al=SSL_AD_DECRYPT_ERROR;
3054                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3055                         goto f_err;
3056                         }
3057                 }
3058         else
3059 #endif
3060 #ifndef OPENSSL_NO_DSA
3061                 if (pkey->type == EVP_PKEY_DSA)
3062                 {
3063                 j=DSA_verify(pkey->save_type,
3064                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3065                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3066                 if (j <= 0)
3067                         {
3068                         /* bad signature */
3069                         al=SSL_AD_DECRYPT_ERROR;
3070                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3071                         goto f_err;
3072                         }
3073                 }
3074         else
3075 #endif
3076 #ifndef OPENSSL_NO_ECDSA
3077                 if (pkey->type == EVP_PKEY_EC)
3078                 {
3079                 j=ECDSA_verify(pkey->save_type,
3080                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3081                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3082                 if (j <= 0)
3083                         {
3084                         /* bad signature */
3085                         al=SSL_AD_DECRYPT_ERROR;
3086                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3087                             SSL_R_BAD_ECDSA_SIGNATURE);
3088                         goto f_err;
3089                         }
3090                 }
3091         else
3092 #endif
3093         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3094                 {   unsigned char signature[64];
3095                         int idx;
3096                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3097                         EVP_PKEY_verify_init(pctx);
3098                         if (i!=64) {
3099                                 fprintf(stderr,"GOST signature length is %d",i);
3100                         }       
3101                         for (idx=0;idx<64;idx++) {
3102                                 signature[63-idx]=p[idx];
3103                         }       
3104                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3105                         EVP_PKEY_CTX_free(pctx);
3106                         if (j<=0) 
3107                                 {
3108                                 al=SSL_AD_DECRYPT_ERROR;
3109                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3110                                         SSL_R_BAD_ECDSA_SIGNATURE);
3111                                 goto f_err;
3112                                 }       
3113                 }
3114         else    
3115                 {
3116                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3117                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3118                 goto f_err;
3119                 }
3120
3121
3122         ret=1;
3123         if (0)
3124                 {
3125 f_err:
3126                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3127                 }
3128 end:
3129         if (s->s3->handshake_buffer)
3130                 {
3131                 BIO_free(s->s3->handshake_buffer);
3132                 s->s3->handshake_buffer = NULL;
3133                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3134                 }
3135         EVP_MD_CTX_cleanup(&mctx);
3136         EVP_PKEY_free(pkey);
3137         return(ret);
3138         }
3139
3140 int ssl3_get_client_certificate(SSL *s)
3141         {
3142         int i,ok,al,ret= -1;
3143         X509 *x=NULL;
3144         unsigned long l,nc,llen,n;
3145         const unsigned char *p,*q;
3146         unsigned char *d;
3147         STACK_OF(X509) *sk=NULL;
3148
3149         n=s->method->ssl_get_message(s,
3150                 SSL3_ST_SR_CERT_A,
3151                 SSL3_ST_SR_CERT_B,
3152                 -1,
3153                 s->max_cert_list,
3154                 &ok);
3155
3156         if (!ok) return((int)n);
3157
3158         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3159                 {
3160                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3161                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3162                         {
3163                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3164                         al=SSL_AD_HANDSHAKE_FAILURE;
3165                         goto f_err;
3166                         }
3167                 /* If tls asked for a client cert, the client must return a 0 list */
3168                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3169                         {
3170                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3171                         al=SSL_AD_UNEXPECTED_MESSAGE;
3172                         goto f_err;
3173                         }
3174                 s->s3->tmp.reuse_message=1;
3175                 return(1);
3176                 }
3177
3178         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3179                 {
3180                 al=SSL_AD_UNEXPECTED_MESSAGE;
3181                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3182                 goto f_err;
3183                 }
3184         p=d=(unsigned char *)s->init_msg;
3185
3186         if ((sk=sk_X509_new_null()) == NULL)
3187                 {
3188                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3189                 goto err;
3190                 }
3191
3192         n2l3(p,llen);
3193         if (llen+3 != n)
3194                 {
3195                 al=SSL_AD_DECODE_ERROR;
3196                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3197                 goto f_err;
3198                 }
3199         for (nc=0; nc<llen; )
3200                 {
3201                 n2l3(p,l);
3202                 if ((l+nc+3) > llen)
3203                         {
3204                         al=SSL_AD_DECODE_ERROR;
3205                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3206                         goto f_err;
3207                         }
3208
3209                 q=p;
3210                 x=d2i_X509(NULL,&p,l);
3211                 if (x == NULL)
3212                         {
3213                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3214                         goto err;
3215                         }
3216                 if (p != (q+l))
3217                         {
3218                         al=SSL_AD_DECODE_ERROR;
3219                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3220                         goto f_err;
3221                         }
3222                 if (!sk_X509_push(sk,x))
3223                         {
3224                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3225                         goto err;
3226                         }
3227                 x=NULL;
3228                 nc+=l+3;
3229                 }
3230
3231         if (sk_X509_num(sk) <= 0)
3232                 {
3233                 /* TLS does not mind 0 certs returned */
3234                 if (s->version == SSL3_VERSION)
3235                         {
3236                         al=SSL_AD_HANDSHAKE_FAILURE;
3237                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3238                         goto f_err;
3239                         }
3240                 /* Fail for TLS only if we required a certificate */
3241                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3242                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3243                         {
3244                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3245                         al=SSL_AD_HANDSHAKE_FAILURE;
3246                         goto f_err;
3247                         }
3248                 /* No client certificate so digest cached records */
3249                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3250                         {
3251                         al=SSL_AD_INTERNAL_ERROR;
3252                         goto f_err;
3253                         }
3254                 }
3255         else
3256                 {
3257                 i=ssl_verify_cert_chain(s,sk);
3258                 if (i <= 0)
3259                         {
3260                         al=ssl_verify_alarm_type(s->verify_result);
3261                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
3262                         goto f_err;
3263                         }
3264                 }
3265
3266         if (s->session->peer != NULL) /* This should not be needed */
3267                 X509_free(s->session->peer);
3268         s->session->peer=sk_X509_shift(sk);
3269         s->session->verify_result = s->verify_result;
3270
3271         /* With the current implementation, sess_cert will always be NULL
3272          * when we arrive here. */
3273         if (s->session->sess_cert == NULL)
3274                 {
3275                 s->session->sess_cert = ssl_sess_cert_new();
3276                 if (s->session->sess_cert == NULL)
3277                         {
3278                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3279                         goto err;
3280                         }
3281                 }
3282         if (s->session->sess_cert->cert_chain != NULL)
3283                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3284         s->session->sess_cert->cert_chain=sk;
3285         /* Inconsistency alert: cert_chain does *not* include the
3286          * peer's own certificate, while we do include it in s3_clnt.c */
3287
3288         sk=NULL;
3289
3290         ret=1;
3291         if (0)
3292                 {
3293 f_err:
3294                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3295                 }
3296 err:
3297         if (x != NULL) X509_free(x);
3298         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3299         return(ret);
3300         }
3301
3302 int ssl3_send_server_certificate(SSL *s)
3303         {
3304         unsigned long l;
3305         X509 *x;
3306
3307         if (s->state == SSL3_ST_SW_CERT_A)
3308                 {
3309                 x=ssl_get_server_send_cert(s);
3310                 if (x == NULL)
3311                         {
3312                         /* VRS: allow null cert if auth == KRB5 */
3313                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3314                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3315                                 {
3316                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3317                                 return(0);
3318                                 }
3319                         }
3320
3321                 l=ssl3_output_cert_chain(s,x);
3322                 s->state=SSL3_ST_SW_CERT_B;
3323                 s->init_num=(int)l;
3324                 s->init_off=0;
3325                 }
3326
3327         /* SSL3_ST_SW_CERT_B */
3328         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3329         }
3330
3331 #ifndef OPENSSL_NO_TLSEXT
3332 /* send a new session ticket (not necessarily for a new session) */
3333 int ssl3_send_newsession_ticket(SSL *s)
3334         {
3335         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3336                 {
3337                 unsigned char *p, *senc, *macstart;
3338                 const unsigned char *const_p;
3339                 int len, slen_full, slen;
3340                 SSL_SESSION *sess;
3341                 unsigned int hlen;
3342                 EVP_CIPHER_CTX ctx;
3343                 HMAC_CTX hctx;
3344                 SSL_CTX *tctx = s->initial_ctx;
3345                 unsigned char iv[EVP_MAX_IV_LENGTH];
3346                 unsigned char key_name[16];
3347
3348                 /* get session encoding length */
3349                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3350                 /* Some length values are 16 bits, so forget it if session is
3351                  * too long
3352                  */
3353                 if (slen_full > 0xFF00)
3354                         return -1;
3355                 senc = OPENSSL_malloc(slen_full);
3356                 if (!senc)
3357                         return -1;
3358                 p = senc;
3359                 i2d_SSL_SESSION(s->session, &p);
3360
3361                 /* create a fresh copy (not shared with other threads) to clean up */
3362                 const_p = senc;
3363                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3364                 if (sess == NULL)
3365                         {
3366                         OPENSSL_free(senc);
3367                         return -1;
3368                         }
3369                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3370
3371                 slen = i2d_SSL_SESSION(sess, NULL);
3372                 if (slen > slen_full) /* shouldn't ever happen */
3373                         {
3374                         OPENSSL_free(senc);
3375                         return -1;
3376                         }
3377                 p = senc;
3378                 i2d_SSL_SESSION(sess, &p);
3379                 SSL_SESSION_free(sess);
3380
3381                 /* Grow buffer if need be: the length calculation is as
3382                  * follows 1 (size of message name) + 3 (message length
3383                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
3384                  * 16 (key name) + max_iv_len (iv length) +
3385                  * session_length + max_enc_block_size (max encrypted session
3386                  * length) + max_md_size (HMAC).
3387                  */
3388                 if (!BUF_MEM_grow(s->init_buf,
3389                         26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
3390                         EVP_MAX_MD_SIZE + slen))
3391                         return -1;
3392
3393                 p=(unsigned char *)s->init_buf->data;
3394                 /* do the header */
3395                 *(p++)=SSL3_MT_NEWSESSION_TICKET;
3396                 /* Skip message length for now */
3397                 p += 3;
3398                 EVP_CIPHER_CTX_init(&ctx);
3399                 HMAC_CTX_init(&hctx);
3400                 /* Initialize HMAC and cipher contexts. If callback present
3401                  * it does all the work otherwise use generated values
3402                  * from parent ctx.
3403                  */
3404                 if (tctx->tlsext_ticket_key_cb)
3405                         {
3406                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3407                                                          &hctx, 1) < 0)
3408                                 {
3409                                 OPENSSL_free(senc);
3410                                 return -1;
3411                                 }
3412                         }
3413                 else
3414                         {
3415                         RAND_pseudo_bytes(iv, 16);
3416                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3417                                         tctx->tlsext_tick_aes_key, iv);
3418                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3419                                         tlsext_tick_md(), NULL);
3420                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3421                         }
3422
3423                 /* Ticket lifetime hint (advisory only):
3424                  * We leave this unspecified for resumed session (for simplicity),
3425                  * and guess that tickets for new sessions will live as long
3426                  * as their sessions. */
3427                 l2n(s->hit ? 0 : s->session->timeout, p);
3428
3429                 /* Skip ticket length for now */
3430                 p += 2;
3431                 /* Output key name */
3432                 macstart = p;
3433                 memcpy(p, key_name, 16);
3434                 p += 16;
3435                 /* output IV */
3436                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3437                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3438                 /* Encrypt session data */
3439                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3440                 p += len;
3441                 EVP_EncryptFinal(&ctx, p, &len);
3442                 p += len;
3443                 EVP_CIPHER_CTX_cleanup(&ctx);
3444
3445                 HMAC_Update(&hctx, macstart, p - macstart);
3446                 HMAC_Final(&hctx, p, &hlen);
3447                 HMAC_CTX_cleanup(&hctx);
3448
3449                 p += hlen;
3450                 /* Now write out lengths: p points to end of data written */
3451                 /* Total length */
3452                 len = p - (unsigned char *)s->init_buf->data;
3453                 p=(unsigned char *)s->init_buf->data + 1;
3454                 l2n3(len - 4, p); /* Message length */
3455                 p += 4;
3456                 s2n(len - 10, p);  /* Ticket length */
3457
3458                 /* number of bytes to write */
3459                 s->init_num= len;
3460                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3461                 s->init_off=0;
3462                 OPENSSL_free(senc);
3463                 }
3464
3465         /* SSL3_ST_SW_SESSION_TICKET_B */
3466         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3467         }
3468
3469 int ssl3_send_cert_status(SSL *s)
3470         {
3471         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3472                 {
3473                 unsigned char *p;
3474                 /* Grow buffer if need be: the length calculation is as
3475                  * follows 1 (message type) + 3 (message length) +
3476                  * 1 (ocsp response type) + 3 (ocsp response length)
3477                  * + (ocsp response)
3478                  */
3479                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3480                         return -1;
3481
3482                 p=(unsigned char *)s->init_buf->data;
3483
3484                 /* do the header */
3485                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3486                 /* message length */
3487                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3488                 /* status type */
3489                 *(p++)= s->tlsext_status_type;
3490                 /* length of OCSP response */
3491                 l2n3(s->tlsext_ocsp_resplen, p);
3492                 /* actual response */
3493                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3494                 /* number of bytes to write */
3495                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3496                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3497                 s->init_off = 0;
3498                 }
3499
3500         /* SSL3_ST_SW_CERT_STATUS_B */
3501         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3502         }
3503
3504 # ifndef OPENSSL_NO_NEXTPROTONEG
3505 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3506  * sets the next_proto member in s if found */
3507 int ssl3_get_next_proto(SSL *s)
3508         {
3509         int ok;
3510         int proto_len, padding_len;
3511         long n;
3512         const unsigned char *p;
3513
3514         /* Clients cannot send a NextProtocol message if we didn't see the
3515          * extension in their ClientHello */
3516         if (!s->s3->next_proto_neg_seen)
3517                 {
3518                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3519                 return -1;
3520                 }
3521
3522         n=s->method->ssl_get_message(s,
3523                 SSL3_ST_SR_NEXT_PROTO_A,
3524                 SSL3_ST_SR_NEXT_PROTO_B,
3525                 SSL3_MT_NEXT_PROTO,
3526                 514,  /* See the payload format below */
3527                 &ok);
3528
3529         if (!ok)
3530                 return((int)n);
3531
3532         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3533          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3534          * by ssl3_get_finished). */
3535         if (!s->s3->change_cipher_spec)
3536                 {
3537                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3538                 return -1;
3539                 }
3540
3541         if (n < 2)
3542                 return 0;  /* The body must be > 1 bytes long */
3543
3544         p=(unsigned char *)s->init_msg;
3545
3546         /* The payload looks like:
3547          *   uint8 proto_len;
3548          *   uint8 proto[proto_len];
3549          *   uint8 padding_len;
3550          *   uint8 padding[padding_len];
3551          */
3552         proto_len = p[0];
3553         if (proto_len + 2 > s->init_num)
3554                 return 0;
3555         padding_len = p[proto_len + 1];
3556         if (proto_len + padding_len + 2 != s->init_num)
3557                 return 0;
3558
3559         s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3560         if (!s->next_proto_negotiated)
3561                 {
3562                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3563                 return 0;
3564                 }
3565         memcpy(s->next_proto_negotiated, p + 1, proto_len);
3566         s->next_proto_negotiated_len = proto_len;
3567
3568         return 1;
3569         }
3570 # endif
3571 #endif