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