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