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