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