DTLS handshake message fragments musn't span packets
[openssl.git] / 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 #include "ssl_locl.h"
153 #include "kssl_lcl.h"
154 #include <openssl/buffer.h>
155 #include <openssl/rand.h>
156 #include <openssl/objects.h>
157 #include <openssl/evp.h>
158 #include <openssl/md5.h>
159 #ifdef OPENSSL_FIPS
160 # include <openssl/fips.h>
161 #endif
162 #ifndef OPENSSL_NO_DH
163 # include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #ifndef OPENSSL_NO_ENGINE
167 # include <openssl/engine.h>
168 #endif
169
170 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
171 #ifndef OPENSSL_NO_TLSEXT
172 static int ssl3_check_finished(SSL *s);
173 #endif
174
175 #ifndef OPENSSL_NO_SSL3_METHOD
176 static const SSL_METHOD *ssl3_get_client_method(int ver)
177 {
178     if (ver == SSL3_VERSION)
179         return (SSLv3_client_method());
180     else
181         return (NULL);
182 }
183
184 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
185                          ssl_undefined_function,
186                          ssl3_connect, ssl3_get_client_method)
187 #endif
188 int ssl3_connect(SSL *s)
189 {
190     BUF_MEM *buf = NULL;
191     unsigned long Time = (unsigned long)time(NULL);
192     void (*cb) (const SSL *ssl, int type, int val) = NULL;
193     int ret = -1;
194     int new_state, state, skip = 0;
195
196     RAND_add(&Time, sizeof(Time), 0);
197     ERR_clear_error();
198     clear_sys_error();
199
200     if (s->info_callback != NULL)
201         cb = s->info_callback;
202     else if (s->ctx->info_callback != NULL)
203         cb = s->ctx->info_callback;
204
205     s->in_handshake++;
206     if (!SSL_in_init(s) || SSL_in_before(s))
207         SSL_clear(s);
208
209 #ifndef OPENSSL_NO_HEARTBEATS
210     /*
211      * If we're awaiting a HeartbeatResponse, pretend we already got and
212      * don't await it anymore, because Heartbeats don't make sense during
213      * handshakes anyway.
214      */
215     if (s->tlsext_hb_pending) {
216         s->tlsext_hb_pending = 0;
217         s->tlsext_hb_seq++;
218     }
219 #endif
220
221     for (;;) {
222         state = s->state;
223
224         switch (s->state) {
225         case SSL_ST_RENEGOTIATE:
226             s->renegotiate = 1;
227             s->state = SSL_ST_CONNECT;
228             s->ctx->stats.sess_connect_renegotiate++;
229             /* break */
230         case SSL_ST_BEFORE:
231         case SSL_ST_CONNECT:
232         case SSL_ST_BEFORE | SSL_ST_CONNECT:
233         case SSL_ST_OK | SSL_ST_CONNECT:
234
235             s->server = 0;
236             if (cb != NULL)
237                 cb(s, SSL_CB_HANDSHAKE_START, 1);
238
239             if ((s->version & 0xff00) != 0x0300) {
240                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
241                 s->state = SSL_ST_ERR;
242                 ret = -1;
243                 goto end;
244             }
245
246             /* s->version=SSL3_VERSION; */
247             s->type = SSL_ST_CONNECT;
248
249             if (s->init_buf == NULL) {
250                 if ((buf = BUF_MEM_new()) == NULL) {
251                     ret = -1;
252                     s->state = SSL_ST_ERR;
253                     goto end;
254                 }
255                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
256                     ret = -1;
257                     s->state = SSL_ST_ERR;
258                     goto end;
259                 }
260                 s->init_buf = buf;
261                 buf = NULL;
262             }
263
264             if (!ssl3_setup_buffers(s)) {
265                 ret = -1;
266                 goto end;
267             }
268
269             /* setup buffing BIO */
270             if (!ssl_init_wbio_buffer(s, 0)) {
271                 ret = -1;
272                 s->state = SSL_ST_ERR;
273                 goto end;
274             }
275
276             /* don't push the buffering BIO quite yet */
277
278             ssl3_init_finished_mac(s);
279
280             s->state = SSL3_ST_CW_CLNT_HELLO_A;
281             s->ctx->stats.sess_connect++;
282             s->init_num = 0;
283             s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
284             /*
285              * Should have been reset by ssl3_get_finished, too.
286              */
287             s->s3->change_cipher_spec = 0;
288             break;
289
290         case SSL3_ST_CW_CLNT_HELLO_A:
291         case SSL3_ST_CW_CLNT_HELLO_B:
292
293             s->shutdown = 0;
294             ret = ssl3_client_hello(s);
295             if (ret <= 0)
296                 goto end;
297             s->state = SSL3_ST_CR_SRVR_HELLO_A;
298             s->init_num = 0;
299
300             /* turn on buffering for the next lot of output */
301             if (s->bbio != s->wbio)
302                 s->wbio = BIO_push(s->bbio, s->wbio);
303
304             break;
305
306         case SSL3_ST_CR_SRVR_HELLO_A:
307         case SSL3_ST_CR_SRVR_HELLO_B:
308             ret = ssl3_get_server_hello(s);
309             if (ret <= 0)
310                 goto end;
311
312             if (s->hit) {
313                 s->state = SSL3_ST_CR_FINISHED_A;
314 #ifndef OPENSSL_NO_TLSEXT
315                 if (s->tlsext_ticket_expected) {
316                     /* receive renewed session ticket */
317                     s->state = SSL3_ST_CR_SESSION_TICKET_A;
318                 }
319 #endif
320             } else
321                 s->state = SSL3_ST_CR_CERT_A;
322             s->init_num = 0;
323             break;
324
325         case SSL3_ST_CR_CERT_A:
326         case SSL3_ST_CR_CERT_B:
327 #ifndef OPENSSL_NO_TLSEXT
328             /* Noop (ret = 0) for everything but EAP-FAST. */
329             ret = ssl3_check_finished(s);
330             if (ret < 0)
331                 goto end;
332             if (ret == 1) {
333                 s->hit = 1;
334                 s->state = SSL3_ST_CR_FINISHED_A;
335                 s->init_num = 0;
336                 break;
337             }
338 #endif
339             /* Check if it is anon DH/ECDH, SRP auth */
340             /* or PSK */
341             if (!
342                 (s->s3->tmp.
343                  new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
344 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
345                 ret = ssl3_get_server_certificate(s);
346                 if (ret <= 0)
347                     goto end;
348 #ifndef OPENSSL_NO_TLSEXT
349                 if (s->tlsext_status_expected)
350                     s->state = SSL3_ST_CR_CERT_STATUS_A;
351                 else
352                     s->state = SSL3_ST_CR_KEY_EXCH_A;
353             } else {
354                 skip = 1;
355                 s->state = SSL3_ST_CR_KEY_EXCH_A;
356             }
357 #else
358             } else
359                 skip = 1;
360
361             s->state = SSL3_ST_CR_KEY_EXCH_A;
362 #endif
363             s->init_num = 0;
364             break;
365
366         case SSL3_ST_CR_KEY_EXCH_A:
367         case SSL3_ST_CR_KEY_EXCH_B:
368             ret = ssl3_get_key_exchange(s);
369             if (ret <= 0)
370                 goto end;
371             s->state = SSL3_ST_CR_CERT_REQ_A;
372             s->init_num = 0;
373
374             /*
375              * at this point we check that we have the required stuff from
376              * the server
377              */
378             if (!ssl3_check_cert_and_algorithm(s)) {
379                 ret = -1;
380                 s->state = SSL_ST_ERR;
381                 goto end;
382             }
383             break;
384
385         case SSL3_ST_CR_CERT_REQ_A:
386         case SSL3_ST_CR_CERT_REQ_B:
387             ret = ssl3_get_certificate_request(s);
388             if (ret <= 0)
389                 goto end;
390             s->state = SSL3_ST_CR_SRVR_DONE_A;
391             s->init_num = 0;
392             break;
393
394         case SSL3_ST_CR_SRVR_DONE_A:
395         case SSL3_ST_CR_SRVR_DONE_B:
396             ret = ssl3_get_server_done(s);
397             if (ret <= 0)
398                 goto end;
399 #ifndef OPENSSL_NO_SRP
400             if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
401                 if ((ret = SRP_Calc_A_param(s)) <= 0) {
402                     SSLerr(SSL_F_SSL3_CONNECT, SSL_R_SRP_A_CALC);
403                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
404                     s->state = SSL_ST_ERR;
405                     goto end;
406                 }
407             }
408 #endif
409             if (s->s3->tmp.cert_req)
410                 s->state = SSL3_ST_CW_CERT_A;
411             else
412                 s->state = SSL3_ST_CW_KEY_EXCH_A;
413             s->init_num = 0;
414
415             break;
416
417         case SSL3_ST_CW_CERT_A:
418         case SSL3_ST_CW_CERT_B:
419         case SSL3_ST_CW_CERT_C:
420         case SSL3_ST_CW_CERT_D:
421             ret = ssl3_send_client_certificate(s);
422             if (ret <= 0)
423                 goto end;
424             s->state = SSL3_ST_CW_KEY_EXCH_A;
425             s->init_num = 0;
426             break;
427
428         case SSL3_ST_CW_KEY_EXCH_A:
429         case SSL3_ST_CW_KEY_EXCH_B:
430             ret = ssl3_send_client_key_exchange(s);
431             if (ret <= 0)
432                 goto end;
433             /*
434              * EAY EAY EAY need to check for DH fix cert sent back
435              */
436             /*
437              * For TLS, cert_req is set to 2, so a cert chain of nothing is
438              * sent, but no verify packet is sent
439              */
440             /*
441              * XXX: For now, we do not support client authentication in ECDH
442              * cipher suites with ECDH (rather than ECDSA) certificates. We
443              * need to skip the certificate verify message when client's
444              * ECDH public key is sent inside the client certificate.
445              */
446             if (s->s3->tmp.cert_req == 1) {
447                 s->state = SSL3_ST_CW_CERT_VRFY_A;
448             } else {
449                 s->state = SSL3_ST_CW_CHANGE_A;
450             }
451             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
452                 s->state = SSL3_ST_CW_CHANGE_A;
453             }
454
455             s->init_num = 0;
456             break;
457
458         case SSL3_ST_CW_CERT_VRFY_A:
459         case SSL3_ST_CW_CERT_VRFY_B:
460             ret = ssl3_send_client_verify(s);
461             if (ret <= 0)
462                 goto end;
463             s->state = SSL3_ST_CW_CHANGE_A;
464             s->init_num = 0;
465             break;
466
467         case SSL3_ST_CW_CHANGE_A:
468         case SSL3_ST_CW_CHANGE_B:
469             ret = ssl3_send_change_cipher_spec(s,
470                                                SSL3_ST_CW_CHANGE_A,
471                                                SSL3_ST_CW_CHANGE_B);
472             if (ret <= 0)
473                 goto end;
474
475 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
476             s->state = SSL3_ST_CW_FINISHED_A;
477 #else
478             if (s->s3->next_proto_neg_seen)
479                 s->state = SSL3_ST_CW_NEXT_PROTO_A;
480             else
481                 s->state = SSL3_ST_CW_FINISHED_A;
482 #endif
483             s->init_num = 0;
484
485             s->session->cipher = s->s3->tmp.new_cipher;
486 #ifdef OPENSSL_NO_COMP
487             s->session->compress_meth = 0;
488 #else
489             if (s->s3->tmp.new_compression == NULL)
490                 s->session->compress_meth = 0;
491             else
492                 s->session->compress_meth = s->s3->tmp.new_compression->id;
493 #endif
494             if (!s->method->ssl3_enc->setup_key_block(s)) {
495                 ret = -1;
496                 s->state = SSL_ST_ERR;
497                 goto end;
498             }
499
500             if (!s->method->ssl3_enc->change_cipher_state(s,
501                                                           SSL3_CHANGE_CIPHER_CLIENT_WRITE))
502             {
503                 ret = -1;
504                 s->state = SSL_ST_ERR;
505                 goto end;
506             }
507
508             break;
509
510 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
511         case SSL3_ST_CW_NEXT_PROTO_A:
512         case SSL3_ST_CW_NEXT_PROTO_B:
513             ret = ssl3_send_next_proto(s);
514             if (ret <= 0)
515                 goto end;
516             s->state = SSL3_ST_CW_FINISHED_A;
517             break;
518 #endif
519
520         case SSL3_ST_CW_FINISHED_A:
521         case SSL3_ST_CW_FINISHED_B:
522             ret = ssl3_send_finished(s,
523                                      SSL3_ST_CW_FINISHED_A,
524                                      SSL3_ST_CW_FINISHED_B,
525                                      s->method->
526                                      ssl3_enc->client_finished_label,
527                                      s->method->
528                                      ssl3_enc->client_finished_label_len);
529             if (ret <= 0)
530                 goto end;
531             s->state = SSL3_ST_CW_FLUSH;
532
533             /* clear flags */
534             s->s3->flags &= ~SSL3_FLAGS_POP_BUFFER;
535             if (s->hit) {
536                 s->s3->tmp.next_state = SSL_ST_OK;
537                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) {
538                     s->state = SSL_ST_OK;
539                     s->s3->flags |= SSL3_FLAGS_POP_BUFFER;
540                     s->s3->delay_buf_pop_ret = 0;
541                 }
542             } else {
543 #ifndef OPENSSL_NO_TLSEXT
544                 /*
545                  * Allow NewSessionTicket if ticket expected
546                  */
547                 if (s->tlsext_ticket_expected)
548                     s->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
549                 else
550 #endif
551
552                     s->s3->tmp.next_state = SSL3_ST_CR_FINISHED_A;
553             }
554             s->init_num = 0;
555             break;
556
557 #ifndef OPENSSL_NO_TLSEXT
558         case SSL3_ST_CR_SESSION_TICKET_A:
559         case SSL3_ST_CR_SESSION_TICKET_B:
560             ret = ssl3_get_new_session_ticket(s);
561             if (ret <= 0)
562                 goto end;
563             s->state = SSL3_ST_CR_FINISHED_A;
564             s->init_num = 0;
565             break;
566
567         case SSL3_ST_CR_CERT_STATUS_A:
568         case SSL3_ST_CR_CERT_STATUS_B:
569             ret = ssl3_get_cert_status(s);
570             if (ret <= 0)
571                 goto end;
572             s->state = SSL3_ST_CR_KEY_EXCH_A;
573             s->init_num = 0;
574             break;
575 #endif
576
577         case SSL3_ST_CR_FINISHED_A:
578         case SSL3_ST_CR_FINISHED_B:
579             if (!s->s3->change_cipher_spec)
580                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
581             ret = ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A,
582                                     SSL3_ST_CR_FINISHED_B);
583             if (ret <= 0)
584                 goto end;
585
586             if (s->hit)
587                 s->state = SSL3_ST_CW_CHANGE_A;
588             else
589                 s->state = SSL_ST_OK;
590             s->init_num = 0;
591             break;
592
593         case SSL3_ST_CW_FLUSH:
594             s->rwstate = SSL_WRITING;
595             if (BIO_flush(s->wbio) <= 0) {
596                 ret = -1;
597                 goto end;
598             }
599             s->rwstate = SSL_NOTHING;
600             s->state = s->s3->tmp.next_state;
601             break;
602
603         case SSL_ST_OK:
604             /* clean a few things up */
605             ssl3_cleanup_key_block(s);
606
607             if (s->init_buf != NULL) {
608                 BUF_MEM_free(s->init_buf);
609                 s->init_buf = NULL;
610             }
611
612             /*
613              * If we are not 'joining' the last two packets, remove the
614              * buffering now
615              */
616             if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
617                 ssl_free_wbio_buffer(s);
618             /* else do it later in ssl3_write */
619
620             s->init_num = 0;
621             s->renegotiate = 0;
622             s->new_session = 0;
623
624             ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
625             if (s->hit)
626                 s->ctx->stats.sess_hit++;
627
628             ret = 1;
629             /* s->server=0; */
630             s->handshake_func = ssl3_connect;
631             s->ctx->stats.sess_connect_good++;
632
633             if (cb != NULL)
634                 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
635
636             goto end;
637             /* break; */
638
639         case SSL_ST_ERR:
640         default:
641             SSLerr(SSL_F_SSL3_CONNECT, SSL_R_UNKNOWN_STATE);
642             ret = -1;
643             goto end;
644             /* break; */
645         }
646
647         /* did we do anything */
648         if (!s->s3->tmp.reuse_message && !skip) {
649             if (s->debug) {
650                 if ((ret = BIO_flush(s->wbio)) <= 0)
651                     goto end;
652             }
653
654             if ((cb != NULL) && (s->state != state)) {
655                 new_state = s->state;
656                 s->state = state;
657                 cb(s, SSL_CB_CONNECT_LOOP, 1);
658                 s->state = new_state;
659             }
660         }
661         skip = 0;
662     }
663  end:
664     s->in_handshake--;
665     if (buf != NULL)
666         BUF_MEM_free(buf);
667     if (cb != NULL)
668         cb(s, SSL_CB_CONNECT_EXIT, ret);
669     return (ret);
670 }
671
672 int ssl3_client_hello(SSL *s)
673 {
674     unsigned char *buf;
675     unsigned char *p, *d;
676     int i;
677     unsigned long l;
678 #ifndef OPENSSL_NO_COMP
679     int j;
680     SSL_COMP *comp;
681 #endif
682
683     buf = (unsigned char *)s->init_buf->data;
684     if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
685         SSL_SESSION *sess = s->session;
686         if ((sess == NULL) || (sess->ssl_version != s->version) ||
687 #ifdef OPENSSL_NO_TLSEXT
688             !sess->session_id_length ||
689 #else
690             /*
691              * In the case of EAP-FAST, we can have a pre-shared
692              * "ticket" without a session ID.
693              */
694             (!sess->session_id_length && !sess->tlsext_tick) ||
695 #endif
696             (sess->not_resumable)) {
697             if (!ssl_get_new_session(s, 0))
698                 goto err;
699         }
700         /* else use the pre-loaded session */
701
702         p = s->s3->client_random;
703
704         if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
705             goto err;
706
707         /* Do the message type and length last */
708         d = p = &(buf[4]);
709
710         /*-
711          * version indicates the negotiated version: for example from
712          * an SSLv2/v3 compatible client hello). The client_version
713          * field is the maximum version we permit and it is also
714          * used in RSA encrypted premaster secrets. Some servers can
715          * choke if we initially report a higher version then
716          * renegotiate to a lower one in the premaster secret. This
717          * didn't happen with TLS 1.0 as most servers supported it
718          * but it can with TLS 1.1 or later if the server only supports
719          * 1.0.
720          *
721          * Possible scenario with previous logic:
722          *      1. Client hello indicates TLS 1.2
723          *      2. Server hello says TLS 1.0
724          *      3. RSA encrypted premaster secret uses 1.2.
725          *      4. Handhaked proceeds using TLS 1.0.
726          *      5. Server sends hello request to renegotiate.
727          *      6. Client hello indicates TLS v1.0 as we now
728          *         know that is maximum server supports.
729          *      7. Server chokes on RSA encrypted premaster secret
730          *         containing version 1.0.
731          *
732          * For interoperability it should be OK to always use the
733          * maximum version we support in client hello and then rely
734          * on the checking of version to ensure the servers isn't
735          * being inconsistent: for example initially negotiating with
736          * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
737          * client_version in client hello and not resetting it to
738          * the negotiated version.
739          */
740 #if 0
741         *(p++) = s->version >> 8;
742         *(p++) = s->version & 0xff;
743         s->client_version = s->version;
744 #else
745         *(p++) = s->client_version >> 8;
746         *(p++) = s->client_version & 0xff;
747 #endif
748
749         /* Random stuff */
750         memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
751         p += SSL3_RANDOM_SIZE;
752
753         /* Session ID */
754         if (s->new_session)
755             i = 0;
756         else
757             i = s->session->session_id_length;
758         *(p++) = i;
759         if (i != 0) {
760             if (i > (int)sizeof(s->session->session_id)) {
761                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
762                 goto err;
763             }
764             memcpy(p, s->session->session_id, i);
765             p += i;
766         }
767
768         /* Ciphers supported */
769         i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
770         if (i == 0) {
771             SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
772             goto err;
773         }
774 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
775         /*
776          * Some servers hang if client hello > 256 bytes as hack workaround
777          * chop number of supported ciphers to keep it well below this if we
778          * use TLS v1.2
779          */
780         if (TLS1_get_version(s) >= TLS1_2_VERSION
781             && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
782             i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
783 #endif
784         s2n(i, p);
785         p += i;
786
787         /* COMPRESSION */
788 #ifdef OPENSSL_NO_COMP
789         *(p++) = 1;
790 #else
791
792         if ((s->options & SSL_OP_NO_COMPRESSION)
793             || !s->ctx->comp_methods)
794             j = 0;
795         else
796             j = sk_SSL_COMP_num(s->ctx->comp_methods);
797         *(p++) = 1 + j;
798         for (i = 0; i < j; i++) {
799             comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
800             *(p++) = comp->id;
801         }
802 #endif
803         *(p++) = 0;             /* Add the NULL method */
804
805 #ifndef OPENSSL_NO_TLSEXT
806         /* TLS extensions */
807         if (ssl_prepare_clienthello_tlsext(s) <= 0) {
808             SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
809             goto err;
810         }
811         if ((p =
812              ssl_add_clienthello_tlsext(s, p,
813                                         buf + SSL3_RT_MAX_PLAIN_LENGTH)) ==
814             NULL) {
815             SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
816             goto err;
817         }
818 #endif
819
820         l = (p - d);
821         d = buf;
822         *(d++) = SSL3_MT_CLIENT_HELLO;
823         l2n3(l, d);
824
825         s->state = SSL3_ST_CW_CLNT_HELLO_B;
826         /* number of bytes to write */
827         s->init_num = p - buf;
828         s->init_off = 0;
829     }
830
831     /* SSL3_ST_CW_CLNT_HELLO_B */
832     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
833  err:
834     s->state = SSL_ST_ERR;
835     return (-1);
836 }
837
838 int ssl3_get_server_hello(SSL *s)
839 {
840     STACK_OF(SSL_CIPHER) *sk;
841     const SSL_CIPHER *c;
842     unsigned char *p, *d;
843     int i, al, ok;
844     unsigned int j;
845     long n;
846 #ifndef OPENSSL_NO_COMP
847     SSL_COMP *comp;
848 #endif
849
850     n = s->method->ssl_get_message(s,
851                                    SSL3_ST_CR_SRVR_HELLO_A,
852                                    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, &ok);
853
854     if (!ok)
855         return ((int)n);
856
857     if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) {
858         if (s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
859             if (s->d1->send_cookie == 0) {
860                 s->s3->tmp.reuse_message = 1;
861                 return 1;
862             } else {            /* already sent a cookie */
863
864                 al = SSL_AD_UNEXPECTED_MESSAGE;
865                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
866                 goto f_err;
867             }
868         }
869     }
870
871     if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) {
872         al = SSL_AD_UNEXPECTED_MESSAGE;
873         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
874         goto f_err;
875     }
876
877     d = p = (unsigned char *)s->init_msg;
878
879     if ((p[0] != (s->version >> 8)) || (p[1] != (s->version & 0xff))) {
880         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
881         s->version = (s->version & 0xff00) | p[1];
882         al = SSL_AD_PROTOCOL_VERSION;
883         goto f_err;
884     }
885     p += 2;
886
887     /* load the server hello data */
888     /* load the server random */
889     memcpy(s->s3->server_random, p, SSL3_RANDOM_SIZE);
890     p += SSL3_RANDOM_SIZE;
891
892     s->hit = 0;
893
894     /* get the session-id */
895     j = *(p++);
896
897     if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) {
898         al = SSL_AD_ILLEGAL_PARAMETER;
899         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
900         goto f_err;
901     }
902 #ifndef OPENSSL_NO_TLSEXT
903     /*
904      * Check if we can resume the session based on external pre-shared secret.
905      * EAP-FAST (RFC 4851) supports two types of session resumption.
906      * Resumption based on server-side state works with session IDs.
907      * Resumption based on pre-shared Protected Access Credentials (PACs)
908      * works by overriding the SessionTicket extension at the application
909      * layer, and does not send a session ID. (We do not know whether EAP-FAST
910      * servers would honour the session ID.) Therefore, the session ID alone
911      * is not a reliable indicator of session resumption, so we first check if
912      * we can resume, and later peek at the next handshake message to see if the
913      * server wants to resume.
914      */
915     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
916         s->session->tlsext_tick) {
917         SSL_CIPHER *pref_cipher = NULL;
918         s->session->master_key_length = sizeof(s->session->master_key);
919         if (s->tls_session_secret_cb(s, s->session->master_key,
920                                      &s->session->master_key_length,
921                                      NULL, &pref_cipher,
922                                      s->tls_session_secret_cb_arg)) {
923             s->session->cipher = pref_cipher ?
924                 pref_cipher : ssl_get_cipher_by_char(s, p + j);
925         } else {
926             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
927             al = SSL_AD_INTERNAL_ERROR;
928             goto f_err;
929         }
930     }
931 #endif                          /* OPENSSL_NO_TLSEXT */
932
933     if (j != 0 && j == s->session->session_id_length
934         && memcmp(p, s->session->session_id, j) == 0) {
935         if (s->sid_ctx_length != s->session->sid_ctx_length
936             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
937             /* actually a client application bug */
938             al = SSL_AD_ILLEGAL_PARAMETER;
939             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
940                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
941             goto f_err;
942         }
943         s->hit = 1;
944     } else {
945         /*
946          * If we were trying for session-id reuse but the server
947          * didn't echo the ID, make a new SSL_SESSION.
948          * In the case of EAP-FAST and PAC, we do not send a session ID,
949          * so the PAC-based session secret is always preserved. It'll be
950          * overwritten if the server refuses resumption.
951          */
952         if (s->session->session_id_length > 0) {
953             if (!ssl_get_new_session(s, 0)) {
954                 al = SSL_AD_INTERNAL_ERROR;
955                 goto f_err;
956             }
957         }
958         s->session->session_id_length = j;
959         memcpy(s->session->session_id, p, j); /* j could be 0 */
960     }
961     p += j;
962     c = ssl_get_cipher_by_char(s, p);
963     if (c == NULL) {
964         /* unknown cipher */
965         al = SSL_AD_ILLEGAL_PARAMETER;
966         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
967         goto f_err;
968     }
969     /* TLS v1.2 only ciphersuites require v1.2 or later */
970     if ((c->algorithm_ssl & SSL_TLSV1_2) &&
971         (TLS1_get_version(s) < TLS1_2_VERSION)) {
972         al = SSL_AD_ILLEGAL_PARAMETER;
973         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
974         goto f_err;
975     }
976 #ifndef OPENSSL_NO_SRP
977     if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) &&
978         !(s->srp_ctx.srp_Mask & SSL_kSRP)) {
979         al = SSL_AD_ILLEGAL_PARAMETER;
980         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
981         goto f_err;
982     }
983 #endif                          /* OPENSSL_NO_SRP */
984     p += ssl_put_cipher_by_char(s, NULL, NULL);
985
986     sk = ssl_get_ciphers_by_id(s);
987     i = sk_SSL_CIPHER_find(sk, c);
988     if (i < 0) {
989         /* we did not say we would use this cipher */
990         al = SSL_AD_ILLEGAL_PARAMETER;
991         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
992         goto f_err;
993     }
994
995     /*
996      * Depending on the session caching (internal/external), the cipher
997      * and/or cipher_id values may not be set. Make sure that cipher_id is
998      * set and use it for comparison.
999      */
1000     if (s->session->cipher)
1001         s->session->cipher_id = s->session->cipher->id;
1002     if (s->hit && (s->session->cipher_id != c->id)) {
1003 /* Workaround is now obsolete */
1004 #if 0
1005         if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
1006 #endif
1007         {
1008             al = SSL_AD_ILLEGAL_PARAMETER;
1009             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1010                    SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1011             goto f_err;
1012         }
1013     }
1014     s->s3->tmp.new_cipher = c;
1015     /*
1016      * Don't digest cached records if TLS v1.2: we may need them for client
1017      * authentication.
1018      */
1019     if (TLS1_get_version(s) < TLS1_2_VERSION
1020         && !ssl3_digest_cached_records(s)) {
1021         al = SSL_AD_INTERNAL_ERROR;
1022         goto f_err;
1023     }
1024     /* lets get the compression algorithm */
1025     /* COMPRESSION */
1026 #ifdef OPENSSL_NO_COMP
1027     if (*(p++) != 0) {
1028         al = SSL_AD_ILLEGAL_PARAMETER;
1029         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1030                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1031         goto f_err;
1032     }
1033     /*
1034      * If compression is disabled we'd better not try to resume a session
1035      * using compression.
1036      */
1037     if (s->session->compress_meth != 0) {
1038         al = SSL_AD_INTERNAL_ERROR;
1039         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1040         goto f_err;
1041     }
1042 #else
1043     j = *(p++);
1044     if (s->hit && j != s->session->compress_meth) {
1045         al = SSL_AD_ILLEGAL_PARAMETER;
1046         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1047                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1048         goto f_err;
1049     }
1050     if (j == 0)
1051         comp = NULL;
1052     else if (s->options & SSL_OP_NO_COMPRESSION) {
1053         al = SSL_AD_ILLEGAL_PARAMETER;
1054         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1055         goto f_err;
1056     } else
1057         comp = ssl3_comp_find(s->ctx->comp_methods, j);
1058
1059     if ((j != 0) && (comp == NULL)) {
1060         al = SSL_AD_ILLEGAL_PARAMETER;
1061         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1062                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1063         goto f_err;
1064     } else {
1065         s->s3->tmp.new_compression = comp;
1066     }
1067 #endif
1068
1069 #ifndef OPENSSL_NO_TLSEXT
1070     /* TLS extensions */
1071     if (s->version >= SSL3_VERSION) {
1072         if (!ssl_parse_serverhello_tlsext(s, &p, d, n, &al)) {
1073             /* 'al' set by ssl_parse_serverhello_tlsext */
1074             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1075             goto f_err;
1076         }
1077         if (ssl_check_serverhello_tlsext(s) <= 0) {
1078             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1079             goto err;
1080         }
1081     }
1082 #endif
1083
1084     if (p != (d + n)) {
1085         /* wrong packet length */
1086         al = SSL_AD_DECODE_ERROR;
1087         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1088         goto f_err;
1089     }
1090
1091     return (1);
1092  f_err:
1093     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1094  err:
1095     s->state = SSL_ST_ERR;
1096     return (-1);
1097 }
1098
1099 int ssl3_get_server_certificate(SSL *s)
1100 {
1101     int al, i, ok, ret = -1;
1102     unsigned long n, nc, llen, l;
1103     X509 *x = NULL;
1104     const unsigned char *q, *p;
1105     unsigned char *d;
1106     STACK_OF(X509) *sk = NULL;
1107     SESS_CERT *sc;
1108     EVP_PKEY *pkey = NULL;
1109     int need_cert = 1;          /* VRS: 0=> will allow null cert if auth ==
1110                                  * KRB5 */
1111
1112     n = s->method->ssl_get_message(s,
1113                                    SSL3_ST_CR_CERT_A,
1114                                    SSL3_ST_CR_CERT_B,
1115                                    -1, s->max_cert_list, &ok);
1116
1117     if (!ok)
1118         return ((int)n);
1119
1120     if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1121         ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&
1122          (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) {
1123         s->s3->tmp.reuse_message = 1;
1124         return (1);
1125     }
1126
1127     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
1128         al = SSL_AD_UNEXPECTED_MESSAGE;
1129         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_BAD_MESSAGE_TYPE);
1130         goto f_err;
1131     }
1132     p = d = (unsigned char *)s->init_msg;
1133
1134     if ((sk = sk_X509_new_null()) == NULL) {
1135         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1136         goto err;
1137     }
1138
1139     n2l3(p, llen);
1140     if (llen + 3 != n) {
1141         al = SSL_AD_DECODE_ERROR;
1142         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1143         goto f_err;
1144     }
1145     for (nc = 0; nc < llen;) {
1146         n2l3(p, l);
1147         if ((l + nc + 3) > llen) {
1148             al = SSL_AD_DECODE_ERROR;
1149             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1150                    SSL_R_CERT_LENGTH_MISMATCH);
1151             goto f_err;
1152         }
1153
1154         q = p;
1155         x = d2i_X509(NULL, &q, l);
1156         if (x == NULL) {
1157             al = SSL_AD_BAD_CERTIFICATE;
1158             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1159             goto f_err;
1160         }
1161         if (q != (p + l)) {
1162             al = SSL_AD_DECODE_ERROR;
1163             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1164                    SSL_R_CERT_LENGTH_MISMATCH);
1165             goto f_err;
1166         }
1167         if (!sk_X509_push(sk, x)) {
1168             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1169             goto err;
1170         }
1171         x = NULL;
1172         nc += l + 3;
1173         p = q;
1174     }
1175
1176     i = ssl_verify_cert_chain(s, sk);
1177     if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1178 #ifndef OPENSSL_NO_KRB5
1179         && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1180              (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1181 #endif                          /* OPENSSL_NO_KRB5 */
1182         ) {
1183         al = ssl_verify_alarm_type(s->verify_result);
1184         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1185                SSL_R_CERTIFICATE_VERIFY_FAILED);
1186         goto f_err;
1187     }
1188     ERR_clear_error();          /* but we keep s->verify_result */
1189
1190     sc = ssl_sess_cert_new();
1191     if (sc == NULL)
1192         goto err;
1193
1194     if (s->session->sess_cert)
1195         ssl_sess_cert_free(s->session->sess_cert);
1196     s->session->sess_cert = sc;
1197
1198     sc->cert_chain = sk;
1199     /*
1200      * Inconsistency alert: cert_chain does include the peer's certificate,
1201      * which we don't include in s3_srvr.c
1202      */
1203     x = sk_X509_value(sk, 0);
1204     sk = NULL;
1205     /*
1206      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1207      */
1208
1209     pkey = X509_get_pubkey(x);
1210
1211     /* VRS: allow null cert if auth == KRB5 */
1212     need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1213                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1214         ? 0 : 1;
1215
1216 #ifdef KSSL_DEBUG
1217     fprintf(stderr, "pkey,x = %p, %p\n", pkey, x);
1218     fprintf(stderr, "ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x, pkey));
1219     fprintf(stderr, "cipher, alg, nc = %s, %lx, %lx, %d\n",
1220             s->s3->tmp.new_cipher->name,
1221             s->s3->tmp.new_cipher->algorithm_mkey,
1222             s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1223 #endif                          /* KSSL_DEBUG */
1224
1225     if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) {
1226         x = NULL;
1227         al = SSL3_AL_FATAL;
1228         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1229                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1230         goto f_err;
1231     }
1232
1233     i = ssl_cert_type(x, pkey);
1234     if (need_cert && i < 0) {
1235         x = NULL;
1236         al = SSL3_AL_FATAL;
1237         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1238                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1239         goto f_err;
1240     }
1241
1242     if (need_cert) {
1243         sc->peer_cert_type = i;
1244         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1245         /*
1246          * Why would the following ever happen? We just created sc a couple
1247          * of lines ago.
1248          */
1249         if (sc->peer_pkeys[i].x509 != NULL)
1250             X509_free(sc->peer_pkeys[i].x509);
1251         sc->peer_pkeys[i].x509 = x;
1252         sc->peer_key = &(sc->peer_pkeys[i]);
1253
1254         if (s->session->peer != NULL)
1255             X509_free(s->session->peer);
1256         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1257         s->session->peer = x;
1258     } else {
1259         sc->peer_cert_type = i;
1260         sc->peer_key = NULL;
1261
1262         if (s->session->peer != NULL)
1263             X509_free(s->session->peer);
1264         s->session->peer = NULL;
1265     }
1266     s->session->verify_result = s->verify_result;
1267
1268     x = NULL;
1269     ret = 1;
1270
1271     if (0) {
1272  f_err:
1273         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1274  err:
1275         s->state = SSL_ST_ERR;
1276     }
1277
1278     EVP_PKEY_free(pkey);
1279     X509_free(x);
1280     sk_X509_pop_free(sk, X509_free);
1281     return (ret);
1282 }
1283
1284 int ssl3_get_key_exchange(SSL *s)
1285 {
1286 #ifndef OPENSSL_NO_RSA
1287     unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
1288 #endif
1289     EVP_MD_CTX md_ctx;
1290     unsigned char *param, *p;
1291     int al, j, ok;
1292     long i, param_len, n, alg_k, alg_a;
1293     EVP_PKEY *pkey = NULL;
1294     const EVP_MD *md = NULL;
1295 #ifndef OPENSSL_NO_RSA
1296     RSA *rsa = NULL;
1297 #endif
1298 #ifndef OPENSSL_NO_DH
1299     DH *dh = NULL;
1300 #endif
1301 #ifndef OPENSSL_NO_ECDH
1302     EC_KEY *ecdh = NULL;
1303     BN_CTX *bn_ctx = NULL;
1304     EC_POINT *srvr_ecpoint = NULL;
1305     int curve_nid = 0;
1306     int encoded_pt_len = 0;
1307 #endif
1308
1309     EVP_MD_CTX_init(&md_ctx);
1310
1311     /*
1312      * use same message size as in ssl3_get_certificate_request() as
1313      * ServerKeyExchange message may be skipped
1314      */
1315     n = s->method->ssl_get_message(s,
1316                                    SSL3_ST_CR_KEY_EXCH_A,
1317                                    SSL3_ST_CR_KEY_EXCH_B,
1318                                    -1, s->max_cert_list, &ok);
1319     if (!ok)
1320         return ((int)n);
1321
1322     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1323
1324     if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1325         /*
1326          * Can't skip server key exchange if this is an ephemeral
1327          * ciphersuite.
1328          */
1329         if (alg_k & (SSL_kEDH | SSL_kEECDH)) {
1330             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1331             al = SSL_AD_UNEXPECTED_MESSAGE;
1332             goto f_err;
1333         }
1334 #ifndef OPENSSL_NO_PSK
1335         /*
1336          * In plain PSK ciphersuite, ServerKeyExchange can be omitted if no
1337          * identity hint is sent. Set session->sess_cert anyway to avoid
1338          * problems later.
1339          */
1340         if (alg_k & SSL_kPSK) {
1341             s->session->sess_cert = ssl_sess_cert_new();
1342             if (s->ctx->psk_identity_hint)
1343                 OPENSSL_free(s->ctx->psk_identity_hint);
1344             s->ctx->psk_identity_hint = NULL;
1345         }
1346 #endif
1347         s->s3->tmp.reuse_message = 1;
1348         return (1);
1349     }
1350
1351     param = p = (unsigned char *)s->init_msg;
1352     if (s->session->sess_cert != NULL) {
1353 #ifndef OPENSSL_NO_RSA
1354         if (s->session->sess_cert->peer_rsa_tmp != NULL) {
1355             RSA_free(s->session->sess_cert->peer_rsa_tmp);
1356             s->session->sess_cert->peer_rsa_tmp = NULL;
1357         }
1358 #endif
1359 #ifndef OPENSSL_NO_DH
1360         if (s->session->sess_cert->peer_dh_tmp) {
1361             DH_free(s->session->sess_cert->peer_dh_tmp);
1362             s->session->sess_cert->peer_dh_tmp = NULL;
1363         }
1364 #endif
1365 #ifndef OPENSSL_NO_ECDH
1366         if (s->session->sess_cert->peer_ecdh_tmp) {
1367             EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1368             s->session->sess_cert->peer_ecdh_tmp = NULL;
1369         }
1370 #endif
1371     } else {
1372         s->session->sess_cert = ssl_sess_cert_new();
1373     }
1374
1375     /* Total length of the parameters including the length prefix */
1376     param_len = 0;
1377
1378     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1379
1380     al = SSL_AD_DECODE_ERROR;
1381
1382 #ifndef OPENSSL_NO_PSK
1383     if (alg_k & SSL_kPSK) {
1384         char tmp_id_hint[PSK_MAX_IDENTITY_LEN + 1];
1385
1386         param_len = 2;
1387         if (param_len > n) {
1388             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1389             goto f_err;
1390         }
1391         n2s(p, i);
1392
1393         /*
1394          * Store PSK identity hint for later use, hint is used in
1395          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1396          * a PSK identity hint can be as long as the maximum length of a PSK
1397          * identity.
1398          */
1399         if (i > PSK_MAX_IDENTITY_LEN) {
1400             al = SSL_AD_HANDSHAKE_FAILURE;
1401             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1402             goto f_err;
1403         }
1404         if (i > n - param_len) {
1405             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1406                    SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1407             goto f_err;
1408         }
1409         param_len += i;
1410
1411         /*
1412          * If received PSK identity hint contains NULL characters, the hint
1413          * is truncated from the first NULL. p may not be ending with NULL,
1414          * so create a NULL-terminated string.
1415          */
1416         memcpy(tmp_id_hint, p, i);
1417         memset(tmp_id_hint + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
1418         if (s->ctx->psk_identity_hint != NULL)
1419             OPENSSL_free(s->ctx->psk_identity_hint);
1420         s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1421         if (s->ctx->psk_identity_hint == NULL) {
1422             al = SSL_AD_HANDSHAKE_FAILURE;
1423             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1424             goto f_err;
1425         }
1426
1427         p += i;
1428         n -= param_len;
1429     } else
1430 #endif                          /* !OPENSSL_NO_PSK */
1431 #ifndef OPENSSL_NO_SRP
1432     if (alg_k & SSL_kSRP) {
1433         param_len = 2;
1434         if (param_len > n) {
1435             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1436             goto f_err;
1437         }
1438         n2s(p, i);
1439
1440         if (i > n - param_len) {
1441             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_N_LENGTH);
1442             goto f_err;
1443         }
1444         param_len += i;
1445
1446         if (!(s->srp_ctx.N = BN_bin2bn(p, i, NULL))) {
1447             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1448             goto err;
1449         }
1450         p += i;
1451
1452         if (2 > n - param_len) {
1453             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1454             goto f_err;
1455         }
1456         param_len += 2;
1457
1458         n2s(p, i);
1459
1460         if (i > n - param_len) {
1461             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_G_LENGTH);
1462             goto f_err;
1463         }
1464         param_len += i;
1465
1466         if (!(s->srp_ctx.g = BN_bin2bn(p, i, NULL))) {
1467             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1468             goto err;
1469         }
1470         p += i;
1471
1472         if (1 > n - param_len) {
1473             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1474             goto f_err;
1475         }
1476         param_len += 1;
1477
1478         i = (unsigned int)(p[0]);
1479         p++;
1480
1481         if (i > n - param_len) {
1482             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_S_LENGTH);
1483             goto f_err;
1484         }
1485         param_len += i;
1486
1487         if (!(s->srp_ctx.s = BN_bin2bn(p, i, NULL))) {
1488             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1489             goto err;
1490         }
1491         p += i;
1492
1493         if (2 > n - param_len) {
1494             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1495             goto f_err;
1496         }
1497         param_len += 2;
1498
1499         n2s(p, i);
1500
1501         if (i > n - param_len) {
1502             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_B_LENGTH);
1503             goto f_err;
1504         }
1505         param_len += i;
1506
1507         if (!(s->srp_ctx.B = BN_bin2bn(p, i, NULL))) {
1508             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1509             goto err;
1510         }
1511         p += i;
1512         n -= param_len;
1513
1514         if (!srp_verify_server_param(s, &al)) {
1515             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1516             goto f_err;
1517         }
1518
1519 /* We must check if there is a certificate */
1520 # ifndef OPENSSL_NO_RSA
1521         if (alg_a & SSL_aRSA)
1522             pkey =
1523                 X509_get_pubkey(s->session->
1524                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1525 # else
1526         if (0) ;
1527 # endif
1528 # ifndef OPENSSL_NO_DSA
1529         else if (alg_a & SSL_aDSS)
1530             pkey =
1531                 X509_get_pubkey(s->session->
1532                                 sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1533                                 x509);
1534 # endif
1535     } else
1536 #endif                          /* !OPENSSL_NO_SRP */
1537 #ifndef OPENSSL_NO_RSA
1538     if (alg_k & SSL_kRSA) {
1539         /* Temporary RSA keys only allowed in export ciphersuites */
1540         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
1541             al = SSL_AD_UNEXPECTED_MESSAGE;
1542             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1543             goto f_err;
1544         }
1545         if ((rsa = RSA_new()) == NULL) {
1546             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1547             goto err;
1548         }
1549
1550         param_len = 2;
1551         if (param_len > n) {
1552             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1553             goto f_err;
1554         }
1555         n2s(p, i);
1556
1557         if (i > n - param_len) {
1558             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_MODULUS_LENGTH);
1559             goto f_err;
1560         }
1561         param_len += i;
1562
1563         if (!(rsa->n = BN_bin2bn(p, i, rsa->n))) {
1564             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1565             goto err;
1566         }
1567         p += i;
1568
1569         if (2 > n - param_len) {
1570             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1571             goto f_err;
1572         }
1573         param_len += 2;
1574
1575         n2s(p, i);
1576
1577         if (i > n - param_len) {
1578             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_E_LENGTH);
1579             goto f_err;
1580         }
1581         param_len += i;
1582
1583         if (!(rsa->e = BN_bin2bn(p, i, rsa->e))) {
1584             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1585             goto err;
1586         }
1587         p += i;
1588         n -= param_len;
1589
1590         /* this should be because we are using an export cipher */
1591         if (alg_a & SSL_aRSA)
1592             pkey =
1593                 X509_get_pubkey(s->session->
1594                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1595         else {
1596             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1597             goto err;
1598         }
1599         s->session->sess_cert->peer_rsa_tmp = rsa;
1600         rsa = NULL;
1601     }
1602 #else                           /* OPENSSL_NO_RSA */
1603     if (0) ;
1604 #endif
1605 #ifndef OPENSSL_NO_DH
1606     else if (alg_k & SSL_kEDH) {
1607         if ((dh = DH_new()) == NULL) {
1608             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
1609             goto err;
1610         }
1611
1612         param_len = 2;
1613         if (param_len > n) {
1614             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1615             goto f_err;
1616         }
1617         n2s(p, i);
1618
1619         if (i > n - param_len) {
1620             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_LENGTH);
1621             goto f_err;
1622         }
1623         param_len += i;
1624
1625         if (!(dh->p = BN_bin2bn(p, i, NULL))) {
1626             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1627             goto err;
1628         }
1629         p += i;
1630
1631         if (2 > n - param_len) {
1632             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1633             goto f_err;
1634         }
1635         param_len += 2;
1636
1637         n2s(p, i);
1638
1639         if (i > n - param_len) {
1640             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_LENGTH);
1641             goto f_err;
1642         }
1643         param_len += i;
1644
1645         if (!(dh->g = BN_bin2bn(p, i, NULL))) {
1646             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1647             goto err;
1648         }
1649         p += i;
1650
1651         if (2 > n - param_len) {
1652             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1653             goto f_err;
1654         }
1655         param_len += 2;
1656
1657         n2s(p, i);
1658
1659         if (i > n - param_len) {
1660             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1661             goto f_err;
1662         }
1663         param_len += i;
1664
1665         if (!(dh->pub_key = BN_bin2bn(p, i, NULL))) {
1666             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1667             goto err;
1668         }
1669         p += i;
1670         n -= param_len;
1671
1672 # ifndef OPENSSL_NO_RSA
1673         if (alg_a & SSL_aRSA)
1674             pkey =
1675                 X509_get_pubkey(s->session->
1676                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1677 # else
1678         if (0) ;
1679 # endif
1680 # ifndef OPENSSL_NO_DSA
1681         else if (alg_a & SSL_aDSS)
1682             pkey =
1683                 X509_get_pubkey(s->session->
1684                                 sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1685                                 x509);
1686 # endif
1687         /* else anonymous DH, so no certificate or pkey. */
1688
1689         s->session->sess_cert->peer_dh_tmp = dh;
1690         dh = NULL;
1691     } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) {
1692         al = SSL_AD_ILLEGAL_PARAMETER;
1693         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1694                SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1695         goto f_err;
1696     }
1697 #endif                          /* !OPENSSL_NO_DH */
1698
1699 #ifndef OPENSSL_NO_ECDH
1700     else if (alg_k & SSL_kEECDH) {
1701         EC_GROUP *ngroup;
1702         const EC_GROUP *group;
1703
1704         if ((ecdh = EC_KEY_new()) == NULL) {
1705             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1706             goto err;
1707         }
1708
1709         /*
1710          * Extract elliptic curve parameters and the server's ephemeral ECDH
1711          * public key. Keep accumulating lengths of various components in
1712          * param_len and make sure it never exceeds n.
1713          */
1714
1715         /*
1716          * XXX: For now we only support named (not generic) curves and the
1717          * ECParameters in this case is just three bytes. We also need one
1718          * byte for the length of the encoded point
1719          */
1720         param_len = 4;
1721         if (param_len > n) {
1722             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1723             goto f_err;
1724         }
1725
1726         if ((*p != NAMED_CURVE_TYPE) ||
1727             ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) {
1728             al = SSL_AD_INTERNAL_ERROR;
1729             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1730                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1731             goto f_err;
1732         }
1733
1734         ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1735         if (ngroup == NULL) {
1736             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1737             goto err;
1738         }
1739         if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1740             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1741             goto err;
1742         }
1743         EC_GROUP_free(ngroup);
1744
1745         group = EC_KEY_get0_group(ecdh);
1746
1747         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1748             (EC_GROUP_get_degree(group) > 163)) {
1749             al = SSL_AD_EXPORT_RESTRICTION;
1750             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1751                    SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1752             goto f_err;
1753         }
1754
1755         p += 3;
1756
1757         /* Next, get the encoded ECPoint */
1758         if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1759             ((bn_ctx = BN_CTX_new()) == NULL)) {
1760             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1761             goto err;
1762         }
1763
1764         encoded_pt_len = *p;    /* length of encoded point */
1765         p += 1;
1766
1767         if ((encoded_pt_len > n - param_len) ||
1768             (EC_POINT_oct2point(group, srvr_ecpoint,
1769                                 p, encoded_pt_len, bn_ctx) == 0)) {
1770             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1771             goto f_err;
1772         }
1773         param_len += encoded_pt_len;
1774
1775         n -= param_len;
1776         p += encoded_pt_len;
1777
1778         /*
1779          * The ECC/TLS specification does not mention the use of DSA to sign
1780          * ECParameters in the server key exchange message. We do support RSA
1781          * and ECDSA.
1782          */
1783         if (0) ;
1784 # ifndef OPENSSL_NO_RSA
1785         else if (alg_a & SSL_aRSA)
1786             pkey =
1787                 X509_get_pubkey(s->session->
1788                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1789 # endif
1790 # ifndef OPENSSL_NO_ECDSA
1791         else if (alg_a & SSL_aECDSA)
1792             pkey =
1793                 X509_get_pubkey(s->session->
1794                                 sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1795 # endif
1796         /* else anonymous ECDH, so no certificate or pkey. */
1797         EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1798         s->session->sess_cert->peer_ecdh_tmp = ecdh;
1799         ecdh = NULL;
1800         BN_CTX_free(bn_ctx);
1801         bn_ctx = NULL;
1802         EC_POINT_free(srvr_ecpoint);
1803         srvr_ecpoint = NULL;
1804     } else if (alg_k) {
1805         al = SSL_AD_UNEXPECTED_MESSAGE;
1806         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1807         goto f_err;
1808     }
1809 #endif                          /* !OPENSSL_NO_ECDH */
1810
1811     /* p points to the next byte, there are 'n' bytes left */
1812
1813     /* if it was signed, check the signature */
1814     if (pkey != NULL) {
1815         if (TLS1_get_version(s) >= TLS1_2_VERSION) {
1816             int sigalg;
1817             if (2 > n) {
1818                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1819                 goto f_err;
1820             }
1821
1822             sigalg = tls12_get_sigid(pkey);
1823             /* Should never happen */
1824             if (sigalg == -1) {
1825                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1826                 goto err;
1827             }
1828             /* Check key type is consistent with signature */
1829             if (sigalg != (int)p[1]) {
1830                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1831                        SSL_R_WRONG_SIGNATURE_TYPE);
1832                 al = SSL_AD_DECODE_ERROR;
1833                 goto f_err;
1834             }
1835             md = tls12_get_hash(p[0]);
1836             if (md == NULL) {
1837                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNKNOWN_DIGEST);
1838                 goto f_err;
1839             }
1840 #ifdef SSL_DEBUG
1841             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1842 #endif
1843             p += 2;
1844             n -= 2;
1845         } else
1846             md = EVP_sha1();
1847
1848         if (2 > n) {
1849             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1850             goto f_err;
1851         }
1852         n2s(p, i);
1853         n -= 2;
1854         j = EVP_PKEY_size(pkey);
1855
1856         /*
1857          * Check signature length. If n is 0 then signature is empty
1858          */
1859         if ((i != n) || (n > j) || (n <= 0)) {
1860             /* wrong packet length */
1861             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1862             goto f_err;
1863         }
1864 #ifndef OPENSSL_NO_RSA
1865         if (pkey->type == EVP_PKEY_RSA
1866             && TLS1_get_version(s) < TLS1_2_VERSION) {
1867             int num;
1868             unsigned int size;
1869
1870             j = 0;
1871             q = md_buf;
1872             for (num = 2; num > 0; num--) {
1873                 EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1874                 EVP_DigestInit_ex(&md_ctx, (num == 2)
1875                                   ? s->ctx->md5 : s->ctx->sha1, NULL);
1876                 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1877                                  SSL3_RANDOM_SIZE);
1878                 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1879                                  SSL3_RANDOM_SIZE);
1880                 EVP_DigestUpdate(&md_ctx, param, param_len);
1881                 EVP_DigestFinal_ex(&md_ctx, q, &size);
1882                 q += size;
1883                 j += size;
1884             }
1885             i = RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa);
1886             if (i < 0) {
1887                 al = SSL_AD_DECRYPT_ERROR;
1888                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
1889                 goto f_err;
1890             }
1891             if (i == 0) {
1892                 /* bad signature */
1893                 al = SSL_AD_DECRYPT_ERROR;
1894                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1895                 goto f_err;
1896             }
1897         } else
1898 #endif
1899         {
1900             EVP_VerifyInit_ex(&md_ctx, md, NULL);
1901             EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1902                              SSL3_RANDOM_SIZE);
1903             EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1904                              SSL3_RANDOM_SIZE);
1905             EVP_VerifyUpdate(&md_ctx, param, param_len);
1906             if (EVP_VerifyFinal(&md_ctx, p, (int)n, pkey) <= 0) {
1907                 /* bad signature */
1908                 al = SSL_AD_DECRYPT_ERROR;
1909                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1910                 goto f_err;
1911             }
1912         }
1913     } else {
1914         /* aNULL, aSRP or kPSK do not need public keys */
1915         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_kPSK)) {
1916             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1917             goto err;
1918         }
1919         /* still data left over */
1920         if (n != 0) {
1921             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1922             goto f_err;
1923         }
1924     }
1925     EVP_PKEY_free(pkey);
1926     EVP_MD_CTX_cleanup(&md_ctx);
1927     return (1);
1928  f_err:
1929     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1930  err:
1931     EVP_PKEY_free(pkey);
1932 #ifndef OPENSSL_NO_RSA
1933     if (rsa != NULL)
1934         RSA_free(rsa);
1935 #endif
1936 #ifndef OPENSSL_NO_DH
1937     if (dh != NULL)
1938         DH_free(dh);
1939 #endif
1940 #ifndef OPENSSL_NO_ECDH
1941     BN_CTX_free(bn_ctx);
1942     EC_POINT_free(srvr_ecpoint);
1943     if (ecdh != NULL)
1944         EC_KEY_free(ecdh);
1945 #endif
1946     EVP_MD_CTX_cleanup(&md_ctx);
1947     s->state = SSL_ST_ERR;
1948     return (-1);
1949 }
1950
1951 int ssl3_get_certificate_request(SSL *s)
1952 {
1953     int ok, ret = 0;
1954     unsigned long n, nc, l;
1955     unsigned int llen, ctype_num, i;
1956     X509_NAME *xn = NULL;
1957     const unsigned char *p, *q;
1958     unsigned char *d;
1959     STACK_OF(X509_NAME) *ca_sk = NULL;
1960
1961     n = s->method->ssl_get_message(s,
1962                                    SSL3_ST_CR_CERT_REQ_A,
1963                                    SSL3_ST_CR_CERT_REQ_B,
1964                                    -1, s->max_cert_list, &ok);
1965
1966     if (!ok)
1967         return ((int)n);
1968
1969     s->s3->tmp.cert_req = 0;
1970
1971     if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
1972         s->s3->tmp.reuse_message = 1;
1973         /*
1974          * If we get here we don't need any cached handshake records as we
1975          * wont be doing client auth.
1976          */
1977         if (s->s3->handshake_buffer) {
1978             if (!ssl3_digest_cached_records(s))
1979                 goto err;
1980         }
1981         return (1);
1982     }
1983
1984     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1985         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1986         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
1987         goto err;
1988     }
1989
1990     /* TLS does not like anon-DH with client cert */
1991     if (s->version > SSL3_VERSION) {
1992         if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
1993             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1994             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
1995                    SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1996             goto err;
1997         }
1998     }
1999
2000     p = d = (unsigned char *)s->init_msg;
2001
2002     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
2003         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2004         goto err;
2005     }
2006
2007     /* get the certificate types */
2008     ctype_num = *(p++);
2009     if (ctype_num > SSL3_CT_NUMBER)
2010         ctype_num = SSL3_CT_NUMBER;
2011     for (i = 0; i < ctype_num; i++)
2012         s->s3->tmp.ctype[i] = p[i];
2013     p += ctype_num;
2014     if (TLS1_get_version(s) >= TLS1_2_VERSION) {
2015         n2s(p, llen);
2016         /*
2017          * Check we have enough room for signature algorithms and following
2018          * length value.
2019          */
2020         if ((unsigned long)(p - d + llen + 2) > n) {
2021             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2022             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2023                    SSL_R_DATA_LENGTH_TOO_LONG);
2024             goto err;
2025         }
2026         if ((llen & 1) || !tls1_process_sigalgs(s, p, llen)) {
2027             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2028             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2029                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2030             goto err;
2031         }
2032         p += llen;
2033     }
2034
2035     /* get the CA RDNs */
2036     n2s(p, llen);
2037 #if 0
2038     {
2039         FILE *out;
2040         out = fopen("/tmp/vsign.der", "w");
2041         fwrite(p, 1, llen, out);
2042         fclose(out);
2043     }
2044 #endif
2045
2046     if ((unsigned long)(p - d + llen) != n) {
2047         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2048         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2049         goto err;
2050     }
2051
2052     for (nc = 0; nc < llen;) {
2053         n2s(p, l);
2054         if ((l + nc + 2) > llen) {
2055             if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2056                 goto cont;      /* netscape bugs */
2057             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2058             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2059             goto err;
2060         }
2061
2062         q = p;
2063
2064         if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
2065             /* If netscape tolerance is on, ignore errors */
2066             if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2067                 goto cont;
2068             else {
2069                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2070                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2071                 goto err;
2072             }
2073         }
2074
2075         if (q != (p + l)) {
2076             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2077             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2078                    SSL_R_CA_DN_LENGTH_MISMATCH);
2079             goto err;
2080         }
2081         if (!sk_X509_NAME_push(ca_sk, xn)) {
2082             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2083             goto err;
2084         }
2085
2086         p += l;
2087         nc += l + 2;
2088     }
2089
2090     if (0) {
2091  cont:
2092         ERR_clear_error();
2093     }
2094
2095     /* we should setup a certificate to return.... */
2096     s->s3->tmp.cert_req = 1;
2097     s->s3->tmp.ctype_num = ctype_num;
2098     if (s->s3->tmp.ca_names != NULL)
2099         sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2100     s->s3->tmp.ca_names = ca_sk;
2101     ca_sk = NULL;
2102
2103     ret = 1;
2104     goto done;
2105  err:
2106     s->state = SSL_ST_ERR;
2107  done:
2108     if (ca_sk != NULL)
2109         sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2110     return (ret);
2111 }
2112
2113 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2114 {
2115     return (X509_NAME_cmp(*a, *b));
2116 }
2117
2118 #ifndef OPENSSL_NO_TLSEXT
2119 int ssl3_get_new_session_ticket(SSL *s)
2120 {
2121     int ok, al, ret = 0, ticklen;
2122     long n;
2123     const unsigned char *p;
2124     unsigned char *d;
2125
2126     n = s->method->ssl_get_message(s,
2127                                    SSL3_ST_CR_SESSION_TICKET_A,
2128                                    SSL3_ST_CR_SESSION_TICKET_B,
2129                                    SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
2130
2131     if (!ok)
2132         return ((int)n);
2133
2134     if (n < 6) {
2135         /* need at least ticket_lifetime_hint + ticket length */
2136         al = SSL_AD_DECODE_ERROR;
2137         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2138         goto f_err;
2139     }
2140
2141     p = d = (unsigned char *)s->init_msg;
2142
2143     if (s->session->session_id_length > 0) {
2144         int i = s->session_ctx->session_cache_mode;
2145         SSL_SESSION *new_sess;
2146         /*
2147          * We reused an existing session, so we need to replace it with a new
2148          * one
2149          */
2150         if (i & SSL_SESS_CACHE_CLIENT) {
2151             /*
2152              * Remove the old session from the cache
2153              */
2154             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2155                 if (s->session_ctx->remove_session_cb != NULL)
2156                     s->session_ctx->remove_session_cb(s->session_ctx,
2157                                                       s->session);
2158             } else {
2159                 /* We carry on if this fails */
2160                 SSL_CTX_remove_session(s->session_ctx, s->session);
2161             }
2162         }
2163
2164         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2165             al = SSL_AD_INTERNAL_ERROR;
2166             SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2167             goto f_err;
2168         }
2169
2170         SSL_SESSION_free(s->session);
2171         s->session = new_sess;
2172     }
2173
2174     n2l(p, s->session->tlsext_tick_lifetime_hint);
2175     n2s(p, ticklen);
2176     /* ticket_lifetime_hint + ticket_length + ticket */
2177     if (ticklen + 6 != n) {
2178         al = SSL_AD_DECODE_ERROR;
2179         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2180         goto f_err;
2181     }
2182     if (s->session->tlsext_tick) {
2183         OPENSSL_free(s->session->tlsext_tick);
2184         s->session->tlsext_ticklen = 0;
2185     }
2186     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2187     if (!s->session->tlsext_tick) {
2188         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2189         goto err;
2190     }
2191     memcpy(s->session->tlsext_tick, p, ticklen);
2192     s->session->tlsext_ticklen = ticklen;
2193     /*
2194      * There are two ways to detect a resumed ticket session. One is to set
2195      * an appropriate session ID and then the server must return a match in
2196      * ServerHello. This allows the normal client session ID matching to work
2197      * and we know much earlier that the ticket has been accepted. The
2198      * other way is to set zero length session ID when the ticket is
2199      * presented and rely on the handshake to determine session resumption.
2200      * We choose the former approach because this fits in with assumptions
2201      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2202      * SHA256 is disabled) hash of the ticket.
2203      */
2204     EVP_Digest(p, ticklen,
2205                s->session->session_id, &s->session->session_id_length,
2206 # ifndef OPENSSL_NO_SHA256
2207                EVP_sha256(), NULL);
2208 # else
2209                EVP_sha1(), NULL);
2210 # endif
2211     ret = 1;
2212     return (ret);
2213  f_err:
2214     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2215  err:
2216     s->state = SSL_ST_ERR;
2217     return (-1);
2218 }
2219
2220 int ssl3_get_cert_status(SSL *s)
2221 {
2222     int ok, al;
2223     unsigned long resplen, n;
2224     const unsigned char *p;
2225
2226     n = s->method->ssl_get_message(s,
2227                                    SSL3_ST_CR_CERT_STATUS_A,
2228                                    SSL3_ST_CR_CERT_STATUS_B,
2229                                    SSL3_MT_CERTIFICATE_STATUS, 16384, &ok);
2230
2231     if (!ok)
2232         return ((int)n);
2233     if (n < 4) {
2234         /* need at least status type + length */
2235         al = SSL_AD_DECODE_ERROR;
2236         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2237         goto f_err;
2238     }
2239     p = (unsigned char *)s->init_msg;
2240     if (*p++ != TLSEXT_STATUSTYPE_ocsp) {
2241         al = SSL_AD_DECODE_ERROR;
2242         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2243         goto f_err;
2244     }
2245     n2l3(p, resplen);
2246     if (resplen + 4 != n) {
2247         al = SSL_AD_DECODE_ERROR;
2248         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2249         goto f_err;
2250     }
2251     if (s->tlsext_ocsp_resp)
2252         OPENSSL_free(s->tlsext_ocsp_resp);
2253     s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2254     if (!s->tlsext_ocsp_resp) {
2255         al = SSL_AD_INTERNAL_ERROR;
2256         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2257         goto f_err;
2258     }
2259     s->tlsext_ocsp_resplen = resplen;
2260     if (s->ctx->tlsext_status_cb) {
2261         int ret;
2262         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2263         if (ret == 0) {
2264             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2265             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
2266             goto f_err;
2267         }
2268         if (ret < 0) {
2269             al = SSL_AD_INTERNAL_ERROR;
2270             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2271             goto f_err;
2272         }
2273     }
2274     return 1;
2275  f_err:
2276     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2277     s->state = SSL_ST_ERR;
2278     return (-1);
2279 }
2280 #endif
2281
2282 int ssl3_get_server_done(SSL *s)
2283 {
2284     int ok, ret = 0;
2285     long n;
2286
2287     /* Second to last param should be very small, like 0 :-) */
2288     n = s->method->ssl_get_message(s,
2289                                    SSL3_ST_CR_SRVR_DONE_A,
2290                                    SSL3_ST_CR_SRVR_DONE_B,
2291                                    SSL3_MT_SERVER_DONE, 30, &ok);
2292
2293     if (!ok)
2294         return ((int)n);
2295     if (n > 0) {
2296         /* should contain no data */
2297         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2298         SSLerr(SSL_F_SSL3_GET_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2299         s->state = SSL_ST_ERR;
2300         return -1;
2301     }
2302     ret = 1;
2303     return (ret);
2304 }
2305
2306 int ssl3_send_client_key_exchange(SSL *s)
2307 {
2308     unsigned char *p, *d;
2309     int n;
2310     unsigned long alg_k;
2311 #ifndef OPENSSL_NO_RSA
2312     unsigned char *q;
2313     EVP_PKEY *pkey = NULL;
2314 #endif
2315 #ifndef OPENSSL_NO_KRB5
2316     KSSL_ERR kssl_err;
2317 #endif                          /* OPENSSL_NO_KRB5 */
2318 #ifndef OPENSSL_NO_ECDH
2319     EC_KEY *clnt_ecdh = NULL;
2320     const EC_POINT *srvr_ecpoint = NULL;
2321     EVP_PKEY *srvr_pub_pkey = NULL;
2322     unsigned char *encodedPoint = NULL;
2323     int encoded_pt_len = 0;
2324     BN_CTX *bn_ctx = NULL;
2325 #endif
2326
2327     if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
2328         d = (unsigned char *)s->init_buf->data;
2329         p = &(d[4]);
2330
2331         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2332
2333         /* Fool emacs indentation */
2334         if (0) {
2335         }
2336 #ifndef OPENSSL_NO_RSA
2337         else if (alg_k & SSL_kRSA) {
2338             RSA *rsa;
2339             unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2340
2341             if (s->session->sess_cert == NULL) {
2342                 /*
2343                  * We should always have a server certificate with SSL_kRSA.
2344                  */
2345                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2346                        ERR_R_INTERNAL_ERROR);
2347                 goto err;
2348             }
2349
2350             if (s->session->sess_cert->peer_rsa_tmp != NULL)
2351                 rsa = s->session->sess_cert->peer_rsa_tmp;
2352             else {
2353                 pkey =
2354                     X509_get_pubkey(s->session->
2355                                     sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].
2356                                     x509);
2357                 if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2358                     || (pkey->pkey.rsa == NULL)) {
2359                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2360                            ERR_R_INTERNAL_ERROR);
2361                     goto err;
2362                 }
2363                 rsa = pkey->pkey.rsa;
2364                 EVP_PKEY_free(pkey);
2365             }
2366
2367             tmp_buf[0] = s->client_version >> 8;
2368             tmp_buf[1] = s->client_version & 0xff;
2369             if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2370                 goto err;
2371
2372             s->session->master_key_length = sizeof tmp_buf;
2373
2374             q = p;
2375             /* Fix buf for TLS and beyond */
2376             if (s->version > SSL3_VERSION)
2377                 p += 2;
2378             n = RSA_public_encrypt(sizeof tmp_buf,
2379                                    tmp_buf, p, rsa, RSA_PKCS1_PADDING);
2380 # ifdef PKCS1_CHECK
2381             if (s->options & SSL_OP_PKCS1_CHECK_1)
2382                 p[1]++;
2383             if (s->options & SSL_OP_PKCS1_CHECK_2)
2384                 tmp_buf[0] = 0x70;
2385 # endif
2386             if (n <= 0) {
2387                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2388                        SSL_R_BAD_RSA_ENCRYPT);
2389                 goto err;
2390             }
2391
2392             /* Fix buf for TLS and beyond */
2393             if (s->version > SSL3_VERSION) {
2394                 s2n(n, q);
2395                 n += 2;
2396             }
2397
2398             s->session->master_key_length =
2399                 s->method->ssl3_enc->generate_master_secret(s,
2400                                                             s->
2401                                                             session->master_key,
2402                                                             tmp_buf,
2403                                                             sizeof tmp_buf);
2404             OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2405         }
2406 #endif
2407 #ifndef OPENSSL_NO_KRB5
2408         else if (alg_k & SSL_kKRB5) {
2409             krb5_error_code krb5rc;
2410             KSSL_CTX *kssl_ctx = s->kssl_ctx;
2411             /*  krb5_data   krb5_ap_req;  */
2412             krb5_data *enc_ticket;
2413             krb5_data authenticator, *authp = NULL;
2414             EVP_CIPHER_CTX ciph_ctx;
2415             const EVP_CIPHER *enc = NULL;
2416             unsigned char iv[EVP_MAX_IV_LENGTH];
2417             unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2418             unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH];
2419             int padl, outl = sizeof(epms);
2420
2421             EVP_CIPHER_CTX_init(&ciph_ctx);
2422
2423 # ifdef KSSL_DEBUG
2424             fprintf(stderr, "ssl3_send_client_key_exchange(%lx & %lx)\n",
2425                     alg_k, SSL_kKRB5);
2426 # endif                         /* KSSL_DEBUG */
2427
2428             authp = NULL;
2429 # ifdef KRB5SENDAUTH
2430             if (KRB5SENDAUTH)
2431                 authp = &authenticator;
2432 # endif                         /* KRB5SENDAUTH */
2433
2434             krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err);
2435             enc = kssl_map_enc(kssl_ctx->enctype);
2436             if (enc == NULL)
2437                 goto err;
2438 # ifdef KSSL_DEBUG
2439             {
2440                 fprintf(stderr, "kssl_cget_tkt rtn %d\n", krb5rc);
2441                 if (krb5rc && kssl_err.text)
2442                     fprintf(stderr, "kssl_cget_tkt kssl_err=%s\n",
2443                             kssl_err.text);
2444             }
2445 # endif                         /* KSSL_DEBUG */
2446
2447             if (krb5rc) {
2448                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2449                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2450                 goto err;
2451             }
2452
2453             /*-
2454              * 20010406 VRS - Earlier versions used KRB5 AP_REQ
2455              * in place of RFC 2712 KerberosWrapper, as in:
2456              *
2457              * Send ticket (copy to *p, set n = length)
2458              * n = krb5_ap_req.length;
2459              * memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2460              * if (krb5_ap_req.data)
2461              *   kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2462              *
2463              * Now using real RFC 2712 KerberosWrapper
2464              * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2465              * Note: 2712 "opaque" types are here replaced
2466              * with a 2-byte length followed by the value.
2467              * Example:
2468              * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2469              * Where "xx xx" = length bytes.  Shown here with
2470              * optional authenticator omitted.
2471              */
2472
2473             /*  KerberosWrapper.Ticket              */
2474             s2n(enc_ticket->length, p);
2475             memcpy(p, enc_ticket->data, enc_ticket->length);
2476             p += enc_ticket->length;
2477             n = enc_ticket->length + 2;
2478
2479             /*  KerberosWrapper.Authenticator       */
2480             if (authp && authp->length) {
2481                 s2n(authp->length, p);
2482                 memcpy(p, authp->data, authp->length);
2483                 p += authp->length;
2484                 n += authp->length + 2;
2485
2486                 free(authp->data);
2487                 authp->data = NULL;
2488                 authp->length = 0;
2489             } else {
2490                 s2n(0, p);      /* null authenticator length */
2491                 n += 2;
2492             }
2493
2494             tmp_buf[0] = s->client_version >> 8;
2495             tmp_buf[1] = s->client_version & 0xff;
2496             if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2497                 goto err;
2498
2499             /*-
2500              * 20010420 VRS.  Tried it this way; failed.
2501              *      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2502              *      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2503              *                              kssl_ctx->length);
2504              *      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2505              */
2506
2507             memset(iv, 0, sizeof iv); /* per RFC 1510 */
2508             EVP_EncryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv);
2509             EVP_EncryptUpdate(&ciph_ctx, epms, &outl, tmp_buf,
2510                               sizeof tmp_buf);
2511             EVP_EncryptFinal_ex(&ciph_ctx, &(epms[outl]), &padl);
2512             outl += padl;
2513             if (outl > (int)sizeof epms) {
2514                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2515                        ERR_R_INTERNAL_ERROR);
2516                 goto err;
2517             }
2518             EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2519
2520             /*  KerberosWrapper.EncryptedPreMasterSecret    */
2521             s2n(outl, p);
2522             memcpy(p, epms, outl);
2523             p += outl;
2524             n += outl + 2;
2525
2526             s->session->master_key_length =
2527                 s->method->ssl3_enc->generate_master_secret(s,
2528                                                             s->
2529                                                             session->master_key,
2530                                                             tmp_buf,
2531                                                             sizeof tmp_buf);
2532
2533             OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2534             OPENSSL_cleanse(epms, outl);
2535         }
2536 #endif
2537 #ifndef OPENSSL_NO_DH
2538         else if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2539             DH *dh_srvr, *dh_clnt;
2540
2541             if (s->session->sess_cert == NULL) {
2542                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2543                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2544                        SSL_R_UNEXPECTED_MESSAGE);
2545                 goto err;
2546             }
2547
2548             if (s->session->sess_cert->peer_dh_tmp != NULL)
2549                 dh_srvr = s->session->sess_cert->peer_dh_tmp;
2550             else {
2551                 /* we get them from the cert */
2552                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2553                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2554                        SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2555                 goto err;
2556             }
2557
2558             /* generate a new random key */
2559             if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2560                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2561                 goto err;
2562             }
2563             if (!DH_generate_key(dh_clnt)) {
2564                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2565                 DH_free(dh_clnt);
2566                 goto err;
2567             }
2568
2569             /*
2570              * use the 'p' output buffer for the DH key, but make sure to
2571              * clear it out afterwards
2572              */
2573
2574             n = DH_compute_key(p, dh_srvr->pub_key, dh_clnt);
2575
2576             if (n <= 0) {
2577                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2578                 DH_free(dh_clnt);
2579                 goto err;
2580             }
2581
2582             /* generate master key from the result */
2583             s->session->master_key_length =
2584                 s->method->ssl3_enc->generate_master_secret(s,
2585                                                             s->
2586                                                             session->master_key,
2587                                                             p, n);
2588             /* clean up */
2589             memset(p, 0, n);
2590
2591             /* send off the data */
2592             n = BN_num_bytes(dh_clnt->pub_key);
2593             s2n(n, p);
2594             BN_bn2bin(dh_clnt->pub_key, p);
2595             n += 2;
2596
2597             DH_free(dh_clnt);
2598         }
2599 #endif
2600
2601 #ifndef OPENSSL_NO_ECDH
2602         else if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2603             const EC_GROUP *srvr_group = NULL;
2604             EC_KEY *tkey;
2605             int ecdh_clnt_cert = 0;
2606             int field_size = 0;
2607
2608             if (s->session->sess_cert == NULL) {
2609                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2610                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2611                        SSL_R_UNEXPECTED_MESSAGE);
2612                 goto err;
2613             }
2614
2615             /*
2616              * Did we send out the client's ECDH share for use in premaster
2617              * computation as part of client certificate? If so, set
2618              * ecdh_clnt_cert to 1.
2619              */
2620             if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2621                 /*-
2622                  * XXX: For now, we do not support client
2623                  * authentication using ECDH certificates.
2624                  * To add such support, one needs to add
2625                  * code that checks for appropriate
2626                  * conditions and sets ecdh_clnt_cert to 1.
2627                  * For example, the cert have an ECC
2628                  * key on the same curve as the server's
2629                  * and the key should be authorized for
2630                  * key agreement.
2631                  *
2632                  * One also needs to add code in ssl3_connect
2633                  * to skip sending the certificate verify
2634                  * message.
2635                  *
2636                  * if ((s->cert->key->privatekey != NULL) &&
2637                  *     (s->cert->key->privatekey->type ==
2638                  *      EVP_PKEY_EC) && ...)
2639                  * ecdh_clnt_cert = 1;
2640                  */
2641             }
2642
2643             if (s->session->sess_cert->peer_ecdh_tmp != NULL) {
2644                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2645             } else {
2646                 /* Get the Server Public Key from Cert */
2647                 srvr_pub_pkey =
2648                     X509_get_pubkey(s->session->
2649                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2650                 if ((srvr_pub_pkey == NULL)
2651                     || (srvr_pub_pkey->type != EVP_PKEY_EC)
2652                     || (srvr_pub_pkey->pkey.ec == NULL)) {
2653                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2654                            ERR_R_INTERNAL_ERROR);
2655                     goto err;
2656                 }
2657
2658                 tkey = srvr_pub_pkey->pkey.ec;
2659             }
2660
2661             srvr_group = EC_KEY_get0_group(tkey);
2662             srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2663
2664             if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2665                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2666                        ERR_R_INTERNAL_ERROR);
2667                 goto err;
2668             }
2669
2670             if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2671                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2672                        ERR_R_MALLOC_FAILURE);
2673                 goto err;
2674             }
2675
2676             if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2677                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2678                 goto err;
2679             }
2680             if (ecdh_clnt_cert) {
2681                 /*
2682                  * Reuse key info from our certificate We only need our
2683                  * private key to perform the ECDH computation.
2684                  */
2685                 const BIGNUM *priv_key;
2686                 tkey = s->cert->key->privatekey->pkey.ec;
2687                 priv_key = EC_KEY_get0_private_key(tkey);
2688                 if (priv_key == NULL) {
2689                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2690                            ERR_R_MALLOC_FAILURE);
2691                     goto err;
2692                 }
2693                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2694                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2695                     goto err;
2696                 }
2697             } else {
2698                 /* Generate a new ECDH key pair */
2699                 if (!(EC_KEY_generate_key(clnt_ecdh))) {
2700                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2701                            ERR_R_ECDH_LIB);
2702                     goto err;
2703                 }
2704             }
2705
2706             /*
2707              * use the 'p' output buffer for the ECDH key, but make sure to
2708              * clear it out afterwards
2709              */
2710
2711             field_size = EC_GROUP_get_degree(srvr_group);
2712             if (field_size <= 0) {
2713                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2714                 goto err;
2715             }
2716             n = ECDH_compute_key(p, (field_size + 7) / 8, srvr_ecpoint,
2717                                  clnt_ecdh, NULL);
2718             if (n <= 0) {
2719                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2720                 goto err;
2721             }
2722
2723             /* generate master key from the result */
2724             s->session->master_key_length =
2725                 s->method->ssl3_enc->generate_master_secret(s,
2726                                                             s->
2727                                                             session->master_key,
2728                                                             p, n);
2729
2730             memset(p, 0, n);    /* clean up */
2731
2732             if (ecdh_clnt_cert) {
2733                 /* Send empty client key exch message */
2734                 n = 0;
2735             } else {
2736                 /*
2737                  * First check the size of encoding and allocate memory
2738                  * accordingly.
2739                  */
2740                 encoded_pt_len =
2741                     EC_POINT_point2oct(srvr_group,
2742                                        EC_KEY_get0_public_key(clnt_ecdh),
2743                                        POINT_CONVERSION_UNCOMPRESSED,
2744                                        NULL, 0, NULL);
2745
2746                 encodedPoint = (unsigned char *)
2747                     OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2748                 bn_ctx = BN_CTX_new();
2749                 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2750                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2751                            ERR_R_MALLOC_FAILURE);
2752                     goto err;
2753                 }
2754
2755                 /* Encode the public key */
2756                 n = EC_POINT_point2oct(srvr_group,
2757                                        EC_KEY_get0_public_key(clnt_ecdh),
2758                                        POINT_CONVERSION_UNCOMPRESSED,
2759                                        encodedPoint, encoded_pt_len, bn_ctx);
2760
2761                 *p = n;         /* length of encoded point */
2762                 /* Encoded point will be copied here */
2763                 p += 1;
2764                 /* copy the point */
2765                 memcpy((unsigned char *)p, encodedPoint, n);
2766                 /* increment n to account for length field */
2767                 n += 1;
2768             }
2769
2770             /* Free allocated memory */
2771             BN_CTX_free(bn_ctx);
2772             if (encodedPoint != NULL)
2773                 OPENSSL_free(encodedPoint);
2774             if (clnt_ecdh != NULL)
2775                 EC_KEY_free(clnt_ecdh);
2776             EVP_PKEY_free(srvr_pub_pkey);
2777         }
2778 #endif                          /* !OPENSSL_NO_ECDH */
2779         else if (alg_k & SSL_kGOST) {
2780             /* GOST key exchange message creation */
2781             EVP_PKEY_CTX *pkey_ctx;
2782             X509 *peer_cert;
2783             size_t msglen;
2784             unsigned int md_len;
2785             int keytype;
2786             unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2787             EVP_MD_CTX *ukm_hash;
2788             EVP_PKEY *pub_key;
2789
2790             /*
2791              * Get server sertificate PKEY and create ctx from it
2792              */
2793             peer_cert =
2794                 s->session->
2795                 sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST01)].x509;
2796             if (!peer_cert)
2797                 peer_cert =
2798                     s->session->
2799                     sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST94)].x509;
2800             if (!peer_cert) {
2801                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2802                        SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2803                 goto err;
2804             }
2805
2806             pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2807                                         X509_get_pubkey(peer_cert), NULL);
2808             /*
2809              * If we have send a certificate, and certificate key
2810              *
2811              * * parameters match those of server certificate, use
2812              * certificate key for key exchange
2813              */
2814
2815             /* Otherwise, generate ephemeral key pair */
2816
2817             EVP_PKEY_encrypt_init(pkey_ctx);
2818             /* Generate session key */
2819             if (RAND_bytes(premaster_secret, 32) <= 0) {
2820                 EVP_PKEY_CTX_free(pkey_ctx);
2821                 goto err;
2822             }
2823             /*
2824              * If we have client certificate, use its secret as peer key
2825              */
2826             if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2827                 if (EVP_PKEY_derive_set_peer
2828                     (pkey_ctx, s->cert->key->privatekey) <= 0) {
2829                     /*
2830                      * If there was an error - just ignore it. Ephemeral key
2831                      * * would be used
2832                      */
2833                     ERR_clear_error();
2834                 }
2835             }
2836             /*
2837              * Compute shared IV and store it in algorithm-specific context
2838              * data
2839              */
2840             ukm_hash = EVP_MD_CTX_create();
2841             EVP_DigestInit(ukm_hash,
2842                            EVP_get_digestbynid(NID_id_GostR3411_94));
2843             EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2844                              SSL3_RANDOM_SIZE);
2845             EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2846                              SSL3_RANDOM_SIZE);
2847             EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2848             EVP_MD_CTX_destroy(ukm_hash);
2849             if (EVP_PKEY_CTX_ctrl
2850                 (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2851                  shared_ukm) < 0) {
2852                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2853                        SSL_R_LIBRARY_BUG);
2854                 goto err;
2855             }
2856             /* Make GOST keytransport blob message */
2857             /*
2858              * Encapsulate it into sequence
2859              */
2860             *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2861             msglen = 255;
2862             if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret, 32)
2863                 < 0) {
2864                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2865                        SSL_R_LIBRARY_BUG);
2866                 goto err;
2867             }
2868             if (msglen >= 0x80) {
2869                 *(p++) = 0x81;
2870                 *(p++) = msglen & 0xff;
2871                 n = msglen + 3;
2872             } else {
2873                 *(p++) = msglen & 0xff;
2874                 n = msglen + 2;
2875             }
2876             memcpy(p, tmp, msglen);
2877             /* Check if pubkey from client certificate was used */
2878             if (EVP_PKEY_CTX_ctrl
2879                 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2880                 /* Set flag "skip certificate verify" */
2881                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2882             }
2883             EVP_PKEY_CTX_free(pkey_ctx);
2884             s->session->master_key_length =
2885                 s->method->ssl3_enc->generate_master_secret(s,
2886                                                             s->
2887                                                             session->master_key,
2888                                                             premaster_secret,
2889                                                             32);
2890             EVP_PKEY_free(pub_key);
2891
2892         }
2893 #ifndef OPENSSL_NO_SRP
2894         else if (alg_k & SSL_kSRP) {
2895             if (s->srp_ctx.A != NULL) {
2896                 /* send off the data */
2897                 n = BN_num_bytes(s->srp_ctx.A);
2898                 s2n(n, p);
2899                 BN_bn2bin(s->srp_ctx.A, p);
2900                 n += 2;
2901             } else {
2902                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2903                        ERR_R_INTERNAL_ERROR);
2904                 goto err;
2905             }
2906             if (s->session->srp_username != NULL)
2907                 OPENSSL_free(s->session->srp_username);
2908             s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2909             if (s->session->srp_username == NULL) {
2910                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2911                        ERR_R_MALLOC_FAILURE);
2912                 goto err;
2913             }
2914
2915             if ((s->session->master_key_length =
2916                  SRP_generate_client_master_secret(s,
2917                                                    s->session->master_key)) <
2918                 0) {
2919                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2920                        ERR_R_INTERNAL_ERROR);
2921                 goto err;
2922             }
2923         }
2924 #endif
2925 #ifndef OPENSSL_NO_PSK
2926         else if (alg_k & SSL_kPSK) {
2927             /*
2928              * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2929              * \0-terminated identity. The last byte is for us for simulating
2930              * strnlen.
2931              */
2932             char identity[PSK_MAX_IDENTITY_LEN + 2];
2933             size_t identity_len;
2934             unsigned char *t = NULL;
2935             unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2936             unsigned int pre_ms_len = 0, psk_len = 0;
2937             int psk_err = 1;
2938
2939             n = 0;
2940             if (s->psk_client_callback == NULL) {
2941                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2942                        SSL_R_PSK_NO_CLIENT_CB);
2943                 goto err;
2944             }
2945
2946             memset(identity, 0, sizeof(identity));
2947             psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
2948                                              identity, sizeof(identity) - 1,
2949                                              psk_or_pre_ms,
2950                                              sizeof(psk_or_pre_ms));
2951             if (psk_len > PSK_MAX_PSK_LEN) {
2952                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2953                        ERR_R_INTERNAL_ERROR);
2954                 goto psk_err;
2955             } else if (psk_len == 0) {
2956                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2957                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2958                 goto psk_err;
2959             }
2960             identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
2961             identity_len = strlen(identity);
2962             if (identity_len > PSK_MAX_IDENTITY_LEN) {
2963                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2964                        ERR_R_INTERNAL_ERROR);
2965                 goto psk_err;
2966             }
2967             /* create PSK pre_master_secret */
2968             pre_ms_len = 2 + psk_len + 2 + psk_len;
2969             t = psk_or_pre_ms;
2970             memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2971             s2n(psk_len, t);
2972             memset(t, 0, psk_len);
2973             t += psk_len;
2974             s2n(psk_len, t);
2975
2976             if (s->session->psk_identity_hint != NULL)
2977                 OPENSSL_free(s->session->psk_identity_hint);
2978             s->session->psk_identity_hint =
2979                 BUF_strdup(s->ctx->psk_identity_hint);
2980             if (s->ctx->psk_identity_hint != NULL
2981                 && s->session->psk_identity_hint == NULL) {
2982                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2983                        ERR_R_MALLOC_FAILURE);
2984                 goto psk_err;
2985             }
2986
2987             if (s->session->psk_identity != NULL)
2988                 OPENSSL_free(s->session->psk_identity);
2989             s->session->psk_identity = BUF_strdup(identity);
2990             if (s->session->psk_identity == NULL) {
2991                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2992                        ERR_R_MALLOC_FAILURE);
2993                 goto psk_err;
2994             }
2995
2996             s->session->master_key_length =
2997                 s->method->ssl3_enc->generate_master_secret(s,
2998                                                             s->
2999                                                             session->master_key,
3000                                                             psk_or_pre_ms,
3001                                                             pre_ms_len);
3002             s2n(identity_len, p);
3003             memcpy(p, identity, identity_len);
3004             n = 2 + identity_len;
3005             psk_err = 0;
3006  psk_err:
3007             OPENSSL_cleanse(identity, sizeof(identity));
3008             OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3009             if (psk_err != 0) {
3010                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3011                 goto err;
3012             }
3013         }
3014 #endif
3015         else {
3016             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3017             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3018             goto err;
3019         }
3020
3021         *(d++) = SSL3_MT_CLIENT_KEY_EXCHANGE;
3022         l2n3(n, d);
3023
3024         s->state = SSL3_ST_CW_KEY_EXCH_B;
3025         /* number of bytes to write */
3026         s->init_num = n + 4;
3027         s->init_off = 0;
3028     }
3029
3030     /* SSL3_ST_CW_KEY_EXCH_B */
3031     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3032  err:
3033 #ifndef OPENSSL_NO_ECDH
3034     BN_CTX_free(bn_ctx);
3035     if (encodedPoint != NULL)
3036         OPENSSL_free(encodedPoint);
3037     if (clnt_ecdh != NULL)
3038         EC_KEY_free(clnt_ecdh);
3039     EVP_PKEY_free(srvr_pub_pkey);
3040 #endif
3041     s->state = SSL_ST_ERR;
3042     return (-1);
3043 }
3044
3045 int ssl3_send_client_verify(SSL *s)
3046 {
3047     unsigned char *p, *d;
3048     unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
3049     EVP_PKEY *pkey;
3050     EVP_PKEY_CTX *pctx = NULL;
3051     EVP_MD_CTX mctx;
3052     unsigned u = 0;
3053     unsigned long n;
3054     int j;
3055
3056     EVP_MD_CTX_init(&mctx);
3057
3058     if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
3059         d = (unsigned char *)s->init_buf->data;
3060         p = &(d[4]);
3061         pkey = s->cert->key->privatekey;
3062 /* Create context from key and test if sha1 is allowed as digest */
3063         pctx = EVP_PKEY_CTX_new(pkey, NULL);
3064         EVP_PKEY_sign_init(pctx);
3065         if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
3066             if (TLS1_get_version(s) < TLS1_2_VERSION)
3067                 s->method->ssl3_enc->cert_verify_mac(s,
3068                                                      NID_sha1,
3069                                                      &(data
3070                                                        [MD5_DIGEST_LENGTH]));
3071         } else {
3072             ERR_clear_error();
3073         }
3074         /*
3075          * For TLS v1.2 send signature algorithm and signature using agreed
3076          * digest and cached handshake records.
3077          */
3078         if (TLS1_get_version(s) >= TLS1_2_VERSION) {
3079             long hdatalen = 0;
3080             void *hdata;
3081             const EVP_MD *md = s->cert->key->digest;
3082             hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3083             if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
3084                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3085                 goto err;
3086             }
3087             p += 2;
3088 #ifdef SSL_DEBUG
3089             fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3090                     EVP_MD_name(md));
3091 #endif
3092             if (!EVP_SignInit_ex(&mctx, md, NULL)
3093                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3094                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
3095                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
3096                 goto err;
3097             }
3098             s2n(u, p);
3099             n = u + 4;
3100             if (!ssl3_digest_cached_records(s))
3101                 goto err;
3102         } else
3103 #ifndef OPENSSL_NO_RSA
3104         if (pkey->type == EVP_PKEY_RSA) {
3105             s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
3106             if (RSA_sign(NID_md5_sha1, data,
3107                          MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
3108                          &(p[2]), &u, pkey->pkey.rsa) <= 0) {
3109                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
3110                 goto err;
3111             }
3112             s2n(u, p);
3113             n = u + 2;
3114         } else
3115 #endif
3116 #ifndef OPENSSL_NO_DSA
3117         if (pkey->type == EVP_PKEY_DSA) {
3118             if (!DSA_sign(pkey->save_type,
3119                           &(data[MD5_DIGEST_LENGTH]),
3120                           SHA_DIGEST_LENGTH, &(p[2]),
3121                           (unsigned int *)&j, pkey->pkey.dsa)) {
3122                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
3123                 goto err;
3124             }
3125             s2n(j, p);
3126             n = j + 2;
3127         } else
3128 #endif
3129 #ifndef OPENSSL_NO_ECDSA
3130         if (pkey->type == EVP_PKEY_EC) {
3131             if (!ECDSA_sign(pkey->save_type,
3132                             &(data[MD5_DIGEST_LENGTH]),
3133                             SHA_DIGEST_LENGTH, &(p[2]),
3134                             (unsigned int *)&j, pkey->pkey.ec)) {
3135                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
3136                 goto err;
3137             }
3138             s2n(j, p);
3139             n = j + 2;
3140         } else
3141 #endif
3142         if (pkey->type == NID_id_GostR3410_94
3143                 || pkey->type == NID_id_GostR3410_2001) {
3144             unsigned char signbuf[64];
3145             int i;
3146             size_t sigsize = 64;
3147             s->method->ssl3_enc->cert_verify_mac(s,
3148                                                  NID_id_GostR3411_94, data);
3149             if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3150                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3151                 goto err;
3152             }
3153             for (i = 63, j = 0; i >= 0; j++, i--) {
3154                 p[2 + j] = signbuf[i];
3155             }
3156             s2n(j, p);
3157             n = j + 2;
3158         } else {
3159             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3160             goto err;
3161         }
3162         *(d++) = SSL3_MT_CERTIFICATE_VERIFY;
3163         l2n3(n, d);
3164
3165         s->state = SSL3_ST_CW_CERT_VRFY_B;
3166         s->init_num = (int)n + 4;
3167         s->init_off = 0;
3168     }
3169     EVP_MD_CTX_cleanup(&mctx);
3170     EVP_PKEY_CTX_free(pctx);
3171     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3172  err:
3173     EVP_MD_CTX_cleanup(&mctx);
3174     EVP_PKEY_CTX_free(pctx);
3175     s->state = SSL_ST_ERR;
3176     return (-1);
3177 }
3178
3179 int ssl3_send_client_certificate(SSL *s)
3180 {
3181     X509 *x509 = NULL;
3182     EVP_PKEY *pkey = NULL;
3183     int i;
3184     unsigned long l;
3185
3186     if (s->state == SSL3_ST_CW_CERT_A) {
3187         if ((s->cert == NULL) ||
3188             (s->cert->key->x509 == NULL) ||
3189             (s->cert->key->privatekey == NULL))
3190             s->state = SSL3_ST_CW_CERT_B;
3191         else
3192             s->state = SSL3_ST_CW_CERT_C;
3193     }
3194
3195     /* We need to get a client cert */
3196     if (s->state == SSL3_ST_CW_CERT_B) {
3197         /*
3198          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3199          * return(-1); We then get retied later
3200          */
3201         i = 0;
3202         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3203         if (i < 0) {
3204             s->rwstate = SSL_X509_LOOKUP;
3205             return (-1);
3206         }
3207         s->rwstate = SSL_NOTHING;
3208         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3209             s->state = SSL3_ST_CW_CERT_B;
3210             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3211                 i = 0;
3212         } else if (i == 1) {
3213             i = 0;
3214             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
3215                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3216         }
3217
3218         if (x509 != NULL)
3219             X509_free(x509);
3220         if (pkey != NULL)
3221             EVP_PKEY_free(pkey);
3222         if (i == 0) {
3223             if (s->version == SSL3_VERSION) {
3224                 s->s3->tmp.cert_req = 0;
3225                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3226                 return (1);
3227             } else {
3228                 s->s3->tmp.cert_req = 2;
3229             }
3230         }
3231
3232         /* Ok, we have a cert */
3233         s->state = SSL3_ST_CW_CERT_C;
3234     }
3235
3236     if (s->state == SSL3_ST_CW_CERT_C) {
3237         s->state = SSL3_ST_CW_CERT_D;
3238         l = ssl3_output_cert_chain(s,
3239                                    (s->s3->tmp.cert_req ==
3240                                     2) ? NULL : s->cert->key->x509);
3241         if (!l) {
3242             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3243             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3244             s->state = SSL_ST_ERR;
3245             return 0;
3246         }
3247         s->init_num = (int)l;
3248         s->init_off = 0;
3249     }
3250     /* SSL3_ST_CW_CERT_D */
3251     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3252 }
3253
3254 #define has_bits(i,m)   (((i)&(m)) == (m))
3255
3256 int ssl3_check_cert_and_algorithm(SSL *s)
3257 {
3258     int i, idx;
3259     long alg_k, alg_a;
3260     EVP_PKEY *pkey = NULL;
3261     int pkey_bits;
3262     SESS_CERT *sc;
3263 #ifndef OPENSSL_NO_RSA
3264     RSA *rsa;
3265 #endif
3266 #ifndef OPENSSL_NO_DH
3267     DH *dh;
3268 #endif
3269
3270     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3271     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3272
3273     /* we don't have a certificate */
3274     if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK))
3275         return (1);
3276
3277     sc = s->session->sess_cert;
3278     if (sc == NULL) {
3279         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3280         goto err;
3281     }
3282 #ifndef OPENSSL_NO_RSA
3283     rsa = s->session->sess_cert->peer_rsa_tmp;
3284 #endif
3285 #ifndef OPENSSL_NO_DH
3286     dh = s->session->sess_cert->peer_dh_tmp;
3287 #endif
3288
3289     /* This is the passed certificate */
3290
3291     idx = sc->peer_cert_type;
3292 #ifndef OPENSSL_NO_ECDH
3293     if (idx == SSL_PKEY_ECC) {
3294         if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {
3295             /* check failed */
3296             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3297             goto f_err;
3298         } else {
3299             return 1;
3300         }
3301     }
3302 #endif
3303     pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
3304     pkey_bits = EVP_PKEY_bits(pkey);
3305     i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
3306     EVP_PKEY_free(pkey);
3307
3308     /* Check that we have a certificate if we require one */
3309     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3310         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3311                SSL_R_MISSING_RSA_SIGNING_CERT);
3312         goto f_err;
3313     }
3314 #ifndef OPENSSL_NO_DSA
3315     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3316         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3317                SSL_R_MISSING_DSA_SIGNING_CERT);
3318         goto f_err;
3319     }
3320 #endif
3321 #ifndef OPENSSL_NO_RSA
3322     if ((alg_k & SSL_kRSA) &&
3323         !(has_bits(i, EVP_PK_RSA | EVP_PKT_ENC) || (rsa != NULL))) {
3324         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3325                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3326         goto f_err;
3327     }
3328 #endif
3329 #ifndef OPENSSL_NO_DH
3330     if ((alg_k & SSL_kEDH) && dh == NULL) {
3331         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3332         goto f_err;
3333     }
3334     if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3335         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3336                SSL_R_MISSING_DH_RSA_CERT);
3337         goto f_err;
3338     }
3339 # ifndef OPENSSL_NO_DSA
3340     if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3341         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3342                SSL_R_MISSING_DH_DSA_CERT);
3343         goto f_err;
3344     }
3345 # endif
3346
3347     /* Check DHE only: static DH not implemented. */
3348     if (alg_k & SSL_kEDH) {
3349         int dh_size = BN_num_bits(dh->p);
3350         if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 768)
3351             || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) {
3352             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL);
3353             goto f_err;
3354         }
3355     }
3356 #endif  /* !OPENSSL_NO_DH */
3357
3358     if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3359         pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3360 #ifndef OPENSSL_NO_RSA
3361         if (alg_k & SSL_kRSA) {
3362             if (rsa == NULL
3363                 || RSA_size(rsa) * 8 >
3364                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3365                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3366                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3367                 goto f_err;
3368             }
3369         } else
3370 #endif
3371 #ifndef OPENSSL_NO_DH
3372         if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
3373             if (dh == NULL
3374                 || DH_size(dh) * 8 >
3375                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3376                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3377                        SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3378                 goto f_err;
3379             }
3380         } else
3381 #endif
3382         {
3383             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3384                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3385             goto f_err;
3386         }
3387     }
3388     return (1);
3389  f_err:
3390     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3391  err:
3392     return (0);
3393 }
3394
3395 #ifndef OPENSSL_NO_TLSEXT
3396 /*
3397  * Normally, we can tell if the server is resuming the session from
3398  * the session ID. EAP-FAST (RFC 4851), however, relies on the next server
3399  * message after the ServerHello to determine if the server is resuming.
3400  * Therefore, we allow EAP-FAST to peek ahead.
3401  * ssl3_check_finished returns 1 if we are resuming from an external
3402  * pre-shared secret, we have a "ticket" and the next server handshake message
3403  * is Finished; and 0 otherwise. It returns -1 upon an error.
3404  */
3405 static int ssl3_check_finished(SSL *s)
3406 {
3407     int ok = 0;
3408
3409     if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
3410         !s->session->tlsext_tick)
3411         return 0;
3412
3413     /* Need to permit this temporarily, in case the next message is Finished. */
3414     s->s3->flags |= SSL3_FLAGS_CCS_OK;
3415     /*
3416      * This function is called when we might get a Certificate message instead,
3417      * so permit appropriate message length.
3418      * We ignore the return value as we're only interested in the message type
3419      * and not its length.
3420      */
3421     s->method->ssl_get_message(s,
3422                                SSL3_ST_CR_CERT_A,
3423                                SSL3_ST_CR_CERT_B,
3424                                -1, s->max_cert_list, &ok);
3425     s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
3426
3427     if (!ok)
3428         return -1;
3429
3430     s->s3->tmp.reuse_message = 1;
3431
3432     if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
3433         return 1;
3434
3435     /* If we're not done, then the CCS arrived early and we should bail. */
3436     if (s->s3->change_cipher_spec) {
3437         SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
3438         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
3439         return -1;
3440     }
3441
3442     return 0;
3443 }
3444
3445 # ifndef OPENSSL_NO_NEXTPROTONEG
3446 int ssl3_send_next_proto(SSL *s)
3447 {
3448     unsigned int len, padding_len;
3449     unsigned char *d;
3450
3451     if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
3452         len = s->next_proto_negotiated_len;
3453         padding_len = 32 - ((len + 2) % 32);
3454         d = (unsigned char *)s->init_buf->data;
3455         d[4] = len;
3456         memcpy(d + 5, s->next_proto_negotiated, len);
3457         d[5 + len] = padding_len;
3458         memset(d + 6 + len, 0, padding_len);
3459         *(d++) = SSL3_MT_NEXT_PROTO;
3460         l2n3(2 + len + padding_len, d);
3461         s->state = SSL3_ST_CW_NEXT_PROTO_B;
3462         s->init_num = 4 + 2 + len + padding_len;
3463         s->init_off = 0;
3464     }
3465
3466     return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3467 }
3468 #endif                          /* !OPENSSL_NO_NEXTPROTONEG */
3469 #endif                          /* !OPENSSL_NO_TLSEXT */
3470
3471 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3472 {
3473     int i = 0;
3474 #ifndef OPENSSL_NO_ENGINE
3475     if (s->ctx->client_cert_engine) {
3476         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3477                                         SSL_get_client_CA_list(s),
3478                                         px509, ppkey, NULL, NULL, NULL);
3479         if (i != 0)
3480             return i;
3481     }
3482 #endif
3483     if (s->ctx->client_cert_cb)
3484         i = s->ctx->client_cert_cb(s, px509, ppkey);
3485     return i;
3486 }