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