Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by 
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150
151 #include <stdio.h>
152
153 #include <openssl/buf.h>
154 #include <openssl/bytestring.h>
155 #include <openssl/rand.h>
156 #include <openssl/obj.h>
157 #include <openssl/evp.h>
158 #include <openssl/mem.h>
159 #include <openssl/md5.h>
160 #include <openssl/dh.h>
161 #include <openssl/bn.h>
162 #include <openssl/engine.h>
163 #include <openssl/x509.h>
164
165 #include "ssl_locl.h"
166 #include "../crypto/dh/internal.h"
167
168 static const SSL_METHOD *ssl3_get_client_method(int ver)
169         {
170         switch (ver)
171                 {
172         case TLS1_2_VERSION:
173                 return TLSv1_2_client_method();
174         case TLS1_1_VERSION:
175                 return TLSv1_1_client_method();
176         case TLS1_VERSION:
177                 return TLSv1_client_method();
178         case SSL3_VERSION:
179                 return SSLv3_client_method();
180         default:
181                 return NULL;
182                 }
183         }
184
185 IMPLEMENT_tls_meth_func(TLS1_2_VERSION, TLSv1_2_client_method,
186                         ssl_undefined_function,
187                         ssl3_connect,
188                         ssl3_get_client_method,
189                         TLSv1_2_enc_data)
190
191 IMPLEMENT_tls_meth_func(TLS1_1_VERSION, TLSv1_1_client_method,
192                         ssl_undefined_function,
193                         ssl3_connect,
194                         ssl3_get_client_method,
195                         TLSv1_1_enc_data)
196
197 IMPLEMENT_tls_meth_func(TLS1_VERSION, TLSv1_client_method,
198                         ssl_undefined_function,
199                         ssl3_connect,
200                         ssl3_get_client_method,
201                         TLSv1_enc_data)
202
203 IMPLEMENT_tls_meth_func(SSL3_VERSION, SSLv3_client_method,
204                         ssl_undefined_function,
205                         ssl3_connect,
206                         ssl3_get_client_method,
207                         SSLv3_enc_data)
208
209 int ssl3_connect(SSL *s)
210         {
211         BUF_MEM *buf=NULL;
212         void (*cb)(const SSL *ssl,int type,int val)=NULL;
213         int ret= -1;
214         int new_state,state,skip=0;
215
216         ERR_clear_error();
217         ERR_clear_system_error();
218
219         if (s->info_callback != NULL)
220                 cb=s->info_callback;
221         else if (s->ctx->info_callback != NULL)
222                 cb=s->ctx->info_callback;
223         
224         s->in_handshake++;
225         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
226
227         for (;;)
228                 {
229                 state=s->state;
230
231                 switch(s->state)
232                         {
233                 case SSL_ST_RENEGOTIATE:
234                         s->renegotiate=1;
235                         s->state=SSL_ST_CONNECT;
236                         s->ctx->stats.sess_connect_renegotiate++;
237                         /* break */
238                 case SSL_ST_BEFORE:
239                 case SSL_ST_CONNECT:
240                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
241                 case SSL_ST_OK|SSL_ST_CONNECT:
242
243                         s->server=0;
244                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
245
246                         if ((s->version & 0xff00 ) != 0x0300)
247                                 {
248                                 OPENSSL_PUT_ERROR(SSL, ssl3_connect, ERR_R_INTERNAL_ERROR);
249                                 ret = -1;
250                                 goto end;
251                                 }
252                                 
253                         /* s->version=SSL3_VERSION; */
254                         s->type=SSL_ST_CONNECT;
255
256                         if (s->init_buf == NULL)
257                                 {
258                                 if ((buf=BUF_MEM_new()) == NULL)
259                                         {
260                                         ret= -1;
261                                         goto end;
262                                         }
263                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
264                                         {
265                                         ret= -1;
266                                         goto end;
267                                         }
268                                 s->init_buf=buf;
269                                 buf=NULL;
270                                 }
271
272                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
273
274                         /* setup buffing BIO */
275                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
276
277                         /* don't push the buffering BIO quite yet */
278
279                         ssl3_init_finished_mac(s);
280
281                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
282                         s->ctx->stats.sess_connect++;
283                         s->init_num=0;
284                         break;
285
286                 case SSL3_ST_CW_CLNT_HELLO_A:
287                 case SSL3_ST_CW_CLNT_HELLO_B:
288
289                         s->shutdown=0;
290                         ret=ssl3_send_client_hello(s);
291                         if (ret <= 0) goto end;
292                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
293                         s->init_num=0;
294
295                         /* turn on buffering for the next lot of output */
296                         if (s->bbio != s->wbio)
297                                 s->wbio=BIO_push(s->bbio,s->wbio);
298
299                         break;
300
301                 case SSL3_ST_CR_SRVR_HELLO_A:
302                 case SSL3_ST_CR_SRVR_HELLO_B:
303                         ret=ssl3_get_server_hello(s);
304                         if (ret <= 0) goto end;
305
306                         if (s->hit)
307                                 {
308                                 s->state=SSL3_ST_CR_CHANGE;
309                                 if (s->tlsext_ticket_expected)
310                                         {
311                                         /* receive renewed session ticket */
312                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
313                                         }
314                                 }
315                         else
316                                 {
317                                 s->state=SSL3_ST_CR_CERT_A;
318                                 }
319                         s->init_num=0;
320                         break;
321
322                 case SSL3_ST_CR_CERT_A:
323                 case SSL3_ST_CR_CERT_B:
324                         if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
325                                 {
326                                 ret=ssl3_get_server_certificate(s);
327                                 if (ret <= 0) goto end;
328                                 if (s->s3->tmp.certificate_status_expected)
329                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
330                                 else
331                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
332                                 }
333                         else
334                                 {
335                                 skip = 1;
336                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
337                                 }
338                         s->init_num=0;
339                         break;
340
341                 case SSL3_ST_CR_KEY_EXCH_A:
342                 case SSL3_ST_CR_KEY_EXCH_B:
343                         ret=ssl3_get_server_key_exchange(s);
344                         if (ret <= 0) goto end;
345                         s->state=SSL3_ST_CR_CERT_REQ_A;
346                         s->init_num=0;
347
348                         /* at this point we check that we have the
349                          * required stuff from the server */
350                         if (!ssl3_check_cert_and_algorithm(s))
351                                 {
352                                 ret= -1;
353                                 goto end;
354                                 }
355                         break;
356
357                 case SSL3_ST_CR_CERT_REQ_A:
358                 case SSL3_ST_CR_CERT_REQ_B:
359                         ret=ssl3_get_certificate_request(s);
360                         if (ret <= 0) goto end;
361                         s->state=SSL3_ST_CR_SRVR_DONE_A;
362                         s->init_num=0;
363                         break;
364
365                 case SSL3_ST_CR_SRVR_DONE_A:
366                 case SSL3_ST_CR_SRVR_DONE_B:
367                         ret=ssl3_get_server_done(s);
368                         if (ret <= 0) goto end;
369                         if (s->s3->tmp.cert_req)
370                                 s->state=SSL3_ST_CW_CERT_A;
371                         else
372                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
373                         s->init_num=0;
374
375                         break;
376
377                 case SSL3_ST_CW_CERT_A:
378                 case SSL3_ST_CW_CERT_B:
379                 case SSL3_ST_CW_CERT_C:
380                 case SSL3_ST_CW_CERT_D:
381                         ret=ssl3_send_client_certificate(s);
382                         if (ret <= 0) goto end;
383                         s->state=SSL3_ST_CW_KEY_EXCH_A;
384                         s->init_num=0;
385                         break;
386
387                 case SSL3_ST_CW_KEY_EXCH_A:
388                 case SSL3_ST_CW_KEY_EXCH_B:
389                         ret=ssl3_send_client_key_exchange(s);
390                         if (ret <= 0) goto end;
391                         /* For TLS, cert_req is set to 2, so a cert chain
392                          * of nothing is sent, but no verify packet is sent */
393                         if (s->s3->tmp.cert_req == 1)
394                                 {
395                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
396                                 }
397                         else
398                                 {
399                                 s->state=SSL3_ST_CW_CHANGE_A;
400                                 s->s3->change_cipher_spec=0;
401                                 }
402
403                         s->init_num=0;
404                         break;
405
406                 case SSL3_ST_CW_CERT_VRFY_A:
407                 case SSL3_ST_CW_CERT_VRFY_B:
408                         ret=ssl3_send_cert_verify(s);
409                         if (ret <= 0) goto end;
410                         s->state=SSL3_ST_CW_CHANGE_A;
411                         s->init_num=0;
412                         s->s3->change_cipher_spec=0;
413                         break;
414
415                 case SSL3_ST_CW_CHANGE_A:
416                 case SSL3_ST_CW_CHANGE_B:
417                         ret=ssl3_send_change_cipher_spec(s,
418                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
419                         if (ret <= 0) goto end;
420
421                         s->state=SSL3_ST_CW_FINISHED_A;
422                         if (s->s3->tlsext_channel_id_valid)
423                                 s->state=SSL3_ST_CW_CHANNEL_ID_A;
424                         if (s->s3->next_proto_neg_seen)
425                                 s->state=SSL3_ST_CW_NEXT_PROTO_A;
426                         s->init_num=0;
427
428                         s->session->cipher=s->s3->tmp.new_cipher;
429                         if (!s->method->ssl3_enc->setup_key_block(s))
430                                 {
431                                 ret= -1;
432                                 goto end;
433                                 }
434
435                         if (!s->method->ssl3_enc->change_cipher_state(s,
436                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
437                                 {
438                                 ret= -1;
439                                 goto end;
440                                 }
441
442                         break;
443
444                 case SSL3_ST_CW_NEXT_PROTO_A:
445                 case SSL3_ST_CW_NEXT_PROTO_B:
446                         ret=ssl3_send_next_proto(s);
447                         if (ret <= 0) goto end;
448                         if (s->s3->tlsext_channel_id_valid)
449                                 s->state=SSL3_ST_CW_CHANNEL_ID_A;
450                         else
451                                 s->state=SSL3_ST_CW_FINISHED_A;
452                         break;
453
454                 case SSL3_ST_CW_CHANNEL_ID_A:
455                 case SSL3_ST_CW_CHANNEL_ID_B:
456                         ret=ssl3_send_channel_id(s);
457                         if (ret <= 0) goto end;
458                         s->state=SSL3_ST_CW_FINISHED_A;
459                         break;
460
461                 case SSL3_ST_CW_FINISHED_A:
462                 case SSL3_ST_CW_FINISHED_B:
463                         ret=ssl3_send_finished(s,
464                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
465                                 s->method->ssl3_enc->client_finished_label,
466                                 s->method->ssl3_enc->client_finished_label_len);
467                         if (ret <= 0) goto end;
468                         s->state=SSL3_ST_CW_FLUSH;
469
470                         /* clear flags */
471                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
472                         if (s->hit)
473                                 {
474                                 s->s3->tmp.next_state=SSL_ST_OK;
475                                 }
476                         else
477                                 {
478                                 /* This is a non-resumption handshake. If it
479                                  * involves ChannelID, then record the
480                                  * handshake hashes at this point in the
481                                  * session so that any resumption of this
482                                  * session with ChannelID can sign those
483                                  * hashes. */
484                                 if (s->s3->tlsext_channel_id_new)
485                                         {
486                                         ret = tls1_record_handshake_hashes_for_channel_id(s);
487                                         if (ret <= 0)
488                                                 goto end;
489                                         }
490                                 if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH)
491                                     && ssl3_can_cutthrough(s)
492                                     && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */
493                                    )
494                                         {
495                                         s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE;
496                                         }
497                                 else
498                                         {
499                                         /* Allow NewSessionTicket if ticket expected */
500                                         if (s->tlsext_ticket_expected)
501                                                 s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
502                                         else
503                                                 s->s3->tmp.next_state=SSL3_ST_CR_CHANGE;
504                                         }
505                                 }
506                         s->init_num=0;
507                         break;
508
509                 case SSL3_ST_CR_SESSION_TICKET_A:
510                 case SSL3_ST_CR_SESSION_TICKET_B:
511                         ret=ssl3_get_new_session_ticket(s);
512                         if (ret <= 0) goto end;
513                         s->state=SSL3_ST_CR_CHANGE;
514                         s->init_num=0;
515                 break;
516
517                 case SSL3_ST_CR_CERT_STATUS_A:
518                 case SSL3_ST_CR_CERT_STATUS_B:
519                         ret=ssl3_get_cert_status(s);
520                         if (ret <= 0) goto end;
521                         s->state=SSL3_ST_CR_KEY_EXCH_A;
522                         s->init_num=0;
523                 break;
524
525                 case SSL3_ST_CR_CHANGE:
526                         /* At this point, the next message must be entirely
527                          * behind a ChangeCipherSpec. */
528                         if (!ssl3_expect_change_cipher_spec(s))
529                                 {
530                                 ret = -1;
531                                 goto end;
532                                 }
533                         s->state = SSL3_ST_CR_FINISHED_A;
534                         break;
535
536                 case SSL3_ST_CR_FINISHED_A:
537                 case SSL3_ST_CR_FINISHED_B:
538                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
539                                 SSL3_ST_CR_FINISHED_B);
540                         if (ret <= 0) goto end;
541
542                         if (s->hit)
543                                 s->state=SSL3_ST_CW_CHANGE_A;
544                         else
545                                 s->state=SSL_ST_OK;
546                         s->init_num=0;
547                         break;
548
549                 case SSL3_ST_CW_FLUSH:
550                         s->rwstate=SSL_WRITING;
551                         if (BIO_flush(s->wbio) <= 0)
552                                 {
553                                 ret= -1;
554                                 goto end;
555                                 }
556                         s->rwstate=SSL_NOTHING;
557                         s->state=s->s3->tmp.next_state;
558                         break;
559
560                 case SSL3_ST_CUTTHROUGH_COMPLETE:
561                         /* Allow NewSessionTicket if ticket expected */
562                         if (s->tlsext_ticket_expected)
563                                 s->state=SSL3_ST_CR_SESSION_TICKET_A;
564                         else
565                                 s->state=SSL3_ST_CR_CHANGE;
566
567                         ssl_free_wbio_buffer(s);
568                         ret = 1;
569                         goto end;
570                         /* break; */
571
572                 case SSL_ST_OK:
573                         /* clean a few things up */
574                         ssl3_cleanup_key_block(s);
575
576                         if (s->init_buf != NULL)
577                                 {
578                                 BUF_MEM_free(s->init_buf);
579                                 s->init_buf=NULL;
580                                 }
581
582                         /* If we are not 'joining' the last two packets,
583                          * remove the buffering now */
584                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
585                                 ssl_free_wbio_buffer(s);
586                         /* else do it later in ssl3_write */
587
588                         s->init_num=0;
589                         s->renegotiate=0;
590                         s->new_session=0;
591
592                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
593                         if (s->hit) s->ctx->stats.sess_hit++;
594
595                         ret=1;
596                         /* s->server=0; */
597                         s->handshake_func=ssl3_connect;
598                         s->ctx->stats.sess_connect_good++;
599
600                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
601
602                         goto end;
603                         /* break; */
604                         
605                 default:
606                         OPENSSL_PUT_ERROR(SSL, ssl3_connect, SSL_R_UNKNOWN_STATE);
607                         ret= -1;
608                         goto end;
609                         /* break; */
610                         }
611
612                 /* did we do anything */
613                 if (!s->s3->tmp.reuse_message && !skip)
614                         {
615                         if (s->debug)
616                                 {
617                                 if ((ret=BIO_flush(s->wbio)) <= 0)
618                                         goto end;
619                                 }
620
621                         if ((cb != NULL) && (s->state != state))
622                                 {
623                                 new_state=s->state;
624                                 s->state=state;
625                                 cb(s,SSL_CB_CONNECT_LOOP,1);
626                                 s->state=new_state;
627                                 }
628                         }
629                 skip=0;
630                 }
631 end:
632         s->in_handshake--;
633         if (buf != NULL)
634                 BUF_MEM_free(buf);
635         if (cb != NULL)
636                 cb(s,SSL_CB_CONNECT_EXIT,ret);
637         return(ret);
638         }
639
640
641 int ssl3_send_client_hello(SSL *s)
642         {
643         unsigned char *buf;
644         unsigned char *p,*d;
645         int i;
646         unsigned long l;
647
648         buf=(unsigned char *)s->init_buf->data;
649         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
650                 {
651                 SSL_SESSION *sess = s->session;
652                 if (sess == NULL ||
653                         sess->ssl_version != s->version ||
654                         !sess->session_id_length ||
655                         sess->not_resumable)
656                         {
657                         if (!ssl_get_new_session(s,0))
658                                 goto err;
659                         }
660                 if (s->method->version == DTLS_ANY_VERSION)
661                         {
662                         /* Determine which DTLS version to use */
663                         int options = s->options;
664                         /* If DTLS 1.2 disabled correct the version number */
665                         if (options & SSL_OP_NO_DTLSv1_2)
666                                 {
667                                 /* Disabling all versions is silly: return an
668                                  * error.
669                                  */
670                                 if (options & SSL_OP_NO_DTLSv1)
671                                         {
672                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_WRONG_SSL_VERSION);
673                                         goto err;
674                                         }
675                                 /* Update method so we don't use any DTLS 1.2
676                                  * features.
677                                  */
678                                 s->method = DTLSv1_client_method();
679                                 s->version = DTLS1_VERSION;
680                                 }
681                         else
682                                 {
683                                 /* We only support one version: update method */
684                                 if (options & SSL_OP_NO_DTLSv1)
685                                         s->method = DTLSv1_2_client_method();
686                                 s->version = DTLS1_2_VERSION;
687                                 }
688                         s->client_version = s->version;
689                         }
690                 /* else use the pre-loaded session */
691
692                 p=s->s3->client_random;
693
694                 /* If resending the ClientHello in DTLS after a
695                  * HelloVerifyRequest, don't renegerate the client_random. The
696                  * random must be reused. */
697                 if (!SSL_IS_DTLS(s) || !s->d1->send_cookie)
698                         {
699                         ssl_fill_hello_random(s, 0, p,
700                                               sizeof(s->s3->client_random));
701                         }
702
703                 /* Do the message type and length last.
704                  * Note: the final argument to ssl_add_clienthello_tlsext below
705                  * depends on the size of this prefix. */
706                 d=p= ssl_handshake_start(s);
707
708                 /* version indicates the negotiated version: for example from
709                  * an SSLv2/v3 compatible client hello). The client_version
710                  * field is the maximum version we permit and it is also
711                  * used in RSA encrypted premaster secrets. Some servers can
712                  * choke if we initially report a higher version then
713                  * renegotiate to a lower one in the premaster secret. This
714                  * didn't happen with TLS 1.0 as most servers supported it
715                  * but it can with TLS 1.1 or later if the server only supports
716                  * 1.0.
717                  *
718                  * Possible scenario with previous logic:
719                  *      1. Client hello indicates TLS 1.2
720                  *      2. Server hello says TLS 1.0
721                  *      3. RSA encrypted premaster secret uses 1.2.
722                  *      4. Handhaked proceeds using TLS 1.0.
723                  *      5. Server sends hello request to renegotiate.
724                  *      6. Client hello indicates TLS v1.0 as we now
725                  *         know that is maximum server supports.
726                  *      7. Server chokes on RSA encrypted premaster secret
727                  *         containing version 1.0.
728                  *
729                  * For interoperability it should be OK to always use the
730                  * maximum version we support in client hello and then rely
731                  * on the checking of version to ensure the servers isn't
732                  * being inconsistent: for example initially negotiating with
733                  * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
734                  * client_version in client hello and not resetting it to
735                  * the negotiated version.
736                  */
737 #if 0
738                 *(p++)=s->version>>8;
739                 *(p++)=s->version&0xff;
740                 s->client_version=s->version;
741 #else
742                 *(p++)=s->client_version>>8;
743                 *(p++)=s->client_version&0xff;
744 #endif
745
746                 /* Random stuff */
747                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
748                 p+=SSL3_RANDOM_SIZE;
749
750                 /* Session ID */
751                 if (s->new_session)
752                         i=0;
753                 else
754                         i=s->session->session_id_length;
755                 *(p++)=i;
756                 if (i != 0)
757                         {
758                         if (i > (int)sizeof(s->session->session_id))
759                                 {
760                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
761                                 goto err;
762                                 }
763                         memcpy(p,s->session->session_id,i);
764                         p+=i;
765                         }
766                 
767                 /* cookie stuff for DTLS */
768                 if (SSL_IS_DTLS(s))
769                         {
770                         if ( s->d1->cookie_len > sizeof(s->d1->cookie))
771                                 {
772                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
773                                 goto err;
774                                 }
775                         *(p++) = s->d1->cookie_len;
776                         memcpy(p, s->d1->cookie, s->d1->cookie_len);
777                         p += s->d1->cookie_len;
778                         }
779                 
780                 /* Ciphers supported */
781                 i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &p[2]);
782                 if (i == 0)
783                         {
784                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_NO_CIPHERS_AVAILABLE);
785                         goto err;
786                         }
787                 s2n(i,p);
788                 p+=i;
789
790                 /* COMPRESSION */
791                 *(p++)=1;
792                 *(p++)=0; /* Add the NULL method */
793
794                 /* TLS extensions*/
795                 if (ssl_prepare_clienthello_tlsext(s) <= 0)
796                         {
797                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
798                         goto err;
799                         }
800                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, p-buf)) == NULL)
801                         {
802                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
803                         goto err;
804                         }
805                 
806                 l= p-d;
807                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
808                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
809                 }
810
811         /* SSL3_ST_CW_CLNT_HELLO_B */
812         return ssl_do_write(s);
813 err:
814         return(-1);
815         }
816
817 int ssl3_get_server_hello(SSL *s)
818         {
819         STACK_OF(SSL_CIPHER) *sk;
820         const SSL_CIPHER *c;
821         CERT *ct = s->cert;
822         int al=SSL_AD_INTERNAL_ERROR,ok;
823         long n;
824         CBS server_hello, server_random, session_id;
825         uint16_t server_version, cipher_suite;
826         uint8_t compression_method;
827         unsigned long mask_ssl;
828
829         n=s->method->ssl_get_message(s,
830                 SSL3_ST_CR_SRVR_HELLO_A,
831                 SSL3_ST_CR_SRVR_HELLO_B,
832                 SSL3_MT_SERVER_HELLO,
833                 20000, /* ?? */
834                 SSL_GET_MESSAGE_HASH_MESSAGE,
835                 &ok);
836
837         if (!ok) return((int)n);
838
839         CBS_init(&server_hello, s->init_msg, n);
840
841         if (!CBS_get_u16(&server_hello, &server_version) ||
842                 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
843                 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
844                 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
845                 !CBS_get_u16(&server_hello, &cipher_suite) ||
846                 !CBS_get_u8(&server_hello, &compression_method))
847                 {
848                 al = SSL_AD_DECODE_ERROR;
849                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_DECODE_ERROR);
850                 goto f_err;
851                 }
852
853         if (s->method->version == DTLS_ANY_VERSION)
854                 {
855                 /* Work out correct protocol version to use */
856                 int options = s->options;
857                 if (server_version == DTLS1_2_VERSION
858                         && !(options & SSL_OP_NO_DTLSv1_2))
859                         s->method = DTLSv1_2_client_method();
860                 else if (server_version == DTLS1_VERSION
861                         && !(options & SSL_OP_NO_DTLSv1))
862                         s->method = DTLSv1_client_method();
863                 else
864                         {
865                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
866                         s->version = server_version;
867                         al = SSL_AD_PROTOCOL_VERSION;
868                         goto f_err;
869                         }
870                 s->version = s->client_version = s->method->version;
871                 }
872
873         if (server_version != s->version)
874                 {
875                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
876                 s->version = (s->version & 0xff00) | (server_version & 0xff);
877                 al = SSL_AD_PROTOCOL_VERSION;
878                 goto f_err;
879                 }
880
881         /* Copy over the server random. */
882         memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
883
884         s->hit = 0;
885
886         /* check if we want to resume the session based on external pre-shared secret */
887         if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
888                 {
889                 const SSL_CIPHER *pref_cipher=NULL;
890                 s->session->master_key_length=sizeof(s->session->master_key);
891                 if (s->tls_session_secret_cb(s, s->session->master_key,
892                                              &s->session->master_key_length,
893                                              NULL, &pref_cipher,
894                                              s->tls_session_secret_cb_arg))
895                         {
896                         s->session->cipher = pref_cipher ?
897                                 pref_cipher :
898                                 ssl3_get_cipher_by_value(cipher_suite);
899                         s->hit = 1;
900                         }
901                 }
902
903         if (!s->hit && CBS_len(&session_id) != 0 &&
904                 CBS_mem_equal(&session_id,
905                         s->session->session_id, s->session->session_id_length))
906                 {
907                 if(s->sid_ctx_length != s->session->sid_ctx_length
908                         || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length))
909                         {
910                         /* actually a client application bug */
911                         al = SSL_AD_ILLEGAL_PARAMETER;
912                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
913                         goto f_err;
914                         }
915                 s->hit = 1;
916                 }
917
918         /* a miss or crap from the other end */
919         if (!s->hit)
920                 {
921                 /* If we were trying for session-id reuse, make a new
922                  * SSL_SESSION so we don't stuff up other people */
923                 if (s->session->session_id_length > 0)
924                         {
925                         if (!ssl_get_new_session(s,0))
926                                 {
927                                 goto f_err;
928                                 }
929                         }
930                 /* Note: session_id could be empty. */
931                 s->session->session_id_length = CBS_len(&session_id);
932                 memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
933                 }
934
935         c = ssl3_get_cipher_by_value(cipher_suite);
936         if (c == NULL)
937                 {
938                 /* unknown cipher */
939                 al = SSL_AD_ILLEGAL_PARAMETER;
940                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNKNOWN_CIPHER_RETURNED);
941                 goto f_err;
942                 }
943         /* ct->mask_ssl was computed from client capabilities. Now
944          * that the final version is known, compute a new mask_ssl. */
945         if (!SSL_USE_TLS1_2_CIPHERS(s))
946                 mask_ssl = SSL_TLSV1_2;
947         else
948                 mask_ssl = 0;
949         /* If it is a disabled cipher we didn't send it in client hello,
950          * so return an error.
951          */
952         if (c->algorithm_ssl & mask_ssl ||
953                 c->algorithm_mkey & ct->mask_k ||
954                 c->algorithm_auth & ct->mask_a)
955                 {
956                 al=SSL_AD_ILLEGAL_PARAMETER;
957                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
958                 goto f_err;
959                 }
960
961         sk=ssl_get_ciphers_by_id(s);
962         if (!sk_SSL_CIPHER_find(sk, NULL, c))
963                 {
964                 /* we did not say we would use this cipher */
965                 al=SSL_AD_ILLEGAL_PARAMETER;
966                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
967                 goto f_err;
968                 }
969
970         /* Depending on the session caching (internal/external), the cipher
971            and/or cipher_id values may not be set. Make sure that
972            cipher_id is set and use it for comparison. */
973         if (s->session->cipher)
974                 s->session->cipher_id = s->session->cipher->id;
975         if (s->hit && (s->session->cipher_id != c->id))
976                 {
977                 al = SSL_AD_ILLEGAL_PARAMETER;
978                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
979                 goto f_err;
980                 }
981         s->s3->tmp.new_cipher=c;
982         /* Don't digest cached records if no sigalgs: we may need them for
983          * client authentication.
984          */
985         if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s, free_handshake_buffer))
986                 goto f_err;
987
988         /* Only the NULL compression algorithm is supported. */
989         if (compression_method != 0)
990                 {
991                 al = SSL_AD_ILLEGAL_PARAMETER;
992                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
993                 goto f_err;
994                 }
995
996         /* TLS extensions */
997         if (!ssl_parse_serverhello_tlsext(s, &server_hello))
998                 {
999                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_PARSE_TLSEXT);
1000                 goto err; 
1001                 }
1002
1003         /* There should be nothing left over in the record. */
1004         if (CBS_len(&server_hello) != 0)
1005                 {
1006                 /* wrong packet length */
1007                 al=SSL_AD_DECODE_ERROR;
1008                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_BAD_PACKET_LENGTH);
1009                 goto f_err;
1010                 }
1011
1012         return(1);
1013 f_err:
1014         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1015 err:
1016         return(-1);
1017         }
1018
1019 int ssl3_get_server_certificate(SSL *s)
1020         {
1021         int al,i,ok,ret= -1;
1022         unsigned long n;
1023         X509 *x=NULL;
1024         STACK_OF(X509) *sk=NULL;
1025         SESS_CERT *sc;
1026         EVP_PKEY *pkey=NULL;
1027         CBS cbs, certificate_list;
1028         const uint8_t* data;
1029
1030         n=s->method->ssl_get_message(s,
1031                 SSL3_ST_CR_CERT_A,
1032                 SSL3_ST_CR_CERT_B,
1033                 SSL3_MT_CERTIFICATE,
1034                 s->max_cert_list,
1035                 SSL_GET_MESSAGE_HASH_MESSAGE,
1036                 &ok);
1037
1038         if (!ok) return((int)n);
1039
1040         CBS_init(&cbs, s->init_msg, n);
1041
1042         if ((sk=sk_X509_new_null()) == NULL)
1043                 {
1044                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
1045                 goto err;
1046                 }
1047
1048         if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
1049                 CBS_len(&cbs) != 0)
1050                 {
1051                 al = SSL_AD_DECODE_ERROR;
1052                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_LENGTH_MISMATCH);
1053                 goto f_err;
1054                 }
1055
1056         while (CBS_len(&certificate_list) > 0)
1057                 {
1058                 CBS certificate;
1059                 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
1060                         {
1061                         al = SSL_AD_DECODE_ERROR;
1062                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
1063                         goto f_err;
1064                         }
1065                 data = CBS_data(&certificate);
1066                 x = d2i_X509(NULL, &data, CBS_len(&certificate));
1067                 if (x == NULL)
1068                         {
1069                         al=SSL_AD_BAD_CERTIFICATE;
1070                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_ASN1_LIB);
1071                         goto f_err;
1072                         }
1073                 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
1074                         {
1075                         al = SSL_AD_INTERNAL_ERROR;
1076                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
1077                         goto f_err;
1078                         }
1079                 if (CBS_len(&certificate) != 0)
1080                         {
1081                         al = SSL_AD_DECODE_ERROR;
1082                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
1083                         goto f_err;
1084                         }
1085                 if (!sk_X509_push(sk,x))
1086                         {
1087                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
1088                         goto err;
1089                         }
1090                 x=NULL;
1091                 }
1092
1093         i=ssl_verify_cert_chain(s,sk);
1094         if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1095                 )
1096                 {
1097                 al=ssl_verify_alarm_type(s->verify_result);
1098                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
1099                 goto f_err; 
1100                 }
1101         ERR_clear_error(); /* but we keep s->verify_result */
1102
1103         sc=ssl_sess_cert_new();
1104         if (sc == NULL) goto err;
1105
1106         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1107         s->session->sess_cert=sc;
1108
1109         sc->cert_chain=sk;
1110         /* Inconsistency alert: cert_chain does include the peer's
1111          * certificate, which we don't include in s3_srvr.c */
1112         x=sk_X509_value(sk,0);
1113         sk=NULL;
1114         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1115
1116         pkey=X509_get_pubkey(x);
1117
1118         if ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))
1119                 {
1120                 x=NULL;
1121                 al=SSL3_AL_FATAL;
1122                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1123                 goto f_err;
1124                 }
1125
1126         i=ssl_cert_type(x,pkey);
1127         if (i < 0)
1128                 {
1129                 x=NULL;
1130                 al=SSL3_AL_FATAL;
1131                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1132                 goto f_err;
1133                 }
1134
1135         int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1136         if (exp_idx >= 0 && i != exp_idx)
1137                 {
1138                 x=NULL;
1139                 al=SSL_AD_ILLEGAL_PARAMETER;
1140                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_WRONG_CERTIFICATE_TYPE);
1141                 goto f_err;
1142                 }
1143         sc->peer_cert_type=i;
1144         /* Why would the following ever happen?
1145          * We just created sc a couple of lines ago. */
1146         if (sc->peer_pkeys[i].x509 != NULL)
1147                 X509_free(sc->peer_pkeys[i].x509);
1148         sc->peer_pkeys[i].x509 = X509_up_ref(x);
1149         sc->peer_key = &(sc->peer_pkeys[i]);
1150
1151         if (s->session->peer != NULL)
1152                 X509_free(s->session->peer);
1153         s->session->peer = X509_up_ref(x);
1154
1155         s->session->verify_result = s->verify_result;
1156
1157         x=NULL;
1158         ret=1;
1159         if (0)
1160                 {
1161 f_err:
1162                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1163                 }
1164 err:
1165         EVP_PKEY_free(pkey);
1166         X509_free(x);
1167         sk_X509_pop_free(sk,X509_free);
1168         return(ret);
1169         }
1170
1171 int ssl3_get_server_key_exchange(SSL *s)
1172         {
1173         EVP_MD_CTX md_ctx;
1174         int al,ok;
1175         long n,alg_k,alg_a;
1176         EVP_PKEY *pkey=NULL;
1177         const EVP_MD *md = NULL;
1178         RSA *rsa=NULL;
1179         DH *dh=NULL;
1180         EC_KEY *ecdh = NULL;
1181         BN_CTX *bn_ctx = NULL;
1182         EC_POINT *srvr_ecpoint = NULL;
1183         CBS server_key_exchange, server_key_exchange_orig, parameter;
1184
1185         /* use same message size as in ssl3_get_certificate_request()
1186          * as ServerKeyExchange message may be skipped */
1187         n=s->method->ssl_get_message(s,
1188                 SSL3_ST_CR_KEY_EXCH_A,
1189                 SSL3_ST_CR_KEY_EXCH_B,
1190                 -1,
1191                 s->max_cert_list,
1192                 SSL_GET_MESSAGE_HASH_MESSAGE,
1193                 &ok);
1194         if (!ok) return((int)n);
1195
1196         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1197                 {
1198                 if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher))
1199                         {
1200                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
1201                         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1202                         return -1;
1203                         }
1204
1205                 /* In plain PSK ciphersuite, ServerKeyExchange can be
1206                    omitted if no identity hint is sent. Set
1207                    session->sess_cert anyway to avoid problems
1208                    later.*/
1209                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)
1210                         {
1211                         /* PSK ciphersuites that also send a
1212                          * Certificate would have already initialized
1213                          * |sess_cert|. */
1214                         if (s->session->sess_cert == NULL)
1215                                 s->session->sess_cert = ssl_sess_cert_new();
1216                         if (s->session->psk_identity_hint)
1217                                 {
1218                                 OPENSSL_free(s->session->psk_identity_hint);
1219                                 s->session->psk_identity_hint = NULL;
1220                                 }
1221                         }
1222                 s->s3->tmp.reuse_message=1;
1223                 return(1);
1224                 }
1225
1226         /* Retain a copy of the original CBS to compute the signature
1227          * over. */
1228         CBS_init(&server_key_exchange, s->init_msg, n);
1229         server_key_exchange_orig = server_key_exchange;
1230
1231         if (s->session->sess_cert != NULL)
1232                 {
1233                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1234                         {
1235                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1236                         s->session->sess_cert->peer_rsa_tmp=NULL;
1237                         }
1238                 if (s->session->sess_cert->peer_dh_tmp)
1239                         {
1240                         DH_free(s->session->sess_cert->peer_dh_tmp);
1241                         s->session->sess_cert->peer_dh_tmp=NULL;
1242                         }
1243                 if (s->session->sess_cert->peer_ecdh_tmp)
1244                         {
1245                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1246                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1247                         }
1248                 }
1249         else
1250                 {
1251                 s->session->sess_cert=ssl_sess_cert_new();
1252                 }
1253
1254         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1255         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1256         EVP_MD_CTX_init(&md_ctx);
1257
1258         if (alg_a & SSL_aPSK)
1259                 {
1260                 CBS psk_identity_hint;
1261
1262                 /* Each of the PSK key exchanges begins with a
1263                  * psk_identity_hint. */
1264                 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &psk_identity_hint))
1265                         {
1266                         al = SSL_AD_DECODE_ERROR;
1267                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1268                         goto f_err;
1269                         }
1270
1271                 /* Store PSK identity hint for later use, hint is used in
1272                  * ssl3_send_client_key_exchange.  Assume that the maximum
1273                  * length of a PSK identity hint can be as long as the maximum
1274                  * length of a PSK identity. Also do not allow NULL
1275                  * characters; identities are saved as C strings.
1276                  *
1277                  * TODO(davidben): Should invalid hints be ignored? It's a hint
1278                  * rather than a specific identity. */
1279                 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
1280                         CBS_contains_zero_byte(&psk_identity_hint))
1281                         {
1282                         al = SSL_AD_HANDSHAKE_FAILURE;
1283                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1284                         goto f_err;
1285                         }
1286
1287                 /* Save the identity hint as a C string. */
1288                 if (!CBS_strdup(&psk_identity_hint, &s->session->psk_identity_hint))
1289                         {
1290                         al = SSL_AD_HANDSHAKE_FAILURE;
1291                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1292                         goto f_err;
1293                         }
1294                 }
1295
1296         if (alg_k & SSL_kRSA)
1297                 {
1298                 CBS rsa_modulus, rsa_exponent;
1299
1300                 /* TODO(davidben): This was originally for export
1301                  * reasons. Do we still need to support it? */
1302
1303                 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_modulus) ||
1304                         CBS_len(&rsa_modulus) == 0 ||
1305                         !CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_exponent) ||
1306                         CBS_len(&rsa_exponent) == 0)
1307                         {
1308                         al = SSL_AD_DECODE_ERROR;
1309                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1310                         goto f_err;
1311                         }
1312
1313                 if ((rsa=RSA_new()) == NULL)
1314                         {
1315                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1316                         goto err;
1317                         }
1318
1319                 if (!(rsa->n = BN_bin2bn(CBS_data(&rsa_modulus),
1320                                         CBS_len(&rsa_modulus), rsa->n)))
1321                         {
1322                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1323                         goto err;
1324                         }
1325
1326                 if (!(rsa->e = BN_bin2bn(CBS_data(&rsa_exponent),
1327                                         CBS_len(&rsa_exponent), rsa->e)))
1328                         {
1329                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1330                         goto err;
1331                         }
1332
1333                 /* this should be because we are using an export cipher */
1334                 if (alg_a & SSL_aRSA)
1335                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1336                 else
1337                         {
1338                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
1339                         goto err;
1340                         }
1341                 s->session->sess_cert->peer_rsa_tmp=rsa;
1342                 rsa=NULL;
1343                 }
1344         else if (alg_k & SSL_kEDH)
1345                 {
1346                 CBS dh_p, dh_g, dh_Ys;
1347
1348                 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
1349                         CBS_len(&dh_p) == 0 ||
1350                         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
1351                         CBS_len(&dh_g) == 0 ||
1352                         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
1353                         CBS_len(&dh_Ys) == 0)
1354                         {
1355                         al = SSL_AD_DECODE_ERROR;
1356                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1357                         goto f_err;
1358                         }
1359
1360                 if ((dh=DH_new()) == NULL)
1361                         {
1362                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_DH_LIB);
1363                         goto err;
1364                         }
1365
1366                 if (!(dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)))
1367                         {
1368                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1369                         goto err;
1370                         }
1371                 if (!(dh->g=BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)))
1372                         {
1373                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1374                         goto err;
1375                         }
1376                 if (!(dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)))
1377                         {
1378                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1379                         goto err;
1380                         }
1381
1382                 if (DH_size(dh) < 512/8)
1383                         {
1384                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_DH_P_LENGTH);
1385                         goto err;
1386                         }
1387
1388                 if (alg_a & SSL_aRSA)
1389                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1390                 /* else anonymous DH, so no certificate or pkey. */
1391
1392                 s->session->sess_cert->peer_dh_tmp=dh;
1393                 dh=NULL;
1394                 }
1395
1396         else if (alg_k & SSL_kEECDH)
1397                 {
1398                 uint16_t curve_id;
1399                 int curve_nid = 0;
1400                 EC_GROUP *ngroup;
1401                 const EC_GROUP *group;
1402                 CBS point;
1403
1404                 /* Extract elliptic curve parameters and the server's
1405                  * ephemeral ECDH public key.  Check curve is one of
1406                  * our preferences, if not server has sent an invalid
1407                  * curve.
1408                  */
1409                 if (!tls1_check_curve(s, &server_key_exchange, &curve_id))
1410                         {
1411                         al = SSL_AD_DECODE_ERROR;
1412                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_WRONG_CURVE);
1413                         goto f_err;
1414                         }
1415
1416                 if ((curve_nid = tls1_ec_curve_id2nid(curve_id)) == 0)
1417                         {
1418                         al=SSL_AD_INTERNAL_ERROR;
1419                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1420                         goto f_err;
1421                         }
1422
1423                 if ((ecdh=EC_KEY_new()) == NULL)
1424                         {
1425                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1426                         goto err;
1427                         }
1428                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1429                 if (ngroup == NULL)
1430                         {
1431                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
1432                         goto err;
1433                         }
1434                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1435                         {
1436                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
1437                         goto err;
1438                         }
1439                 EC_GROUP_free(ngroup);
1440
1441                 group = EC_KEY_get0_group(ecdh);
1442
1443                 /* Next, get the encoded ECPoint */
1444                 if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point))
1445                         {
1446                         al = SSL_AD_DECODE_ERROR;
1447                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1448                         goto f_err;
1449                         }
1450
1451                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1452                     ((bn_ctx = BN_CTX_new()) == NULL))
1453                         {
1454                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1455                         goto err;
1456                         }
1457
1458                 if (!EC_POINT_oct2point(group, srvr_ecpoint,
1459                                 CBS_data(&point), CBS_len(&point), bn_ctx))
1460                         {
1461                         al = SSL_AD_DECODE_ERROR;
1462                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_ECPOINT);
1463                         goto f_err;
1464                         }
1465
1466                 /* The ECC/TLS specification does not mention
1467                  * the use of DSA to sign ECParameters in the server
1468                  * key exchange message. We do support RSA and ECDSA.
1469                  */
1470                 if (0) ;
1471                 else if (alg_a & SSL_aRSA)
1472                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1473                 else if (alg_a & SSL_aECDSA)
1474                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1475                 /* else anonymous ECDH, so no certificate or pkey. */
1476                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1477                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1478                 ecdh=NULL;
1479                 BN_CTX_free(bn_ctx);
1480                 bn_ctx = NULL;
1481                 EC_POINT_free(srvr_ecpoint);
1482                 srvr_ecpoint = NULL;
1483                 }
1484
1485         else if (!(alg_k & SSL_kPSK))
1486                 {
1487                 al=SSL_AD_UNEXPECTED_MESSAGE;
1488                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
1489                 goto f_err;
1490                 }
1491
1492         /* At this point, |server_key_exchange| contains the
1493          * signature, if any, while |server_key_exchange_orig|
1494          * contains the entire message. From that, derive a CBS
1495          * containing just the parameter. */
1496         CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
1497                 CBS_len(&server_key_exchange_orig) -
1498                 CBS_len(&server_key_exchange));
1499
1500         /* if it was signed, check the signature */
1501         if (pkey != NULL)
1502                 {
1503                 CBS signature;
1504
1505                 if (SSL_USE_SIGALGS(s))
1506                         {
1507                         if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey))
1508                                 goto f_err;
1509                         }
1510                 else
1511                         md = EVP_sha1();
1512
1513                 /* The last field in |server_key_exchange| is the
1514                  * signature. */
1515                 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1516                         CBS_len(&server_key_exchange) != 0)
1517                         {
1518                         al = SSL_AD_DECODE_ERROR;
1519                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1520                         goto f_err;
1521                         }
1522
1523                 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1524                         {
1525                         int num;
1526                         unsigned char *q, md_buf[EVP_MAX_MD_SIZE*2];
1527                         size_t md_len = 0;
1528
1529                         q=md_buf;
1530                         for (num=2; num > 0; num--)
1531                                 {
1532                                 unsigned int digest_len;
1533                                 EVP_DigestInit_ex(&md_ctx,
1534                                         (num == 2) ? EVP_md5() : EVP_sha1(), NULL);
1535                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1536                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1537                                 EVP_DigestUpdate(&md_ctx, CBS_data(&parameter), CBS_len(&parameter));
1538                                 EVP_DigestFinal_ex(&md_ctx, q, &digest_len);
1539                                 q += digest_len;
1540                                 md_len += digest_len;
1541                                 }
1542                         if (!RSA_verify(NID_md5_sha1, md_buf, md_len,
1543                                         CBS_data(&signature), CBS_len(&signature),
1544                                         pkey->pkey.rsa))
1545                                 {
1546                                 al = SSL_AD_DECRYPT_ERROR;
1547                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
1548                                 goto f_err;
1549                                 }
1550                         }
1551                 else
1552                         {
1553                         if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
1554                                 !EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random, SSL3_RANDOM_SIZE) ||
1555                                 !EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random, SSL3_RANDOM_SIZE) ||
1556                                 !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter), CBS_len(&parameter)) ||
1557                                 !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature), CBS_len(&signature)))
1558                                 {
1559                                 /* bad signature */
1560                                 al=SSL_AD_DECRYPT_ERROR;
1561                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
1562                                 goto f_err;
1563                                 }
1564                         }
1565                 }
1566         else
1567                 {
1568                 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1569                         {
1570                         /* Might be wrong key type, check it */
1571                         if (ssl3_check_cert_and_algorithm(s))
1572                                 /* Otherwise this shouldn't happen */
1573                                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
1574                         goto err;
1575                         }
1576                 /* still data left over */
1577                 if (CBS_len(&server_key_exchange) > 0)
1578                         {
1579                         al=SSL_AD_DECODE_ERROR;
1580                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_EXTRA_DATA_IN_MESSAGE);
1581                         goto f_err;
1582                         }
1583                 }
1584         EVP_PKEY_free(pkey);
1585         EVP_MD_CTX_cleanup(&md_ctx);
1586         return(1);
1587 f_err:
1588         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1589 err:
1590         EVP_PKEY_free(pkey);
1591         if (rsa != NULL)
1592                 RSA_free(rsa);
1593         if (dh != NULL)
1594                 DH_free(dh);
1595         BN_CTX_free(bn_ctx);
1596         EC_POINT_free(srvr_ecpoint);
1597         if (ecdh != NULL)
1598                 EC_KEY_free(ecdh);
1599         EVP_MD_CTX_cleanup(&md_ctx);
1600         return(-1);
1601         }
1602
1603 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b)
1604         {
1605         return(X509_NAME_cmp(*a,*b));
1606         }
1607
1608 int ssl3_get_certificate_request(SSL *s)
1609         {
1610         int ok,ret=0;
1611         unsigned long n;
1612         unsigned int i;
1613         X509_NAME *xn=NULL;
1614         STACK_OF(X509_NAME) *ca_sk=NULL;
1615         CBS cbs;
1616         CBS certificate_types;
1617         CBS certificate_authorities;
1618         const uint8_t *data;
1619
1620         n=s->method->ssl_get_message(s,
1621                 SSL3_ST_CR_CERT_REQ_A,
1622                 SSL3_ST_CR_CERT_REQ_B,
1623                 -1,
1624                 s->max_cert_list,
1625                 SSL_GET_MESSAGE_HASH_MESSAGE,
1626                 &ok);
1627
1628         if (!ok) return((int)n);
1629
1630         s->s3->tmp.cert_req=0;
1631
1632         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1633                 {
1634                 s->s3->tmp.reuse_message=1;
1635                 /* If we get here we don't need any cached handshake records
1636                  * as we wont be doing client auth.
1637                  */
1638                 if (s->s3->handshake_buffer)
1639                         {
1640                         if (!ssl3_digest_cached_records(s, free_handshake_buffer))
1641                                 goto err;
1642                         }
1643                 return(1);
1644                 }
1645
1646         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1647                 {
1648                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1649                 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_WRONG_MESSAGE_TYPE);
1650                 goto err;
1651                 }
1652
1653         /* TLS does not like anon-DH with client cert */
1654         if (s->version > SSL3_VERSION)
1655                 {
1656                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1657                         {
1658                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1659                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1660                         goto err;
1661                         }
1662                 }
1663
1664         CBS_init(&cbs, s->init_msg, n);
1665
1666         ca_sk = sk_X509_NAME_new(ca_dn_cmp);
1667         if (ca_sk == NULL)
1668                 {
1669                 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
1670                 goto err;
1671                 }
1672
1673         /* get the certificate types */
1674         if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types))
1675                 {
1676                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1677                 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
1678                 goto err;
1679                 }
1680         if (!CBS_stow(&certificate_types,
1681                         &s->s3->tmp.certificate_types,
1682                         &s->s3->tmp.num_certificate_types))
1683                 {
1684                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1685                 goto err;
1686                 }
1687         if (SSL_USE_SIGALGS(s))
1688                 {
1689                 CBS supported_signature_algorithms;
1690                 if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms))
1691                         {
1692                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1693                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
1694                         goto err;
1695                         }
1696                 /* Clear certificate digests and validity flags */
1697                 for (i = 0; i < SSL_PKEY_NUM; i++)
1698                         {
1699                         s->cert->pkeys[i].digest = NULL;
1700                         s->cert->pkeys[i].valid_flags = 0;
1701                         }
1702                 if (!tls1_process_sigalgs(s, &supported_signature_algorithms))
1703                         {
1704                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1705                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1706                         goto err;
1707                         }
1708                 }
1709
1710         /* get the CA RDNs */
1711         if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities))
1712                 {
1713                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1714                 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_LENGTH_MISMATCH);
1715                 goto err;
1716                 }
1717
1718         while (CBS_len(&certificate_authorities) > 0)
1719                 {
1720                 CBS distinguished_name;
1721                 if (!CBS_get_u16_length_prefixed(&certificate_authorities, &distinguished_name))
1722                         {
1723                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1724                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_TOO_LONG);
1725                         goto err;
1726                         }
1727
1728                 data = CBS_data(&distinguished_name);
1729                 if ((xn=d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name))) == NULL)
1730                         {
1731                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1732                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_ASN1_LIB);
1733                         goto err;
1734                         }
1735
1736                 if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name)))
1737                         {
1738                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1739                         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
1740                         goto err;
1741                         }
1742                 if (CBS_len(&distinguished_name) != 0)
1743                         {
1744                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1745                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_LENGTH_MISMATCH);
1746                         goto err;
1747                         }
1748                 if (!sk_X509_NAME_push(ca_sk,xn))
1749                         {
1750                         OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
1751                         goto err;
1752                         }
1753                 }
1754
1755         /* we should setup a certificate to return.... */
1756         s->s3->tmp.cert_req=1;
1757         if (s->s3->tmp.ca_names != NULL)
1758                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1759         s->s3->tmp.ca_names=ca_sk;
1760         ca_sk=NULL;
1761
1762         ret=1;
1763 err:
1764         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1765         return(ret);
1766         }
1767
1768 int ssl3_get_new_session_ticket(SSL *s)
1769         {
1770         int ok,al,ret=0;
1771         long n;
1772         CBS new_session_ticket, ticket;
1773
1774         n=s->method->ssl_get_message(s,
1775                 SSL3_ST_CR_SESSION_TICKET_A,
1776                 SSL3_ST_CR_SESSION_TICKET_B,
1777                 SSL3_MT_NEWSESSION_TICKET,
1778                 16384,
1779                 SSL_GET_MESSAGE_HASH_MESSAGE,
1780                 &ok);
1781
1782         if (!ok)
1783                 return((int)n);
1784
1785         CBS_init(&new_session_ticket, s->init_msg, n);
1786
1787         if (!CBS_get_u32(&new_session_ticket, &s->session->tlsext_tick_lifetime_hint) ||
1788                 !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1789                 CBS_len(&new_session_ticket) != 0)
1790                 {
1791                 al = SSL_AD_DECODE_ERROR;
1792                 OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, SSL_R_DECODE_ERROR);
1793                 goto f_err;
1794                 }
1795
1796         if (!CBS_stow(&ticket, &s->session->tlsext_tick, &s->session->tlsext_ticklen))
1797                 {
1798                 OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, ERR_R_MALLOC_FAILURE);
1799                 goto err;
1800                 }
1801
1802         /* There are two ways to detect a resumed ticket sesion.
1803          * One is to set an appropriate session ID and then the server
1804          * must return a match in ServerHello. This allows the normal
1805          * client session ID matching to work and we know much 
1806          * earlier that the ticket has been accepted.
1807          * 
1808          * The other way is to set zero length session ID when the
1809          * ticket is presented and rely on the handshake to determine
1810          * session resumption.
1811          *
1812          * We choose the former approach because this fits in with
1813          * assumptions elsewhere in OpenSSL. The session ID is set
1814          * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1815          * ticket.
1816          */ 
1817         EVP_Digest(CBS_data(&ticket), CBS_len(&ticket),
1818                         s->session->session_id, &s->session->session_id_length,
1819                                                         EVP_sha256(), NULL);
1820         ret=1;
1821         return(ret);
1822 f_err:
1823         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1824 err:
1825         return(-1);
1826         }
1827
1828 int ssl3_get_cert_status(SSL *s)
1829         {
1830         int ok, al;
1831         long n;
1832         CBS certificate_status, ocsp_response;
1833         uint8_t status_type;
1834
1835         n=s->method->ssl_get_message(s,
1836                 SSL3_ST_CR_CERT_STATUS_A,
1837                 SSL3_ST_CR_CERT_STATUS_B,
1838                 SSL3_MT_CERTIFICATE_STATUS,
1839                 16384,
1840                 SSL_GET_MESSAGE_HASH_MESSAGE,
1841                 &ok);
1842
1843         if (!ok) return((int)n);
1844
1845         CBS_init(&certificate_status, s->init_msg, n);
1846         if (!CBS_get_u8(&certificate_status, &status_type) ||
1847                 status_type != TLSEXT_STATUSTYPE_ocsp ||
1848                 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
1849                 CBS_len(&ocsp_response) == 0 ||
1850                 CBS_len(&certificate_status) != 0)
1851                 {
1852                 al = SSL_AD_DECODE_ERROR;
1853                 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, SSL_R_DECODE_ERROR);
1854                 goto f_err;
1855                 }
1856
1857         if (!CBS_stow(&ocsp_response,
1858                         &s->session->ocsp_response, &s->session->ocsp_response_length))
1859                 {
1860                 al = SSL_AD_INTERNAL_ERROR;
1861                 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, ERR_R_MALLOC_FAILURE);
1862                 goto f_err;
1863                 }
1864         return 1;
1865 f_err:
1866         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1867         return(-1);
1868         }
1869
1870 int ssl3_get_server_done(SSL *s)
1871         {
1872         int ok,ret=0;
1873         long n;
1874
1875         n=s->method->ssl_get_message(s,
1876                 SSL3_ST_CR_SRVR_DONE_A,
1877                 SSL3_ST_CR_SRVR_DONE_B,
1878                 SSL3_MT_SERVER_DONE,
1879                 30, /* should be very small, like 0 :-) */
1880                 SSL_GET_MESSAGE_HASH_MESSAGE,
1881                 &ok);
1882
1883         if (!ok) return((int)n);
1884         if (n > 0)
1885                 {
1886                 /* should contain no data */
1887                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1888                 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_done, SSL_R_LENGTH_MISMATCH);
1889                 return -1;
1890                 }
1891         ret=1;
1892         return(ret);
1893         }
1894
1895
1896 int ssl3_send_client_key_exchange(SSL *s)
1897         {
1898         unsigned char *p;
1899         int n = 0;
1900         unsigned long alg_k;
1901         unsigned long alg_a;
1902         unsigned char *q;
1903         EVP_PKEY *pkey=NULL;
1904         EC_KEY *clnt_ecdh = NULL;
1905         const EC_POINT *srvr_ecpoint = NULL;
1906         EVP_PKEY *srvr_pub_pkey = NULL;
1907         unsigned char *encodedPoint = NULL;
1908         int encoded_pt_len = 0;
1909         BN_CTX * bn_ctx = NULL;
1910         unsigned int psk_len = 0;
1911         unsigned char psk[PSK_MAX_PSK_LEN];
1912         uint8_t *pms = NULL;
1913         size_t pms_len = 0;
1914
1915         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1916                 {
1917                 p = ssl_handshake_start(s);
1918
1919                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1920                 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1921
1922                 /* If using a PSK key exchange, prepare the pre-shared key. */
1923                 if (alg_a & SSL_aPSK)
1924                         {
1925                         char identity[PSK_MAX_IDENTITY_LEN + 1];
1926                         size_t identity_len;
1927
1928                         if (s->psk_client_callback == NULL)
1929                                 {
1930                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_NO_CLIENT_CB);
1931                                 goto err;
1932                                 }
1933
1934                         memset(identity, 0, sizeof(identity));
1935                         psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
1936                                 identity, sizeof(identity), psk, sizeof(psk));
1937                         if (psk_len > PSK_MAX_PSK_LEN)
1938                                 {
1939                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1940                                 goto err;
1941                                 }
1942                         else if (psk_len == 0)
1943                                 {
1944                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1945                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1946                                 goto err;
1947                                 }
1948                         identity_len = OPENSSL_strnlen(identity, sizeof(identity));
1949                         if (identity_len > PSK_MAX_IDENTITY_LEN)
1950                                 {
1951                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1952                                 goto err;
1953                                 }
1954
1955                         if (s->session->psk_identity != NULL)
1956                                 OPENSSL_free(s->session->psk_identity);
1957                         s->session->psk_identity = BUF_strdup(identity);
1958                         if (s->session->psk_identity == NULL)
1959                                 {
1960                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
1961                                 goto err;
1962                                 }
1963
1964                         /* Write out psk_identity. */
1965                         s2n(identity_len, p);
1966                         memcpy(p, identity, identity_len);
1967                         p += identity_len;
1968                         n = 2 + identity_len;
1969                         }
1970
1971                 /* Depending on the key exchange method, compute |pms|
1972                  * and |pms_len|. */
1973                 if (alg_k & SSL_kRSA)
1974                         {
1975                         RSA *rsa;
1976                         size_t enc_pms_len;
1977
1978                         pms_len = SSL_MAX_MASTER_KEY_LENGTH;
1979                         pms = OPENSSL_malloc(pms_len);
1980                         if (pms == NULL)
1981                                 {
1982                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
1983                                 goto err;
1984                                 }
1985
1986                         if (s->session->sess_cert == NULL)
1987                                 {
1988                                 /* We should always have a server certificate with SSL_kRSA. */
1989                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1990                                 goto err;
1991                                 }
1992
1993                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
1994                                 rsa=s->session->sess_cert->peer_rsa_tmp;
1995                         else
1996                                 {
1997                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1998                                 if ((pkey == NULL) ||
1999                                         (pkey->type != EVP_PKEY_RSA) ||
2000                                         (pkey->pkey.rsa == NULL))
2001                                         {
2002                                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2003                                         goto err;
2004                                         }
2005                                 rsa=pkey->pkey.rsa;
2006                                 EVP_PKEY_free(pkey);
2007                                 }
2008                                 
2009                         pms[0]=s->client_version>>8;
2010                         pms[1]=s->client_version&0xff;
2011                         if (RAND_bytes(&pms[2],SSL_MAX_MASTER_KEY_LENGTH-2) <= 0)
2012                                         goto err;
2013
2014                         s->session->master_key_length=SSL_MAX_MASTER_KEY_LENGTH;
2015
2016                         q=p;
2017                         /* In TLS and beyond, reserve space for the length prefix. */
2018                         if (s->version > SSL3_VERSION)
2019                                 {
2020                                 p += 2;
2021                                 n += 2;
2022                                 }
2023                         if (!RSA_encrypt(rsa, &enc_pms_len, p, RSA_size(rsa),
2024                                         pms, pms_len, RSA_PKCS1_PADDING))
2025                                 {
2026                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_BAD_RSA_ENCRYPT);
2027                                 goto err;
2028                                 }
2029                         n += enc_pms_len;
2030
2031                         /* Log the premaster secret, if logging is enabled. */
2032                         if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx,
2033                                         p, enc_pms_len, pms, pms_len))
2034                                 {
2035                                 goto err;
2036                                 }
2037
2038                         /* Fill in the length prefix. */
2039                         if (s->version > SSL3_VERSION)
2040                                 {
2041                                 s2n(enc_pms_len, q);
2042                                 }
2043                         }
2044                 else if (alg_k & SSL_kEDH)
2045                         {
2046                         DH *dh_srvr, *dh_clnt;
2047                         SESS_CERT *scert = s->session->sess_cert;
2048                         int dh_len;
2049                         size_t pub_len;
2050
2051                         if (scert == NULL) 
2052                                 {
2053                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2054                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
2055                                 goto err;
2056                                 }
2057
2058                         if (scert->peer_dh_tmp == NULL)
2059                                 {
2060                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2061                                 goto err;
2062                                 }
2063                         dh_srvr=scert->peer_dh_tmp;
2064
2065                         /* generate a new random key */
2066                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2067                                 {
2068                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2069                                 goto err;
2070                                 }
2071                         if (!DH_generate_key(dh_clnt))
2072                                 {
2073                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2074                                 DH_free(dh_clnt);
2075                                 goto err;
2076                                 }
2077
2078                         pms_len = DH_size(dh_clnt);
2079                         pms = OPENSSL_malloc(pms_len);
2080                         if (pms == NULL)
2081                                 {
2082                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2083                                 DH_free(dh_clnt);
2084                                 goto err;
2085                                 }
2086
2087                         dh_len = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
2088                         if (dh_len <= 0)
2089                                 {
2090                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2091                                 DH_free(dh_clnt);
2092                                 goto err;
2093                                 }
2094                         pms_len = dh_len;
2095
2096                         /* send off the data */
2097                         pub_len = BN_num_bytes(dh_clnt->pub_key);
2098                         s2n(pub_len, p);
2099                         BN_bn2bin(dh_clnt->pub_key, p);
2100                         n += 2 + pub_len;
2101
2102                         DH_free(dh_clnt);
2103                         }
2104
2105                 else if (alg_k & SSL_kEECDH)
2106                         {
2107                         const EC_GROUP *srvr_group = NULL;
2108                         EC_KEY *tkey;
2109                         int field_size = 0, ecdh_len;
2110
2111                         if (s->session->sess_cert == NULL) 
2112                                 {
2113                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2114                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
2115                                 goto err;
2116                                 }
2117
2118                         if (s->session->sess_cert->peer_ecdh_tmp == NULL)
2119                                 {
2120                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2121                                 goto err;
2122                                 }
2123                         tkey = s->session->sess_cert->peer_ecdh_tmp;
2124
2125                         srvr_group   = EC_KEY_get0_group(tkey);
2126                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2127
2128                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2129                                 {
2130                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2131                                 goto err;
2132                                 }
2133
2134                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2135                                 {
2136                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2137                                 goto err;
2138                                 }
2139
2140                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2141                                 {
2142                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_EC_LIB);
2143                                 goto err;
2144                                 }
2145                         /* Generate a new ECDH key pair */
2146                         if (!(EC_KEY_generate_key(clnt_ecdh)))
2147                                 {
2148                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2149                                 goto err;
2150                                 }
2151
2152                         field_size = EC_GROUP_get_degree(srvr_group);
2153                         if (field_size <= 0)
2154                                 {
2155                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2156                                 goto err;
2157                                 }
2158
2159                         pms_len = (field_size + 7) / 8;
2160                         pms = OPENSSL_malloc(pms_len);
2161                         if (pms == NULL)
2162                                 {
2163                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2164                                 goto err;
2165                                 }
2166
2167                         ecdh_len = ECDH_compute_key(pms, pms_len, srvr_ecpoint, clnt_ecdh, NULL);
2168                         if (ecdh_len <= 0)
2169                                 {
2170                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2171                                 goto err;
2172                                 }
2173                         pms_len = ecdh_len;
2174
2175                         /* First check the size of encoding and
2176                          * allocate memory accordingly.
2177                          */
2178                         encoded_pt_len = 
2179                                 EC_POINT_point2oct(srvr_group, 
2180                                         EC_KEY_get0_public_key(clnt_ecdh), 
2181                                         POINT_CONVERSION_UNCOMPRESSED, 
2182                                         NULL, 0, NULL);
2183
2184                         encodedPoint = (unsigned char *) 
2185                                 OPENSSL_malloc(encoded_pt_len * 
2186                                         sizeof(unsigned char)); 
2187                         bn_ctx = BN_CTX_new();
2188                         if ((encodedPoint == NULL) || 
2189                                 (bn_ctx == NULL)) 
2190                                 {
2191                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2192                                 goto err;
2193                                 }
2194
2195                         /* Encode the public key */
2196                         encoded_pt_len = EC_POINT_point2oct(srvr_group,
2197                                 EC_KEY_get0_public_key(clnt_ecdh),
2198                                 POINT_CONVERSION_UNCOMPRESSED,
2199                                 encodedPoint, encoded_pt_len, bn_ctx);
2200
2201                         *p = encoded_pt_len; /* length of encoded point */
2202                         /* Encoded point will be copied here */
2203                         p += 1;
2204                         n += 1;
2205                         /* copy the point */
2206                         memcpy(p, encodedPoint, encoded_pt_len);
2207                         /* increment n to account for length field */
2208                         n += encoded_pt_len;
2209
2210                         /* Free allocated memory */
2211                         BN_CTX_free(bn_ctx);
2212                         bn_ctx = NULL;
2213                         OPENSSL_free(encodedPoint);
2214                         encodedPoint = NULL;
2215                         EC_KEY_free(clnt_ecdh);
2216                         clnt_ecdh = NULL;
2217                         EVP_PKEY_free(srvr_pub_pkey);
2218                         srvr_pub_pkey = NULL;
2219                         }
2220                 else if (alg_k & SSL_kPSK)
2221                         {
2222                         /* For plain PSK, other_secret is a block of 0s with the same
2223                          * length as the pre-shared key. */
2224                         pms_len = psk_len;
2225                         pms = OPENSSL_malloc(pms_len);
2226                         if (pms == NULL)
2227                                 {
2228                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2229                                 goto err;
2230                                 }
2231                         memset(pms, 0, pms_len);
2232                         }
2233                 else
2234                         {
2235                         ssl3_send_alert(s, SSL3_AL_FATAL,
2236                             SSL_AD_HANDSHAKE_FAILURE);
2237                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2238                         goto err;
2239                         }
2240
2241                 /* For a PSK cipher suite, other_secret is combined
2242                  * with the pre-shared key. */
2243                 if ((alg_a & SSL_aPSK) && psk_len != 0)
2244                         {
2245                         CBB cbb, child;
2246                         uint8_t *new_pms;
2247                         size_t new_pms_len;
2248
2249                         if (!CBB_init(&cbb, 2 + psk_len + 2 + pms_len))
2250                                 {
2251                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2252                                 goto err;
2253                                 }
2254                         if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
2255                                 !CBB_add_bytes(&child, pms, pms_len) ||
2256                                 !CBB_add_u16_length_prefixed(&cbb, &child) ||
2257                                 !CBB_add_bytes(&child, psk, psk_len) ||
2258                                 !CBB_finish(&cbb, &new_pms, &new_pms_len))
2259                                 {
2260                                 CBB_cleanup(&cbb);
2261                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2262                                 goto err;
2263                                 }
2264                         OPENSSL_cleanse(pms, pms_len);
2265                         OPENSSL_free(pms);
2266                         pms = new_pms;
2267                         pms_len = new_pms_len;
2268                         }
2269
2270                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
2271                 s->state=SSL3_ST_CW_KEY_EXCH_B;
2272
2273                 /* The message must be added to the finished hash before
2274                  * calculating the master secret. */
2275                 s->method->ssl3_enc->add_to_finished_hash(s);
2276
2277                 s->session->master_key_length =
2278                         s->method->ssl3_enc->generate_master_secret(s,
2279                                 s->session->master_key,
2280                                 pms, pms_len);
2281                 if (s->session->master_key_length == 0)
2282                         {
2283                         goto err;
2284                         }
2285                 s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
2286                 OPENSSL_cleanse(pms, pms_len);
2287                 OPENSSL_free(pms);
2288                 }
2289
2290         /* SSL3_ST_CW_KEY_EXCH_B */
2291         /* The message has already been added to the finished hash. */
2292         return s->method->ssl3_enc->do_write(s, dont_add_to_finished_hash);
2293
2294 err:
2295         BN_CTX_free(bn_ctx);
2296         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2297         if (clnt_ecdh != NULL) 
2298                 EC_KEY_free(clnt_ecdh);
2299         EVP_PKEY_free(srvr_pub_pkey);
2300         if (pms)
2301                 {
2302                 OPENSSL_cleanse(pms, pms_len);
2303                 OPENSSL_free(pms);
2304                 }
2305         return -1;
2306         }
2307
2308 int ssl3_send_cert_verify(SSL *s)
2309         {
2310         unsigned char *buf, *p;
2311         const EVP_MD *md = NULL;
2312         uint8_t digest[EVP_MAX_MD_SIZE];
2313         size_t digest_length;
2314         EVP_PKEY *pkey;
2315         EVP_PKEY_CTX *pctx = NULL;
2316         size_t signature_length = 0;
2317         unsigned long n = 0;
2318
2319         buf=(unsigned char *)s->init_buf->data;
2320
2321         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2322                 {
2323                 p= ssl_handshake_start(s);
2324                 pkey = s->cert->key->privatekey;
2325
2326                 /* Write out the digest type if needbe. */
2327                 if (SSL_USE_SIGALGS(s))
2328                         {
2329                         md = s->cert->key->digest;
2330                         if (!tls12_get_sigandhash(p, pkey, md))
2331                                 {
2332                                 OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_INTERNAL_ERROR);
2333                                 goto err;
2334                                 }
2335                         p += 2;
2336                         n += 2;
2337                         }
2338
2339                 /* Compute the digest. */
2340                 if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
2341                         goto err;
2342
2343                 /* The handshake buffer is no longer necessary. */
2344                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
2345                         goto err;
2346
2347                 /* Sign the digest. */
2348                 pctx = EVP_PKEY_CTX_new(pkey, NULL);
2349                 if (pctx == NULL)
2350                         goto err;
2351
2352                 /* Initialize the EVP_PKEY_CTX and determine the size of the signature. */
2353                 if (!EVP_PKEY_sign_init(pctx) ||
2354                         !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
2355                         !EVP_PKEY_sign(pctx, NULL, &signature_length,
2356                                 digest, digest_length))
2357                         {
2358                         OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
2359                         goto err;
2360                         }
2361
2362                 if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH)
2363                         {
2364                         OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, SSL_R_DATA_LENGTH_TOO_LONG);
2365                         goto err;
2366                         }
2367
2368                 if (!EVP_PKEY_sign(pctx, &p[2], &signature_length,
2369                                 digest, digest_length))
2370                         {
2371                         OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
2372                         goto err;
2373                         }
2374
2375                 s2n(signature_length, p);
2376                 n += signature_length + 2;
2377
2378                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
2379                 s->state=SSL3_ST_CW_CERT_VRFY_B;
2380                 }
2381         EVP_PKEY_CTX_free(pctx);
2382         return ssl_do_write(s);
2383 err:
2384         EVP_PKEY_CTX_free(pctx);
2385         return(-1);
2386         }
2387
2388 /* Check a certificate can be used for client authentication. Currently
2389  * check the cert exists and if we have a suitable digest for TLS 1.2.
2390  */
2391 static int ssl3_check_client_certificate(SSL *s)
2392         {
2393         if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2394                 return 0;
2395         /* If no suitable signature algorithm can't use certificate */
2396         if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
2397                 return 0;
2398         /* If strict mode check suitability of chain before using it.
2399          */
2400         if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2401                 !tls1_check_chain(s, NULL, NULL, NULL, -2))
2402                 return 0;
2403         return 1;
2404         }
2405
2406 int ssl3_send_client_certificate(SSL *s)
2407         {
2408         X509 *x509=NULL;
2409         EVP_PKEY *pkey=NULL;
2410         int i;
2411
2412         if (s->state == SSL3_ST_CW_CERT_A)
2413                 {
2414                 /* Let cert callback update client certificates if required */
2415                 if (s->cert->cert_cb)
2416                         {
2417                         i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2418                         if (i < 0)
2419                                 {
2420                                 s->rwstate=SSL_X509_LOOKUP;
2421                                 return -1;
2422                                 }
2423                         if (i == 0)
2424                                 {
2425                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
2426                                 return 0;
2427                                 }
2428                         s->rwstate=SSL_NOTHING;
2429                         }
2430                 if (ssl3_check_client_certificate(s))
2431                         s->state=SSL3_ST_CW_CERT_C;
2432                 else
2433                         s->state=SSL3_ST_CW_CERT_B;
2434                 }
2435
2436         /* We need to get a client cert */
2437         if (s->state == SSL3_ST_CW_CERT_B)
2438                 {
2439                 /* If we get an error, we need to
2440                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2441                  * We then get retried later */
2442                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
2443                 if (i < 0)
2444                         {
2445                         s->rwstate=SSL_X509_LOOKUP;
2446                         return(-1);
2447                         }
2448                 s->rwstate=SSL_NOTHING;
2449                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2450                         {
2451                         s->state=SSL3_ST_CW_CERT_B;
2452                         if (    !SSL_use_certificate(s,x509) ||
2453                                 !SSL_use_PrivateKey(s,pkey))
2454                                 i=0;
2455                         }
2456                 else if (i == 1)
2457                         {
2458                         i=0;
2459                         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_certificate, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2460                         }
2461
2462                 if (x509 != NULL) X509_free(x509);
2463                 if (pkey != NULL) EVP_PKEY_free(pkey);
2464                 if (i && !ssl3_check_client_certificate(s))
2465                         i = 0;
2466                 if (i == 0)
2467                         {
2468                         if (s->version == SSL3_VERSION)
2469                                 {
2470                                 s->s3->tmp.cert_req=0;
2471                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2472                                 return(1);
2473                                 }
2474                         else
2475                                 {
2476                                 s->s3->tmp.cert_req=2;
2477                                 }
2478                         }
2479
2480                 /* Ok, we have a cert */
2481                 s->state=SSL3_ST_CW_CERT_C;
2482                 }
2483
2484         if (s->state == SSL3_ST_CW_CERT_C)
2485                 {
2486                 s->state=SSL3_ST_CW_CERT_D;
2487                 ssl3_output_cert_chain(s,
2488                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key);
2489                 }
2490         /* SSL3_ST_CW_CERT_D */
2491         return ssl_do_write(s);
2492         }
2493
2494 #define has_bits(i,m)   (((i)&(m)) == (m))
2495
2496 int ssl3_check_cert_and_algorithm(SSL *s)
2497         {
2498         int i,idx;
2499         long alg_k,alg_a;
2500         EVP_PKEY *pkey=NULL;
2501         SESS_CERT *sc;
2502         RSA *rsa;
2503         DH *dh;
2504
2505         /* we don't have a certificate */
2506         if (!ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
2507                 return 1;
2508
2509         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2510         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
2511
2512         sc=s->session->sess_cert;
2513         if (sc == NULL)
2514                 {
2515                 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, ERR_R_INTERNAL_ERROR);
2516                 goto err;
2517                 }
2518
2519         rsa=s->session->sess_cert->peer_rsa_tmp;
2520         dh=s->session->sess_cert->peer_dh_tmp;
2521
2522         /* This is the passed certificate */
2523
2524         idx=sc->peer_cert_type;
2525         if (idx == SSL_PKEY_ECC)
2526                 {
2527                 if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
2528                                                                 s) == 0) 
2529                         { /* check failed */
2530                         OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_BAD_ECC_CERT);
2531                         goto f_err;
2532                         }
2533                 else 
2534                         {
2535                         return 1;
2536                         }
2537                 }
2538         else if (alg_a & SSL_aECDSA)
2539                 {
2540                 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_ECDSA_SIGNING_CERT);
2541                 goto f_err;
2542                 }
2543         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
2544         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
2545         EVP_PKEY_free(pkey);
2546
2547         
2548         /* Check that we have a certificate if we require one */
2549         if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
2550                 {
2551                 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_SIGNING_CERT);
2552                 goto f_err;
2553                 }
2554         if ((alg_k & SSL_kRSA) &&
2555                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
2556                 {
2557                 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2558                 goto f_err;
2559                 }
2560         if ((alg_k & SSL_kEDH) && 
2561                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
2562                 {
2563                 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_DH_KEY);
2564                 goto f_err;
2565                 }
2566
2567         return(1);
2568 f_err:
2569         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2570 err:
2571         return(0);
2572         }
2573
2574 int ssl3_send_next_proto(SSL *s)
2575         {
2576         unsigned int len, padding_len;
2577         unsigned char *d;
2578
2579         if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
2580                 {
2581                 len = s->next_proto_negotiated_len;
2582                 padding_len = 32 - ((len + 2) % 32);
2583                 d = (unsigned char *)s->init_buf->data;
2584                 d[4] = len;
2585                 memcpy(d + 5, s->next_proto_negotiated, len);
2586                 d[5 + len] = padding_len;
2587                 memset(d + 6 + len, 0, padding_len);
2588                 *(d++)=SSL3_MT_NEXT_PROTO;
2589                 l2n3(2 + len + padding_len, d);
2590                 s->state = SSL3_ST_CW_NEXT_PROTO_B;
2591                 s->init_num = 4 + 2 + len + padding_len;
2592                 s->init_off = 0;
2593                 }
2594
2595         return ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2596 }
2597
2598
2599 int ssl3_send_channel_id(SSL *s)
2600         {
2601         unsigned char *d;
2602         int ret = -1, public_key_len;
2603         EVP_MD_CTX md_ctx;
2604         size_t sig_len;
2605         ECDSA_SIG *sig = NULL;
2606         unsigned char *public_key = NULL, *derp, *der_sig = NULL;
2607
2608         if (s->state != SSL3_ST_CW_CHANNEL_ID_A)
2609                 return ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2610
2611         if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb)
2612                 {
2613                 EVP_PKEY *key = NULL;
2614                 s->ctx->channel_id_cb(s, &key);
2615                 if (key != NULL)
2616                         {
2617                         s->tlsext_channel_id_private = key;
2618                         }
2619                 }
2620         if (!s->tlsext_channel_id_private)
2621                 {
2622                 s->rwstate=SSL_CHANNEL_ID_LOOKUP;
2623                 return (-1);
2624                 }
2625         s->rwstate=SSL_NOTHING;
2626
2627         d = (unsigned char *)s->init_buf->data;
2628         *(d++)=SSL3_MT_ENCRYPTED_EXTENSIONS;
2629         l2n3(2 + 2 + TLSEXT_CHANNEL_ID_SIZE, d);
2630         if (s->s3->tlsext_channel_id_new)
2631                 s2n(TLSEXT_TYPE_channel_id_new, d);
2632         else
2633                 s2n(TLSEXT_TYPE_channel_id, d);
2634         s2n(TLSEXT_CHANNEL_ID_SIZE, d);
2635
2636         EVP_MD_CTX_init(&md_ctx);
2637
2638         public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
2639         if (public_key_len <= 0)
2640                 {
2641                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
2642                 goto err;
2643                 }
2644         /* i2d_PublicKey will produce an ANSI X9.62 public key which, for a
2645          * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
2646          * field elements as 32-byte, big-endian numbers. */
2647         if (public_key_len != 65)
2648                 {
2649                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CHANNEL_ID_NOT_P256);
2650                 goto err;
2651                 }
2652         public_key = OPENSSL_malloc(public_key_len);
2653         if (!public_key)
2654                 {
2655                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
2656                 goto err;
2657                 }
2658
2659         derp = public_key;
2660         i2d_PublicKey(s->tlsext_channel_id_private, &derp);
2661
2662         if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
2663                                s->tlsext_channel_id_private) != 1)
2664                 {
2665                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNINIT_FAILED);
2666                 goto err;
2667                 }
2668
2669         if (!tls1_channel_id_hash(&md_ctx, s))
2670                 goto err;
2671
2672         if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len))
2673                 {
2674                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
2675                 goto err;
2676                 }
2677
2678         der_sig = OPENSSL_malloc(sig_len);
2679         if (!der_sig)
2680                 {
2681                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
2682                 goto err;
2683                 }
2684
2685         if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len))
2686                 {
2687                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
2688                 goto err;
2689                 }
2690
2691         derp = der_sig;
2692         sig = d2i_ECDSA_SIG(NULL, (const unsigned char**) &derp, sig_len);
2693         if (sig == NULL)
2694                 {
2695                 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_D2I_ECDSA_SIG);
2696                 goto err;
2697                 }
2698
2699         /* The first byte of public_key will be 0x4, denoting an uncompressed key. */
2700         memcpy(d, public_key + 1, 64);
2701         d += 64;
2702         memset(d, 0, 2 * 32);
2703         BN_bn2bin(sig->r, d + 32 - BN_num_bytes(sig->r));
2704         d += 32;
2705         BN_bn2bin(sig->s, d + 32 - BN_num_bytes(sig->s));
2706         d += 32;
2707
2708         s->state = SSL3_ST_CW_CHANNEL_ID_B;
2709         s->init_num = 4 + 2 + 2 + TLSEXT_CHANNEL_ID_SIZE;
2710         s->init_off = 0;
2711
2712         ret = ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2713
2714 err:
2715         EVP_MD_CTX_cleanup(&md_ctx);
2716         if (public_key)
2717                 OPENSSL_free(public_key);
2718         if (der_sig)
2719                 OPENSSL_free(der_sig);
2720         if (sig)
2721                 ECDSA_SIG_free(sig);
2722
2723         return ret;
2724         }
2725
2726 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2727         {
2728         int i = 0;
2729         if (s->ctx->client_cert_cb)
2730                 i = s->ctx->client_cert_cb(s,px509,ppkey);
2731         return i;
2732         }