7221fb0b3d416855ed71c217251fa4e28b362877
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / s3_srvr.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  * 
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  * 
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  * 
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from 
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  * 
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  * 
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer. 
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  *
113  * Portions of the attached software ("Contribution") are developed by 
114  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115  *
116  * The Contribution is licensed pursuant to the OpenSSL open source
117  * license provided above.
118  *
119  * ECC cipher suite support in OpenSSL originally written by
120  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121  *
122  */
123 /* ====================================================================
124  * Copyright 2005 Nokia. All rights reserved.
125  *
126  * The portions of the attached software ("Contribution") is developed by
127  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128  * license.
129  *
130  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132  * support (see RFC 4279) to OpenSSL.
133  *
134  * No patent licenses or other rights except those expressly stated in
135  * the OpenSSL open source license shall be deemed granted or received
136  * expressly, by implication, estoppel, or otherwise.
137  *
138  * No assurances are provided by Nokia that the Contribution does not
139  * infringe the patent or other intellectual property rights of any third
140  * party or that the license provides you with all the necessary rights
141  * to make use of the Contribution.
142  *
143  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147  * OTHERWISE. */
148
149 #define NETSCAPE_HANG_BUG
150
151 #include <stdio.h>
152 #include <string.h>
153
154 #include <openssl/bn.h>
155 #include <openssl/buf.h>
156 #include <openssl/bytestring.h>
157 #include <openssl/cipher.h>
158 #include <openssl/dh.h>
159 #include <openssl/ec.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/md5.h>
164 #include <openssl/mem.h>
165 #include <openssl/obj.h>
166 #include <openssl/rand.h>
167 #include <openssl/sha.h>
168 #include <openssl/x509.h>
169
170 #include "ssl_locl.h"
171 #include "../crypto/dh/internal.h"
172
173 static const SSL_METHOD *ssl3_get_server_method(int ver);
174
175 static const SSL_METHOD *ssl3_get_server_method(int ver)
176         {
177         if (ver == SSL3_VERSION)
178                 return(SSLv3_server_method());
179         else
180                 return(NULL);
181         }
182
183 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
184                         ssl3_accept,
185                         ssl_undefined_function,
186                         ssl3_get_server_method)
187
188 int ssl3_accept(SSL *s)
189         {
190         BUF_MEM *buf;
191         unsigned long alg_a;
192         void (*cb)(const SSL *ssl,int type,int val)=NULL;
193         int ret= -1;
194         int new_state,state,skip=0;
195
196         ERR_clear_error();
197         ERR_clear_system_error();
198
199         if (s->info_callback != NULL)
200                 cb=s->info_callback;
201         else if (s->ctx->info_callback != NULL)
202                 cb=s->ctx->info_callback;
203
204         /* init things to blank */
205         s->in_handshake++;
206         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
207
208         if (s->cert == NULL)
209                 {
210                 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
211                 return(-1);
212                 }
213
214         for (;;)
215                 {
216                 state=s->state;
217
218                 switch (s->state)
219                         {
220                 case SSL_ST_RENEGOTIATE:
221                         s->renegotiate=1;
222                         /* s->state=SSL_ST_ACCEPT; */
223
224                 case SSL_ST_BEFORE:
225                 case SSL_ST_ACCEPT:
226                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
227                 case SSL_ST_OK|SSL_ST_ACCEPT:
228
229                         s->server=1;
230                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
231
232                         if ((s->version>>8) != 3)
233                                 {
234                                 OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
235                                 return -1;
236                                 }
237                         s->type=SSL_ST_ACCEPT;
238
239                         if (s->init_buf == NULL)
240                                 {
241                                 if ((buf=BUF_MEM_new()) == NULL)
242                                         {
243                                         ret= -1;
244                                         goto end;
245                                         }
246                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
247                                         {
248                                         ret= -1;
249                                         goto end;
250                                         }
251                                 s->init_buf=buf;
252                                 }
253
254                         if (!ssl3_setup_buffers(s))
255                                 {
256                                 ret= -1;
257                                 goto end;
258                                 }
259
260                         s->init_num=0;
261                         s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
262                         s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
263
264                         if (s->state != SSL_ST_RENEGOTIATE)
265                                 {
266                                 /* Ok, we now need to push on a buffering BIO so that
267                                  * the output is sent in a way that TCP likes :-)
268                                  */
269                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
270                                 
271                                 ssl3_init_finished_mac(s);
272                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
273                                 s->ctx->stats.sess_accept++;
274                                 }
275                         else if (!s->s3->send_connection_binding &&
276                                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
277                                 {
278                                 /* Server attempting to renegotiate with
279                                  * client that doesn't support secure
280                                  * renegotiation.
281                                  */
282                                 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
283                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
284                                 ret = -1;
285                                 goto end;
286                                 }
287                         else
288                                 {
289                                 /* s->state == SSL_ST_RENEGOTIATE,
290                                  * we will just send a HelloRequest */
291                                 s->ctx->stats.sess_accept_renegotiate++;
292                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
293                                 }
294                         break;
295
296                 case SSL3_ST_SW_HELLO_REQ_A:
297                 case SSL3_ST_SW_HELLO_REQ_B:
298
299                         s->shutdown=0;
300                         ret=ssl3_send_hello_request(s);
301                         if (ret <= 0) goto end;
302                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
303                         s->state=SSL3_ST_SW_FLUSH;
304                         s->init_num=0;
305
306                         ssl3_init_finished_mac(s);
307                         break;
308
309                 case SSL3_ST_SW_HELLO_REQ_C:
310                         s->state=SSL_ST_OK;
311                         break;
312
313                 case SSL3_ST_SR_CLNT_HELLO_A:
314                 case SSL3_ST_SR_CLNT_HELLO_B:
315                 case SSL3_ST_SR_CLNT_HELLO_C:
316                 case SSL3_ST_SR_CLNT_HELLO_D:
317                         s->shutdown=0;
318                         ret=ssl3_get_client_hello(s);
319                         if (ret == PENDING_SESSION) {
320                                 s->rwstate = SSL_PENDING_SESSION;
321                                 goto end;
322                         }
323                         if (ret == CERTIFICATE_SELECTION_PENDING)
324                                 {
325                                 s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
326                                 goto end;
327                                 }
328                         if (ret <= 0) goto end;
329                         s->renegotiate = 2;
330                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
331                         s->init_num=0;
332                         break;
333
334                 case SSL3_ST_SW_SRVR_HELLO_A:
335                 case SSL3_ST_SW_SRVR_HELLO_B:
336                         ret=ssl3_send_server_hello(s);
337                         if (ret <= 0) goto end;
338                         if (s->hit)
339                                 {
340                                 if (s->tlsext_ticket_expected)
341                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
342                                 else
343                                         s->state=SSL3_ST_SW_CHANGE_A;
344                                 }
345                         else
346                                 s->state = SSL3_ST_SW_CERT_A;
347                         s->init_num = 0;
348                         break;
349
350                 case SSL3_ST_SW_CERT_A:
351                 case SSL3_ST_SW_CERT_B:
352                         if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
353                                 {
354                                 ret=ssl3_send_server_certificate(s);
355                                 if (ret <= 0) goto end;
356                                 if (s->tlsext_status_expected)
357                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
358                                 else
359                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
360                                 }
361                         else
362                                 {
363                                 skip = 1;
364                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
365                                 }
366                         s->init_num=0;
367                         break;
368
369                 case SSL3_ST_SW_KEY_EXCH_A:
370                 case SSL3_ST_SW_KEY_EXCH_B:
371                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
372
373                         /* Send a ServerKeyExchange message if:
374                          * - The key exchange is ephemeral or anonymous
375                          *   Diffie-Hellman.
376                          * - There is a PSK identity hint.
377                          *
378                          * TODO(davidben): This logic is currently duplicated
379                          * in d1_srvr.c. Fix this. In the meantime, keep them
380                          * in sync.
381                          */
382                         if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
383                             ((alg_a & SSL_aPSK) && s->session->psk_identity_hint))
384                                 {
385                                 ret=ssl3_send_server_key_exchange(s);
386                                 if (ret <= 0) goto end;
387                                 }
388                         else
389                                 skip=1;
390
391                         s->state=SSL3_ST_SW_CERT_REQ_A;
392                         s->init_num=0;
393                         break;
394
395                 case SSL3_ST_SW_CERT_REQ_A:
396                 case SSL3_ST_SW_CERT_REQ_B:
397                         if (/* don't request cert unless asked for it: */
398                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
399                                 /* Don't request a certificate if an obc was presented */
400                                 ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
401                                  s->s3->tlsext_channel_id_valid) ||
402                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
403                                  * don't request cert during re-negotiation: */
404                                 ((s->session->peer != NULL) &&
405                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
406                                 /* never request cert in anonymous ciphersuites
407                                  * (see section "Certificate request" in SSL 3 drafts
408                                  * and in RFC 2246): */
409                                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
410                                  /* ... except when the application insists on verification
411                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
412                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
413                                 /* With normal PSK Certificates and
414                                  * Certificate Requests are omitted */
415                                 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
416                                 {
417                                 /* no cert request */
418                                 skip=1;
419                                 s->s3->tmp.cert_request=0;
420                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
421                                 if (s->s3->handshake_buffer)
422                                         if (!ssl3_digest_cached_records(s))
423                                                 return -1;
424                                 }
425                         else
426                                 {
427                                 s->s3->tmp.cert_request=1;
428                                 ret=ssl3_send_certificate_request(s);
429                                 if (ret <= 0) goto end;
430 #ifndef NETSCAPE_HANG_BUG
431                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
432 #else
433                                 s->state=SSL3_ST_SW_FLUSH;
434                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
435 #endif
436                                 s->init_num=0;
437                                 }
438                         break;
439
440                 case SSL3_ST_SW_SRVR_DONE_A:
441                 case SSL3_ST_SW_SRVR_DONE_B:
442                         ret=ssl3_send_server_done(s);
443                         if (ret <= 0) goto end;
444                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
445                         s->state=SSL3_ST_SW_FLUSH;
446                         s->init_num=0;
447                         break;
448                 
449                 case SSL3_ST_SW_FLUSH:
450
451                         /* This code originally checked to see if
452                          * any data was pending using BIO_CTRL_INFO
453                          * and then flushed. This caused problems
454                          * as documented in PR#1939. The proposed
455                          * fix doesn't completely resolve this issue
456                          * as buggy implementations of BIO_CTRL_PENDING
457                          * still exist. So instead we just flush
458                          * unconditionally.
459                          */
460
461                         s->rwstate=SSL_WRITING;
462                         if (BIO_flush(s->wbio) <= 0)
463                                 {
464                                 ret= -1;
465                                 goto end;
466                                 }
467                         s->rwstate=SSL_NOTHING;
468
469                         s->state=s->s3->tmp.next_state;
470                         break;
471
472                 case SSL3_ST_SR_CERT_A:
473                 case SSL3_ST_SR_CERT_B:
474                         /* Check for second client hello (MS SGC) */
475                         ret = ssl3_check_client_hello(s);
476                         if (ret <= 0)
477                                 goto end;
478                         if (ret == 2)
479                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
480                         else {
481                                 if (s->s3->tmp.cert_request)
482                                         {
483                                         ret=ssl3_get_client_certificate(s);
484                                         if (ret <= 0) goto end;
485                                         }
486                                 s->init_num=0;
487                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
488                         }
489                         break;
490
491                 case SSL3_ST_SR_KEY_EXCH_A:
492                 case SSL3_ST_SR_KEY_EXCH_B:
493                         ret=ssl3_get_client_key_exchange(s);
494                         if (ret <= 0)
495                                 goto end;
496                         if (ret == 2)
497                                 {
498                                 /* For the ECDH ciphersuites when
499                                  * the client sends its ECDH pub key in
500                                  * a certificate, the CertificateVerify
501                                  * message is not sent.
502                                  */
503                                 s->init_num = 0;
504                                 s->state = SSL3_ST_SR_CHANGE;
505                                 }
506                         else if (SSL_USE_SIGALGS(s))
507                                 {
508                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
509                                 s->init_num=0;
510                                 if (!s->session->peer)
511                                         break;
512                                 /* For sigalgs freeze the handshake buffer
513                                  * at this point and digest cached records.
514                                  */
515                                 if (!s->s3->handshake_buffer)
516                                         {
517                                         OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
518                                         return -1;
519                                         }
520                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
521                                 if (!ssl3_digest_cached_records(s))
522                                         return -1;
523                                 }
524                         else
525                                 {
526                                 int offset=0;
527                                 int dgst_num;
528
529                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
530                                 s->init_num=0;
531
532                                 /* We need to get hashes here so if there is
533                                  * a client cert, it can be verified
534                                  * FIXME - digest processing for CertificateVerify
535                                  * should be generalized. But it is next step
536                                  */
537                                 if (s->s3->handshake_buffer)
538                                         if (!ssl3_digest_cached_records(s))
539                                                 return -1;
540                                 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
541                                         if (s->s3->handshake_dgst[dgst_num]) 
542                                                 {
543                                                 int dgst_size;
544
545                                                 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]));
546                                                 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
547                                                 if (dgst_size < 0)
548                                                         {
549                                                         ret = -1;
550                                                         goto end;
551                                                         }
552                                                 offset+=dgst_size;
553                                                 }               
554                                 }
555                         break;
556
557                 case SSL3_ST_SR_CERT_VRFY_A:
558                 case SSL3_ST_SR_CERT_VRFY_B:
559                         ret=ssl3_get_cert_verify(s);
560                         if (ret <= 0) goto end;
561
562                         s->state = SSL3_ST_SR_CHANGE;
563                         s->init_num=0;
564                         break;
565
566                 case SSL3_ST_SR_CHANGE: {
567                         char next_proto_neg = 0;
568                         char channel_id = 0;
569 # if !defined(OPENSSL_NO_NEXTPROTONEG)
570                         next_proto_neg = s->s3->next_proto_neg_seen;
571 # endif
572                         channel_id = s->s3->tlsext_channel_id_valid;
573
574                         /* At this point, the next message must be entirely
575                          * behind a ChangeCipherSpec. */
576                         if (!ssl3_expect_change_cipher_spec(s))
577                                 {
578                                 ret = -1;
579                                 goto end;
580                                 }
581                         if (next_proto_neg)
582                                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
583                         else if (channel_id)
584                                 s->state = SSL3_ST_SR_CHANNEL_ID_A;
585                         else
586                                 s->state = SSL3_ST_SR_FINISHED_A;
587                         break;
588                 }
589
590 #if !defined(OPENSSL_NO_NEXTPROTONEG)
591                 case SSL3_ST_SR_NEXT_PROTO_A:
592                 case SSL3_ST_SR_NEXT_PROTO_B:
593                         ret=ssl3_get_next_proto(s);
594                         if (ret <= 0) goto end;
595                         s->init_num = 0;
596                         if (s->s3->tlsext_channel_id_valid)
597                                 s->state=SSL3_ST_SR_CHANNEL_ID_A;
598                         else
599                                 s->state=SSL3_ST_SR_FINISHED_A;
600                         break;
601 #endif
602
603                 case SSL3_ST_SR_CHANNEL_ID_A:
604                 case SSL3_ST_SR_CHANNEL_ID_B:
605                         ret=ssl3_get_channel_id(s);
606                         if (ret <= 0) goto end;
607                         s->init_num = 0;
608                         s->state=SSL3_ST_SR_FINISHED_A;
609                         break;
610
611                 case SSL3_ST_SR_FINISHED_A:
612                 case SSL3_ST_SR_FINISHED_B:
613                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
614                                 SSL3_ST_SR_FINISHED_B);
615                         if (ret <= 0) goto end;
616                         if (s->hit)
617                                 s->state=SSL_ST_OK;
618                         else if (s->tlsext_ticket_expected)
619                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
620                         else
621                                 s->state=SSL3_ST_SW_CHANGE_A;
622                         /* If this is a full handshake with ChannelID then
623                          * record the hashshake hashes in |s->session| in case
624                          * we need them to verify a ChannelID signature on a
625                          * resumption of this session in the future. */
626                         if (!s->hit && s->s3->tlsext_channel_id_new)
627                                 {
628                                 ret = tls1_record_handshake_hashes_for_channel_id(s);
629                                 if (ret <= 0) goto end;
630                                 }
631                         s->init_num=0;
632                         break;
633
634                 case SSL3_ST_SW_SESSION_TICKET_A:
635                 case SSL3_ST_SW_SESSION_TICKET_B:
636                         ret=ssl3_send_newsession_ticket(s);
637                         if (ret <= 0) goto end;
638                         s->state=SSL3_ST_SW_CHANGE_A;
639                         s->init_num=0;
640                         break;
641
642                 case SSL3_ST_SW_CERT_STATUS_A:
643                 case SSL3_ST_SW_CERT_STATUS_B:
644                         ret=ssl3_send_cert_status(s);
645                         if (ret <= 0) goto end;
646                         s->state=SSL3_ST_SW_KEY_EXCH_A;
647                         s->init_num=0;
648                         break;
649
650                 case SSL3_ST_SW_CHANGE_A:
651                 case SSL3_ST_SW_CHANGE_B:
652
653                         s->session->cipher=s->s3->tmp.new_cipher;
654                         if (!s->method->ssl3_enc->setup_key_block(s))
655                                 { ret= -1; goto end; }
656
657                         ret=ssl3_send_change_cipher_spec(s,
658                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
659
660                         if (ret <= 0) goto end;
661                         s->state=SSL3_ST_SW_FINISHED_A;
662                         s->init_num=0;
663
664                         if (!s->method->ssl3_enc->change_cipher_state(s,
665                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
666                                 {
667                                 ret= -1;
668                                 goto end;
669                                 }
670
671                         break;
672
673                 case SSL3_ST_SW_FINISHED_A:
674                 case SSL3_ST_SW_FINISHED_B:
675                         ret=ssl3_send_finished(s,
676                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
677                                 s->method->ssl3_enc->server_finished_label,
678                                 s->method->ssl3_enc->server_finished_label_len);
679                         if (ret <= 0) goto end;
680                         s->state = SSL3_ST_SW_FLUSH;
681                         if (s->hit)
682                                 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
683                         else
684                                 s->s3->tmp.next_state = SSL_ST_OK;
685                         s->init_num=0;
686                         break;
687
688                 case SSL_ST_OK:
689                         /* clean a few things up */
690                         ssl3_cleanup_key_block(s);
691
692                         BUF_MEM_free(s->init_buf);
693                         s->init_buf=NULL;
694
695                         /* remove buffering on output */
696                         ssl_free_wbio_buffer(s);
697
698                         s->init_num=0;
699
700                         /* If we aren't retaining peer certificates then we can
701                          * discard it now. */
702                         if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs)
703                                 {
704                                 X509_free(s->session->peer);
705                                 s->session->peer = NULL;
706                                 }
707
708                         if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
709                                 {
710                                 s->renegotiate=0;
711                                 s->new_session=0;
712                                 
713                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
714                                 
715                                 s->ctx->stats.sess_accept_good++;
716                                 /* s->server=1; */
717                                 s->handshake_func=ssl3_accept;
718
719                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
720                                 }
721                         
722                         ret = 1;
723                         goto end;
724                         /* break; */
725
726                 default:
727                         OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
728                         ret= -1;
729                         goto end;
730                         /* break; */
731                         }
732                 
733                 if (!s->s3->tmp.reuse_message && !skip)
734                         {
735                         if (s->debug)
736                                 {
737                                 if ((ret=BIO_flush(s->wbio)) <= 0)
738                                         goto end;
739                                 }
740
741
742                         if ((cb != NULL) && (s->state != state))
743                                 {
744                                 new_state=s->state;
745                                 s->state=state;
746                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
747                                 s->state=new_state;
748                                 }
749                         }
750                 skip=0;
751                 }
752 end:
753         /* BIO_flush(s->wbio); */
754
755         s->in_handshake--;
756         if (cb != NULL)
757                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
758         return(ret);
759         }
760
761 int ssl3_send_hello_request(SSL *s)
762         {
763
764         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
765                 {
766                 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
767                 s->state=SSL3_ST_SW_HELLO_REQ_B;
768                 }
769
770         /* SSL3_ST_SW_HELLO_REQ_B */
771         return ssl_do_write(s);
772         }
773
774 int ssl3_check_client_hello(SSL *s)
775         {
776         int ok;
777         long n;
778
779         /* this function is called when we really expect a Certificate message,
780          * so permit appropriate message length */
781         n=s->method->ssl_get_message(s,
782                 SSL3_ST_SR_CERT_A,
783                 SSL3_ST_SR_CERT_B,
784                 -1,
785                 s->max_cert_list,
786                 &ok);
787         if (!ok) return((int)n);
788         s->s3->tmp.reuse_message = 1;
789         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
790                 {
791                 /* We only allow the client to restart the handshake once per
792                  * negotiation. */
793                 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
794                         {
795                         OPENSSL_PUT_ERROR(SSL, ssl3_check_client_hello, SSL_R_MULTIPLE_SGC_RESTARTS);
796                         return -1;
797                         }
798                 /* Throw away what we have done so far in the current handshake,
799                  * which will now be aborted. (A full SSL_clear would be too much.) */
800 #ifndef OPENSSL_NO_DH
801                 if (s->s3->tmp.dh != NULL)
802                         {
803                         DH_free(s->s3->tmp.dh);
804                         s->s3->tmp.dh = NULL;
805                         }
806 #endif
807 #ifndef OPENSSL_NO_ECDH
808                 if (s->s3->tmp.ecdh != NULL)
809                         {
810                         EC_KEY_free(s->s3->tmp.ecdh);
811                         s->s3->tmp.ecdh = NULL;
812                         }
813 #endif
814                 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
815                 return 2;
816                 }
817         return 1;
818 }
819
820 int ssl3_get_client_hello(SSL *s)
821         {
822         int i,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
823         long n;
824         SSL_CIPHER *c;
825         STACK_OF(SSL_CIPHER) *ciphers=NULL;
826         struct ssl_early_callback_ctx early_ctx;
827         CBS client_hello;
828         uint16_t client_version;
829         CBS client_random, session_id, cipher_suites, compression_methods;
830
831         /* We do this so that we will respond with our native type.
832          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
833          * This down switching should be handled by a different method.
834          * If we are SSLv3, we will respond with SSLv3, even if prompted with
835          * TLSv1.
836          */
837         switch (s->state) {
838         case SSL3_ST_SR_CLNT_HELLO_A:
839         case SSL3_ST_SR_CLNT_HELLO_B:
840                 s->first_packet=1;
841                 n=s->method->ssl_get_message(s,
842                         SSL3_ST_SR_CLNT_HELLO_A,
843                         SSL3_ST_SR_CLNT_HELLO_B,
844                         SSL3_MT_CLIENT_HELLO,
845                         SSL3_RT_MAX_PLAIN_LENGTH,
846                         &ok);
847
848                 if (!ok) return((int)n);
849                 s->first_packet=0;
850
851                 /* If we require cookies and this ClientHello doesn't
852                  * contain one, just return since we do not want to
853                  * allocate any memory yet. So check cookie length...
854                  */
855                 if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
856                         {
857                         CBS session_id;
858                         uint8_t cookie_length;
859
860                         CBS_init(&client_hello, s->init_msg, n);
861                         if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
862                                 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
863                                 !CBS_get_u8(&client_hello, &cookie_length))
864                                 {
865                                 al = SSL_AD_DECODE_ERROR;
866                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
867                                 goto f_err;
868                                 }
869
870                         if (cookie_length == 0)
871                                 return 1;
872                         }
873                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
874                 /* fallthrough */
875         case SSL3_ST_SR_CLNT_HELLO_C:
876         case SSL3_ST_SR_CLNT_HELLO_D:
877                 /* We have previously parsed the ClientHello message,
878                  * and can't call ssl_get_message again without hashing
879                  * the message into the Finished digest again. */
880                 n = s->init_num;
881
882                 memset(&early_ctx, 0, sizeof(early_ctx));
883                 early_ctx.ssl = s;
884                 early_ctx.client_hello = s->init_msg;
885                 early_ctx.client_hello_len = n;
886                 if (!ssl_early_callback_init(&early_ctx))
887                         {
888                         al = SSL_AD_DECODE_ERROR;
889                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_PARSE_FAILED);
890                         goto f_err;
891                         }
892
893                 if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
894                     s->ctx->select_certificate_cb != NULL)
895                         {
896                         int ret;
897
898                         s->state = SSL3_ST_SR_CLNT_HELLO_D;
899                         ret = s->ctx->select_certificate_cb(&early_ctx);
900                         if (ret == 0)
901                                 return CERTIFICATE_SELECTION_PENDING;
902                         else if (ret == -1)
903                                 {
904                                 /* Connection rejected. */
905                                 al = SSL_AD_ACCESS_DENIED;
906                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
907                                 goto f_err;
908                                 }
909                         }
910                 s->state = SSL3_ST_SR_CLNT_HELLO_D;
911                 break;
912         default:
913                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
914                 return -1;
915         }
916
917         CBS_init(&client_hello, s->init_msg, n);
918         if (!CBS_get_u16(&client_hello, &client_version) ||
919                 !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
920                 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
921                 CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
922                 {
923                 al = SSL_AD_DECODE_ERROR;
924                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
925                 goto f_err;
926                 }
927
928         /* use version from inside client hello, not from record header
929          * (may differ: see RFC 2246, Appendix E, second paragraph) */
930         s->client_version = client_version;
931
932         if (SSL_IS_DTLS(s)  ?   (s->client_version > s->version &&
933                                  s->method->version != DTLS_ANY_VERSION)
934                             :   (s->client_version < s->version))
935                 {
936                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
937                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
938                         !s->enc_write_ctx && !s->write_hash)
939                         {
940                         /* similar to ssl3_get_record, send alert using remote version number */
941                         s->version = s->client_version;
942                         }
943                 al = SSL_AD_PROTOCOL_VERSION;
944                 goto f_err;
945                 }
946
947         /* Load the client random. */
948         memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
949
950         s->hit=0;
951         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
952          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
953          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
954          * than a change to default behavior so that applications relying on this for security
955          * won't even compile against older library versions).
956          *
957          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
958          * renegotiation but not a new session (s->new_session remains unset): for servers,
959          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
960          * setting will be ignored.
961          */
962         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
963                 {
964                 if (!ssl_get_new_session(s,1))
965                         goto err;
966                 }
967         else
968                 {
969                 i=ssl_get_prev_session(s, &early_ctx);
970                 if (i == 1)
971                         { /* previous session */
972                         s->hit=1;
973                         }
974                 else if (i == -1)
975                         goto err;
976                 else if (i == PENDING_SESSION)
977                         {
978                         ret = PENDING_SESSION;
979                         goto err;
980                         }
981                 else /* i == 0 */
982                         {
983                         if (!ssl_get_new_session(s,1))
984                                 goto err;
985                         }
986                 }
987
988         if (SSL_IS_DTLS(s))
989                 {
990                 CBS cookie;
991
992                 /* TODO(davidben): The length check here is off. Per
993                  * spec, the maximum cookie length is 32. However, the
994                  * DTLS1_COOKIE_LENGTH check is checking against 256,
995                  * not 32 (so it's actually redundant).
996                  * 07a9d1a2c2b735cbc327065000b545deb5e136cf from
997                  * OpenSSL switched this from 32 to 256. */
998                 if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
999                         CBS_len(&cookie) > DTLS1_COOKIE_LENGTH)
1000                         {
1001                         al = SSL_AD_DECODE_ERROR;
1002                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
1003                         goto f_err;
1004                         }
1005
1006                 /* Verify the cookie if appropriate option is set. */
1007                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1008                         CBS_len(&cookie) > 0)
1009                         {
1010                         if (s->ctx->app_verify_cookie_cb != NULL)
1011                                 {
1012                                 if (s->ctx->app_verify_cookie_cb(s,
1013                                                 (unsigned char*)CBS_data(&cookie),
1014                                                 CBS_len(&cookie)) == 0)
1015                                         {
1016                                         al=SSL_AD_HANDSHAKE_FAILURE;
1017                                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
1018                                         goto f_err;
1019                                         }
1020                                 /* else cookie verification succeeded */
1021                                 }
1022                         else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len))
1023                                 {
1024                                 /* default verification */
1025                                 al=SSL_AD_HANDSHAKE_FAILURE;
1026                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
1027                                 goto f_err;
1028                                 }
1029                         /* Set to -2 so if successful we return 2 and
1030                          * don't send HelloVerifyRequest. */
1031                         ret = -2;
1032                         }
1033
1034                 if (s->method->version == DTLS_ANY_VERSION)
1035                         {
1036                         /* Select version to use */
1037                         if (s->client_version <= DTLS1_2_VERSION &&
1038                                 !(s->options & SSL_OP_NO_DTLSv1_2))
1039                                 {
1040                                 s->version = DTLS1_2_VERSION;
1041                                 s->method = DTLSv1_2_server_method();
1042                                 }
1043                         else if (tls1_suiteb(s))
1044                                 {
1045                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1046                                 s->version = s->client_version;
1047                                 al = SSL_AD_PROTOCOL_VERSION;
1048                                 goto f_err;
1049                                 }
1050                         else if (s->client_version <= DTLS1_VERSION &&
1051                                 !(s->options & SSL_OP_NO_DTLSv1))
1052                                 {
1053                                 s->version = DTLS1_VERSION;
1054                                 s->method = DTLSv1_server_method();
1055                                 }
1056                         else
1057                                 {
1058                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
1059                                 s->version = s->client_version;
1060                                 al = SSL_AD_PROTOCOL_VERSION;
1061                                 goto f_err;
1062                                 }
1063                         s->session->ssl_version = s->version;
1064                         }
1065                 }
1066
1067         if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
1068                 !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
1069                 CBS_len(&compression_methods) == 0)
1070                 {
1071                 al = SSL_AD_DECODE_ERROR;
1072                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
1073                 goto f_err;
1074                 }
1075
1076         /* TODO(davidben): Per spec, cipher_suites can never be empty
1077          * (specified at the ClientHello structure level). This logic
1078          * allows it to be empty if resuming a session. Can we always
1079          * require non-empty? If a client sends empty cipher_suites
1080          * because it's resuming a session, it could always fail to
1081          * resume a session, so it's unlikely to actually work. */
1082         if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0)
1083                 {
1084                 /* We need a cipher if we are not resuming a session. */
1085                 al = SSL_AD_ILLEGAL_PARAMETER;
1086                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
1087                 goto f_err;
1088                 }
1089
1090         if (ssl_bytes_to_cipher_list(s, &cipher_suites, &ciphers) == NULL)
1091                 {
1092                 goto err;
1093                 }
1094
1095         /* If it is a hit, check that the cipher is in the list */
1096         if (s->hit && CBS_len(&cipher_suites) > 0)
1097                 {
1098                 int found_cipher = 0;
1099                 unsigned long id = s->session->cipher->id;
1100
1101                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1102                         {
1103                         c=sk_SSL_CIPHER_value(ciphers,i);
1104                         if (c->id == id)
1105                                 {
1106                                 found_cipher = 1;
1107                                 break;
1108                                 }
1109                         }
1110                 if (!found_cipher)
1111                         {
1112                         /* we need to have the cipher in the cipher
1113                          * list if we are asked to reuse it */
1114                         al=SSL_AD_ILLEGAL_PARAMETER;
1115                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_REQUIRED_CIPHER_MISSING);
1116                         goto f_err;
1117                         }
1118                 }
1119
1120         /* Only null compression is supported. */
1121         if (memchr(CBS_data(&compression_methods), 0,
1122                         CBS_len(&compression_methods)) == NULL)
1123                 {
1124                 al = SSL_AD_ILLEGAL_PARAMETER;
1125                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_COMPRESSION_SPECIFIED);
1126                 goto f_err;
1127                 }
1128
1129         /* TLS extensions*/
1130         if (s->version >= SSL3_VERSION)
1131                 {
1132                 if (!ssl_parse_clienthello_tlsext(s, &client_hello))
1133                         {
1134                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
1135                         goto err;
1136                         }
1137                 }
1138
1139         /* There should be nothing left over in the record. */
1140         if (CBS_len(&client_hello) != 0)
1141                 {
1142                 /* wrong packet length */
1143                 al=SSL_AD_DECODE_ERROR;
1144                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
1145                 goto f_err;
1146                 }
1147
1148         /* Check if we want to use external pre-shared secret for this
1149          * handshake for not reused session only. We need to generate
1150          * server_random before calling tls_session_secret_cb in order to allow
1151          * SessionTicket processing to use it in key derivation. */
1152         {
1153                 unsigned char *pos;
1154                 pos=s->s3->server_random;
1155                 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1156                         {
1157                         goto f_err;
1158                         }
1159         }
1160
1161         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1162                 {
1163                 SSL_CIPHER *pref_cipher=NULL;
1164
1165                 s->session->master_key_length=sizeof(s->session->master_key);
1166                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1167                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1168                         {
1169                         s->hit=1;
1170                         s->session->ciphers=ciphers;
1171                         s->session->verify_result=X509_V_OK;
1172
1173                         ciphers=NULL;
1174
1175                         /* check if some cipher was preferred by call back */
1176                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, ssl_get_cipher_preferences(s));
1177                         if (pref_cipher == NULL)
1178                                 {
1179                                 al=SSL_AD_HANDSHAKE_FAILURE;
1180                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1181                                 goto f_err;
1182                                 }
1183
1184                         s->session->cipher=pref_cipher;
1185
1186                         if (s->cipher_list)
1187                                 ssl_cipher_preference_list_free(s->cipher_list);
1188
1189                         if (s->cipher_list_by_id)
1190                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1191
1192                         s->cipher_list = ssl_cipher_preference_list_from_ciphers(s->session->ciphers);
1193                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1194                         }
1195                 }
1196
1197         /* Given s->session->ciphers and SSL_get_ciphers, we must
1198          * pick a cipher */
1199
1200         if (!s->hit)
1201                 {
1202                 if (s->session->ciphers != NULL)
1203                         sk_SSL_CIPHER_free(s->session->ciphers);
1204                 s->session->ciphers=ciphers;
1205                 if (ciphers == NULL)
1206                         {
1207                         al=SSL_AD_ILLEGAL_PARAMETER;
1208                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
1209                         goto f_err;
1210                         }
1211                 ciphers=NULL;
1212                 /* Let cert callback update server certificates if required */
1213                 if (s->cert->cert_cb)
1214                         {
1215                         int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1216                         if (rv == 0)
1217                                 {
1218                                 al=SSL_AD_INTERNAL_ERROR;
1219                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
1220                                 goto f_err;
1221                                 }
1222                         if (rv < 0)
1223                                 {
1224                                 s->rwstate=SSL_X509_LOOKUP;
1225                                 return -1;
1226                                 }
1227                         s->rwstate = SSL_NOTHING;
1228                         }
1229                 c=ssl3_choose_cipher(s,s->session->ciphers,
1230                                      ssl_get_cipher_preferences(s));
1231
1232                 if (c == NULL)
1233                         {
1234                         al=SSL_AD_HANDSHAKE_FAILURE;
1235                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1236                         goto f_err;
1237                         }
1238                 s->s3->tmp.new_cipher=c;
1239                 }
1240         else
1241                 {
1242                 /* Session-id reuse */
1243                 s->s3->tmp.new_cipher=s->session->cipher;
1244                 }
1245
1246         if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1247                 {
1248                 if (!ssl3_digest_cached_records(s))
1249                         goto f_err;
1250                 }
1251         
1252         /* we now have the following setup. 
1253          * client_random
1254          * cipher_list          - our prefered list of ciphers
1255          * ciphers              - the clients prefered list of ciphers
1256          * compression          - basically ignored right now
1257          * ssl version is set   - sslv3
1258          * s->session           - The ssl session has been setup.
1259          * s->hit               - session reuse flag
1260          * s->tmp.new_cipher    - the new cipher to use.
1261          */
1262
1263         /* Handles TLS extensions that we couldn't check earlier */
1264         if (s->version >= SSL3_VERSION)
1265                 {
1266                 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1267                         {
1268                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
1269                         goto err;
1270                         }
1271                 }
1272
1273         if (ret < 0) ret=-ret;
1274         if (0)
1275                 {
1276 f_err:
1277                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1278                 }
1279 err:
1280         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1281         return ret;
1282         }
1283
1284 int ssl3_send_server_hello(SSL *s)
1285         {
1286         unsigned char *buf;
1287         unsigned char *p,*d;
1288         int sl;
1289         unsigned long l;
1290
1291         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1292                 {
1293                 /* We only accept ChannelIDs on connections with ECDHE in order
1294                  * to avoid a known attack while we fix ChannelID itself. */
1295                 if (s->s3 &&
1296                     s->s3->tlsext_channel_id_valid &&
1297                     (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
1298                         s->s3->tlsext_channel_id_valid = 0;
1299
1300                 /* If this is a resumption and the original handshake didn't
1301                  * support ChannelID then we didn't record the original
1302                  * handshake hashes in the session and so cannot resume with
1303                  * ChannelIDs. */
1304                 if (s->hit &&
1305                     s->s3->tlsext_channel_id_new &&
1306                     s->session->original_handshake_hash_len == 0)
1307                         s->s3->tlsext_channel_id_valid = 0;
1308
1309                 if (s->mode & SSL_MODE_RELEASE_BUFFERS)
1310                         {
1311                         /* Free s->session->ciphers in order to release memory. This
1312                          * breaks SSL_get_shared_ciphers(), but many servers will
1313                          * prefer the memory savings. */
1314                         sk_SSL_CIPHER_free(s->session->ciphers);
1315                         s->session->ciphers = NULL;
1316                         }
1317
1318                 buf=(unsigned char *)s->init_buf->data;
1319                 /* Do the message type and length last */
1320                 d=p= ssl_handshake_start(s);
1321
1322                 *(p++)=s->version>>8;
1323                 *(p++)=s->version&0xff;
1324
1325                 /* Random stuff */
1326                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1327                 p+=SSL3_RANDOM_SIZE;
1328
1329                 /* There are several cases for the session ID to send
1330                  * back in the server hello:
1331                  * - For session reuse from the session cache,
1332                  *   we send back the old session ID.
1333                  * - If stateless session reuse (using a session ticket)
1334                  *   is successful, we send back the client's "session ID"
1335                  *   (which doesn't actually identify the session).
1336                  * - If it is a new session, we send back the new
1337                  *   session ID.
1338                  * - However, if we want the new session to be single-use,
1339                  *   we send back a 0-length session ID.
1340                  * s->hit is non-zero in either case of session reuse,
1341                  * so the following won't overwrite an ID that we're supposed
1342                  * to send back.
1343                  */
1344                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1345                         && !s->hit)
1346                         s->session->session_id_length=0;
1347
1348                 sl=s->session->session_id_length;
1349                 if (sl > (int)sizeof(s->session->session_id))
1350                         {
1351                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1352                         return -1;
1353                         }
1354                 *(p++)=sl;
1355                 memcpy(p,s->session->session_id,sl);
1356                 p+=sl;
1357
1358                 /* put the cipher */
1359                 s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
1360
1361                 /* put the compression method */
1362                         *(p++)=0;
1363                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1364                         {
1365                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
1366                         return -1;
1367                         }
1368                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1369                         {
1370                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1371                         return -1;
1372                         }
1373                 /* do the header */
1374                 l=(p-d);
1375                 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1376                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1377                 }
1378
1379         /* SSL3_ST_SW_SRVR_HELLO_B */
1380         return ssl_do_write(s);
1381         }
1382
1383 int ssl3_send_server_done(SSL *s)
1384         {
1385
1386         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1387                 {
1388                 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1389                 s->state = SSL3_ST_SW_SRVR_DONE_B;
1390                 }
1391
1392         /* SSL3_ST_SW_SRVR_DONE_B */
1393         return ssl_do_write(s);
1394         }
1395
1396 int ssl3_send_server_key_exchange(SSL *s)
1397         {
1398         unsigned char *q;
1399         int j,num;
1400         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1401         unsigned int u;
1402 #ifndef OPENSSL_NO_DH
1403         DH *dh=NULL,*dhp;
1404 #endif
1405 #ifndef OPENSSL_NO_ECDH
1406         EC_KEY *ecdh=NULL, *ecdhp;
1407         unsigned char *encodedPoint = NULL;
1408         int encodedlen = 0;
1409         int curve_id = 0;
1410         BN_CTX *bn_ctx = NULL; 
1411 #endif
1412         const char* psk_identity_hint = NULL;
1413         size_t psk_identity_hint_len = 0;
1414         EVP_PKEY *pkey;
1415         const EVP_MD *md = NULL;
1416         unsigned char *p,*d;
1417         int al,i;
1418         unsigned long alg_k;
1419         unsigned long alg_a;
1420         int n;
1421         CERT *cert;
1422         BIGNUM *r[4];
1423         int nr[4],kn;
1424         BUF_MEM *buf;
1425         EVP_MD_CTX md_ctx;
1426
1427         EVP_MD_CTX_init(&md_ctx);
1428         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1429                 {
1430                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1431                 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1432                 cert=s->cert;
1433
1434                 buf=s->init_buf;
1435
1436                 r[0]=r[1]=r[2]=r[3]=NULL;
1437                 n=0;
1438                 if (alg_a & SSL_aPSK)
1439                         {
1440                         /* size for PSK identity hint */
1441                         psk_identity_hint = s->session->psk_identity_hint;
1442                         if (psk_identity_hint)
1443                                 psk_identity_hint_len = strlen(psk_identity_hint);
1444                         else
1445                                 psk_identity_hint_len = 0;
1446                         n+=2+psk_identity_hint_len;
1447                         }
1448 #ifndef OPENSSL_NO_DH
1449                 if (alg_k & SSL_kEDH)
1450                         {
1451                         dhp=cert->dh_tmp;
1452                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1453                                 dhp=s->cert->dh_tmp_cb(s, 0, 1024);
1454                         if (dhp == NULL)
1455                                 {
1456                                 al=SSL_AD_HANDSHAKE_FAILURE;
1457                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
1458                                 goto f_err;
1459                                 }
1460
1461                         if (s->s3->tmp.dh != NULL)
1462                                 {
1463                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1464                                 goto err;
1465                                 }
1466
1467                         if ((dh=DHparams_dup(dhp)) == NULL)
1468                                 {
1469                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1470                                 goto err;
1471                                 }
1472
1473                         s->s3->tmp.dh=dh;
1474                         if ((dhp->pub_key == NULL ||
1475                              dhp->priv_key == NULL ||
1476                              (s->options & SSL_OP_SINGLE_DH_USE)))
1477                                 {
1478                                 if(!DH_generate_key(dh))
1479                                     {
1480                                     OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1481                                     goto err;
1482                                     }
1483                                 }
1484                         else
1485                                 {
1486                                 dh->pub_key=BN_dup(dhp->pub_key);
1487                                 dh->priv_key=BN_dup(dhp->priv_key);
1488                                 if ((dh->pub_key == NULL) ||
1489                                         (dh->priv_key == NULL))
1490                                         {
1491                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1492                                         goto err;
1493                                         }
1494                                 }
1495                         r[0]=dh->p;
1496                         r[1]=dh->g;
1497                         r[2]=dh->pub_key;
1498                         }
1499                 else
1500 #endif
1501 #ifndef OPENSSL_NO_ECDH
1502                 if (alg_k & SSL_kEECDH)
1503                         {
1504                         const EC_GROUP *group;
1505
1506                         ecdhp=cert->ecdh_tmp;
1507                         if (s->cert->ecdh_tmp_auto)
1508                                 {
1509                                 /* Get NID of appropriate shared curve */
1510                                 int nid = tls1_get_shared_curve(s);
1511                                 if (nid != NID_undef)
1512                                         ecdhp = EC_KEY_new_by_curve_name(nid);
1513                                 }
1514                         else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1515                                 {
1516                                 ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
1517                                 }
1518                         if (ecdhp == NULL)
1519                                 {
1520                                 al=SSL_AD_HANDSHAKE_FAILURE;
1521                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
1522                                 goto f_err;
1523                                 }
1524
1525                         if (s->s3->tmp.ecdh != NULL)
1526                                 {
1527                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1528                                 goto err;
1529                                 }
1530
1531                         /* Duplicate the ECDH structure. */
1532                         if (ecdhp == NULL)
1533                                 {
1534                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1535                                 goto err;
1536                                 }
1537                         if (s->cert->ecdh_tmp_auto)
1538                                 ecdh = ecdhp;
1539                         else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1540                                 {
1541                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1542                                 goto err;
1543                                 }
1544
1545                         s->s3->tmp.ecdh=ecdh;
1546                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1547                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1548                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1549                                 {
1550                                 if(!EC_KEY_generate_key(ecdh))
1551                                     {
1552                                     OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1553                                     goto err;
1554                                     }
1555                                 }
1556
1557                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1558                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1559                             (EC_KEY_get0_private_key(ecdh) == NULL))
1560                                 {
1561                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1562                                 goto err;
1563                                 }
1564
1565                         /* XXX: For now, we only support ephemeral ECDH
1566                          * keys over named (not generic) curves. For 
1567                          * supported named curves, curve_id is non-zero.
1568                          */
1569                         if ((curve_id = 
1570                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1571                             == 0)
1572                                 {
1573                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1574                                 goto err;
1575                                 }
1576
1577                         /* Encode the public key.
1578                          * First check the size of encoding and
1579                          * allocate memory accordingly.
1580                          */
1581                         encodedlen = EC_POINT_point2oct(group, 
1582                             EC_KEY_get0_public_key(ecdh),
1583                             POINT_CONVERSION_UNCOMPRESSED, 
1584                             NULL, 0, NULL);
1585
1586                         encodedPoint = (unsigned char *) 
1587                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1588                         bn_ctx = BN_CTX_new();
1589                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1590                                 {
1591                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_MALLOC_FAILURE);
1592                                 goto err;
1593                                 }
1594
1595
1596                         encodedlen = EC_POINT_point2oct(group, 
1597                             EC_KEY_get0_public_key(ecdh), 
1598                             POINT_CONVERSION_UNCOMPRESSED, 
1599                             encodedPoint, encodedlen, bn_ctx);
1600
1601                         if (encodedlen == 0) 
1602                                 {
1603                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1604                                 goto err;
1605                                 }
1606
1607                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1608
1609                         /* XXX: For now, we only support named (not 
1610                          * generic) curves in ECDH ephemeral key exchanges.
1611                          * In this situation, we need four additional bytes
1612                          * to encode the entire ServerECDHParams
1613                          * structure. 
1614                          */
1615                         n += 4 + encodedlen;
1616
1617                         /* We'll generate the serverKeyExchange message
1618                          * explicitly so we can set these to NULLs
1619                          */
1620                         r[0]=NULL;
1621                         r[1]=NULL;
1622                         r[2]=NULL;
1623                         r[3]=NULL;
1624                         }
1625                 else
1626 #endif /* !OPENSSL_NO_ECDH */
1627                 if (!(alg_k & SSL_kPSK))
1628                         {
1629                         al=SSL_AD_HANDSHAKE_FAILURE;
1630                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1631                         goto f_err;
1632                         }
1633                 for (i=0; i < 4 && r[i] != NULL; i++)
1634                         {
1635                         nr[i]=BN_num_bytes(r[i]);
1636                         n+=2+nr[i];
1637                         }
1638
1639                 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1640                         {
1641                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1642                                 == NULL)
1643                                 {
1644                                 al=SSL_AD_DECODE_ERROR;
1645                                 goto f_err;
1646                                 }
1647                         kn=EVP_PKEY_size(pkey);
1648                         }
1649                 else
1650                         {
1651                         pkey=NULL;
1652                         kn=0;
1653                         }
1654
1655                 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1656                         {
1657                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
1658                         goto err;
1659                         }
1660                 d = p = ssl_handshake_start(s);
1661
1662                 for (i=0; i < 4 && r[i] != NULL; i++)
1663                         {
1664                         s2n(nr[i],p);
1665                         BN_bn2bin(r[i],p);
1666                         p+=nr[i];
1667                         }
1668
1669 /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
1670  * When one of them is used, the server key exchange record needs to have both
1671  * the psk_identity_hint and the ServerECDHParams. */
1672                 if (alg_a & SSL_aPSK)
1673                         {
1674                         /* copy PSK identity hint (if provided) */
1675                         s2n(psk_identity_hint_len, p);
1676                         if (psk_identity_hint_len > 0)
1677                                 {
1678                                 memcpy(p, psk_identity_hint, psk_identity_hint_len);
1679                                 p+=psk_identity_hint_len;
1680                                 }
1681                         }
1682
1683 #ifndef OPENSSL_NO_ECDH
1684                 if (alg_k & SSL_kEECDH)
1685                         {
1686                         /* XXX: For now, we only support named (not generic) curves.
1687                          * In this situation, the serverKeyExchange message has:
1688                          * [1 byte CurveType], [2 byte CurveName]
1689                          * [1 byte length of encoded point], followed by
1690                          * the actual encoded point itself
1691                          */
1692                         *p = NAMED_CURVE_TYPE;
1693                         p += 1;
1694                         *p = 0;
1695                         p += 1;
1696                         *p = curve_id;
1697                         p += 1;
1698                         *p = encodedlen;
1699                         p += 1;
1700                         memcpy((unsigned char*)p, 
1701                             (unsigned char *)encodedPoint, 
1702                             encodedlen);
1703                         OPENSSL_free(encodedPoint);
1704                         encodedPoint = NULL;
1705                         p += encodedlen;
1706                         }
1707 #endif /* OPENSSL_NO_ECDH */
1708
1709                 /* not anonymous */
1710                 if (pkey != NULL)
1711                         {
1712                         /* n is the length of the params, they start at &(d[4])
1713                          * and p points to the space at the end. */
1714                         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1715                                 {
1716                                 q=md_buf;
1717                                 j=0;
1718                                 for (num=2; num > 0; num--)
1719                                         {
1720                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1721                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1722                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1723                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1724                                         EVP_DigestUpdate(&md_ctx,d,n);
1725                                         EVP_DigestFinal_ex(&md_ctx,q,
1726                                                 (unsigned int *)&i);
1727                                         q+=i;
1728                                         j+=i;
1729                                         }
1730                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1731                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1732                                         {
1733                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_RSA);
1734                                         goto err;
1735                                         }
1736                                 s2n(u,p);
1737                                 n+=u+2;
1738                                 }
1739                         else
1740                         if (md)
1741                                 {
1742                                 /* send signature algorithm */
1743                                 if (SSL_USE_SIGALGS(s))
1744                                         {
1745                                         if (!tls12_get_sigandhash(p, pkey, md))
1746                                                 {
1747                                                 /* Should never happen */
1748                                                 al=SSL_AD_INTERNAL_ERROR;
1749                                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1750                                                 goto f_err;
1751                                                 }
1752                                         p+=2;
1753                                         }
1754 #ifdef SSL_DEBUG
1755                                 fprintf(stderr, "Using hash %s\n",
1756                                                         EVP_MD_name(md));
1757 #endif
1758                                 EVP_SignInit_ex(&md_ctx, md, NULL);
1759                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1760                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1761                                 EVP_SignUpdate(&md_ctx,d,n);
1762                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1763                                         (unsigned int *)&i,pkey))
1764                                         {
1765                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
1766                                         goto err;
1767                                         }
1768                                 s2n(i,p);
1769                                 n+=i+2;
1770                                 if (SSL_USE_SIGALGS(s))
1771                                         n+= 2;
1772                                 }
1773                         else
1774                                 {
1775                                 /* Is this error check actually needed? */
1776                                 al=SSL_AD_HANDSHAKE_FAILURE;
1777                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_PKEY_TYPE);
1778                                 goto f_err;
1779                                 }
1780                         }
1781
1782                 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1783                 }
1784
1785         s->state = SSL3_ST_SW_KEY_EXCH_B;
1786         EVP_MD_CTX_cleanup(&md_ctx);
1787         return ssl_do_write(s);
1788 f_err:
1789         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1790 err:
1791 #ifndef OPENSSL_NO_ECDH
1792         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1793         BN_CTX_free(bn_ctx);
1794 #endif
1795         EVP_MD_CTX_cleanup(&md_ctx);
1796         return(-1);
1797         }
1798
1799 int ssl3_send_certificate_request(SSL *s)
1800         {
1801         unsigned char *p,*d;
1802         int i,j,nl,off,n;
1803         STACK_OF(X509_NAME) *sk=NULL;
1804         X509_NAME *name;
1805         BUF_MEM *buf;
1806
1807         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1808                 {
1809                 buf=s->init_buf;
1810
1811                 d=p=ssl_handshake_start(s);
1812
1813                 /* get the list of acceptable cert types */
1814                 p++;
1815                 n=ssl3_get_req_cert_type(s,p);
1816                 d[0]=n;
1817                 p+=n;
1818                 n++;
1819
1820                 if (SSL_USE_SIGALGS(s))
1821                         {
1822                         const unsigned char *psigs;
1823                         nl = tls12_get_psigalgs(s, &psigs);
1824                         s2n(nl, p);
1825                         memcpy(p, psigs, nl);
1826                         p += nl;
1827                         n += nl + 2;
1828                         }
1829
1830                 off=n;
1831                 p+=2;
1832                 n+=2;
1833
1834                 sk=SSL_get_client_CA_list(s);
1835                 nl=0;
1836                 if (sk != NULL)
1837                         {
1838                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1839                                 {
1840                                 name=sk_X509_NAME_value(sk,i);
1841                                 j=i2d_X509_NAME(name,NULL);
1842                                 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
1843                                         {
1844                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1845                                         goto err;
1846                                         }
1847                                 p = ssl_handshake_start(s) + n;
1848                                 s2n(j,p);
1849                                 i2d_X509_NAME(name,&p);
1850                                 n+=2+j;
1851                                 nl+=2+j;
1852                                 }
1853                         }
1854                 /* else no CA names */
1855                 p = ssl_handshake_start(s) + off;
1856                 s2n(nl,p);
1857
1858                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
1859
1860 #ifdef NETSCAPE_HANG_BUG
1861                 if (!SSL_IS_DTLS(s))
1862                         {
1863                         if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
1864                                 {
1865                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1866                                 goto err;
1867                                 }
1868                         p=(unsigned char *)s->init_buf->data + s->init_num;
1869                         /* do the header */
1870                         *(p++)=SSL3_MT_SERVER_DONE;
1871                         *(p++)=0;
1872                         *(p++)=0;
1873                         *(p++)=0;
1874                         s->init_num += 4;
1875                         }
1876 #endif
1877
1878                 s->state = SSL3_ST_SW_CERT_REQ_B;
1879                 }
1880
1881         /* SSL3_ST_SW_CERT_REQ_B */
1882         return ssl_do_write(s);
1883 err:
1884         return(-1);
1885         }
1886
1887 int ssl3_get_client_key_exchange(SSL *s)
1888         {
1889         int al,ok;
1890         long n;
1891         CBS client_key_exchange;
1892         unsigned long alg_k;
1893         unsigned long alg_a;
1894         uint8_t *premaster_secret = NULL;
1895         size_t premaster_secret_len = 0;
1896         int skip_certificate_verify = 0;
1897         RSA *rsa=NULL;
1898         uint8_t *decrypt_buf = NULL;
1899         EVP_PKEY *pkey=NULL;
1900 #ifndef OPENSSL_NO_DH
1901         BIGNUM *pub=NULL;
1902         DH *dh_srvr, *dh_clnt = NULL;
1903 #endif
1904
1905 #ifndef OPENSSL_NO_ECDH
1906         EC_KEY *srvr_ecdh = NULL;
1907         EVP_PKEY *clnt_pub_pkey = NULL;
1908         EC_POINT *clnt_ecpoint = NULL;
1909         BN_CTX *bn_ctx = NULL;
1910         unsigned int psk_len = 0;
1911         unsigned char psk[PSK_MAX_PSK_LEN];
1912 #endif
1913
1914         n=s->method->ssl_get_message(s,
1915                 SSL3_ST_SR_KEY_EXCH_A,
1916                 SSL3_ST_SR_KEY_EXCH_B,
1917                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1918                 2048, /* ??? */
1919                 &ok);
1920
1921         if (!ok) return((int)n);
1922         CBS_init(&client_key_exchange, s->init_msg, n);
1923
1924         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1925         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1926
1927         /* If using a PSK key exchange, prepare the pre-shared key. */
1928         if (alg_a & SSL_aPSK)
1929                 {
1930                 CBS psk_identity;
1931
1932                 /* If using PSK, the ClientKeyExchange contains a
1933                  * psk_identity. If PSK, then this is the only field
1934                  * in the message. */
1935                 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1936                         ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0))
1937                         {
1938                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1939                         al = SSL_AD_DECODE_ERROR;
1940                         goto f_err;
1941                         }
1942
1943                 if (s->psk_server_callback == NULL)
1944                         {
1945                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_NO_SERVER_CB);
1946                         al = SSL_AD_INTERNAL_ERROR;
1947                         goto f_err;
1948                         }
1949
1950                 if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1951                         CBS_contains_zero_byte(&psk_identity))
1952                         {
1953                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1954                         al = SSL_AD_ILLEGAL_PARAMETER;
1955                         goto f_err;
1956                         }
1957
1958                 if (!CBS_strdup(&psk_identity, &s->session->psk_identity))
1959                         {
1960                         al = SSL_AD_INTERNAL_ERROR;
1961                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1962                         goto f_err;
1963                         }
1964
1965                 /* Look up the key for the identity. */
1966                 psk_len = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
1967                 if (psk_len > PSK_MAX_PSK_LEN)
1968                         {
1969                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1970                         al = SSL_AD_INTERNAL_ERROR;
1971                         goto f_err;
1972                         }
1973                 else if (psk_len == 0)
1974                         {
1975                         /* PSK related to the given identity not found */
1976                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1977                         al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1978                         goto f_err;
1979                         }
1980                 }
1981
1982         /* Depending on the key exchange method, compute |premaster_secret| and
1983          * |premaster_secret_len|. Also, for DH and ECDH, set
1984          * |skip_certificate_verify| as appropriate. */
1985         if (alg_k & SSL_kRSA)
1986                 {
1987                 CBS encrypted_premaster_secret;
1988                 uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1989                 int decrypt_good_mask;
1990                 uint8_t version_good;
1991                 size_t rsa_size, decrypt_len, premaster_index, j;
1992
1993                 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1994                 if (    (pkey == NULL) ||
1995                         (pkey->type != EVP_PKEY_RSA) ||
1996                         (pkey->pkey.rsa == NULL))
1997                         {
1998                         al=SSL_AD_HANDSHAKE_FAILURE;
1999                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
2000                         goto f_err;
2001                         }
2002                 rsa=pkey->pkey.rsa;
2003
2004                 /* TLS and [incidentally] DTLS{0xFEFF}
2005                  *
2006                  * TODO(davidben): Should this (and
2007                  * ssl3_send_client_key_exchange) include DTLS1_BAD_VER?
2008                  * Alternatively, get rid of DTLS1_BAD_VER?
2009                  */
2010                 if (s->version > SSL3_VERSION)
2011                         {
2012                         CBS copy = client_key_exchange;
2013                         if (!CBS_get_u16_length_prefixed(&client_key_exchange,
2014                                         &encrypted_premaster_secret) ||
2015                                 CBS_len(&client_key_exchange) != 0)
2016                                 {
2017                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2018                                         {
2019                                         al = SSL_AD_DECODE_ERROR;
2020                                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2021                                         goto f_err;
2022                                         }
2023                                 else
2024                                         encrypted_premaster_secret = copy;
2025                                 }
2026                         }
2027                 else
2028                         encrypted_premaster_secret = client_key_exchange;
2029
2030                 /* Reject overly short RSA keys because we want to be sure that
2031                  * the buffer size makes it safe to iterate over the entire size
2032                  * of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The actual
2033                  * expected size is larger due to RSA padding, but the bound is
2034                  * sufficient to be safe. */
2035                 rsa_size = RSA_size(rsa);
2036                 if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH)
2037                         {
2038                         al = SSL_AD_DECRYPT_ERROR;
2039                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECRYPTION_FAILED);
2040                         goto f_err;
2041                         }
2042
2043                 /* We must not leak whether a decryption failure occurs because
2044                  * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2045                  * RFC 2246, section 7.4.7.1). The code follows that advice of
2046                  * the TLS RFC and generates a random premaster secret for the
2047                  * case that the decrypt fails. See
2048                  * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2049                 if (RAND_pseudo_bytes(rand_premaster_secret,
2050                                       sizeof(rand_premaster_secret)) <= 0)
2051                         goto err;
2052
2053                 /* Allocate a buffer large enough for an RSA decryption. */
2054                 decrypt_buf = OPENSSL_malloc(rsa_size);
2055                 if (decrypt_buf == NULL)
2056                         {
2057                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2058                         goto err;
2059                         }
2060
2061                 /* Decrypt with no padding. PKCS#1 padding will be removed as
2062                  * part of the timing-sensitive code below. */
2063                 if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
2064                                 CBS_data(&encrypted_premaster_secret),
2065                                 CBS_len(&encrypted_premaster_secret),
2066                                 RSA_NO_PADDING))
2067                         {
2068                         goto err;
2069                         }
2070                 if (decrypt_len != rsa_size)
2071                         {
2072                         /* This should never happen, but do a check so we do not
2073                          * read uninitialized memory. */
2074                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2075                         goto err;
2076                         }
2077
2078                 /* Remove the PKCS#1 padding and adjust decrypt_len as
2079                  * appropriate. decrypt_good_mask will be zero if the premaster
2080                  * if good and non-zero otherwise. */
2081                 decrypt_good_mask = RSA_message_index_PKCS1_type_2(
2082                         decrypt_buf, decrypt_len, &premaster_index);
2083                 decrypt_good_mask--;
2084                 decrypt_len = decrypt_len - premaster_index;
2085
2086                 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
2087                 decrypt_good_mask |= decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
2088
2089                 /* Copy over the unpadded premaster. Whatever the value of
2090                  * |decrypt_good_mask|, copy as if the premaster were the right
2091                  * length. It is important the memory access pattern be
2092                  * constant. */
2093                 premaster_secret = BUF_memdup(
2094                         decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
2095                         SSL_MAX_MASTER_KEY_LENGTH);
2096                 if (premaster_secret == NULL)
2097                         {
2098                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2099                         goto err;
2100                         }
2101                 OPENSSL_free(decrypt_buf);
2102                 decrypt_buf = NULL;
2103
2104                 /* If the version in the decrypted pre-master secret is correct
2105                  * then version_good will be zero. The Klima-Pokorny-Rosa
2106                  * extension of Bleichenbacher's attack
2107                  * (http://eprint.iacr.org/2003/052/) exploits the version
2108                  * number check as a "bad version oracle". Thus version checks
2109                  * are done in constant time and are treated like any other
2110                  * decryption error. */
2111                 version_good = premaster_secret[0] ^ (s->client_version>>8);
2112                 version_good |= premaster_secret[1] ^ (s->client_version&0xff);
2113
2114                 /* The premaster secret must contain the same version number as
2115                  * the ClientHello to detect version rollback attacks
2116                  * (strangely, the protocol does not offer such protection for
2117                  * DH ciphersuites). However, buggy clients exist that send the
2118                  * negotiated protocol version instead if the server does not
2119                  * support the requested protocol version. If
2120                  * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2121                 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2122                         {
2123                         unsigned char workaround_mask = version_good;
2124                         unsigned char workaround;
2125
2126                         /* workaround_mask will be 0xff if version_good is
2127                          * non-zero (i.e. the version match failed). Otherwise
2128                          * it'll be 0x00. */
2129                         workaround_mask |= workaround_mask >> 4;
2130                         workaround_mask |= workaround_mask >> 2;
2131                         workaround_mask |= workaround_mask >> 1;
2132                         workaround_mask = ~((workaround_mask & 1) - 1);
2133
2134                         workaround = premaster_secret[0] ^ (s->version>>8);
2135                         workaround |= premaster_secret[1] ^ (s->version&0xff);
2136
2137                         /* If workaround_mask is 0xff (i.e. there was a version
2138                          * mismatch) then we copy the value of workaround over
2139                          * version_good. */
2140                         version_good = (workaround & workaround_mask) |
2141                                        (version_good & ~workaround_mask);
2142                         }
2143
2144                 /* If any bits in version_good are set then they'll poision
2145                  * decrypt_good_mask and cause rand_premaster_secret to be
2146                  * used. */
2147                 decrypt_good_mask |= version_good;
2148
2149                 /* decrypt_good_mask will be zero iff decrypt_len ==
2150                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
2151                  * fold the bottom 32 bits of it with an OR so that the LSB
2152                  * will be zero iff everything is good. This assumes that we'll
2153                  * never decrypt a value > 2**31 bytes, which seems safe. */
2154                 decrypt_good_mask |= decrypt_good_mask >> 16;
2155                 decrypt_good_mask |= decrypt_good_mask >> 8;
2156                 decrypt_good_mask |= decrypt_good_mask >> 4;
2157                 decrypt_good_mask |= decrypt_good_mask >> 2;
2158                 decrypt_good_mask |= decrypt_good_mask >> 1;
2159                 /* Now select only the LSB and subtract one. If decrypt_len ==
2160                  * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
2161                  * decrypt_good_mask will be all ones. Otherwise it'll be all
2162                  * zeros. */
2163                 decrypt_good_mask &= 1;
2164                 decrypt_good_mask--;
2165
2166                 /* Now copy rand_premaster_secret over premaster_secret using
2167                  * decrypt_good_mask. */
2168                 for (j = 0; j < sizeof(rand_premaster_secret); j++)
2169                         {
2170                         premaster_secret[j] = (premaster_secret[j] & decrypt_good_mask) |
2171                                (rand_premaster_secret[j] & ~decrypt_good_mask);
2172                         }
2173
2174                 premaster_secret_len = sizeof(rand_premaster_secret);
2175                 }
2176 #ifndef OPENSSL_NO_DH
2177         else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2178                 {
2179                 CBS dh_Yc;
2180                 int idx = -1;
2181                 int dh_len;
2182                 EVP_PKEY *skey = NULL;
2183
2184                 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
2185                         CBS_len(&client_key_exchange) != 0)
2186                         {
2187                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2188                         al = SSL_R_DECODE_ERROR;
2189                         goto f_err;
2190                         }
2191
2192                 if (alg_k & SSL_kDHr)
2193                         idx = SSL_PKEY_DH_RSA;
2194                 else if (alg_k & SSL_kDHd)
2195                         idx = SSL_PKEY_DH_DSA;
2196                 if (idx >= 0)
2197                         {
2198                         skey = s->cert->pkeys[idx].privatekey;
2199                         if ((skey == NULL) ||
2200                                 (skey->type != EVP_PKEY_DH) ||
2201                                 (skey->pkey.dh == NULL))
2202                                 {
2203                                 al=SSL_AD_HANDSHAKE_FAILURE;
2204                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
2205                                 goto f_err;
2206                                 }
2207                         dh_srvr = skey->pkey.dh;
2208                         }
2209                 else if (s->s3->tmp.dh == NULL)
2210                         {
2211                         al=SSL_AD_HANDSHAKE_FAILURE;
2212                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2213                         goto f_err;
2214                         }
2215                 else
2216                         dh_srvr=s->s3->tmp.dh;
2217
2218                 if (CBS_len(&dh_Yc) == 0)
2219                         {
2220                         /* Get pubkey from the client certificate. This is the
2221                          * 'implicit' case of ClientDiffieHellman.
2222                          *
2223                          * TODO(davidben): Either lose this code or fix a bug
2224                          * (or get the spec changed): if there is a fixed_dh
2225                          * client certificate, per spec, the 'implicit' mode
2226                          * MUST be used. This logic will still accept 'explicit'
2227                          * mode. */
2228                         EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2229                         if (clkey)
2230                                 {
2231                                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2232                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2233                                 }
2234                         if (dh_clnt == NULL)
2235                                 {
2236                                 al=SSL_AD_HANDSHAKE_FAILURE;
2237                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2238                                 goto f_err;
2239                                 }
2240                         EVP_PKEY_free(clkey);
2241                         pub = dh_clnt->pub_key;
2242                         }
2243                 else
2244                         pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
2245                 if (pub == NULL)
2246                         {
2247                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
2248                         goto err;
2249                         }
2250
2251                 /* Allocate a buffer for the premaster secret. */
2252                 premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
2253                 if (premaster_secret == NULL)
2254                         {
2255                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2256                         goto err;
2257                         }
2258
2259                 dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
2260                 if (dh_len <= 0)
2261                         {
2262                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
2263                         BN_clear_free(pub);
2264                         goto err;
2265                         }
2266
2267                 DH_free(s->s3->tmp.dh);
2268                 s->s3->tmp.dh=NULL;
2269                 if (dh_clnt)
2270                         DH_free(dh_clnt);
2271                 else
2272                         BN_clear_free(pub);
2273                 pub=NULL;
2274
2275                 premaster_secret_len = dh_len;
2276                 if (dh_clnt)
2277                         skip_certificate_verify = 1;
2278                 }
2279 #endif
2280
2281 #ifndef OPENSSL_NO_ECDH
2282         else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2283                 {
2284                 int field_size = 0, ecdh_len;
2285                 const EC_KEY   *tkey;
2286                 const EC_GROUP *group;
2287                 const BIGNUM *priv_key;
2288
2289                 /* initialize structures for server's ECDH key pair */
2290                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2291                         {
2292                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2293                         goto err;
2294                         }
2295
2296                 /* Let's get server private key and group information */
2297                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2298                         { 
2299                         /* use the certificate */
2300                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2301                         }
2302                 else
2303                         {
2304                         /* use the ephermeral values we saved when
2305                          * generating the ServerKeyExchange msg.
2306                          */
2307                         tkey = s->s3->tmp.ecdh;
2308                         }
2309
2310                 group    = EC_KEY_get0_group(tkey);
2311                 priv_key = EC_KEY_get0_private_key(tkey);
2312
2313                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2314                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2315                         {
2316                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2317                         goto err;
2318                         }
2319
2320                 /* Let's get client's public key */
2321                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2322                         {
2323                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2324                         goto err;
2325                         }
2326
2327                 if (CBS_len(&client_key_exchange) == 0)
2328                         {
2329                         /* Client Publickey was in Client Certificate */
2330
2331                          if (alg_k & SSL_kEECDH)
2332                                  {
2333                                  al=SSL_AD_HANDSHAKE_FAILURE;
2334                                  OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
2335                                  goto f_err;
2336                                  }
2337                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2338                             == NULL) || 
2339                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2340                                 {
2341                                 /* XXX: For now, we do not support client
2342                                  * authentication using ECDH certificates
2343                                  * so this branch (n == 0L) of the code is
2344                                  * never executed. When that support is
2345                                  * added, we ought to ensure the key 
2346                                  * received in the certificate is 
2347                                  * authorized for key agreement.
2348                                  * ECDH_compute_key implicitly checks that
2349                                  * the two ECDH shares are for the same
2350                                  * group.
2351                                  */
2352                                 al=SSL_AD_HANDSHAKE_FAILURE;
2353                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2354                                 goto f_err;
2355                                 }
2356
2357                         if (EC_POINT_copy(clnt_ecpoint,
2358                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2359                                 {
2360                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2361                                 goto err;
2362                                 }
2363                         /* Skip certificate verify processing */
2364                         skip_certificate_verify = 1;
2365                         }
2366                 else
2367                         {
2368                         CBS ecdh_Yc;
2369
2370                         /* Get client's public key from encoded point
2371                          * in the ClientKeyExchange message.
2372                          */
2373                         if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
2374                                 CBS_len(&client_key_exchange) != 0)
2375                                 {
2376                                 al = SSL_AD_DECODE_ERROR;
2377                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
2378                                 goto f_err;
2379                                 }
2380
2381                         if ((bn_ctx = BN_CTX_new()) == NULL)
2382                                 {
2383                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2384                                 goto err;
2385                                 }
2386
2387                         if (!EC_POINT_oct2point(group, clnt_ecpoint,
2388                                         CBS_data(&ecdh_Yc), CBS_len(&ecdh_Yc), bn_ctx))
2389                                 {
2390                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2391                                 goto err;
2392                                 }
2393                         }
2394
2395                 /* Allocate a buffer for both the secret and the PSK. */
2396                 field_size = EC_GROUP_get_degree(group);
2397                 if (field_size <= 0)
2398                         {
2399                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2400                         goto err;
2401                         }
2402
2403                 ecdh_len = (field_size + 7) / 8;
2404                 premaster_secret = OPENSSL_malloc(ecdh_len);
2405                 if (premaster_secret == NULL)
2406                         {
2407                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2408                         goto err;
2409                         }
2410
2411                 /* Compute the shared pre-master secret */
2412                 ecdh_len = ECDH_compute_key(premaster_secret,
2413                         ecdh_len, clnt_ecpoint, srvr_ecdh, NULL);
2414                 if (ecdh_len <= 0)
2415                         {
2416                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2417                         goto err;
2418                         }
2419
2420                 EVP_PKEY_free(clnt_pub_pkey);
2421                 EC_POINT_free(clnt_ecpoint);
2422                 EC_KEY_free(srvr_ecdh);
2423                 BN_CTX_free(bn_ctx);
2424                 EC_KEY_free(s->s3->tmp.ecdh);
2425                 s->s3->tmp.ecdh = NULL;
2426
2427                 premaster_secret_len = ecdh_len;
2428                 }
2429 #endif
2430         else if (alg_k & SSL_kPSK)
2431                 {
2432                 /* For plain PSK, other_secret is a block of 0s with the same
2433                  * length as the pre-shared key. */
2434                 premaster_secret_len = psk_len;
2435                 premaster_secret = OPENSSL_malloc(premaster_secret_len);
2436                 if (premaster_secret == NULL)
2437                         {
2438                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2439                         goto err;
2440                         }
2441                 memset(premaster_secret, 0, premaster_secret_len);
2442                 }
2443         else
2444                 {
2445                 al=SSL_AD_HANDSHAKE_FAILURE;
2446                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNKNOWN_CIPHER_TYPE);
2447                 goto f_err;
2448                 }
2449
2450         /* For a PSK cipher suite, the actual pre-master secret is combined with
2451          * the pre-shared key. */
2452         if (alg_a & SSL_aPSK)
2453                 {
2454                 CBB new_premaster, child;
2455                 uint8_t *new_data;
2456                 size_t new_len;
2457
2458                 if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len))
2459                         {
2460                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2461                         goto err;
2462                         }
2463                 if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2464                         !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
2465                         !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2466                         !CBB_add_bytes(&child, psk, psk_len) ||
2467                         !CBB_finish(&new_premaster, &new_data, &new_len))
2468                         {
2469                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2470                         CBB_cleanup(&new_premaster);
2471                         goto err;
2472                         }
2473
2474                 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2475                 OPENSSL_free(premaster_secret);
2476                 premaster_secret = new_data;
2477                 premaster_secret_len = new_len;
2478                 }
2479
2480         /* Compute the master secret */
2481         s->session->master_key_length = s->method->ssl3_enc
2482                 ->generate_master_secret(s,
2483                         s->session->master_key, premaster_secret, premaster_secret_len);
2484
2485         OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2486         OPENSSL_free(premaster_secret);
2487         return skip_certificate_verify ? 2 : 1;
2488 f_err:
2489         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2490 err:
2491         if (premaster_secret)
2492                 {
2493                 if (premaster_secret_len)
2494                         OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2495                 OPENSSL_free(premaster_secret);
2496                 }
2497         if (decrypt_buf)
2498                 OPENSSL_free(decrypt_buf);
2499 #ifndef OPENSSL_NO_ECDH
2500         EVP_PKEY_free(clnt_pub_pkey);
2501         EC_POINT_free(clnt_ecpoint);
2502         if (srvr_ecdh != NULL) 
2503                 EC_KEY_free(srvr_ecdh);
2504         BN_CTX_free(bn_ctx);
2505 #endif
2506         return(-1);
2507         }
2508
2509 int ssl3_get_cert_verify(SSL *s)
2510         {
2511         EVP_PKEY *pkey=NULL;
2512         int al,ok,ret=0;
2513         long n;
2514         CBS certificate_verify, signature;
2515         int type = 0;
2516         X509 *peer = s->session->peer;
2517         const EVP_MD *md = NULL;
2518         EVP_MD_CTX mctx;
2519
2520         EVP_MD_CTX_init(&mctx);
2521
2522         /* Determine if a CertificateVerify message is expected at all. It is
2523          * important that this be determined before ssl_get_message is called,
2524          * so as not to process the ChangeCipherSpec message early. */
2525         if (peer != NULL)
2526                 {
2527                 pkey = X509_get_pubkey(peer);
2528                 type = X509_certificate_type(peer,pkey);
2529                 }
2530         if (!(type & EVP_PKT_SIGN))
2531                 {
2532                 ret = 1;
2533                 goto done_with_buffer;
2534                 }
2535
2536         n=s->method->ssl_get_message(s,
2537                 SSL3_ST_SR_CERT_VRFY_A,
2538                 SSL3_ST_SR_CERT_VRFY_B,
2539                 SSL3_MT_CERTIFICATE_VERIFY,
2540                 SSL3_RT_MAX_PLAIN_LENGTH,
2541                 &ok);
2542
2543         if (!ok)
2544                 {
2545                 ret = (int)n;
2546                 goto done;
2547                 }
2548
2549         CBS_init(&certificate_verify, s->init_msg, n);
2550
2551         /* We now have a signature that we need to verify. */
2552         /* TODO(davidben): This should share code with
2553          * ssl3_get_server_key_exchange. */
2554
2555         if (SSL_USE_SIGALGS(s))
2556                 {
2557                 if (!tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey))
2558                         goto f_err;
2559                 }
2560
2561         if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
2562                 CBS_len(&certificate_verify) != 0)
2563                 {
2564                 al = SSL_AD_DECODE_ERROR;
2565                 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
2566                 goto f_err;
2567                 }
2568
2569         if (SSL_USE_SIGALGS(s))
2570                 {
2571                 size_t hdatalen;
2572                 const uint8_t *hdata;
2573                 if (!BIO_mem_contents(s->s3->handshake_buffer, &hdata, &hdatalen))
2574                         {
2575                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_INTERNAL_ERROR);
2576                         al=SSL_AD_INTERNAL_ERROR;
2577                         goto f_err;
2578                         }
2579                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2580                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
2581                         {
2582                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_EVP_LIB);
2583                         al=SSL_AD_INTERNAL_ERROR;
2584                         goto f_err;
2585                         }
2586
2587                 if (EVP_VerifyFinal(&mctx,
2588                                 CBS_data(&signature), CBS_len(&signature),
2589                                 pkey) <= 0)
2590                         {
2591                         al=SSL_AD_DECRYPT_ERROR;
2592                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
2593                         goto f_err;
2594                         }
2595                 }
2596         else
2597         if (pkey->type == EVP_PKEY_RSA)
2598                 {
2599                 if (!RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2600                                 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2601                                 CBS_data(&signature), CBS_len(&signature),
2602                                 pkey->pkey.rsa))
2603                         {
2604                         al = SSL_AD_DECRYPT_ERROR;
2605                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_RSA_SIGNATURE);
2606                         goto f_err;
2607                         }
2608                 }
2609         else
2610 #ifndef OPENSSL_NO_DSA
2611                 if (pkey->type == EVP_PKEY_DSA)
2612                 {
2613                 if (DSA_verify(pkey->save_type,
2614                                 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2615                                 SHA_DIGEST_LENGTH,
2616                                 CBS_data(&signature), CBS_len(&signature),
2617                                 pkey->pkey.dsa) <= 0)
2618                         {
2619                         /* bad signature */
2620                         al = SSL_AD_DECRYPT_ERROR;
2621                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_DSA_SIGNATURE);
2622                         goto f_err;
2623                         }
2624                 }
2625         else
2626 #endif
2627 #ifndef OPENSSL_NO_ECDSA
2628                 if (pkey->type == EVP_PKEY_EC)
2629                 {
2630                 if (!ECDSA_verify(pkey->save_type,
2631                                 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2632                                 SHA_DIGEST_LENGTH,
2633                                 CBS_data(&signature), CBS_len(&signature),
2634                                 pkey->pkey.ec))
2635                         {
2636                         /* bad signature */
2637                         al = SSL_AD_DECRYPT_ERROR;
2638                         OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_ECDSA_SIGNATURE);
2639                         goto f_err;
2640                         }
2641                 }
2642         else
2643 #endif
2644                 {
2645                 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_INTERNAL_ERROR);
2646                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
2647                 goto f_err;
2648                 }
2649
2650
2651         ret=1;
2652         if (0)
2653                 {
2654 f_err:
2655                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2656                 }
2657 done_with_buffer:
2658         /* There is no more need for the handshake buffer. */
2659         if (s->s3->handshake_buffer)
2660                 {
2661                 BIO_free(s->s3->handshake_buffer);
2662                 s->s3->handshake_buffer = NULL;
2663                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2664                 }
2665 done:
2666         EVP_MD_CTX_cleanup(&mctx);
2667         EVP_PKEY_free(pkey);
2668         return(ret);
2669         }
2670
2671 int ssl3_get_client_certificate(SSL *s)
2672         {
2673         int i,ok,al,ret= -1;
2674         X509 *x=NULL;
2675         unsigned long n;
2676         STACK_OF(X509) *sk=NULL;
2677         SHA256_CTX sha256;
2678         CBS certificate_msg, certificate_list;
2679         int is_first_certificate = 1;
2680
2681         n=s->method->ssl_get_message(s,
2682                 SSL3_ST_SR_CERT_A,
2683                 SSL3_ST_SR_CERT_B,
2684                 -1,
2685                 s->max_cert_list,
2686                 &ok);
2687
2688         if (!ok) return((int)n);
2689
2690         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2691                 {
2692                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
2693                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2694                         {
2695                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2696                         al=SSL_AD_HANDSHAKE_FAILURE;
2697                         goto f_err;
2698                         }
2699                 /* If tls asked for a client cert, the client must return a 0 list */
2700                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2701                         {
2702                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2703                         al=SSL_AD_UNEXPECTED_MESSAGE;
2704                         goto f_err;
2705                         }
2706                 s->s3->tmp.reuse_message=1;
2707                 return(1);
2708                 }
2709
2710         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2711                 {
2712                 al=SSL_AD_UNEXPECTED_MESSAGE;
2713                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_WRONG_MESSAGE_TYPE);
2714                 goto f_err;
2715                 }
2716
2717         CBS_init(&certificate_msg, s->init_msg, n);
2718
2719         if ((sk=sk_X509_new_null()) == NULL)
2720                 {
2721                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2722                 goto err;
2723                 }
2724
2725         if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
2726                 CBS_len(&certificate_msg) != 0)
2727                 {
2728                 al = SSL_AD_DECODE_ERROR;
2729                 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2730                 goto f_err;
2731                 }
2732
2733         while (CBS_len(&certificate_list) > 0)
2734                 {
2735                 CBS certificate;
2736                 const uint8_t *data;
2737
2738                 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
2739                         {
2740                         al = SSL_AD_DECODE_ERROR;
2741                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2742                         goto f_err;
2743                         }
2744                 if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs)
2745                         {
2746                         /* If this is the first certificate, and we don't want
2747                          * to keep peer certificates in memory, then we hash it
2748                          * right away. */
2749                         SHA256_Init(&sha256);
2750                         SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
2751                         SHA256_Final(s->session->peer_sha256, &sha256);
2752                         s->session->peer_sha256_valid = 1;
2753                         }
2754                 is_first_certificate = 0;
2755                 data = CBS_data(&certificate);
2756                 x = d2i_X509(NULL, &data, CBS_len(&certificate));
2757                 if (x == NULL)
2758                         {
2759                         al = SSL_AD_BAD_CERTIFICATE;
2760                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
2761                         goto f_err;
2762                         }
2763                 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
2764                         {
2765                         al = SSL_AD_INTERNAL_ERROR;
2766                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_INTERNAL_ERROR);
2767                         goto f_err;
2768                         }
2769                 if (CBS_len(&certificate) != 0)
2770                         {
2771                         al = SSL_AD_DECODE_ERROR;
2772                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERT_LENGTH_MISMATCH);
2773                         goto f_err;
2774                         }
2775                 if (!sk_X509_push(sk,x))
2776                         {
2777                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2778                         goto err;
2779                         }
2780                 x = NULL;
2781                 }
2782
2783         if (sk_X509_num(sk) <= 0)
2784                 {
2785                 /* TLS does not mind 0 certs returned */
2786                 if (s->version == SSL3_VERSION)
2787                         {
2788                         al=SSL_AD_HANDSHAKE_FAILURE;
2789                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_NO_CERTIFICATES_RETURNED);
2790                         goto f_err;
2791                         }
2792                 /* Fail for TLS only if we required a certificate */
2793                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2794                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2795                         {
2796                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2797                         al=SSL_AD_HANDSHAKE_FAILURE;
2798                         goto f_err;
2799                         }
2800                 /* No client certificate so digest cached records */
2801                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
2802                         {
2803                         al=SSL_AD_INTERNAL_ERROR;
2804                         goto f_err;
2805                         }
2806                 }
2807         else
2808                 {
2809                 i=ssl_verify_cert_chain(s,sk);
2810                 if (i <= 0)
2811                         {
2812                         al=ssl_verify_alarm_type(s->verify_result);
2813                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
2814                         goto f_err;
2815                         }
2816                 }
2817
2818         if (s->session->peer != NULL) /* This should not be needed */
2819                 X509_free(s->session->peer);
2820         s->session->peer=sk_X509_shift(sk);
2821         s->session->verify_result = s->verify_result;
2822
2823         /* With the current implementation, sess_cert will always be NULL
2824          * when we arrive here. */
2825         if (s->session->sess_cert == NULL)
2826                 {
2827                 s->session->sess_cert = ssl_sess_cert_new();
2828                 if (s->session->sess_cert == NULL)
2829                         {
2830                         OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2831                         goto err;
2832                         }
2833                 }
2834         if (s->session->sess_cert->cert_chain != NULL)
2835                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2836         s->session->sess_cert->cert_chain=sk;
2837         /* Inconsistency alert: cert_chain does *not* include the
2838          * peer's own certificate, while we do include it in s3_clnt.c */
2839
2840         sk=NULL;
2841
2842         ret=1;
2843         if (0)
2844                 {
2845 f_err:
2846                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2847                 }
2848 err:
2849         if (x != NULL) X509_free(x);
2850         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2851         return(ret);
2852         }
2853
2854 int ssl3_send_server_certificate(SSL *s)
2855         {
2856         CERT_PKEY *cpk;
2857
2858         if (s->state == SSL3_ST_SW_CERT_A)
2859                 {
2860                 cpk=ssl_get_server_send_pkey(s);
2861                 if (cpk == NULL)
2862                         {
2863                         OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate, ERR_R_INTERNAL_ERROR);
2864                         return(0);
2865                         }
2866
2867                 ssl3_output_cert_chain(s,cpk);
2868                 s->state=SSL3_ST_SW_CERT_B;
2869                 }
2870
2871         /* SSL3_ST_SW_CERT_B */
2872         return ssl_do_write(s);
2873         }
2874
2875 /* send a new session ticket (not necessarily for a new session) */
2876 int ssl3_send_newsession_ticket(SSL *s)
2877         {
2878         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
2879                 {
2880                 unsigned char *p, *senc, *macstart;
2881                 const unsigned char *const_p;
2882                 int len, slen_full, slen;
2883                 SSL_SESSION *sess;
2884                 unsigned int hlen;
2885                 EVP_CIPHER_CTX ctx;
2886                 HMAC_CTX hctx;
2887                 SSL_CTX *tctx = s->initial_ctx;
2888                 unsigned char iv[EVP_MAX_IV_LENGTH];
2889                 unsigned char key_name[16];
2890
2891                 /* get session encoding length */
2892                 slen_full = i2d_SSL_SESSION(s->session, NULL);
2893                 /* Some length values are 16 bits, so forget it if session is
2894                  * too long
2895                  */
2896                 if (slen_full > 0xFF00)
2897                         return -1;
2898                 senc = OPENSSL_malloc(slen_full);
2899                 if (!senc)
2900                         return -1;
2901                 p = senc;
2902                 i2d_SSL_SESSION(s->session, &p);
2903
2904                 /* create a fresh copy (not shared with other threads) to clean up */
2905                 const_p = senc;
2906                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2907                 if (sess == NULL)
2908                         {
2909                         OPENSSL_free(senc);
2910                         return -1;
2911                         }
2912                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2913
2914                 slen = i2d_SSL_SESSION(sess, NULL);
2915                 if (slen > slen_full) /* shouldn't ever happen */
2916                         {
2917                         OPENSSL_free(senc);
2918                         return -1;
2919                         }
2920                 p = senc;
2921                 i2d_SSL_SESSION(sess, &p);
2922                 SSL_SESSION_free(sess);
2923
2924                 /* Grow buffer if need be: the length calculation is as
2925                  * follows handshake_header_length +
2926                  * 4 (ticket lifetime hint) + 2 (ticket length) +
2927                  * 16 (key name) + max_iv_len (iv length) +
2928                  * session_length + max_enc_block_size (max encrypted session
2929                  * length) + max_md_size (HMAC).
2930                  */
2931                 if (!BUF_MEM_grow(s->init_buf,
2932                         SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
2933                         EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
2934                         return -1;
2935                 p = ssl_handshake_start(s);
2936                 EVP_CIPHER_CTX_init(&ctx);
2937                 HMAC_CTX_init(&hctx);
2938                 /* Initialize HMAC and cipher contexts. If callback present
2939                  * it does all the work otherwise use generated values
2940                  * from parent ctx.
2941                  */
2942                 if (tctx->tlsext_ticket_key_cb)
2943                         {
2944                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2945                                                          &hctx, 1) < 0)
2946                                 {
2947                                 OPENSSL_free(senc);
2948                                 return -1;
2949                                 }
2950                         }
2951                 else
2952                         {
2953                         RAND_pseudo_bytes(iv, 16);
2954                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2955                                         tctx->tlsext_tick_aes_key, iv);
2956                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2957                                         tlsext_tick_md(), NULL);
2958                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2959                         }
2960
2961                 /* Ticket lifetime hint (advisory only):
2962                  * We leave this unspecified for resumed session (for simplicity),
2963                  * and guess that tickets for new sessions will live as long
2964                  * as their sessions. */
2965                 l2n(s->hit ? 0 : s->session->timeout, p);
2966
2967                 /* Skip ticket length for now */
2968                 p += 2;
2969                 /* Output key name */
2970                 macstart = p;
2971                 memcpy(p, key_name, 16);
2972                 p += 16;
2973                 /* output IV */
2974                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2975                 p += EVP_CIPHER_CTX_iv_length(&ctx);
2976                 /* Encrypt session data */
2977                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2978                 p += len;
2979                 EVP_EncryptFinal_ex(&ctx, p, &len);
2980                 p += len;
2981                 EVP_CIPHER_CTX_cleanup(&ctx);
2982
2983                 HMAC_Update(&hctx, macstart, p - macstart);
2984                 HMAC_Final(&hctx, p, &hlen);
2985                 HMAC_CTX_cleanup(&hctx);
2986
2987                 p += hlen;
2988                 /* Now write out lengths: p points to end of data written */
2989                 /* Total length */
2990                 len = p - ssl_handshake_start(s);
2991                 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
2992                 /* Skip ticket lifetime hint */
2993                 p = ssl_handshake_start(s) + 4;
2994                 s2n(len - 6, p);
2995                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
2996                 OPENSSL_free(senc);
2997                 }
2998
2999         /* SSL3_ST_SW_SESSION_TICKET_B */
3000         return ssl_do_write(s);
3001         }
3002
3003 int ssl3_send_cert_status(SSL *s)
3004         {
3005         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3006                 {
3007                 unsigned char *p;
3008                 /* Grow buffer if need be: the length calculation is as
3009                  * follows 1 (message type) + 3 (message length) +
3010                  * 1 (ocsp response type) + 3 (ocsp response length)
3011                  * + (ocsp response)
3012                  */
3013                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3014                         return -1;
3015
3016                 p=(unsigned char *)s->init_buf->data;
3017
3018                 /* do the header */
3019                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3020                 /* message length */
3021                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3022                 /* status type */
3023                 *(p++)= s->tlsext_status_type;
3024                 /* length of OCSP response */
3025                 l2n3(s->tlsext_ocsp_resplen, p);
3026                 /* actual response */
3027                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3028                 /* number of bytes to write */
3029                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3030                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3031                 s->init_off = 0;
3032                 }
3033
3034         /* SSL3_ST_SW_CERT_STATUS_B */
3035         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3036         }
3037
3038 # ifndef OPENSSL_NO_NEXTPROTONEG
3039 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3040  * sets the next_proto member in s if found */
3041 int ssl3_get_next_proto(SSL *s)
3042         {
3043         int ok;
3044         long n;
3045         CBS next_protocol, selected_protocol, padding;
3046
3047         /* Clients cannot send a NextProtocol message if we didn't see the
3048          * extension in their ClientHello */
3049         if (!s->s3->next_proto_neg_seen)
3050                 {
3051                 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3052                 return -1;
3053                 }
3054
3055         n=s->method->ssl_get_message(s,
3056                 SSL3_ST_SR_NEXT_PROTO_A,
3057                 SSL3_ST_SR_NEXT_PROTO_B,
3058                 SSL3_MT_NEXT_PROTO,
3059                 514,  /* See the payload format below */
3060                 &ok);
3061
3062         if (!ok)
3063                 return((int)n);
3064
3065         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3066          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3067          * by ssl3_get_finished).
3068          * TODO(davidben): Is this check now redundant with
3069          * SSL3_FLAGS_EXPECT_CCS? */
3070         if (!s->s3->change_cipher_spec)
3071                 {
3072                 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3073                 return -1;
3074                 }
3075
3076         CBS_init(&next_protocol, s->init_msg, n);
3077
3078         /* The payload looks like:
3079          *   uint8 proto_len;
3080          *   uint8 proto[proto_len];
3081          *   uint8 padding_len;
3082          *   uint8 padding[padding_len];
3083          */
3084         if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
3085                 !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
3086                 CBS_len(&next_protocol) != 0)
3087                 return 0;
3088
3089         if (!CBS_stow(&selected_protocol,
3090                         &s->next_proto_negotiated,
3091                         &s->next_proto_negotiated_len))
3092                 return 0;
3093
3094         return 1;
3095         }
3096 # endif
3097
3098 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
3099 int ssl3_get_channel_id(SSL *s)
3100         {
3101         int ret = -1, ok;
3102         long n;
3103         const uint8_t *p;
3104         uint16_t extension_type, expected_extension_type;
3105         EC_GROUP* p256 = NULL;
3106         EC_KEY* key = NULL;
3107         EC_POINT* point = NULL;
3108         ECDSA_SIG sig;
3109         BIGNUM x, y;
3110         CBS encrypted_extensions, extension;
3111
3112         if (s->state == SSL3_ST_SR_CHANNEL_ID_A && s->init_num == 0)
3113                 {
3114                 /* The first time that we're called we take the current
3115                  * handshake hash and store it. */
3116                 EVP_MD_CTX md_ctx;
3117                 unsigned int len;
3118
3119                 EVP_MD_CTX_init(&md_ctx);
3120                 EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL);
3121                 if (!tls1_channel_id_hash(&md_ctx, s))
3122                         return -1;
3123                 len = sizeof(s->s3->tlsext_channel_id);
3124                 EVP_DigestFinal(&md_ctx, s->s3->tlsext_channel_id, &len);
3125                 EVP_MD_CTX_cleanup(&md_ctx);
3126                 }
3127
3128         n = s->method->ssl_get_message(s,
3129                 SSL3_ST_SR_CHANNEL_ID_A,
3130                 SSL3_ST_SR_CHANNEL_ID_B,
3131                 SSL3_MT_ENCRYPTED_EXTENSIONS,
3132                 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
3133                 &ok);
3134
3135         if (!ok)
3136                 return((int)n);
3137
3138         ssl3_finish_mac(s, (unsigned char*)s->init_buf->data, s->init_num + 4);
3139
3140         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3141          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3142          * by ssl3_get_finished).
3143          * TODO(davidben): Is this check now redundant with
3144          * SSL3_FLAGS_EXPECT_CCS? */
3145         if (!s->s3->change_cipher_spec)
3146                 {
3147                 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
3148                 return -1;
3149                 }
3150
3151         CBS_init(&encrypted_extensions, s->init_msg, n);
3152
3153         /* EncryptedExtensions could include multiple extensions, but
3154          * the only extension that could be negotiated is ChannelID,
3155          * so there can only be one entry.
3156          *
3157          * The payload looks like:
3158          *   uint16 extension_type
3159          *   uint16 extension_len;
3160          *   uint8 x[32];
3161          *   uint8 y[32];
3162          *   uint8 r[32];
3163          *   uint8 s[32];
3164          */
3165         expected_extension_type = TLSEXT_TYPE_channel_id;
3166         if (s->s3->tlsext_channel_id_new)
3167                 expected_extension_type = TLSEXT_TYPE_channel_id_new;
3168
3169         if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
3170                 !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
3171                 CBS_len(&encrypted_extensions) != 0 ||
3172                 extension_type != expected_extension_type ||
3173                 CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE)
3174                 {
3175                 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
3176                 return -1;
3177                 }
3178
3179         p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
3180         if (!p256)
3181                 {
3182                 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
3183                 return -1;
3184                 }
3185
3186         BN_init(&x);
3187         BN_init(&y);
3188         sig.r = BN_new();
3189         sig.s = BN_new();
3190
3191         p = CBS_data(&extension);
3192         if (BN_bin2bn(p +  0, 32, &x) == NULL ||
3193             BN_bin2bn(p + 32, 32, &y) == NULL ||
3194             BN_bin2bn(p + 64, 32, sig.r) == NULL ||
3195             BN_bin2bn(p + 96, 32, sig.s) == NULL)
3196                 goto err;
3197
3198         point = EC_POINT_new(p256);
3199         if (!point ||
3200             !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
3201                 goto err;
3202
3203         key = EC_KEY_new();
3204         if (!key ||
3205             !EC_KEY_set_group(key, p256) ||
3206             !EC_KEY_set_public_key(key, point))
3207                 goto err;
3208
3209         /* We stored the handshake hash in |tlsext_channel_id| the first time
3210          * that we were called. */
3211         switch (ECDSA_do_verify(s->s3->tlsext_channel_id, SHA256_DIGEST_LENGTH, &sig, key)) {
3212         case 1:
3213                 break;
3214         case 0:
3215                 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
3216                 s->s3->tlsext_channel_id_valid = 0;
3217                 goto err;
3218         default:
3219                 s->s3->tlsext_channel_id_valid = 0;
3220                 goto err;
3221         }
3222
3223         memcpy(s->s3->tlsext_channel_id, p, 64);
3224         ret = 1;
3225
3226 err:
3227         BN_free(&x);
3228         BN_free(&y);
3229         BN_free(sig.r);
3230         BN_free(sig.s);
3231         if (key)
3232                 EC_KEY_free(key);
3233         if (point)
3234                 EC_POINT_free(point);
3235         if (p256)
3236                 EC_GROUP_free(p256);
3237         return ret;
3238         }
3239