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