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