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