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