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