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