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