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