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