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