]> CyberLeo.Net >> Repos - FreeBSD/releng/10.3.git/blob - crypto/openssl/ssl/s3_clnt.c
Fix multiple OpenSSL vulnerabilitites.
[FreeBSD/releng/10.3.git] / crypto / openssl / 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         if (nc + 3 > llen) {
1147             al = SSL_AD_DECODE_ERROR;
1148             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1149                    SSL_R_CERT_LENGTH_MISMATCH);
1150             goto f_err;
1151         }
1152         n2l3(p, l);
1153         if ((l + nc + 3) > llen) {
1154             al = SSL_AD_DECODE_ERROR;
1155             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1156                    SSL_R_CERT_LENGTH_MISMATCH);
1157             goto f_err;
1158         }
1159
1160         q = p;
1161         x = d2i_X509(NULL, &q, l);
1162         if (x == NULL) {
1163             al = SSL_AD_BAD_CERTIFICATE;
1164             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1165             goto f_err;
1166         }
1167         if (q != (p + l)) {
1168             al = SSL_AD_DECODE_ERROR;
1169             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1170                    SSL_R_CERT_LENGTH_MISMATCH);
1171             goto f_err;
1172         }
1173         if (!sk_X509_push(sk, x)) {
1174             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1175             goto err;
1176         }
1177         x = NULL;
1178         nc += l + 3;
1179         p = q;
1180     }
1181
1182     i = ssl_verify_cert_chain(s, sk);
1183     if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1184 #ifndef OPENSSL_NO_KRB5
1185         && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1186              (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1187 #endif                          /* OPENSSL_NO_KRB5 */
1188         ) {
1189         al = ssl_verify_alarm_type(s->verify_result);
1190         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1191                SSL_R_CERTIFICATE_VERIFY_FAILED);
1192         goto f_err;
1193     }
1194     ERR_clear_error();          /* but we keep s->verify_result */
1195
1196     sc = ssl_sess_cert_new();
1197     if (sc == NULL)
1198         goto err;
1199
1200     if (s->session->sess_cert)
1201         ssl_sess_cert_free(s->session->sess_cert);
1202     s->session->sess_cert = sc;
1203
1204     sc->cert_chain = sk;
1205     /*
1206      * Inconsistency alert: cert_chain does include the peer's certificate,
1207      * which we don't include in s3_srvr.c
1208      */
1209     x = sk_X509_value(sk, 0);
1210     sk = NULL;
1211     /*
1212      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1213      */
1214
1215     pkey = X509_get_pubkey(x);
1216
1217     /* VRS: allow null cert if auth == KRB5 */
1218     need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1219                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1220         ? 0 : 1;
1221
1222 #ifdef KSSL_DEBUG
1223     fprintf(stderr, "pkey,x = %p, %p\n", pkey, x);
1224     fprintf(stderr, "ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x, pkey));
1225     fprintf(stderr, "cipher, alg, nc = %s, %lx, %lx, %d\n",
1226             s->s3->tmp.new_cipher->name,
1227             s->s3->tmp.new_cipher->algorithm_mkey,
1228             s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1229 #endif                          /* KSSL_DEBUG */
1230
1231     if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) {
1232         x = NULL;
1233         al = SSL3_AL_FATAL;
1234         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1235                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1236         goto f_err;
1237     }
1238
1239     i = ssl_cert_type(x, pkey);
1240     if (need_cert && i < 0) {
1241         x = NULL;
1242         al = SSL3_AL_FATAL;
1243         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1244                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1245         goto f_err;
1246     }
1247
1248     if (need_cert) {
1249         sc->peer_cert_type = i;
1250         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1251         /*
1252          * Why would the following ever happen? We just created sc a couple
1253          * of lines ago.
1254          */
1255         if (sc->peer_pkeys[i].x509 != NULL)
1256             X509_free(sc->peer_pkeys[i].x509);
1257         sc->peer_pkeys[i].x509 = x;
1258         sc->peer_key = &(sc->peer_pkeys[i]);
1259
1260         if (s->session->peer != NULL)
1261             X509_free(s->session->peer);
1262         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1263         s->session->peer = x;
1264     } else {
1265         sc->peer_cert_type = i;
1266         sc->peer_key = NULL;
1267
1268         if (s->session->peer != NULL)
1269             X509_free(s->session->peer);
1270         s->session->peer = NULL;
1271     }
1272     s->session->verify_result = s->verify_result;
1273
1274     x = NULL;
1275     ret = 1;
1276
1277     if (0) {
1278  f_err:
1279         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1280  err:
1281         s->state = SSL_ST_ERR;
1282     }
1283
1284     EVP_PKEY_free(pkey);
1285     X509_free(x);
1286     sk_X509_pop_free(sk, X509_free);
1287     return (ret);
1288 }
1289
1290 int ssl3_get_key_exchange(SSL *s)
1291 {
1292 #ifndef OPENSSL_NO_RSA
1293     unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
1294 #endif
1295     EVP_MD_CTX md_ctx;
1296     unsigned char *param, *p;
1297     int al, j, ok;
1298     long i, param_len, n, alg_k, alg_a;
1299     EVP_PKEY *pkey = NULL;
1300     const EVP_MD *md = NULL;
1301 #ifndef OPENSSL_NO_RSA
1302     RSA *rsa = NULL;
1303 #endif
1304 #ifndef OPENSSL_NO_DH
1305     DH *dh = NULL;
1306 #endif
1307 #ifndef OPENSSL_NO_ECDH
1308     EC_KEY *ecdh = NULL;
1309     BN_CTX *bn_ctx = NULL;
1310     EC_POINT *srvr_ecpoint = NULL;
1311     int curve_nid = 0;
1312     int encoded_pt_len = 0;
1313 #endif
1314
1315     EVP_MD_CTX_init(&md_ctx);
1316
1317     /*
1318      * use same message size as in ssl3_get_certificate_request() as
1319      * ServerKeyExchange message may be skipped
1320      */
1321     n = s->method->ssl_get_message(s,
1322                                    SSL3_ST_CR_KEY_EXCH_A,
1323                                    SSL3_ST_CR_KEY_EXCH_B,
1324                                    -1, s->max_cert_list, &ok);
1325     if (!ok)
1326         return ((int)n);
1327
1328     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1329
1330     if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1331         /*
1332          * Can't skip server key exchange if this is an ephemeral
1333          * ciphersuite.
1334          */
1335         if (alg_k & (SSL_kEDH | SSL_kEECDH)) {
1336             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1337             al = SSL_AD_UNEXPECTED_MESSAGE;
1338             goto f_err;
1339         }
1340 #ifndef OPENSSL_NO_PSK
1341         /*
1342          * In plain PSK ciphersuite, ServerKeyExchange can be omitted if no
1343          * identity hint is sent. Set session->sess_cert anyway to avoid
1344          * problems later.
1345          */
1346         if (alg_k & SSL_kPSK) {
1347             s->session->sess_cert = ssl_sess_cert_new();
1348             if (s->ctx->psk_identity_hint)
1349                 OPENSSL_free(s->ctx->psk_identity_hint);
1350             s->ctx->psk_identity_hint = NULL;
1351         }
1352 #endif
1353         s->s3->tmp.reuse_message = 1;
1354         return (1);
1355     }
1356
1357     param = p = (unsigned char *)s->init_msg;
1358     if (s->session->sess_cert != NULL) {
1359 #ifndef OPENSSL_NO_RSA
1360         if (s->session->sess_cert->peer_rsa_tmp != NULL) {
1361             RSA_free(s->session->sess_cert->peer_rsa_tmp);
1362             s->session->sess_cert->peer_rsa_tmp = NULL;
1363         }
1364 #endif
1365 #ifndef OPENSSL_NO_DH
1366         if (s->session->sess_cert->peer_dh_tmp) {
1367             DH_free(s->session->sess_cert->peer_dh_tmp);
1368             s->session->sess_cert->peer_dh_tmp = NULL;
1369         }
1370 #endif
1371 #ifndef OPENSSL_NO_ECDH
1372         if (s->session->sess_cert->peer_ecdh_tmp) {
1373             EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1374             s->session->sess_cert->peer_ecdh_tmp = NULL;
1375         }
1376 #endif
1377     } else {
1378         s->session->sess_cert = ssl_sess_cert_new();
1379     }
1380
1381     /* Total length of the parameters including the length prefix */
1382     param_len = 0;
1383
1384     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1385
1386     al = SSL_AD_DECODE_ERROR;
1387
1388 #ifndef OPENSSL_NO_PSK
1389     if (alg_k & SSL_kPSK) {
1390         param_len = 2;
1391         if (param_len > n) {
1392             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1393             goto f_err;
1394         }
1395         n2s(p, i);
1396
1397         /*
1398          * Store PSK identity hint for later use, hint is used in
1399          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1400          * a PSK identity hint can be as long as the maximum length of a PSK
1401          * identity.
1402          */
1403         if (i > PSK_MAX_IDENTITY_LEN) {
1404             al = SSL_AD_HANDSHAKE_FAILURE;
1405             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1406             goto f_err;
1407         }
1408         if (i > n - param_len) {
1409             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1410                    SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1411             goto f_err;
1412         }
1413         param_len += i;
1414
1415         s->session->psk_identity_hint = BUF_strndup((char *)p, i);
1416         if (s->session->psk_identity_hint == NULL) {
1417             al = SSL_AD_HANDSHAKE_FAILURE;
1418             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1419             goto f_err;
1420         }
1421
1422         p += i;
1423         n -= param_len;
1424     } else
1425 #endif                          /* !OPENSSL_NO_PSK */
1426 #ifndef OPENSSL_NO_SRP
1427     if (alg_k & SSL_kSRP) {
1428         param_len = 2;
1429         if (param_len > n) {
1430             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1431             goto f_err;
1432         }
1433         n2s(p, i);
1434
1435         if (i > n - param_len) {
1436             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_N_LENGTH);
1437             goto f_err;
1438         }
1439         param_len += i;
1440
1441         if (!(s->srp_ctx.N = BN_bin2bn(p, i, NULL))) {
1442             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1443             goto err;
1444         }
1445         p += i;
1446
1447         if (2 > n - param_len) {
1448             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1449             goto f_err;
1450         }
1451         param_len += 2;
1452
1453         n2s(p, i);
1454
1455         if (i > n - param_len) {
1456             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_G_LENGTH);
1457             goto f_err;
1458         }
1459         param_len += i;
1460
1461         if (!(s->srp_ctx.g = BN_bin2bn(p, i, NULL))) {
1462             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1463             goto err;
1464         }
1465         p += i;
1466
1467         if (1 > n - param_len) {
1468             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1469             goto f_err;
1470         }
1471         param_len += 1;
1472
1473         i = (unsigned int)(p[0]);
1474         p++;
1475
1476         if (i > n - param_len) {
1477             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_S_LENGTH);
1478             goto f_err;
1479         }
1480         param_len += i;
1481
1482         if (!(s->srp_ctx.s = BN_bin2bn(p, i, NULL))) {
1483             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1484             goto err;
1485         }
1486         p += i;
1487
1488         if (2 > n - param_len) {
1489             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1490             goto f_err;
1491         }
1492         param_len += 2;
1493
1494         n2s(p, i);
1495
1496         if (i > n - param_len) {
1497             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_B_LENGTH);
1498             goto f_err;
1499         }
1500         param_len += i;
1501
1502         if (!(s->srp_ctx.B = BN_bin2bn(p, i, NULL))) {
1503             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1504             goto err;
1505         }
1506         p += i;
1507         n -= param_len;
1508
1509         if (!srp_verify_server_param(s, &al)) {
1510             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1511             goto f_err;
1512         }
1513
1514 /* We must check if there is a certificate */
1515 # ifndef OPENSSL_NO_RSA
1516         if (alg_a & SSL_aRSA)
1517             pkey =
1518                 X509_get_pubkey(s->session->
1519                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1520 # else
1521         if (0) ;
1522 # endif
1523 # ifndef OPENSSL_NO_DSA
1524         else if (alg_a & SSL_aDSS)
1525             pkey =
1526                 X509_get_pubkey(s->session->
1527                                 sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1528                                 x509);
1529 # endif
1530     } else
1531 #endif                          /* !OPENSSL_NO_SRP */
1532 #ifndef OPENSSL_NO_RSA
1533     if (alg_k & SSL_kRSA) {
1534         /* Temporary RSA keys only allowed in export ciphersuites */
1535         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
1536             al = SSL_AD_UNEXPECTED_MESSAGE;
1537             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1538             goto f_err;
1539         }
1540         if ((rsa = RSA_new()) == NULL) {
1541             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1542             goto err;
1543         }
1544
1545         param_len = 2;
1546         if (param_len > n) {
1547             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1548             goto f_err;
1549         }
1550         n2s(p, i);
1551
1552         if (i > n - param_len) {
1553             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_MODULUS_LENGTH);
1554             goto f_err;
1555         }
1556         param_len += i;
1557
1558         if (!(rsa->n = BN_bin2bn(p, i, rsa->n))) {
1559             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1560             goto err;
1561         }
1562         p += i;
1563
1564         if (2 > n - param_len) {
1565             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1566             goto f_err;
1567         }
1568         param_len += 2;
1569
1570         n2s(p, i);
1571
1572         if (i > n - param_len) {
1573             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_E_LENGTH);
1574             goto f_err;
1575         }
1576         param_len += i;
1577
1578         if (!(rsa->e = BN_bin2bn(p, i, rsa->e))) {
1579             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1580             goto err;
1581         }
1582         p += i;
1583         n -= param_len;
1584
1585         /* this should be because we are using an export cipher */
1586         if (alg_a & SSL_aRSA)
1587             pkey =
1588                 X509_get_pubkey(s->session->
1589                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1590         else {
1591             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1592             goto err;
1593         }
1594
1595         if (EVP_PKEY_bits(pkey) <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
1596             al = SSL_AD_UNEXPECTED_MESSAGE;
1597             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1598             goto f_err;
1599         }
1600
1601         s->session->sess_cert->peer_rsa_tmp = rsa;
1602         rsa = NULL;
1603     }
1604 #else                           /* OPENSSL_NO_RSA */
1605     if (0) ;
1606 #endif
1607 #ifndef OPENSSL_NO_DH
1608     else if (alg_k & SSL_kEDH) {
1609         if ((dh = DH_new()) == NULL) {
1610             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
1611             goto err;
1612         }
1613
1614         param_len = 2;
1615         if (param_len > n) {
1616             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1617             goto f_err;
1618         }
1619         n2s(p, i);
1620
1621         if (i > n - param_len) {
1622             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_LENGTH);
1623             goto f_err;
1624         }
1625         param_len += i;
1626
1627         if (!(dh->p = BN_bin2bn(p, i, NULL))) {
1628             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1629             goto err;
1630         }
1631         p += i;
1632
1633         if (BN_is_zero(dh->p)) {
1634             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_VALUE);
1635             goto f_err;
1636         }
1637
1638
1639         if (2 > n - param_len) {
1640             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1641             goto f_err;
1642         }
1643         param_len += 2;
1644
1645         n2s(p, i);
1646
1647         if (i > n - param_len) {
1648             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_LENGTH);
1649             goto f_err;
1650         }
1651         param_len += i;
1652
1653         if (!(dh->g = BN_bin2bn(p, i, NULL))) {
1654             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1655             goto err;
1656         }
1657         p += i;
1658
1659         if (BN_is_zero(dh->g)) {
1660             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_VALUE);
1661             goto f_err;
1662         }
1663
1664         if (2 > n - param_len) {
1665             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1666             goto f_err;
1667         }
1668         param_len += 2;
1669
1670         n2s(p, i);
1671
1672         if (i > n - param_len) {
1673             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1674             goto f_err;
1675         }
1676         param_len += i;
1677
1678         if (!(dh->pub_key = BN_bin2bn(p, i, NULL))) {
1679             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1680             goto err;
1681         }
1682         p += i;
1683         n -= param_len;
1684
1685         if (BN_is_zero(dh->pub_key)) {
1686             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_VALUE);
1687             goto f_err;
1688         }
1689
1690 # ifndef OPENSSL_NO_RSA
1691         if (alg_a & SSL_aRSA)
1692             pkey =
1693                 X509_get_pubkey(s->session->
1694                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1695 # else
1696         if (0) ;
1697 # endif
1698 # ifndef OPENSSL_NO_DSA
1699         else if (alg_a & SSL_aDSS)
1700             pkey =
1701                 X509_get_pubkey(s->session->
1702                                 sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1703                                 x509);
1704 # endif
1705         /* else anonymous DH, so no certificate or pkey. */
1706
1707         s->session->sess_cert->peer_dh_tmp = dh;
1708         dh = NULL;
1709     } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) {
1710         al = SSL_AD_ILLEGAL_PARAMETER;
1711         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1712                SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1713         goto f_err;
1714     }
1715 #endif                          /* !OPENSSL_NO_DH */
1716
1717 #ifndef OPENSSL_NO_ECDH
1718     else if (alg_k & SSL_kEECDH) {
1719         EC_GROUP *ngroup;
1720         const EC_GROUP *group;
1721
1722         if ((ecdh = EC_KEY_new()) == NULL) {
1723             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1724             goto err;
1725         }
1726
1727         /*
1728          * Extract elliptic curve parameters and the server's ephemeral ECDH
1729          * public key. Keep accumulating lengths of various components in
1730          * param_len and make sure it never exceeds n.
1731          */
1732
1733         /*
1734          * XXX: For now we only support named (not generic) curves and the
1735          * ECParameters in this case is just three bytes. We also need one
1736          * byte for the length of the encoded point
1737          */
1738         param_len = 4;
1739         if (param_len > n) {
1740             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1741             goto f_err;
1742         }
1743
1744         if ((*p != NAMED_CURVE_TYPE) ||
1745             ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) {
1746             al = SSL_AD_INTERNAL_ERROR;
1747             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1748                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1749             goto f_err;
1750         }
1751
1752         ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1753         if (ngroup == NULL) {
1754             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1755             goto err;
1756         }
1757         if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1758             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1759             goto err;
1760         }
1761         EC_GROUP_free(ngroup);
1762
1763         group = EC_KEY_get0_group(ecdh);
1764
1765         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1766             (EC_GROUP_get_degree(group) > 163)) {
1767             al = SSL_AD_EXPORT_RESTRICTION;
1768             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1769                    SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1770             goto f_err;
1771         }
1772
1773         p += 3;
1774
1775         /* Next, get the encoded ECPoint */
1776         if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1777             ((bn_ctx = BN_CTX_new()) == NULL)) {
1778             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1779             goto err;
1780         }
1781
1782         encoded_pt_len = *p;    /* length of encoded point */
1783         p += 1;
1784
1785         if ((encoded_pt_len > n - param_len) ||
1786             (EC_POINT_oct2point(group, srvr_ecpoint,
1787                                 p, encoded_pt_len, bn_ctx) == 0)) {
1788             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1789             goto f_err;
1790         }
1791         param_len += encoded_pt_len;
1792
1793         n -= param_len;
1794         p += encoded_pt_len;
1795
1796         /*
1797          * The ECC/TLS specification does not mention the use of DSA to sign
1798          * ECParameters in the server key exchange message. We do support RSA
1799          * and ECDSA.
1800          */
1801         if (0) ;
1802 # ifndef OPENSSL_NO_RSA
1803         else if (alg_a & SSL_aRSA)
1804             pkey =
1805                 X509_get_pubkey(s->session->
1806                                 sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1807 # endif
1808 # ifndef OPENSSL_NO_ECDSA
1809         else if (alg_a & SSL_aECDSA)
1810             pkey =
1811                 X509_get_pubkey(s->session->
1812                                 sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1813 # endif
1814         /* else anonymous ECDH, so no certificate or pkey. */
1815         EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1816         s->session->sess_cert->peer_ecdh_tmp = ecdh;
1817         ecdh = NULL;
1818         BN_CTX_free(bn_ctx);
1819         bn_ctx = NULL;
1820         EC_POINT_free(srvr_ecpoint);
1821         srvr_ecpoint = NULL;
1822     } else if (alg_k) {
1823         al = SSL_AD_UNEXPECTED_MESSAGE;
1824         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1825         goto f_err;
1826     }
1827 #endif                          /* !OPENSSL_NO_ECDH */
1828
1829     /* p points to the next byte, there are 'n' bytes left */
1830
1831     /* if it was signed, check the signature */
1832     if (pkey != NULL) {
1833         if (TLS1_get_version(s) >= TLS1_2_VERSION) {
1834             int sigalg;
1835             if (2 > n) {
1836                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1837                 goto f_err;
1838             }
1839
1840             sigalg = tls12_get_sigid(pkey);
1841             /* Should never happen */
1842             if (sigalg == -1) {
1843                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1844                 goto err;
1845             }
1846             /* Check key type is consistent with signature */
1847             if (sigalg != (int)p[1]) {
1848                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1849                        SSL_R_WRONG_SIGNATURE_TYPE);
1850                 al = SSL_AD_DECODE_ERROR;
1851                 goto f_err;
1852             }
1853             md = tls12_get_hash(p[0]);
1854             if (md == NULL) {
1855                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNKNOWN_DIGEST);
1856                 goto f_err;
1857             }
1858 #ifdef SSL_DEBUG
1859             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1860 #endif
1861             p += 2;
1862             n -= 2;
1863         } else
1864             md = EVP_sha1();
1865
1866         if (2 > n) {
1867             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1868             goto f_err;
1869         }
1870         n2s(p, i);
1871         n -= 2;
1872         j = EVP_PKEY_size(pkey);
1873
1874         /*
1875          * Check signature length. If n is 0 then signature is empty
1876          */
1877         if ((i != n) || (n > j) || (n <= 0)) {
1878             /* wrong packet length */
1879             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1880             goto f_err;
1881         }
1882 #ifndef OPENSSL_NO_RSA
1883         if (pkey->type == EVP_PKEY_RSA
1884             && TLS1_get_version(s) < TLS1_2_VERSION) {
1885             int num;
1886             unsigned int size;
1887
1888             j = 0;
1889             q = md_buf;
1890             for (num = 2; num > 0; num--) {
1891                 EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1892                 if (EVP_DigestInit_ex(&md_ctx,
1893                                       (num == 2) ? s->ctx->md5 : s->ctx->sha1,
1894                                       NULL) <= 0
1895                         || EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1896                                             SSL3_RANDOM_SIZE) <= 0
1897                         || EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1898                                             SSL3_RANDOM_SIZE) <= 0
1899                         || EVP_DigestUpdate(&md_ctx, param, param_len) <= 0
1900                         || EVP_DigestFinal_ex(&md_ctx, q, &size) <= 0) {
1901                     SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1902                            ERR_R_INTERNAL_ERROR);
1903                     al = SSL_AD_INTERNAL_ERROR;
1904                     goto f_err;
1905                 }
1906                 q += size;
1907                 j += size;
1908             }
1909             i = RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa);
1910             if (i < 0) {
1911                 al = SSL_AD_DECRYPT_ERROR;
1912                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
1913                 goto f_err;
1914             }
1915             if (i == 0) {
1916                 /* bad signature */
1917                 al = SSL_AD_DECRYPT_ERROR;
1918                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1919                 goto f_err;
1920             }
1921         } else
1922 #endif
1923         {
1924             if (EVP_VerifyInit_ex(&md_ctx, md, NULL) <= 0
1925                     || EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1926                                         SSL3_RANDOM_SIZE) <= 0
1927                     || EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1928                                         SSL3_RANDOM_SIZE) <= 0
1929                     || EVP_VerifyUpdate(&md_ctx, param, param_len) <= 0) {
1930                 al = SSL_AD_INTERNAL_ERROR;
1931                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EVP_LIB);
1932                 goto f_err;
1933             }
1934             if (EVP_VerifyFinal(&md_ctx, p, (int)n, pkey) <= 0) {
1935                 /* bad signature */
1936                 al = SSL_AD_DECRYPT_ERROR;
1937                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1938                 goto f_err;
1939             }
1940         }
1941     } else {
1942         /* aNULL, aSRP or kPSK do not need public keys */
1943         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_kPSK)) {
1944             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1945             goto err;
1946         }
1947         /* still data left over */
1948         if (n != 0) {
1949             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1950             goto f_err;
1951         }
1952     }
1953     EVP_PKEY_free(pkey);
1954     EVP_MD_CTX_cleanup(&md_ctx);
1955     return (1);
1956  f_err:
1957     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1958  err:
1959     EVP_PKEY_free(pkey);
1960 #ifndef OPENSSL_NO_RSA
1961     if (rsa != NULL)
1962         RSA_free(rsa);
1963 #endif
1964 #ifndef OPENSSL_NO_DH
1965     if (dh != NULL)
1966         DH_free(dh);
1967 #endif
1968 #ifndef OPENSSL_NO_ECDH
1969     BN_CTX_free(bn_ctx);
1970     EC_POINT_free(srvr_ecpoint);
1971     if (ecdh != NULL)
1972         EC_KEY_free(ecdh);
1973 #endif
1974     EVP_MD_CTX_cleanup(&md_ctx);
1975     s->state = SSL_ST_ERR;
1976     return (-1);
1977 }
1978
1979 int ssl3_get_certificate_request(SSL *s)
1980 {
1981     int ok, ret = 0;
1982     unsigned long n, nc, l;
1983     unsigned int llen, ctype_num, i;
1984     X509_NAME *xn = NULL;
1985     const unsigned char *p, *q;
1986     unsigned char *d;
1987     STACK_OF(X509_NAME) *ca_sk = NULL;
1988
1989     n = s->method->ssl_get_message(s,
1990                                    SSL3_ST_CR_CERT_REQ_A,
1991                                    SSL3_ST_CR_CERT_REQ_B,
1992                                    -1, s->max_cert_list, &ok);
1993
1994     if (!ok)
1995         return ((int)n);
1996
1997     s->s3->tmp.cert_req = 0;
1998
1999     if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
2000         s->s3->tmp.reuse_message = 1;
2001         /*
2002          * If we get here we don't need any cached handshake records as we
2003          * wont be doing client auth.
2004          */
2005         if (s->s3->handshake_buffer) {
2006             if (!ssl3_digest_cached_records(s))
2007                 goto err;
2008         }
2009         return (1);
2010     }
2011
2012     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
2013         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2014         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
2015         goto err;
2016     }
2017
2018     /* TLS does not like anon-DH with client cert */
2019     if (s->version > SSL3_VERSION) {
2020         if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
2021             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2022             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2023                    SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
2024             goto err;
2025         }
2026     }
2027
2028     p = d = (unsigned char *)s->init_msg;
2029
2030     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
2031         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2032         goto err;
2033     }
2034
2035     /* get the certificate types */
2036     ctype_num = *(p++);
2037     if (ctype_num > SSL3_CT_NUMBER)
2038         ctype_num = SSL3_CT_NUMBER;
2039     for (i = 0; i < ctype_num; i++)
2040         s->s3->tmp.ctype[i] = p[i];
2041     p += ctype_num;
2042     if (TLS1_get_version(s) >= TLS1_2_VERSION) {
2043         n2s(p, llen);
2044         /*
2045          * Check we have enough room for signature algorithms and following
2046          * length value.
2047          */
2048         if ((unsigned long)(p - d + llen + 2) > n) {
2049             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2050             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2051                    SSL_R_DATA_LENGTH_TOO_LONG);
2052             goto err;
2053         }
2054         if ((llen & 1) || !tls1_process_sigalgs(s, p, llen)) {
2055             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2056             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2057                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2058             goto err;
2059         }
2060         p += llen;
2061     }
2062
2063     /* get the CA RDNs */
2064     n2s(p, llen);
2065 #if 0
2066     {
2067         FILE *out;
2068         out = fopen("/tmp/vsign.der", "w");
2069         fwrite(p, 1, llen, out);
2070         fclose(out);
2071     }
2072 #endif
2073
2074     if ((unsigned long)(p - d + llen) != n) {
2075         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2076         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2077         goto err;
2078     }
2079
2080     for (nc = 0; nc < llen;) {
2081         if (nc + 2 > llen) {
2082             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2083             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2084             goto err;
2085         }
2086         n2s(p, l);
2087         if ((l + nc + 2) > llen) {
2088             if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2089                 goto cont;      /* netscape bugs */
2090             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2091             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2092             goto err;
2093         }
2094
2095         q = p;
2096
2097         if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
2098             /* If netscape tolerance is on, ignore errors */
2099             if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2100                 goto cont;
2101             else {
2102                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2103                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2104                 goto err;
2105             }
2106         }
2107
2108         if (q != (p + l)) {
2109             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2110             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2111                    SSL_R_CA_DN_LENGTH_MISMATCH);
2112             goto err;
2113         }
2114         if (!sk_X509_NAME_push(ca_sk, xn)) {
2115             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2116             goto err;
2117         }
2118
2119         p += l;
2120         nc += l + 2;
2121     }
2122
2123     if (0) {
2124  cont:
2125         ERR_clear_error();
2126     }
2127
2128     /* we should setup a certificate to return.... */
2129     s->s3->tmp.cert_req = 1;
2130     s->s3->tmp.ctype_num = ctype_num;
2131     if (s->s3->tmp.ca_names != NULL)
2132         sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2133     s->s3->tmp.ca_names = ca_sk;
2134     ca_sk = NULL;
2135
2136     ret = 1;
2137     goto done;
2138  err:
2139     s->state = SSL_ST_ERR;
2140  done:
2141     if (ca_sk != NULL)
2142         sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2143     return (ret);
2144 }
2145
2146 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2147 {
2148     return (X509_NAME_cmp(*a, *b));
2149 }
2150
2151 #ifndef OPENSSL_NO_TLSEXT
2152 int ssl3_get_new_session_ticket(SSL *s)
2153 {
2154     int ok, al, ret = 0, ticklen;
2155     long n;
2156     const unsigned char *p;
2157     unsigned char *d;
2158     unsigned long ticket_lifetime_hint;
2159
2160     n = s->method->ssl_get_message(s,
2161                                    SSL3_ST_CR_SESSION_TICKET_A,
2162                                    SSL3_ST_CR_SESSION_TICKET_B,
2163                                    SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
2164
2165     if (!ok)
2166         return ((int)n);
2167
2168     if (n < 6) {
2169         /* need at least ticket_lifetime_hint + ticket length */
2170         al = SSL_AD_DECODE_ERROR;
2171         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2172         goto f_err;
2173     }
2174
2175     p = d = (unsigned char *)s->init_msg;
2176
2177     n2l(p, ticket_lifetime_hint);
2178     n2s(p, ticklen);
2179     /* ticket_lifetime_hint + ticket_length + ticket */
2180     if (ticklen + 6 != n) {
2181         al = SSL_AD_DECODE_ERROR;
2182         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2183         goto f_err;
2184     }
2185
2186     /* Server is allowed to change its mind and send an empty ticket. */
2187     if (ticklen == 0)
2188         return 1;
2189
2190     if (s->session->session_id_length > 0) {
2191         int i = s->session_ctx->session_cache_mode;
2192         SSL_SESSION *new_sess;
2193         /*
2194          * We reused an existing session, so we need to replace it with a new
2195          * one
2196          */
2197         if (i & SSL_SESS_CACHE_CLIENT) {
2198             /*
2199              * Remove the old session from the cache
2200              */
2201             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2202                 if (s->session_ctx->remove_session_cb != NULL)
2203                     s->session_ctx->remove_session_cb(s->session_ctx,
2204                                                       s->session);
2205             } else {
2206                 /* We carry on if this fails */
2207                 SSL_CTX_remove_session(s->session_ctx, s->session);
2208             }
2209         }
2210
2211         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2212             al = SSL_AD_INTERNAL_ERROR;
2213             SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2214             goto f_err;
2215         }
2216
2217         SSL_SESSION_free(s->session);
2218         s->session = new_sess;
2219     }
2220
2221     if (s->session->tlsext_tick) {
2222         OPENSSL_free(s->session->tlsext_tick);
2223         s->session->tlsext_ticklen = 0;
2224     }
2225     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2226     if (!s->session->tlsext_tick) {
2227         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2228         goto err;
2229     }
2230     memcpy(s->session->tlsext_tick, p, ticklen);
2231     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2232     s->session->tlsext_ticklen = ticklen;
2233     /*
2234      * There are two ways to detect a resumed ticket session. One is to set
2235      * an appropriate session ID and then the server must return a match in
2236      * ServerHello. This allows the normal client session ID matching to work
2237      * and we know much earlier that the ticket has been accepted. The
2238      * other way is to set zero length session ID when the ticket is
2239      * presented and rely on the handshake to determine session resumption.
2240      * We choose the former approach because this fits in with assumptions
2241      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2242      * SHA256 is disabled) hash of the ticket.
2243      */
2244     EVP_Digest(p, ticklen,
2245                s->session->session_id, &s->session->session_id_length,
2246 # ifndef OPENSSL_NO_SHA256
2247                EVP_sha256(), NULL);
2248 # else
2249                EVP_sha1(), NULL);
2250 # endif
2251     ret = 1;
2252     return (ret);
2253  f_err:
2254     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2255  err:
2256     s->state = SSL_ST_ERR;
2257     return (-1);
2258 }
2259
2260 int ssl3_get_cert_status(SSL *s)
2261 {
2262     int ok, al;
2263     unsigned long resplen, n;
2264     const unsigned char *p;
2265
2266     n = s->method->ssl_get_message(s,
2267                                    SSL3_ST_CR_CERT_STATUS_A,
2268                                    SSL3_ST_CR_CERT_STATUS_B,
2269                                    -1, 16384, &ok);
2270
2271     if (!ok)
2272         return ((int)n);
2273
2274     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
2275         /*
2276          * The CertificateStatus message is optional even if
2277          * tlsext_status_expected is set
2278          */
2279         s->s3->tmp.reuse_message = 1;
2280     } else {
2281         if (n < 4) {
2282             /* need at least status type + length */
2283             al = SSL_AD_DECODE_ERROR;
2284             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2285             goto f_err;
2286         }
2287         p = (unsigned char *)s->init_msg;
2288         if (*p++ != TLSEXT_STATUSTYPE_ocsp) {
2289             al = SSL_AD_DECODE_ERROR;
2290             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2291             goto f_err;
2292         }
2293         n2l3(p, resplen);
2294         if (resplen + 4 != n) {
2295             al = SSL_AD_DECODE_ERROR;
2296             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2297             goto f_err;
2298         }
2299         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2300         if (s->tlsext_ocsp_resp == NULL) {
2301             al = SSL_AD_INTERNAL_ERROR;
2302             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2303             goto f_err;
2304         }
2305         s->tlsext_ocsp_resplen = resplen;
2306     }
2307     if (s->ctx->tlsext_status_cb) {
2308         int ret;
2309         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2310         if (ret == 0) {
2311             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2312             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
2313             goto f_err;
2314         }
2315         if (ret < 0) {
2316             al = SSL_AD_INTERNAL_ERROR;
2317             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2318             goto f_err;
2319         }
2320     }
2321     return 1;
2322  f_err:
2323     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2324     s->state = SSL_ST_ERR;
2325     return (-1);
2326 }
2327 #endif
2328
2329 int ssl3_get_server_done(SSL *s)
2330 {
2331     int ok, ret = 0;
2332     long n;
2333
2334     /* Second to last param should be very small, like 0 :-) */
2335     n = s->method->ssl_get_message(s,
2336                                    SSL3_ST_CR_SRVR_DONE_A,
2337                                    SSL3_ST_CR_SRVR_DONE_B,
2338                                    SSL3_MT_SERVER_DONE, 30, &ok);
2339
2340     if (!ok)
2341         return ((int)n);
2342     if (n > 0) {
2343         /* should contain no data */
2344         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2345         SSLerr(SSL_F_SSL3_GET_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2346         s->state = SSL_ST_ERR;
2347         return -1;
2348     }
2349     ret = 1;
2350     return (ret);
2351 }
2352
2353 int ssl3_send_client_key_exchange(SSL *s)
2354 {
2355     unsigned char *p, *d;
2356     int n;
2357     unsigned long alg_k;
2358 #ifndef OPENSSL_NO_RSA
2359     unsigned char *q;
2360     EVP_PKEY *pkey = NULL;
2361 #endif
2362 #ifndef OPENSSL_NO_KRB5
2363     KSSL_ERR kssl_err;
2364 #endif                          /* OPENSSL_NO_KRB5 */
2365 #ifndef OPENSSL_NO_ECDH
2366     EC_KEY *clnt_ecdh = NULL;
2367     const EC_POINT *srvr_ecpoint = NULL;
2368     EVP_PKEY *srvr_pub_pkey = NULL;
2369     unsigned char *encodedPoint = NULL;
2370     int encoded_pt_len = 0;
2371     BN_CTX *bn_ctx = NULL;
2372 #endif
2373
2374     if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
2375         d = (unsigned char *)s->init_buf->data;
2376         p = &(d[4]);
2377
2378         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2379
2380         /* Fool emacs indentation */
2381         if (0) {
2382         }
2383 #ifndef OPENSSL_NO_RSA
2384         else if (alg_k & SSL_kRSA) {
2385             RSA *rsa;
2386             unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2387
2388             if (s->session->sess_cert == NULL) {
2389                 /*
2390                  * We should always have a server certificate with SSL_kRSA.
2391                  */
2392                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2393                        ERR_R_INTERNAL_ERROR);
2394                 goto err;
2395             }
2396
2397             if (s->session->sess_cert->peer_rsa_tmp != NULL)
2398                 rsa = s->session->sess_cert->peer_rsa_tmp;
2399             else {
2400                 pkey =
2401                     X509_get_pubkey(s->session->
2402                                     sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].
2403                                     x509);
2404                 if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2405                     || (pkey->pkey.rsa == NULL)) {
2406                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2407                            ERR_R_INTERNAL_ERROR);
2408                     EVP_PKEY_free(pkey);
2409                     goto err;
2410                 }
2411                 rsa = pkey->pkey.rsa;
2412                 EVP_PKEY_free(pkey);
2413             }
2414
2415             tmp_buf[0] = s->client_version >> 8;
2416             tmp_buf[1] = s->client_version & 0xff;
2417             if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2418                 goto err;
2419
2420             s->session->master_key_length = sizeof tmp_buf;
2421
2422             q = p;
2423             /* Fix buf for TLS and beyond */
2424             if (s->version > SSL3_VERSION)
2425                 p += 2;
2426             n = RSA_public_encrypt(sizeof tmp_buf,
2427                                    tmp_buf, p, rsa, RSA_PKCS1_PADDING);
2428 # ifdef PKCS1_CHECK
2429             if (s->options & SSL_OP_PKCS1_CHECK_1)
2430                 p[1]++;
2431             if (s->options & SSL_OP_PKCS1_CHECK_2)
2432                 tmp_buf[0] = 0x70;
2433 # endif
2434             if (n <= 0) {
2435                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2436                        SSL_R_BAD_RSA_ENCRYPT);
2437                 goto err;
2438             }
2439
2440             /* Fix buf for TLS and beyond */
2441             if (s->version > SSL3_VERSION) {
2442                 s2n(n, q);
2443                 n += 2;
2444             }
2445
2446             s->session->master_key_length =
2447                 s->method->ssl3_enc->generate_master_secret(s,
2448                                                             s->
2449                                                             session->master_key,
2450                                                             tmp_buf,
2451                                                             sizeof tmp_buf);
2452             OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2453         }
2454 #endif
2455 #ifndef OPENSSL_NO_KRB5
2456         else if (alg_k & SSL_kKRB5) {
2457             krb5_error_code krb5rc;
2458             KSSL_CTX *kssl_ctx = s->kssl_ctx;
2459             /*  krb5_data   krb5_ap_req;  */
2460             krb5_data *enc_ticket;
2461             krb5_data authenticator, *authp = NULL;
2462             EVP_CIPHER_CTX ciph_ctx;
2463             const EVP_CIPHER *enc = NULL;
2464             unsigned char iv[EVP_MAX_IV_LENGTH];
2465             unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2466             unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH];
2467             int padl, outl = sizeof(epms);
2468
2469             EVP_CIPHER_CTX_init(&ciph_ctx);
2470
2471 # ifdef KSSL_DEBUG
2472             fprintf(stderr, "ssl3_send_client_key_exchange(%lx & %lx)\n",
2473                     alg_k, SSL_kKRB5);
2474 # endif                         /* KSSL_DEBUG */
2475
2476             authp = NULL;
2477 # ifdef KRB5SENDAUTH
2478             if (KRB5SENDAUTH)
2479                 authp = &authenticator;
2480 # endif                         /* KRB5SENDAUTH */
2481
2482             krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err);
2483             enc = kssl_map_enc(kssl_ctx->enctype);
2484             if (enc == NULL)
2485                 goto err;
2486 # ifdef KSSL_DEBUG
2487             {
2488                 fprintf(stderr, "kssl_cget_tkt rtn %d\n", krb5rc);
2489                 if (krb5rc && kssl_err.text)
2490                     fprintf(stderr, "kssl_cget_tkt kssl_err=%s\n",
2491                             kssl_err.text);
2492             }
2493 # endif                         /* KSSL_DEBUG */
2494
2495             if (krb5rc) {
2496                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2497                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2498                 goto err;
2499             }
2500
2501             /*-
2502              * 20010406 VRS - Earlier versions used KRB5 AP_REQ
2503              * in place of RFC 2712 KerberosWrapper, as in:
2504              *
2505              * Send ticket (copy to *p, set n = length)
2506              * n = krb5_ap_req.length;
2507              * memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2508              * if (krb5_ap_req.data)
2509              *   kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2510              *
2511              * Now using real RFC 2712 KerberosWrapper
2512              * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2513              * Note: 2712 "opaque" types are here replaced
2514              * with a 2-byte length followed by the value.
2515              * Example:
2516              * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2517              * Where "xx xx" = length bytes.  Shown here with
2518              * optional authenticator omitted.
2519              */
2520
2521             /*  KerberosWrapper.Ticket              */
2522             s2n(enc_ticket->length, p);
2523             memcpy(p, enc_ticket->data, enc_ticket->length);
2524             p += enc_ticket->length;
2525             n = enc_ticket->length + 2;
2526
2527             /*  KerberosWrapper.Authenticator       */
2528             if (authp && authp->length) {
2529                 s2n(authp->length, p);
2530                 memcpy(p, authp->data, authp->length);
2531                 p += authp->length;
2532                 n += authp->length + 2;
2533
2534                 free(authp->data);
2535                 authp->data = NULL;
2536                 authp->length = 0;
2537             } else {
2538                 s2n(0, p);      /* null authenticator length */
2539                 n += 2;
2540             }
2541
2542             tmp_buf[0] = s->client_version >> 8;
2543             tmp_buf[1] = s->client_version & 0xff;
2544             if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2545                 goto err;
2546
2547             /*-
2548              * 20010420 VRS.  Tried it this way; failed.
2549              *      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2550              *      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2551              *                              kssl_ctx->length);
2552              *      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2553              */
2554
2555             memset(iv, 0, sizeof iv); /* per RFC 1510 */
2556             EVP_EncryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv);
2557             EVP_EncryptUpdate(&ciph_ctx, epms, &outl, tmp_buf,
2558                               sizeof tmp_buf);
2559             EVP_EncryptFinal_ex(&ciph_ctx, &(epms[outl]), &padl);
2560             outl += padl;
2561             if (outl > (int)sizeof epms) {
2562                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2563                        ERR_R_INTERNAL_ERROR);
2564                 goto err;
2565             }
2566             EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2567
2568             /*  KerberosWrapper.EncryptedPreMasterSecret    */
2569             s2n(outl, p);
2570             memcpy(p, epms, outl);
2571             p += outl;
2572             n += outl + 2;
2573
2574             s->session->master_key_length =
2575                 s->method->ssl3_enc->generate_master_secret(s,
2576                                                             s->
2577                                                             session->master_key,
2578                                                             tmp_buf,
2579                                                             sizeof tmp_buf);
2580
2581             OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2582             OPENSSL_cleanse(epms, outl);
2583         }
2584 #endif
2585 #ifndef OPENSSL_NO_DH
2586         else if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2587             DH *dh_srvr, *dh_clnt;
2588
2589             if (s->session->sess_cert == NULL) {
2590                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2591                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2592                        SSL_R_UNEXPECTED_MESSAGE);
2593                 goto err;
2594             }
2595
2596             if (s->session->sess_cert->peer_dh_tmp != NULL)
2597                 dh_srvr = s->session->sess_cert->peer_dh_tmp;
2598             else {
2599                 /* we get them from the cert */
2600                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2601                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2602                        SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2603                 goto err;
2604             }
2605
2606             /* generate a new random key */
2607             if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2608                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2609                 goto err;
2610             }
2611             if (!DH_generate_key(dh_clnt)) {
2612                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2613                 DH_free(dh_clnt);
2614                 goto err;
2615             }
2616
2617             /*
2618              * use the 'p' output buffer for the DH key, but make sure to
2619              * clear it out afterwards
2620              */
2621
2622             n = DH_compute_key(p, dh_srvr->pub_key, dh_clnt);
2623
2624             if (n <= 0) {
2625                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2626                 DH_free(dh_clnt);
2627                 goto err;
2628             }
2629
2630             /* generate master key from the result */
2631             s->session->master_key_length =
2632                 s->method->ssl3_enc->generate_master_secret(s,
2633                                                             s->
2634                                                             session->master_key,
2635                                                             p, n);
2636             /* clean up */
2637             memset(p, 0, n);
2638
2639             /* send off the data */
2640             n = BN_num_bytes(dh_clnt->pub_key);
2641             s2n(n, p);
2642             BN_bn2bin(dh_clnt->pub_key, p);
2643             n += 2;
2644
2645             DH_free(dh_clnt);
2646         }
2647 #endif
2648
2649 #ifndef OPENSSL_NO_ECDH
2650         else if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2651             const EC_GROUP *srvr_group = NULL;
2652             EC_KEY *tkey;
2653             int ecdh_clnt_cert = 0;
2654             int field_size = 0;
2655
2656             if (s->session->sess_cert == NULL) {
2657                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2658                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2659                        SSL_R_UNEXPECTED_MESSAGE);
2660                 goto err;
2661             }
2662
2663             /*
2664              * Did we send out the client's ECDH share for use in premaster
2665              * computation as part of client certificate? If so, set
2666              * ecdh_clnt_cert to 1.
2667              */
2668             if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2669                 /*-
2670                  * XXX: For now, we do not support client
2671                  * authentication using ECDH certificates.
2672                  * To add such support, one needs to add
2673                  * code that checks for appropriate
2674                  * conditions and sets ecdh_clnt_cert to 1.
2675                  * For example, the cert have an ECC
2676                  * key on the same curve as the server's
2677                  * and the key should be authorized for
2678                  * key agreement.
2679                  *
2680                  * One also needs to add code in ssl3_connect
2681                  * to skip sending the certificate verify
2682                  * message.
2683                  *
2684                  * if ((s->cert->key->privatekey != NULL) &&
2685                  *     (s->cert->key->privatekey->type ==
2686                  *      EVP_PKEY_EC) && ...)
2687                  * ecdh_clnt_cert = 1;
2688                  */
2689             }
2690
2691             if (s->session->sess_cert->peer_ecdh_tmp != NULL) {
2692                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2693             } else {
2694                 /* Get the Server Public Key from Cert */
2695                 srvr_pub_pkey =
2696                     X509_get_pubkey(s->session->
2697                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2698                 if ((srvr_pub_pkey == NULL)
2699                     || (srvr_pub_pkey->type != EVP_PKEY_EC)
2700                     || (srvr_pub_pkey->pkey.ec == NULL)) {
2701                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2702                            ERR_R_INTERNAL_ERROR);
2703                     goto err;
2704                 }
2705
2706                 tkey = srvr_pub_pkey->pkey.ec;
2707             }
2708
2709             srvr_group = EC_KEY_get0_group(tkey);
2710             srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2711
2712             if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2713                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2714                        ERR_R_INTERNAL_ERROR);
2715                 goto err;
2716             }
2717
2718             if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2719                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2720                        ERR_R_MALLOC_FAILURE);
2721                 goto err;
2722             }
2723
2724             if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2725                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2726                 goto err;
2727             }
2728             if (ecdh_clnt_cert) {
2729                 /*
2730                  * Reuse key info from our certificate We only need our
2731                  * private key to perform the ECDH computation.
2732                  */
2733                 const BIGNUM *priv_key;
2734                 tkey = s->cert->key->privatekey->pkey.ec;
2735                 priv_key = EC_KEY_get0_private_key(tkey);
2736                 if (priv_key == NULL) {
2737                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2738                            ERR_R_MALLOC_FAILURE);
2739                     goto err;
2740                 }
2741                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2742                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2743                     goto err;
2744                 }
2745             } else {
2746                 /* Generate a new ECDH key pair */
2747                 if (!(EC_KEY_generate_key(clnt_ecdh))) {
2748                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2749                            ERR_R_ECDH_LIB);
2750                     goto err;
2751                 }
2752             }
2753
2754             /*
2755              * use the 'p' output buffer for the ECDH key, but make sure to
2756              * clear it out afterwards
2757              */
2758
2759             field_size = EC_GROUP_get_degree(srvr_group);
2760             if (field_size <= 0) {
2761                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2762                 goto err;
2763             }
2764             n = ECDH_compute_key(p, (field_size + 7) / 8, srvr_ecpoint,
2765                                  clnt_ecdh, NULL);
2766             if (n <= 0) {
2767                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2768                 goto err;
2769             }
2770
2771             /* generate master key from the result */
2772             s->session->master_key_length =
2773                 s->method->ssl3_enc->generate_master_secret(s,
2774                                                             s->
2775                                                             session->master_key,
2776                                                             p, n);
2777
2778             memset(p, 0, n);    /* clean up */
2779
2780             if (ecdh_clnt_cert) {
2781                 /* Send empty client key exch message */
2782                 n = 0;
2783             } else {
2784                 /*
2785                  * First check the size of encoding and allocate memory
2786                  * accordingly.
2787                  */
2788                 encoded_pt_len =
2789                     EC_POINT_point2oct(srvr_group,
2790                                        EC_KEY_get0_public_key(clnt_ecdh),
2791                                        POINT_CONVERSION_UNCOMPRESSED,
2792                                        NULL, 0, NULL);
2793
2794                 encodedPoint = (unsigned char *)
2795                     OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2796                 bn_ctx = BN_CTX_new();
2797                 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2798                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2799                            ERR_R_MALLOC_FAILURE);
2800                     goto err;
2801                 }
2802
2803                 /* Encode the public key */
2804                 n = EC_POINT_point2oct(srvr_group,
2805                                        EC_KEY_get0_public_key(clnt_ecdh),
2806                                        POINT_CONVERSION_UNCOMPRESSED,
2807                                        encodedPoint, encoded_pt_len, bn_ctx);
2808
2809                 *p = n;         /* length of encoded point */
2810                 /* Encoded point will be copied here */
2811                 p += 1;
2812                 /* copy the point */
2813                 memcpy((unsigned char *)p, encodedPoint, n);
2814                 /* increment n to account for length field */
2815                 n += 1;
2816             }
2817
2818             /* Free allocated memory */
2819             BN_CTX_free(bn_ctx);
2820             if (encodedPoint != NULL)
2821                 OPENSSL_free(encodedPoint);
2822             if (clnt_ecdh != NULL)
2823                 EC_KEY_free(clnt_ecdh);
2824             EVP_PKEY_free(srvr_pub_pkey);
2825         }
2826 #endif                          /* !OPENSSL_NO_ECDH */
2827         else if (alg_k & SSL_kGOST) {
2828             /* GOST key exchange message creation */
2829             EVP_PKEY_CTX *pkey_ctx;
2830             X509 *peer_cert;
2831             size_t msglen;
2832             unsigned int md_len;
2833             int keytype;
2834             unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2835             EVP_MD_CTX *ukm_hash;
2836             EVP_PKEY *pub_key;
2837
2838             /*
2839              * Get server sertificate PKEY and create ctx from it
2840              */
2841             peer_cert =
2842                 s->session->
2843                 sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST01)].x509;
2844             if (!peer_cert)
2845                 peer_cert =
2846                     s->session->
2847                     sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST94)].x509;
2848             if (!peer_cert) {
2849                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2850                        SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2851                 goto err;
2852             }
2853
2854             pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2855                                         X509_get_pubkey(peer_cert), NULL);
2856             if (pkey_ctx == NULL) {
2857                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2858                        ERR_R_MALLOC_FAILURE);
2859                 goto err;
2860             }
2861             /*
2862              * If we have send a certificate, and certificate key
2863              *
2864              * * parameters match those of server certificate, use
2865              * certificate key for key exchange
2866              */
2867
2868             /* Otherwise, generate ephemeral key pair */
2869
2870             if (pkey_ctx == NULL
2871                     || EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2872                     /* Generate session key */
2873                     || RAND_bytes(premaster_secret, 32) <= 0) {
2874                 EVP_PKEY_CTX_free(pkey_ctx);
2875                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2876                        ERR_R_INTERNAL_ERROR);
2877                 goto err;
2878             }
2879             /*
2880              * If we have client certificate, use its secret as peer key
2881              */
2882             if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2883                 if (EVP_PKEY_derive_set_peer
2884                     (pkey_ctx, s->cert->key->privatekey) <= 0) {
2885                     /*
2886                      * If there was an error - just ignore it. Ephemeral key
2887                      * * would be used
2888                      */
2889                     ERR_clear_error();
2890                 }
2891             }
2892             /*
2893              * Compute shared IV and store it in algorithm-specific context
2894              * data
2895              */
2896             ukm_hash = EVP_MD_CTX_create();
2897             if (EVP_DigestInit(ukm_hash,
2898                                EVP_get_digestbynid(NID_id_GostR3411_94)) <= 0
2899                     || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2900                                         SSL3_RANDOM_SIZE) <= 0
2901                     || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2902                                         SSL3_RANDOM_SIZE) <= 0
2903                     || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2904                 EVP_MD_CTX_destroy(ukm_hash);
2905                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2906                        ERR_R_INTERNAL_ERROR);
2907                 goto err;
2908             }
2909             EVP_MD_CTX_destroy(ukm_hash);
2910             if (EVP_PKEY_CTX_ctrl
2911                 (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2912                  shared_ukm) < 0) {
2913                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2914                        SSL_R_LIBRARY_BUG);
2915                 goto err;
2916             }
2917             /* Make GOST keytransport blob message */
2918             /*
2919              * Encapsulate it into sequence
2920              */
2921             *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2922             msglen = 255;
2923             if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret, 32)
2924                 <= 0) {
2925                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2926                        SSL_R_LIBRARY_BUG);
2927                 goto err;
2928             }
2929             if (msglen >= 0x80) {
2930                 *(p++) = 0x81;
2931                 *(p++) = msglen & 0xff;
2932                 n = msglen + 3;
2933             } else {
2934                 *(p++) = msglen & 0xff;
2935                 n = msglen + 2;
2936             }
2937             memcpy(p, tmp, msglen);
2938             /* Check if pubkey from client certificate was used */
2939             if (EVP_PKEY_CTX_ctrl
2940                 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2941                 /* Set flag "skip certificate verify" */
2942                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2943             }
2944             EVP_PKEY_CTX_free(pkey_ctx);
2945             s->session->master_key_length =
2946                 s->method->ssl3_enc->generate_master_secret(s,
2947                                                             s->
2948                                                             session->master_key,
2949                                                             premaster_secret,
2950                                                             32);
2951             EVP_PKEY_free(pub_key);
2952
2953         }
2954 #ifndef OPENSSL_NO_SRP
2955         else if (alg_k & SSL_kSRP) {
2956             if (s->srp_ctx.A != NULL) {
2957                 /* send off the data */
2958                 n = BN_num_bytes(s->srp_ctx.A);
2959                 s2n(n, p);
2960                 BN_bn2bin(s->srp_ctx.A, p);
2961                 n += 2;
2962             } else {
2963                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2964                        ERR_R_INTERNAL_ERROR);
2965                 goto err;
2966             }
2967             if (s->session->srp_username != NULL)
2968                 OPENSSL_free(s->session->srp_username);
2969             s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2970             if (s->session->srp_username == NULL) {
2971                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2972                        ERR_R_MALLOC_FAILURE);
2973                 goto err;
2974             }
2975
2976             if ((s->session->master_key_length =
2977                  SRP_generate_client_master_secret(s,
2978                                                    s->session->master_key)) <
2979                 0) {
2980                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2981                        ERR_R_INTERNAL_ERROR);
2982                 goto err;
2983             }
2984         }
2985 #endif
2986 #ifndef OPENSSL_NO_PSK
2987         else if (alg_k & SSL_kPSK) {
2988             /*
2989              * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2990              * \0-terminated identity. The last byte is for us for simulating
2991              * strnlen.
2992              */
2993             char identity[PSK_MAX_IDENTITY_LEN + 2];
2994             size_t identity_len;
2995             unsigned char *t = NULL;
2996             unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2997             unsigned int pre_ms_len = 0, psk_len = 0;
2998             int psk_err = 1;
2999
3000             n = 0;
3001             if (s->psk_client_callback == NULL) {
3002                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3003                        SSL_R_PSK_NO_CLIENT_CB);
3004                 goto err;
3005             }
3006
3007             memset(identity, 0, sizeof(identity));
3008             psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
3009                                              identity, sizeof(identity) - 1,
3010                                              psk_or_pre_ms,
3011                                              sizeof(psk_or_pre_ms));
3012             if (psk_len > PSK_MAX_PSK_LEN) {
3013                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3014                        ERR_R_INTERNAL_ERROR);
3015                 goto psk_err;
3016             } else if (psk_len == 0) {
3017                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3018                        SSL_R_PSK_IDENTITY_NOT_FOUND);
3019                 goto psk_err;
3020             }
3021             identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
3022             identity_len = strlen(identity);
3023             if (identity_len > PSK_MAX_IDENTITY_LEN) {
3024                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3025                        ERR_R_INTERNAL_ERROR);
3026                 goto psk_err;
3027             }
3028             /* create PSK pre_master_secret */
3029             pre_ms_len = 2 + psk_len + 2 + psk_len;
3030             t = psk_or_pre_ms;
3031             memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
3032             s2n(psk_len, t);
3033             memset(t, 0, psk_len);
3034             t += psk_len;
3035             s2n(psk_len, t);
3036
3037             if (s->session->psk_identity_hint != NULL)
3038                 OPENSSL_free(s->session->psk_identity_hint);
3039             s->session->psk_identity_hint =
3040                 BUF_strdup(s->ctx->psk_identity_hint);
3041             if (s->ctx->psk_identity_hint != NULL
3042                 && s->session->psk_identity_hint == NULL) {
3043                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3044                        ERR_R_MALLOC_FAILURE);
3045                 goto psk_err;
3046             }
3047
3048             if (s->session->psk_identity != NULL)
3049                 OPENSSL_free(s->session->psk_identity);
3050             s->session->psk_identity = BUF_strdup(identity);
3051             if (s->session->psk_identity == NULL) {
3052                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3053                        ERR_R_MALLOC_FAILURE);
3054                 goto psk_err;
3055             }
3056
3057             s->session->master_key_length =
3058                 s->method->ssl3_enc->generate_master_secret(s,
3059                                                             s->
3060                                                             session->master_key,
3061                                                             psk_or_pre_ms,
3062                                                             pre_ms_len);
3063             s2n(identity_len, p);
3064             memcpy(p, identity, identity_len);
3065             n = 2 + identity_len;
3066             psk_err = 0;
3067  psk_err:
3068             OPENSSL_cleanse(identity, sizeof(identity));
3069             OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3070             if (psk_err != 0) {
3071                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3072                 goto err;
3073             }
3074         }
3075 #endif
3076         else {
3077             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3078             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3079             goto err;
3080         }
3081
3082         *(d++) = SSL3_MT_CLIENT_KEY_EXCHANGE;
3083         l2n3(n, d);
3084
3085         s->state = SSL3_ST_CW_KEY_EXCH_B;
3086         /* number of bytes to write */
3087         s->init_num = n + 4;
3088         s->init_off = 0;
3089     }
3090
3091     /* SSL3_ST_CW_KEY_EXCH_B */
3092     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3093  err:
3094 #ifndef OPENSSL_NO_ECDH
3095     BN_CTX_free(bn_ctx);
3096     if (encodedPoint != NULL)
3097         OPENSSL_free(encodedPoint);
3098     if (clnt_ecdh != NULL)
3099         EC_KEY_free(clnt_ecdh);
3100     EVP_PKEY_free(srvr_pub_pkey);
3101 #endif
3102     s->state = SSL_ST_ERR;
3103     return (-1);
3104 }
3105
3106 int ssl3_send_client_verify(SSL *s)
3107 {
3108     unsigned char *p, *d;
3109     unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
3110     EVP_PKEY *pkey;
3111     EVP_PKEY_CTX *pctx = NULL;
3112     EVP_MD_CTX mctx;
3113     unsigned u = 0;
3114     unsigned long n;
3115     int j;
3116
3117     EVP_MD_CTX_init(&mctx);
3118
3119     if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
3120         d = (unsigned char *)s->init_buf->data;
3121         p = &(d[4]);
3122         pkey = s->cert->key->privatekey;
3123 /* Create context from key and test if sha1 is allowed as digest */
3124         pctx = EVP_PKEY_CTX_new(pkey, NULL);
3125         if (pctx == NULL || EVP_PKEY_sign_init(pctx) <= 0) {
3126             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3127             goto err;
3128         }
3129         if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
3130             if (TLS1_get_version(s) < TLS1_2_VERSION)
3131                 s->method->ssl3_enc->cert_verify_mac(s,
3132                                                      NID_sha1,
3133                                                      &(data
3134                                                        [MD5_DIGEST_LENGTH]));
3135         } else {
3136             ERR_clear_error();
3137         }
3138         /*
3139          * For TLS v1.2 send signature algorithm and signature using agreed
3140          * digest and cached handshake records.
3141          */
3142         if (TLS1_get_version(s) >= TLS1_2_VERSION) {
3143             long hdatalen = 0;
3144             void *hdata;
3145             const EVP_MD *md = s->cert->key->digest;
3146             hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3147             if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
3148                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3149                 goto err;
3150             }
3151             p += 2;
3152 #ifdef SSL_DEBUG
3153             fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3154                     EVP_MD_name(md));
3155 #endif
3156             if (!EVP_SignInit_ex(&mctx, md, NULL)
3157                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3158                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
3159                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
3160                 goto err;
3161             }
3162             s2n(u, p);
3163             n = u + 4;
3164             if (!ssl3_digest_cached_records(s))
3165                 goto err;
3166         } else
3167 #ifndef OPENSSL_NO_RSA
3168         if (pkey->type == EVP_PKEY_RSA) {
3169             s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
3170             if (RSA_sign(NID_md5_sha1, data,
3171                          MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
3172                          &(p[2]), &u, pkey->pkey.rsa) <= 0) {
3173                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
3174                 goto err;
3175             }
3176             s2n(u, p);
3177             n = u + 2;
3178         } else
3179 #endif
3180 #ifndef OPENSSL_NO_DSA
3181         if (pkey->type == EVP_PKEY_DSA) {
3182             if (!DSA_sign(pkey->save_type,
3183                           &(data[MD5_DIGEST_LENGTH]),
3184                           SHA_DIGEST_LENGTH, &(p[2]),
3185                           (unsigned int *)&j, pkey->pkey.dsa)) {
3186                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
3187                 goto err;
3188             }
3189             s2n(j, p);
3190             n = j + 2;
3191         } else
3192 #endif
3193 #ifndef OPENSSL_NO_ECDSA
3194         if (pkey->type == EVP_PKEY_EC) {
3195             if (!ECDSA_sign(pkey->save_type,
3196                             &(data[MD5_DIGEST_LENGTH]),
3197                             SHA_DIGEST_LENGTH, &(p[2]),
3198                             (unsigned int *)&j, pkey->pkey.ec)) {
3199                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
3200                 goto err;
3201             }
3202             s2n(j, p);
3203             n = j + 2;
3204         } else
3205 #endif
3206         if (pkey->type == NID_id_GostR3410_94
3207                 || pkey->type == NID_id_GostR3410_2001) {
3208             unsigned char signbuf[64];
3209             int i;
3210             size_t sigsize = 64;
3211             s->method->ssl3_enc->cert_verify_mac(s,
3212                                                  NID_id_GostR3411_94, data);
3213             if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3214                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3215                 goto err;
3216             }
3217             for (i = 63, j = 0; i >= 0; j++, i--) {
3218                 p[2 + j] = signbuf[i];
3219             }
3220             s2n(j, p);
3221             n = j + 2;
3222         } else {
3223             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3224             goto err;
3225         }
3226         *(d++) = SSL3_MT_CERTIFICATE_VERIFY;
3227         l2n3(n, d);
3228
3229         s->state = SSL3_ST_CW_CERT_VRFY_B;
3230         s->init_num = (int)n + 4;
3231         s->init_off = 0;
3232     }
3233     EVP_MD_CTX_cleanup(&mctx);
3234     EVP_PKEY_CTX_free(pctx);
3235     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3236  err:
3237     EVP_MD_CTX_cleanup(&mctx);
3238     EVP_PKEY_CTX_free(pctx);
3239     s->state = SSL_ST_ERR;
3240     return (-1);
3241 }
3242
3243 int ssl3_send_client_certificate(SSL *s)
3244 {
3245     X509 *x509 = NULL;
3246     EVP_PKEY *pkey = NULL;
3247     int i;
3248     unsigned long l;
3249
3250     if (s->state == SSL3_ST_CW_CERT_A) {
3251         if ((s->cert == NULL) ||
3252             (s->cert->key->x509 == NULL) ||
3253             (s->cert->key->privatekey == NULL))
3254             s->state = SSL3_ST_CW_CERT_B;
3255         else
3256             s->state = SSL3_ST_CW_CERT_C;
3257     }
3258
3259     /* We need to get a client cert */
3260     if (s->state == SSL3_ST_CW_CERT_B) {
3261         /*
3262          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3263          * return(-1); We then get retied later
3264          */
3265         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3266         if (i < 0) {
3267             s->rwstate = SSL_X509_LOOKUP;
3268             return (-1);
3269         }
3270         s->rwstate = SSL_NOTHING;
3271         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3272             s->state = SSL3_ST_CW_CERT_B;
3273             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3274                 i = 0;
3275         } else if (i == 1) {
3276             i = 0;
3277             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
3278                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3279         }
3280
3281         if (x509 != NULL)
3282             X509_free(x509);
3283         if (pkey != NULL)
3284             EVP_PKEY_free(pkey);
3285         if (i == 0) {
3286             if (s->version == SSL3_VERSION) {
3287                 s->s3->tmp.cert_req = 0;
3288                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3289                 return (1);
3290             } else {
3291                 s->s3->tmp.cert_req = 2;
3292             }
3293         }
3294
3295         /* Ok, we have a cert */
3296         s->state = SSL3_ST_CW_CERT_C;
3297     }
3298
3299     if (s->state == SSL3_ST_CW_CERT_C) {
3300         s->state = SSL3_ST_CW_CERT_D;
3301         l = ssl3_output_cert_chain(s,
3302                                    (s->s3->tmp.cert_req ==
3303                                     2) ? NULL : s->cert->key->x509);
3304         if (!l) {
3305             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3306             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3307             s->state = SSL_ST_ERR;
3308             return 0;
3309         }
3310         s->init_num = (int)l;
3311         s->init_off = 0;
3312     }
3313     /* SSL3_ST_CW_CERT_D */
3314     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3315 }
3316
3317 #define has_bits(i,m)   (((i)&(m)) == (m))
3318
3319 int ssl3_check_cert_and_algorithm(SSL *s)
3320 {
3321     int i, idx;
3322     long alg_k, alg_a;
3323     EVP_PKEY *pkey = NULL;
3324     int pkey_bits;
3325     SESS_CERT *sc;
3326 #ifndef OPENSSL_NO_RSA
3327     RSA *rsa;
3328 #endif
3329 #ifndef OPENSSL_NO_DH
3330     DH *dh;
3331 #endif
3332     int al = SSL_AD_HANDSHAKE_FAILURE;
3333
3334     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3335     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3336
3337     /* we don't have a certificate */
3338     if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK))
3339         return (1);
3340
3341     sc = s->session->sess_cert;
3342     if (sc == NULL) {
3343         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3344         goto err;
3345     }
3346 #ifndef OPENSSL_NO_RSA
3347     rsa = s->session->sess_cert->peer_rsa_tmp;
3348 #endif
3349 #ifndef OPENSSL_NO_DH
3350     dh = s->session->sess_cert->peer_dh_tmp;
3351 #endif
3352
3353     /* This is the passed certificate */
3354
3355     idx = sc->peer_cert_type;
3356 #ifndef OPENSSL_NO_ECDH
3357     if (idx == SSL_PKEY_ECC) {
3358         if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {
3359             /* check failed */
3360             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3361             goto f_err;
3362         } else {
3363             return 1;
3364         }
3365     }
3366 #endif
3367     pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
3368     pkey_bits = EVP_PKEY_bits(pkey);
3369     i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
3370     EVP_PKEY_free(pkey);
3371
3372     /* Check that we have a certificate if we require one */
3373     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3374         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3375                SSL_R_MISSING_RSA_SIGNING_CERT);
3376         goto f_err;
3377     }
3378 #ifndef OPENSSL_NO_DSA
3379     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3380         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3381                SSL_R_MISSING_DSA_SIGNING_CERT);
3382         goto f_err;
3383     }
3384 #endif
3385 #ifndef OPENSSL_NO_RSA
3386     if (alg_k & SSL_kRSA) {
3387         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3388             !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3389             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3390                    SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3391             goto f_err;
3392         } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
3393             if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3394                 if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3395                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3396                            SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3397                     goto f_err;
3398                 }
3399                 if (rsa != NULL) {
3400                     /* server key exchange is not allowed. */
3401                     al = SSL_AD_INTERNAL_ERROR;
3402                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3403                     goto f_err;
3404                 }
3405             }
3406         }
3407     }
3408 #endif
3409 #ifndef OPENSSL_NO_DH
3410     if ((alg_k & SSL_kEDH) && dh == NULL) {
3411         al = SSL_AD_INTERNAL_ERROR;
3412         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3413         goto f_err;
3414     }
3415     if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3416         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3417                SSL_R_MISSING_DH_RSA_CERT);
3418         goto f_err;
3419     }
3420 # ifndef OPENSSL_NO_DSA
3421     if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3422         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3423                SSL_R_MISSING_DH_DSA_CERT);
3424         goto f_err;
3425     }
3426 # endif
3427
3428     /* Check DHE only: static DH not implemented. */
3429     if (alg_k & SSL_kEDH) {
3430         int dh_size = BN_num_bits(dh->p);
3431         if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 1024)
3432             || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) {
3433             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL);
3434             goto f_err;
3435         }
3436     }
3437 #endif  /* !OPENSSL_NO_DH */
3438
3439     if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3440         pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3441 #ifndef OPENSSL_NO_RSA
3442         if (alg_k & SSL_kRSA) {
3443             if (rsa == NULL) {
3444                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3445                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3446                 goto f_err;
3447             } else if (BN_num_bits(rsa->n) >
3448                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3449                 /* We have a temporary RSA key but it's too large. */
3450                 al = SSL_AD_EXPORT_RESTRICTION;
3451                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3452                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3453                 goto f_err;
3454             }
3455         } else
3456 #endif
3457 #ifndef OPENSSL_NO_DH
3458         if (alg_k & SSL_kEDH) {
3459             if (BN_num_bits(dh->p) >
3460                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3461                 /* We have a temporary DH key but it's too large. */
3462                 al = SSL_AD_EXPORT_RESTRICTION;
3463                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3464                        SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3465                 goto f_err;
3466             }
3467         } else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3468             /* The cert should have had an export DH key. */
3469             al = SSL_AD_EXPORT_RESTRICTION;
3470             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3471                    SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3472                 goto f_err;
3473         } else
3474 #endif
3475         {
3476             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3477                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3478             goto f_err;
3479         }
3480     }
3481     return (1);
3482  f_err:
3483     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3484  err:
3485     return (0);
3486 }
3487
3488 #ifndef OPENSSL_NO_TLSEXT
3489 /*
3490  * Normally, we can tell if the server is resuming the session from
3491  * the session ID. EAP-FAST (RFC 4851), however, relies on the next server
3492  * message after the ServerHello to determine if the server is resuming.
3493  * Therefore, we allow EAP-FAST to peek ahead.
3494  * ssl3_check_finished returns 1 if we are resuming from an external
3495  * pre-shared secret, we have a "ticket" and the next server handshake message
3496  * is Finished; and 0 otherwise. It returns -1 upon an error.
3497  */
3498 static int ssl3_check_finished(SSL *s)
3499 {
3500     int ok = 0;
3501
3502     if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
3503         !s->session->tlsext_tick)
3504         return 0;
3505
3506     /* Need to permit this temporarily, in case the next message is Finished. */
3507     s->s3->flags |= SSL3_FLAGS_CCS_OK;
3508     /*
3509      * This function is called when we might get a Certificate message instead,
3510      * so permit appropriate message length.
3511      * We ignore the return value as we're only interested in the message type
3512      * and not its length.
3513      */
3514     s->method->ssl_get_message(s,
3515                                SSL3_ST_CR_CERT_A,
3516                                SSL3_ST_CR_CERT_B,
3517                                -1, s->max_cert_list, &ok);
3518     s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
3519
3520     if (!ok)
3521         return -1;
3522
3523     s->s3->tmp.reuse_message = 1;
3524
3525     if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
3526         return 1;
3527
3528     /* If we're not done, then the CCS arrived early and we should bail. */
3529     if (s->s3->change_cipher_spec) {
3530         SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
3531         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
3532         return -1;
3533     }
3534
3535     return 0;
3536 }
3537
3538 # ifndef OPENSSL_NO_NEXTPROTONEG
3539 int ssl3_send_next_proto(SSL *s)
3540 {
3541     unsigned int len, padding_len;
3542     unsigned char *d;
3543
3544     if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
3545         len = s->next_proto_negotiated_len;
3546         padding_len = 32 - ((len + 2) % 32);
3547         d = (unsigned char *)s->init_buf->data;
3548         d[4] = len;
3549         memcpy(d + 5, s->next_proto_negotiated, len);
3550         d[5 + len] = padding_len;
3551         memset(d + 6 + len, 0, padding_len);
3552         *(d++) = SSL3_MT_NEXT_PROTO;
3553         l2n3(2 + len + padding_len, d);
3554         s->state = SSL3_ST_CW_NEXT_PROTO_B;
3555         s->init_num = 4 + 2 + len + padding_len;
3556         s->init_off = 0;
3557     }
3558
3559     return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3560 }
3561 #endif                          /* !OPENSSL_NO_NEXTPROTONEG */
3562 #endif                          /* !OPENSSL_NO_TLSEXT */
3563
3564 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3565 {
3566     int i = 0;
3567 #ifndef OPENSSL_NO_ENGINE
3568     if (s->ctx->client_cert_engine) {
3569         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3570                                         SSL_get_client_CA_list(s),
3571                                         px509, ppkey, NULL, NULL, NULL);
3572         if (i != 0)
3573             return i;
3574     }
3575 #endif
3576     if (s->ctx->client_cert_cb)
3577         i = s->ctx->client_cert_cb(s, px509, ppkey);
3578     return i;
3579 }