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