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