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