Extended PSK client support.
[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                 goto memerr;
2396
2397             s->s3->tmp.psklen = psklen;
2398
2399             identitylen = strlen(identity);
2400             if (identitylen > PSK_MAX_IDENTITY_LEN) {
2401                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2402                        ERR_R_INTERNAL_ERROR);
2403                 goto psk_err;
2404             }
2405             OPENSSL_free(s->session->psk_identity);
2406             s->session->psk_identity = BUF_strdup(identity);
2407             if (s->session->psk_identity == NULL)
2408                 goto memerr;
2409
2410             s2n(identitylen, p);
2411             memcpy(p, identity, identitylen);
2412             pskhdrlen = 2 + identitylen;
2413             p += identitylen;
2414             psk_err = 0;
2415  psk_err:
2416             OPENSSL_cleanse(identity, sizeof(identity));
2417             if (psk_err != 0) {
2418                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2419                 goto err;
2420             }
2421         }
2422         if (alg_k & SSL_kPSK) {
2423             n = 0;
2424         } else
2425 #endif
2426
2427         /* Fool emacs indentation */
2428         if (0) {
2429         }
2430 #ifndef OPENSSL_NO_RSA
2431         else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2432             RSA *rsa;
2433             pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2434             pms = OPENSSL_malloc(pmslen);
2435             if (!pms)
2436                 goto memerr;
2437
2438             if (s->session->peer == NULL) {
2439                 /*
2440                  * We should always have a server certificate with SSL_kRSA.
2441                  */
2442                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2443                        ERR_R_INTERNAL_ERROR);
2444                 goto err;
2445             }
2446
2447             if (s->s3->peer_rsa_tmp != NULL)
2448                 rsa = s->s3->peer_rsa_tmp;
2449             else {
2450                 pkey = X509_get_pubkey(s->session->peer);
2451                 if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2452                     || (pkey->pkey.rsa == NULL)) {
2453                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2454                            ERR_R_INTERNAL_ERROR);
2455                     goto err;
2456                 }
2457                 rsa = pkey->pkey.rsa;
2458                 EVP_PKEY_free(pkey);
2459             }
2460
2461             pms[0] = s->client_version >> 8;
2462             pms[1] = s->client_version & 0xff;
2463             if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2464                 goto err;
2465
2466             q = p;
2467             /* Fix buf for TLS and beyond */
2468             if (s->version > SSL3_VERSION)
2469                 p += 2;
2470             n = RSA_public_encrypt(pmslen, pms, p, rsa, RSA_PKCS1_PADDING);
2471 # ifdef PKCS1_CHECK
2472             if (s->options & SSL_OP_PKCS1_CHECK_1)
2473                 p[1]++;
2474             if (s->options & SSL_OP_PKCS1_CHECK_2)
2475                 tmp_buf[0] = 0x70;
2476 # endif
2477             if (n <= 0) {
2478                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2479                        SSL_R_BAD_RSA_ENCRYPT);
2480                 goto err;
2481             }
2482
2483             /* Fix buf for TLS and beyond */
2484             if (s->version > SSL3_VERSION) {
2485                 s2n(n, q);
2486                 n += 2;
2487             }
2488         }
2489 #endif
2490 #ifndef OPENSSL_NO_DH
2491         else if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2492             DH *dh_srvr, *dh_clnt;
2493             if (s->s3->peer_dh_tmp != NULL)
2494                 dh_srvr = s->s3->peer_dh_tmp;
2495             else {
2496                 /* we get them from the cert */
2497                 EVP_PKEY *spkey = NULL;
2498                 dh_srvr = NULL;
2499                 spkey = X509_get_pubkey(s->session->peer);
2500                 if (spkey) {
2501                     dh_srvr = EVP_PKEY_get1_DH(spkey);
2502                     EVP_PKEY_free(spkey);
2503                 }
2504                 if (dh_srvr == NULL) {
2505                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2506                            ERR_R_INTERNAL_ERROR);
2507                     goto err;
2508                 }
2509             }
2510             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
2511                 /* Use client certificate key */
2512                 EVP_PKEY *clkey = s->cert->key->privatekey;
2513                 dh_clnt = NULL;
2514                 if (clkey)
2515                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2516                 if (dh_clnt == NULL) {
2517                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2518                            ERR_R_INTERNAL_ERROR);
2519                     goto err;
2520                 }
2521             } else {
2522                 /* generate a new random key */
2523                 if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2524                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2525                     goto err;
2526                 }
2527                 if (!DH_generate_key(dh_clnt)) {
2528                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2529                     DH_free(dh_clnt);
2530                     goto err;
2531                 }
2532             }
2533
2534             pmslen = DH_size(dh_clnt);
2535             pms = OPENSSL_malloc(pmslen);
2536             if (!pms)
2537                 goto memerr;
2538
2539             /*
2540              * use the 'p' output buffer for the DH key, but make sure to
2541              * clear it out afterwards
2542              */
2543
2544             n = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
2545             if (s->s3->peer_dh_tmp == NULL)
2546                 DH_free(dh_srvr);
2547
2548             if (n <= 0) {
2549                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2550                 DH_free(dh_clnt);
2551                 goto err;
2552             }
2553             pmslen = n;
2554
2555             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2556                 n = 0;
2557             else {
2558                 /* send off the data */
2559                 n = BN_num_bytes(dh_clnt->pub_key);
2560                 s2n(n, p);
2561                 BN_bn2bin(dh_clnt->pub_key, p);
2562                 n += 2;
2563             }
2564
2565             DH_free(dh_clnt);
2566         }
2567 #endif
2568
2569 #ifndef OPENSSL_NO_EC
2570         else if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2571             const EC_GROUP *srvr_group = NULL;
2572             EC_KEY *tkey;
2573             int ecdh_clnt_cert = 0;
2574             int field_size = 0;
2575             /*
2576              * Did we send out the client's ECDH share for use in premaster
2577              * computation as part of client certificate? If so, set
2578              * ecdh_clnt_cert to 1.
2579              */
2580             if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2581                 /*-
2582                  * XXX: For now, we do not support client
2583                  * authentication using ECDH certificates.
2584                  * To add such support, one needs to add
2585                  * code that checks for appropriate
2586                  * conditions and sets ecdh_clnt_cert to 1.
2587                  * For example, the cert have an ECC
2588                  * key on the same curve as the server's
2589                  * and the key should be authorized for
2590                  * key agreement.
2591                  *
2592                  * One also needs to add code in ssl3_connect
2593                  * to skip sending the certificate verify
2594                  * message.
2595                  *
2596                  * if ((s->cert->key->privatekey != NULL) &&
2597                  *     (s->cert->key->privatekey->type ==
2598                  *      EVP_PKEY_EC) && ...)
2599                  * ecdh_clnt_cert = 1;
2600                  */
2601             }
2602
2603             if (s->s3->peer_ecdh_tmp != NULL) {
2604                 tkey = s->s3->peer_ecdh_tmp;
2605             } else {
2606                 /* Get the Server Public Key from Cert */
2607                 srvr_pub_pkey = X509_get_pubkey(s->session->peer);
2608                 if ((srvr_pub_pkey == NULL)
2609                     || (srvr_pub_pkey->type != EVP_PKEY_EC)
2610                     || (srvr_pub_pkey->pkey.ec == NULL)) {
2611                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2612                            ERR_R_INTERNAL_ERROR);
2613                     goto err;
2614                 }
2615
2616                 tkey = srvr_pub_pkey->pkey.ec;
2617             }
2618
2619             srvr_group = EC_KEY_get0_group(tkey);
2620             srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2621
2622             if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2623                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2624                        ERR_R_INTERNAL_ERROR);
2625                 goto err;
2626             }
2627
2628             if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2629                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2630                        ERR_R_MALLOC_FAILURE);
2631                 goto err;
2632             }
2633
2634             if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2635                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2636                 goto err;
2637             }
2638             if (ecdh_clnt_cert) {
2639                 /*
2640                  * Reuse key info from our certificate We only need our
2641                  * private key to perform the ECDH computation.
2642                  */
2643                 const BIGNUM *priv_key;
2644                 tkey = s->cert->key->privatekey->pkey.ec;
2645                 priv_key = EC_KEY_get0_private_key(tkey);
2646                 if (priv_key == NULL) {
2647                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2648                            ERR_R_MALLOC_FAILURE);
2649                     goto err;
2650                 }
2651                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2652                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2653                     goto err;
2654                 }
2655             } else {
2656                 /* Generate a new ECDH key pair */
2657                 if (!(EC_KEY_generate_key(clnt_ecdh))) {
2658                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2659                            ERR_R_ECDH_LIB);
2660                     goto err;
2661                 }
2662             }
2663
2664             /*
2665              * use the 'p' output buffer for the ECDH key, but make sure to
2666              * clear it out afterwards
2667              */
2668
2669             field_size = EC_GROUP_get_degree(srvr_group);
2670             if (field_size <= 0) {
2671                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2672                 goto err;
2673             }
2674             pmslen = (field_size + 7) / 8;
2675             pms = OPENSSL_malloc(pmslen);
2676             if (!pms)
2677                 goto memerr;
2678             n = ECDH_compute_key(pms, pmslen, srvr_ecpoint, clnt_ecdh, NULL);
2679             if (n <= 0 || pmslen != (size_t)n) {
2680                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2681                 goto err;
2682             }
2683
2684             if (ecdh_clnt_cert) {
2685                 /* Send empty client key exch message */
2686                 n = 0;
2687             } else {
2688                 /*
2689                  * First check the size of encoding and allocate memory
2690                  * accordingly.
2691                  */
2692                 encoded_pt_len =
2693                     EC_POINT_point2oct(srvr_group,
2694                                        EC_KEY_get0_public_key(clnt_ecdh),
2695                                        POINT_CONVERSION_UNCOMPRESSED,
2696                                        NULL, 0, NULL);
2697
2698                 encodedPoint = (unsigned char *)
2699                     OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2700                 bn_ctx = BN_CTX_new();
2701                 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2702                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2703                            ERR_R_MALLOC_FAILURE);
2704                     goto err;
2705                 }
2706
2707                 /* Encode the public key */
2708                 n = EC_POINT_point2oct(srvr_group,
2709                                        EC_KEY_get0_public_key(clnt_ecdh),
2710                                        POINT_CONVERSION_UNCOMPRESSED,
2711                                        encodedPoint, encoded_pt_len, bn_ctx);
2712
2713                 *p = n;         /* length of encoded point */
2714                 /* Encoded point will be copied here */
2715                 p += 1;
2716                 /* copy the point */
2717                 memcpy(p, encodedPoint, n);
2718                 /* increment n to account for length field */
2719                 n += 1;
2720             }
2721
2722             /* Free allocated memory */
2723             BN_CTX_free(bn_ctx);
2724             OPENSSL_free(encodedPoint);
2725             EC_KEY_free(clnt_ecdh);
2726             EVP_PKEY_free(srvr_pub_pkey);
2727         }
2728 #endif                          /* !OPENSSL_NO_EC */
2729         else if (alg_k & SSL_kGOST) {
2730             /* GOST key exchange message creation */
2731             EVP_PKEY_CTX *pkey_ctx;
2732             X509 *peer_cert;
2733             size_t msglen;
2734             unsigned int md_len;
2735             unsigned char shared_ukm[32], tmp[256];
2736             EVP_MD_CTX *ukm_hash;
2737             EVP_PKEY *pub_key;
2738
2739             pmslen = 32;
2740             pms = OPENSSL_malloc(pmslen);
2741             if (!pms)
2742                 goto memerr;
2743
2744             /*
2745              * Get server sertificate PKEY and create ctx from it
2746              */
2747             peer_cert = s->session->peer;
2748             if (!peer_cert) {
2749                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2750                        SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2751                 goto err;
2752             }
2753
2754             pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2755                                         X509_get_pubkey(peer_cert), NULL);
2756             /*
2757              * If we have send a certificate, and certificate key
2758              *
2759              * * parameters match those of server certificate, use
2760              * certificate key for key exchange
2761              */
2762
2763             /* Otherwise, generate ephemeral key pair */
2764
2765             EVP_PKEY_encrypt_init(pkey_ctx);
2766             /* Generate session key */
2767             if (RAND_bytes(pms, pmslen) <= 0) {
2768                 EVP_PKEY_CTX_free(pkey_ctx);
2769                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2770                        ERR_R_INTERNAL_ERROR);
2771                 goto err;
2772             };
2773             /*
2774              * If we have client certificate, use its secret as peer key
2775              */
2776             if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2777                 if (EVP_PKEY_derive_set_peer
2778                     (pkey_ctx, s->cert->key->privatekey) <= 0) {
2779                     /*
2780                      * If there was an error - just ignore it. Ephemeral key
2781                      * * would be used
2782                      */
2783                     ERR_clear_error();
2784                 }
2785             }
2786             /*
2787              * Compute shared IV and store it in algorithm-specific context
2788              * data
2789              */
2790             ukm_hash = EVP_MD_CTX_create();
2791             EVP_DigestInit(ukm_hash,
2792                            EVP_get_digestbynid(NID_id_GostR3411_94));
2793             EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2794                              SSL3_RANDOM_SIZE);
2795             EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2796                              SSL3_RANDOM_SIZE);
2797             EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2798             EVP_MD_CTX_destroy(ukm_hash);
2799             if (EVP_PKEY_CTX_ctrl
2800                 (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2801                  shared_ukm) < 0) {
2802                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2803                        SSL_R_LIBRARY_BUG);
2804                 goto err;
2805             }
2806             /* Make GOST keytransport blob message */
2807             /*
2808              * Encapsulate it into sequence
2809              */
2810             *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2811             msglen = 255;
2812             if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) < 0) {
2813                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2814                        SSL_R_LIBRARY_BUG);
2815                 goto err;
2816             }
2817             if (msglen >= 0x80) {
2818                 *(p++) = 0x81;
2819                 *(p++) = msglen & 0xff;
2820                 n = msglen + 3;
2821             } else {
2822                 *(p++) = msglen & 0xff;
2823                 n = msglen + 2;
2824             }
2825             memcpy(p, tmp, msglen);
2826             /* Check if pubkey from client certificate was used */
2827             if (EVP_PKEY_CTX_ctrl
2828                 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2829                 /* Set flag "skip certificate verify" */
2830                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2831             }
2832             EVP_PKEY_CTX_free(pkey_ctx);
2833             EVP_PKEY_free(pub_key);
2834
2835         }
2836 #ifndef OPENSSL_NO_SRP
2837         else if (alg_k & SSL_kSRP) {
2838             if (s->srp_ctx.A != NULL) {
2839                 /* send off the data */
2840                 n = BN_num_bytes(s->srp_ctx.A);
2841                 s2n(n, p);
2842                 BN_bn2bin(s->srp_ctx.A, p);
2843                 n += 2;
2844             } else {
2845                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2846                        ERR_R_INTERNAL_ERROR);
2847                 goto err;
2848             }
2849             OPENSSL_free(s->session->srp_username);
2850             s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2851             if (s->session->srp_username == NULL) {
2852                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2853                        ERR_R_MALLOC_FAILURE);
2854                 goto err;
2855             }
2856         }
2857 #endif
2858         else {
2859             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2860             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2861             goto err;
2862         }
2863
2864 #ifndef OPENSSL_NO_PSK
2865         n += pskhdrlen;
2866 #endif
2867
2868         if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2869             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2870             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2871             goto err;
2872         }
2873
2874         s->state = SSL3_ST_CW_KEY_EXCH_B;
2875     }
2876
2877     /* SSL3_ST_CW_KEY_EXCH_B */
2878     n = ssl_do_write(s);
2879 #ifndef OPENSSL_NO_SRP
2880     /* Check for SRP */
2881     if (alg_k & SSL_kSRP) {
2882         /*
2883          * If everything written generate master key: no need to save PMS as
2884          * srp_generate_client_master_secret generates it internally.
2885          */
2886         if (n > 0) {
2887             if (!srp_generate_client_master_secret(s)) {
2888                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2889                        ERR_R_INTERNAL_ERROR);
2890                 goto err;
2891             }
2892         }
2893     } else
2894 #endif
2895         /* If we haven't written everything save PMS */
2896     if (n <= 0) {
2897         s->s3->tmp.pms = pms;
2898         s->s3->tmp.pmslen = pmslen;
2899     } else {
2900         /* If we don't have a PMS restore */
2901         if (pms == NULL) {
2902             pms = s->s3->tmp.pms;
2903             pmslen = s->s3->tmp.pmslen;
2904         }
2905         if (pms == NULL && !(alg_k & SSL_kPSK)) {
2906             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2907             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2908             goto err;
2909         }
2910         if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2911             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2912             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2913             goto err;
2914         }
2915     }
2916     return n;
2917  memerr:
2918     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2919     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2920  err:
2921     OPENSSL_clear_free(pms, pmslen);
2922     s->s3->tmp.pms = NULL;
2923 #ifndef OPENSSL_NO_EC
2924     BN_CTX_free(bn_ctx);
2925     OPENSSL_free(encodedPoint);
2926     EC_KEY_free(clnt_ecdh);
2927     EVP_PKEY_free(srvr_pub_pkey);
2928 #endif
2929 #ifndef OPENSSL_NO_PSK
2930     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2931     s->s3->tmp.psk = NULL;
2932 #endif
2933     s->state = SSL_ST_ERR;
2934     return (-1);
2935 }
2936
2937 int ssl3_send_client_verify(SSL *s)
2938 {
2939     unsigned char *p;
2940     unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2941     EVP_PKEY *pkey;
2942     EVP_PKEY_CTX *pctx = NULL;
2943     EVP_MD_CTX mctx;
2944     unsigned u = 0;
2945     unsigned long n;
2946     int j;
2947
2948     EVP_MD_CTX_init(&mctx);
2949
2950     if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
2951         p = ssl_handshake_start(s);
2952         pkey = s->cert->key->privatekey;
2953 /* Create context from key and test if sha1 is allowed as digest */
2954         pctx = EVP_PKEY_CTX_new(pkey, NULL);
2955         EVP_PKEY_sign_init(pctx);
2956         if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
2957             if (!SSL_USE_SIGALGS(s))
2958                 s->method->ssl3_enc->cert_verify_mac(s,
2959                                                      NID_sha1,
2960                                                      &(data
2961                                                        [MD5_DIGEST_LENGTH]));
2962         } else {
2963             ERR_clear_error();
2964         }
2965         /*
2966          * For TLS v1.2 send signature algorithm and signature using agreed
2967          * digest and cached handshake records.
2968          */
2969         if (SSL_USE_SIGALGS(s)) {
2970             long hdatalen = 0;
2971             void *hdata;
2972             const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2973             hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2974             if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
2975                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2976                 goto err;
2977             }
2978             p += 2;
2979 #ifdef SSL_DEBUG
2980             fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
2981                     EVP_MD_name(md));
2982 #endif
2983             if (!EVP_SignInit_ex(&mctx, md, NULL)
2984                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
2985                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2986                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
2987                 goto err;
2988             }
2989             s2n(u, p);
2990             n = u + 4;
2991             /* Digest cached records and discard handshake buffer */
2992             if (!ssl3_digest_cached_records(s, 0))
2993                 goto err;
2994         } else
2995 #ifndef OPENSSL_NO_RSA
2996         if (pkey->type == EVP_PKEY_RSA) {
2997             s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
2998             if (RSA_sign(NID_md5_sha1, data,
2999                          MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
3000                          &(p[2]), &u, pkey->pkey.rsa) <= 0) {
3001                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
3002                 goto err;
3003             }
3004             s2n(u, p);
3005             n = u + 2;
3006         } else
3007 #endif
3008 #ifndef OPENSSL_NO_DSA
3009         if (pkey->type == EVP_PKEY_DSA) {
3010             if (!DSA_sign(pkey->save_type,
3011                           &(data[MD5_DIGEST_LENGTH]),
3012                           SHA_DIGEST_LENGTH, &(p[2]),
3013                           (unsigned int *)&j, pkey->pkey.dsa)) {
3014                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
3015                 goto err;
3016             }
3017             s2n(j, p);
3018             n = j + 2;
3019         } else
3020 #endif
3021 #ifndef OPENSSL_NO_EC
3022         if (pkey->type == EVP_PKEY_EC) {
3023             if (!ECDSA_sign(pkey->save_type,
3024                             &(data[MD5_DIGEST_LENGTH]),
3025                             SHA_DIGEST_LENGTH, &(p[2]),
3026                             (unsigned int *)&j, pkey->pkey.ec)) {
3027                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
3028                 goto err;
3029             }
3030             s2n(j, p);
3031             n = j + 2;
3032         } else
3033 #endif
3034         if (pkey->type == NID_id_GostR3410_94
3035                 || pkey->type == NID_id_GostR3410_2001) {
3036             unsigned char signbuf[64];
3037             int i;
3038             size_t sigsize = 64;
3039             s->method->ssl3_enc->cert_verify_mac(s,
3040                                                  NID_id_GostR3411_94, data);
3041             if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3042                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3043                 goto err;
3044             }
3045             for (i = 63, j = 0; i >= 0; j++, i--) {
3046                 p[2 + j] = signbuf[i];
3047             }
3048             s2n(j, p);
3049             n = j + 2;
3050         } else {
3051             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3052             goto err;
3053         }
3054         if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
3055             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3056             goto err;
3057         }
3058         s->state = SSL3_ST_CW_CERT_VRFY_B;
3059     }
3060     EVP_MD_CTX_cleanup(&mctx);
3061     EVP_PKEY_CTX_free(pctx);
3062     return ssl_do_write(s);
3063  err:
3064     EVP_MD_CTX_cleanup(&mctx);
3065     EVP_PKEY_CTX_free(pctx);
3066     s->state = SSL_ST_ERR;
3067     return (-1);
3068 }
3069
3070 /*
3071  * Check a certificate can be used for client authentication. Currently check
3072  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
3073  * certificates can be used and optionally checks suitability for Suite B.
3074  */
3075 static int ssl3_check_client_certificate(SSL *s)
3076 {
3077     unsigned long alg_k;
3078     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
3079         return 0;
3080     /* If no suitable signature algorithm can't use certificate */
3081     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
3082         return 0;
3083     /*
3084      * If strict mode check suitability of chain before using it. This also
3085      * adjusts suite B digest if necessary.
3086      */
3087     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3088         !tls1_check_chain(s, NULL, NULL, NULL, -2))
3089         return 0;
3090     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3091     /* See if we can use client certificate for fixed DH */
3092     if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3093         int i = s->session->peer_type;
3094         EVP_PKEY *clkey = NULL, *spkey = NULL;
3095         clkey = s->cert->key->privatekey;
3096         /* If client key not DH assume it can be used */
3097         if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
3098             return 1;
3099         if (i >= 0)
3100             spkey = X509_get_pubkey(s->session->peer);
3101         if (spkey) {
3102             /* Compare server and client parameters */
3103             i = EVP_PKEY_cmp_parameters(clkey, spkey);
3104             EVP_PKEY_free(spkey);
3105             if (i != 1)
3106                 return 0;
3107         }
3108         s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3109     }
3110     return 1;
3111 }
3112
3113 int ssl3_send_client_certificate(SSL *s)
3114 {
3115     X509 *x509 = NULL;
3116     EVP_PKEY *pkey = NULL;
3117     int i;
3118
3119     if (s->state == SSL3_ST_CW_CERT_A) {
3120         /* Let cert callback update client certificates if required */
3121         if (s->cert->cert_cb) {
3122             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
3123             if (i < 0) {
3124                 s->rwstate = SSL_X509_LOOKUP;
3125                 return -1;
3126             }
3127             if (i == 0) {
3128                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3129                 s->state = SSL_ST_ERR;
3130                 return 0;
3131             }
3132             s->rwstate = SSL_NOTHING;
3133         }
3134         if (ssl3_check_client_certificate(s))
3135             s->state = SSL3_ST_CW_CERT_C;
3136         else
3137             s->state = SSL3_ST_CW_CERT_B;
3138     }
3139
3140     /* We need to get a client cert */
3141     if (s->state == SSL3_ST_CW_CERT_B) {
3142         /*
3143          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3144          * return(-1); We then get retied later
3145          */
3146         i = 0;
3147         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3148         if (i < 0) {
3149             s->rwstate = SSL_X509_LOOKUP;
3150             return (-1);
3151         }
3152         s->rwstate = SSL_NOTHING;
3153         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3154             s->state = SSL3_ST_CW_CERT_B;
3155             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3156                 i = 0;
3157         } else if (i == 1) {
3158             i = 0;
3159             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
3160                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3161         }
3162
3163         X509_free(x509);
3164         EVP_PKEY_free(pkey);
3165         if (i && !ssl3_check_client_certificate(s))
3166             i = 0;
3167         if (i == 0) {
3168             if (s->version == SSL3_VERSION) {
3169                 s->s3->tmp.cert_req = 0;
3170                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3171                 return (1);
3172             } else {
3173                 s->s3->tmp.cert_req = 2;
3174                 if (!ssl3_digest_cached_records(s, 0)) {
3175                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3176                     s->state = SSL_ST_ERR;
3177                     return 0;
3178                 }
3179             }
3180         }
3181
3182         /* Ok, we have a cert */
3183         s->state = SSL3_ST_CW_CERT_C;
3184     }
3185
3186     if (s->state == SSL3_ST_CW_CERT_C) {
3187         s->state = SSL3_ST_CW_CERT_D;
3188         if (!ssl3_output_cert_chain(s,
3189                                     (s->s3->tmp.cert_req ==
3190                                      2) ? NULL : s->cert->key)) {
3191             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3192             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3193             s->state = SSL_ST_ERR;
3194             return 0;
3195         }
3196     }
3197     /* SSL3_ST_CW_CERT_D */
3198     return ssl_do_write(s);
3199 }
3200
3201 #define has_bits(i,m)   (((i)&(m)) == (m))
3202
3203 int ssl3_check_cert_and_algorithm(SSL *s)
3204 {
3205     int i, idx;
3206     long alg_k, alg_a;
3207     EVP_PKEY *pkey = NULL;
3208     int pkey_bits;
3209 #ifndef OPENSSL_NO_RSA
3210     RSA *rsa;
3211 #endif
3212 #ifndef OPENSSL_NO_DH
3213     DH *dh;
3214 #endif
3215     int al = SSL_AD_HANDSHAKE_FAILURE;
3216
3217     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3218     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3219
3220     /* we don't have a certificate */
3221     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
3222         return (1);
3223 #ifndef OPENSSL_NO_RSA
3224     rsa = s->s3->peer_rsa_tmp;
3225 #endif
3226 #ifndef OPENSSL_NO_DH
3227     dh = s->s3->peer_dh_tmp;
3228 #endif
3229
3230     /* This is the passed certificate */
3231
3232     idx = s->session->peer_type;
3233 #ifndef OPENSSL_NO_EC
3234     if (idx == SSL_PKEY_ECC) {
3235         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
3236             /* check failed */
3237             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3238             goto f_err;
3239         } else {
3240             return 1;
3241         }
3242     } else if (alg_a & SSL_aECDSA) {
3243         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3244                SSL_R_MISSING_ECDSA_SIGNING_CERT);
3245         goto f_err;
3246     } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
3247         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
3248         goto f_err;
3249     }
3250 #endif
3251     pkey = X509_get_pubkey(s->session->peer);
3252     pkey_bits = EVP_PKEY_bits(pkey);
3253     i = X509_certificate_type(s->session->peer, pkey);
3254     EVP_PKEY_free(pkey);
3255
3256     /* Check that we have a certificate if we require one */
3257     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3258         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3259                SSL_R_MISSING_RSA_SIGNING_CERT);
3260         goto f_err;
3261     }
3262 #ifndef OPENSSL_NO_DSA
3263     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3264         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3265                SSL_R_MISSING_DSA_SIGNING_CERT);
3266         goto f_err;
3267     }
3268 #endif
3269 #ifndef OPENSSL_NO_RSA
3270     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3271         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3272             !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3273             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3274                    SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3275             goto f_err;
3276         } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
3277             if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3278                 if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3279                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3280                            SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3281                     goto f_err;
3282                 }
3283                 if (rsa != NULL) {
3284                     /* server key exchange is not allowed. */
3285                     al = SSL_AD_INTERNAL_ERROR;
3286                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3287                     goto f_err;
3288                 }
3289             }
3290         }
3291     }
3292 #endif
3293 #ifndef OPENSSL_NO_DH
3294     if ((alg_k & SSL_kDHE) && (dh == NULL)) {
3295         al = SSL_AD_INTERNAL_ERROR;
3296         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3297         goto f_err;
3298     } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
3299                !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3300         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3301                SSL_R_MISSING_DH_RSA_CERT);
3302         goto f_err;
3303     }
3304 # ifndef OPENSSL_NO_DSA
3305     else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
3306              !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3307         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3308                SSL_R_MISSING_DH_DSA_CERT);
3309         goto f_err;
3310     }
3311 # endif
3312 #endif
3313
3314     if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3315         pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3316 #ifndef OPENSSL_NO_RSA
3317         if (alg_k & SSL_kRSA) {
3318             if (rsa == NULL) {
3319                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3320                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3321                 goto f_err;
3322             } else if (RSA_bits(rsa) >
3323                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3324                 /* We have a temporary RSA key but it's too large. */
3325                 al = SSL_AD_EXPORT_RESTRICTION;
3326                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3327                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3328                 goto f_err;
3329             }
3330         } else
3331 #endif
3332 #ifndef OPENSSL_NO_DH
3333         if (alg_k & SSL_kDHE) {
3334             if (DH_bits(dh) >
3335                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3336                 /* We have a temporary DH key but it's too large. */
3337                 al = SSL_AD_EXPORT_RESTRICTION;
3338                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3339                        SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3340                 goto f_err;
3341             }
3342         } else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3343             /* The cert should have had an export DH key. */
3344             al = SSL_AD_EXPORT_RESTRICTION;
3345             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3346                    SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3347                 goto f_err;
3348         } else
3349 #endif
3350         {
3351             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3352                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3353             goto f_err;
3354         }
3355     }
3356     return (1);
3357  f_err:
3358     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3359     return (0);
3360 }
3361
3362 /*
3363  * Normally, we can tell if the server is resuming the session from
3364  * the session ID. EAP-FAST (RFC 4851), however, relies on the next server
3365  * message after the ServerHello to determine if the server is resuming.
3366  * Therefore, we allow EAP-FAST to peek ahead.
3367  * ssl3_check_finished returns 1 if we are resuming from an external
3368  * pre-shared secret, we have a "ticket" and the next server handshake message
3369  * is Finished; and 0 otherwise. It returns -1 upon an error.
3370  */
3371 static int ssl3_check_finished(SSL *s)
3372 {
3373     int ok = 0;
3374
3375     if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
3376         !s->session->tlsext_tick)
3377         return 0;
3378
3379     /* Need to permit this temporarily, in case the next message is Finished. */
3380     s->s3->flags |= SSL3_FLAGS_CCS_OK;
3381     /*
3382      * This function is called when we might get a Certificate message instead,
3383      * so permit appropriate message length.
3384      * We ignore the return value as we're only interested in the message type
3385      * and not its length.
3386      */
3387     s->method->ssl_get_message(s,
3388                                SSL3_ST_CR_CERT_A,
3389                                SSL3_ST_CR_CERT_B,
3390                                -1, s->max_cert_list, &ok);
3391     s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
3392
3393     if (!ok)
3394         return -1;
3395
3396     s->s3->tmp.reuse_message = 1;
3397
3398     if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
3399         return 1;
3400
3401     /* If we're not done, then the CCS arrived early and we should bail. */
3402     if (s->s3->change_cipher_spec) {
3403         SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
3404         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
3405         return -1;
3406     }
3407
3408     return 0;
3409 }
3410
3411 #ifndef OPENSSL_NO_NEXTPROTONEG
3412 int ssl3_send_next_proto(SSL *s)
3413 {
3414     unsigned int len, padding_len;
3415     unsigned char *d;
3416
3417     if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
3418         len = s->next_proto_negotiated_len;
3419         padding_len = 32 - ((len + 2) % 32);
3420         d = (unsigned char *)s->init_buf->data;
3421         d[4] = len;
3422         memcpy(d + 5, s->next_proto_negotiated, len);
3423         d[5 + len] = padding_len;
3424         memset(d + 6 + len, 0, padding_len);
3425         *(d++) = SSL3_MT_NEXT_PROTO;
3426         l2n3(2 + len + padding_len, d);
3427         s->state = SSL3_ST_CW_NEXT_PROTO_B;
3428         s->init_num = 4 + 2 + len + padding_len;
3429         s->init_off = 0;
3430     }
3431
3432     return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3433 }
3434 #endif
3435
3436 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3437 {
3438     int i = 0;
3439 #ifndef OPENSSL_NO_ENGINE
3440     if (s->ctx->client_cert_engine) {
3441         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3442                                         SSL_get_client_CA_list(s),
3443                                         px509, ppkey, NULL, NULL, NULL);
3444         if (i != 0)
3445             return i;
3446     }
3447 #endif
3448     if (s->ctx->client_cert_cb)
3449         i = s->ctx->client_cert_cb(s, px509, ppkey);
3450     return i;
3451 }
3452
3453 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
3454                              unsigned char *p,
3455                              int (*put_cb) (const SSL_CIPHER *,
3456                                             unsigned char *))
3457 {
3458     int i, j = 0;
3459     SSL_CIPHER *c;
3460     unsigned char *q;
3461     int empty_reneg_info_scsv = !s->renegotiate;
3462     /* Set disabled masks for this session */
3463     ssl_set_client_disabled(s);
3464
3465     if (sk == NULL)
3466         return (0);
3467     q = p;
3468     if (put_cb == NULL)
3469         put_cb = s->method->put_cipher_by_char;
3470
3471     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3472         c = sk_SSL_CIPHER_value(sk, i);
3473         /* Skip disabled ciphers */
3474         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3475             continue;
3476 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3477         if (c->id == SSL3_CK_SCSV) {
3478             if (!empty_reneg_info_scsv)
3479                 continue;
3480             else
3481                 empty_reneg_info_scsv = 0;
3482         }
3483 #endif
3484         j = put_cb(c, p);
3485         p += j;
3486     }
3487     /*
3488      * If p == q, no ciphers; caller indicates an error. Otherwise, add
3489      * applicable SCSVs.
3490      */
3491     if (p != q) {
3492         if (empty_reneg_info_scsv) {
3493             static SSL_CIPHER scsv = {
3494                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3495             };
3496             j = put_cb(&scsv, p);
3497             p += j;
3498 #ifdef OPENSSL_RI_DEBUG
3499             fprintf(stderr,
3500                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
3501 #endif
3502         }
3503         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3504             static SSL_CIPHER scsv = {
3505                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3506             };
3507             j = put_cb(&scsv, p);
3508             p += j;
3509         }
3510     }
3511
3512     return (p - q);
3513 }