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