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