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