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