01a0a8c43cd4fd62078d7ec0856d0184ea8133ed
[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     unsigned char *p, *d;
934     int i, al = SSL_AD_INTERNAL_ERROR, ok;
935     unsigned int j;
936     long n;
937 #ifndef OPENSSL_NO_COMP
938     SSL_COMP *comp;
939 #endif
940     /*
941      * Hello verify request and/or server hello version may not match so set
942      * first packet if we're negotiating version.
943      */
944     s->first_packet = 1;
945
946     n = s->method->ssl_get_message(s,
947                                    SSL3_ST_CR_SRVR_HELLO_A,
948                                    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, &ok);
949
950     if (!ok)
951         return ((int)n);
952
953     s->first_packet = 0;
954     if (SSL_IS_DTLS(s)) {
955         if (s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
956             if (s->d1->send_cookie == 0) {
957                 s->s3->tmp.reuse_message = 1;
958                 return 1;
959             } else {            /* already sent a cookie */
960
961                 al = SSL_AD_UNEXPECTED_MESSAGE;
962                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
963                 goto f_err;
964             }
965         }
966     }
967
968     if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) {
969         al = SSL_AD_UNEXPECTED_MESSAGE;
970         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
971         goto f_err;
972     }
973
974     d = p = (unsigned char *)s->init_msg;
975
976     if (s->method->version == TLS_ANY_VERSION) {
977         int sversion = (p[0] << 8) | p[1];
978
979 #if TLS_MAX_VERSION != TLS1_2_VERSION
980 #error Code needs updating for new TLS version
981 #endif
982 #ifndef OPENSSL_NO_SSL3
983         if ((sversion == SSL3_VERSION) && !(s->options & SSL_OP_NO_SSLv3)) {
984             if (FIPS_mode()) {
985                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
986                        SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
987                 al = SSL_AD_PROTOCOL_VERSION;
988                 goto f_err;
989             }
990             s->method = SSLv3_client_method();
991         } else
992 #endif
993         if ((sversion == TLS1_VERSION) && !(s->options & SSL_OP_NO_TLSv1)) {
994             s->method = TLSv1_client_method();
995         } else if ((sversion == TLS1_1_VERSION) &&
996                    !(s->options & SSL_OP_NO_TLSv1_1)) {
997             s->method = TLSv1_1_client_method();
998         } else if ((sversion == TLS1_2_VERSION) &&
999                    !(s->options & SSL_OP_NO_TLSv1_2)) {
1000             s->method = TLSv1_2_client_method();
1001         } else {
1002             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_UNSUPPORTED_PROTOCOL);
1003             al = SSL_AD_PROTOCOL_VERSION;
1004             goto f_err;
1005         }
1006         s->session->ssl_version = s->version = s->method->version;
1007
1008         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
1009             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_VERSION_TOO_LOW);
1010             al = SSL_AD_PROTOCOL_VERSION;
1011             goto f_err;
1012         }
1013     } else if (s->method->version == DTLS_ANY_VERSION) {
1014         /* Work out correct protocol version to use */
1015         int hversion = (p[0] << 8) | p[1];
1016         int options = s->options;
1017         if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2))
1018             s->method = DTLSv1_2_client_method();
1019         else if (tls1_suiteb(s)) {
1020             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1021                    SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1022             s->version = hversion;
1023             al = SSL_AD_PROTOCOL_VERSION;
1024             goto f_err;
1025         } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1))
1026             s->method = DTLSv1_client_method();
1027         else {
1028             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1029             s->version = hversion;
1030             al = SSL_AD_PROTOCOL_VERSION;
1031             goto f_err;
1032         }
1033         s->session->ssl_version = s->version = s->method->version;
1034     } else if ((p[0] != (s->version >> 8)) || (p[1] != (s->version & 0xff))) {
1035         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
1036         s->version = (s->version & 0xff00) | p[1];
1037         al = SSL_AD_PROTOCOL_VERSION;
1038         goto f_err;
1039     }
1040     p += 2;
1041
1042     /* load the server hello data */
1043     /* load the server random */
1044     memcpy(s->s3->server_random, p, SSL3_RANDOM_SIZE);
1045     p += SSL3_RANDOM_SIZE;
1046
1047     s->hit = 0;
1048
1049     /* get the session-id */
1050     j = *(p++);
1051
1052     if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) {
1053         al = SSL_AD_ILLEGAL_PARAMETER;
1054         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1055         goto f_err;
1056     }
1057
1058     /*
1059      * Check if we can resume the session based on external pre-shared secret.
1060      * EAP-FAST (RFC 4851) supports two types of session resumption.
1061      * Resumption based on server-side state works with session IDs.
1062      * Resumption based on pre-shared Protected Access Credentials (PACs)
1063      * works by overriding the SessionTicket extension at the application
1064      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1065      * servers would honour the session ID.) Therefore, the session ID alone
1066      * is not a reliable indicator of session resumption, so we first check if
1067      * we can resume, and later peek at the next handshake message to see if the
1068      * server wants to resume.
1069      */
1070     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
1071         s->session->tlsext_tick) {
1072         SSL_CIPHER *pref_cipher = NULL;
1073         s->session->master_key_length = sizeof(s->session->master_key);
1074         if (s->tls_session_secret_cb(s, s->session->master_key,
1075                                      &s->session->master_key_length,
1076                                      NULL, &pref_cipher,
1077                                      s->tls_session_secret_cb_arg)) {
1078             s->session->cipher = pref_cipher ?
1079                 pref_cipher : ssl_get_cipher_by_char(s, p + j);
1080         } else {
1081             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1082             al = SSL_AD_INTERNAL_ERROR;
1083             goto f_err;
1084         }
1085     }
1086
1087     if (j != 0 && j == s->session->session_id_length
1088         && memcmp(p, s->session->session_id, j) == 0) {
1089         if (s->sid_ctx_length != s->session->sid_ctx_length
1090             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1091             /* actually a client application bug */
1092             al = SSL_AD_ILLEGAL_PARAMETER;
1093             SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1094                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1095             goto f_err;
1096         }
1097         s->hit = 1;
1098     } else {
1099         /*
1100          * If we were trying for session-id reuse but the server
1101          * didn't echo the ID, make a new SSL_SESSION.
1102          * In the case of EAP-FAST and PAC, we do not send a session ID,
1103          * so the PAC-based session secret is always preserved. It'll be
1104          * overwritten if the server refuses resumption.
1105          */
1106         if (s->session->session_id_length > 0) {
1107             if (!ssl_get_new_session(s, 0)) {
1108                 goto f_err;
1109             }
1110         }
1111         s->session->session_id_length = j;
1112         memcpy(s->session->session_id, p, j); /* j could be 0 */
1113     }
1114     p += j;
1115     c = ssl_get_cipher_by_char(s, p);
1116     if (c == NULL) {
1117         /* unknown cipher */
1118         al = SSL_AD_ILLEGAL_PARAMETER;
1119         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1120         goto f_err;
1121     }
1122     /* Set version disabled mask now we know version */
1123     if (!SSL_USE_TLS1_2_CIPHERS(s))
1124         s->s3->tmp.mask_ssl = SSL_TLSV1_2;
1125     else
1126         s->s3->tmp.mask_ssl = 0;
1127     /*
1128      * If it is a disabled cipher we didn't send it in client hello, so
1129      * return an error.
1130      */
1131     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1132         al = SSL_AD_ILLEGAL_PARAMETER;
1133         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1134         goto f_err;
1135     }
1136     p += ssl_put_cipher_by_char(s, NULL, NULL);
1137
1138     sk = ssl_get_ciphers_by_id(s);
1139     i = sk_SSL_CIPHER_find(sk, c);
1140     if (i < 0) {
1141         /* we did not say we would use this cipher */
1142         al = SSL_AD_ILLEGAL_PARAMETER;
1143         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1144         goto f_err;
1145     }
1146
1147     /*
1148      * Depending on the session caching (internal/external), the cipher
1149      * and/or cipher_id values may not be set. Make sure that cipher_id is
1150      * set and use it for comparison.
1151      */
1152     if (s->session->cipher)
1153         s->session->cipher_id = s->session->cipher->id;
1154     if (s->hit && (s->session->cipher_id != c->id)) {
1155         al = SSL_AD_ILLEGAL_PARAMETER;
1156         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1157                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1158         goto f_err;
1159     }
1160     s->s3->tmp.new_cipher = c;
1161     /*
1162      * Don't digest cached records if no sigalgs: we may need them for client
1163      * authentication.
1164      */
1165     if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s, 0))
1166         goto f_err;
1167     /* lets get the compression algorithm */
1168     /* COMPRESSION */
1169 #ifdef OPENSSL_NO_COMP
1170     if (*(p++) != 0) {
1171         al = SSL_AD_ILLEGAL_PARAMETER;
1172         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1173                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1174         goto f_err;
1175     }
1176     /*
1177      * If compression is disabled we'd better not try to resume a session
1178      * using compression.
1179      */
1180     if (s->session->compress_meth != 0) {
1181         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1182         goto f_err;
1183     }
1184 #else
1185     j = *(p++);
1186     if (s->hit && j != s->session->compress_meth) {
1187         al = SSL_AD_ILLEGAL_PARAMETER;
1188         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1189                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1190         goto f_err;
1191     }
1192     if (j == 0)
1193         comp = NULL;
1194     else if (!ssl_allow_compression(s)) {
1195         al = SSL_AD_ILLEGAL_PARAMETER;
1196         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1197         goto f_err;
1198     } else
1199         comp = ssl3_comp_find(s->ctx->comp_methods, j);
1200
1201     if ((j != 0) && (comp == NULL)) {
1202         al = SSL_AD_ILLEGAL_PARAMETER;
1203         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1204                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1205         goto f_err;
1206     } else {
1207         s->s3->tmp.new_compression = comp;
1208     }
1209 #endif
1210
1211     /* TLS extensions */
1212     if (!ssl_parse_serverhello_tlsext(s, &p, d, n)) {
1213         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1214         goto err;
1215     }
1216
1217     if (p != (d + n)) {
1218         /* wrong packet length */
1219         al = SSL_AD_DECODE_ERROR;
1220         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1221         goto f_err;
1222     }
1223
1224     return (1);
1225  f_err:
1226     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1227  err:
1228     s->state = SSL_ST_ERR;
1229     return (-1);
1230 }
1231
1232 int ssl3_get_server_certificate(SSL *s)
1233 {
1234     int al, i, ok, ret = -1, exp_idx;
1235     unsigned long n, nc, llen, l;
1236     X509 *x = NULL;
1237     const unsigned char *q, *p;
1238     unsigned char *d;
1239     STACK_OF(X509) *sk = NULL;
1240     EVP_PKEY *pkey = NULL;
1241
1242     n = s->method->ssl_get_message(s,
1243                                    SSL3_ST_CR_CERT_A,
1244                                    SSL3_ST_CR_CERT_B,
1245                                    -1, s->max_cert_list, &ok);
1246
1247     if (!ok)
1248         return ((int)n);
1249
1250     if (s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1251         s->s3->tmp.reuse_message = 1;
1252         return (1);
1253     }
1254
1255     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
1256         al = SSL_AD_UNEXPECTED_MESSAGE;
1257         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_BAD_MESSAGE_TYPE);
1258         goto f_err;
1259     }
1260     p = d = (unsigned char *)s->init_msg;
1261
1262     if ((sk = sk_X509_new_null()) == NULL) {
1263         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1264         goto err;
1265     }
1266
1267     n2l3(p, llen);
1268     if (llen + 3 != n) {
1269         al = SSL_AD_DECODE_ERROR;
1270         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1271         goto f_err;
1272     }
1273     for (nc = 0; nc < llen;) {
1274         n2l3(p, l);
1275         if ((l + nc + 3) > llen) {
1276             al = SSL_AD_DECODE_ERROR;
1277             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1278                    SSL_R_CERT_LENGTH_MISMATCH);
1279             goto f_err;
1280         }
1281
1282         q = p;
1283         x = d2i_X509(NULL, &q, l);
1284         if (x == NULL) {
1285             al = SSL_AD_BAD_CERTIFICATE;
1286             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1287             goto f_err;
1288         }
1289         if (q != (p + l)) {
1290             al = SSL_AD_DECODE_ERROR;
1291             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1292                    SSL_R_CERT_LENGTH_MISMATCH);
1293             goto f_err;
1294         }
1295         if (!sk_X509_push(sk, x)) {
1296             SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1297             goto err;
1298         }
1299         x = NULL;
1300         nc += l + 3;
1301         p = q;
1302     }
1303
1304     i = ssl_verify_cert_chain(s, sk);
1305     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1306         al = ssl_verify_alarm_type(s->verify_result);
1307         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1308                SSL_R_CERTIFICATE_VERIFY_FAILED);
1309         goto f_err;
1310     }
1311     ERR_clear_error();          /* but we keep s->verify_result */
1312     if (i > 1) {
1313         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, i);
1314         al = SSL_AD_HANDSHAKE_FAILURE;
1315         goto f_err;
1316     }
1317
1318     s->session->peer_chain = sk;
1319     /*
1320      * Inconsistency alert: cert_chain does include the peer's certificate,
1321      * which we don't include in s3_srvr.c
1322      */
1323     x = sk_X509_value(sk, 0);
1324     sk = NULL;
1325     /*
1326      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1327      */
1328
1329     pkey = X509_get_pubkey(x);
1330
1331     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1332         x = NULL;
1333         al = SSL3_AL_FATAL;
1334         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1335                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1336         goto f_err;
1337     }
1338
1339     i = ssl_cert_type(x, pkey);
1340     if (i < 0) {
1341         x = NULL;
1342         al = SSL3_AL_FATAL;
1343         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1344                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1345         goto f_err;
1346     }
1347
1348     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1349     if (exp_idx >= 0 && i != exp_idx) {
1350         x = NULL;
1351         al = SSL_AD_ILLEGAL_PARAMETER;
1352         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1353                SSL_R_WRONG_CERTIFICATE_TYPE);
1354         goto f_err;
1355     }
1356     s->session->peer_type = i;
1357
1358     X509_free(s->session->peer);
1359     CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1360     s->session->peer = x;
1361     s->session->verify_result = s->verify_result;
1362
1363     x = NULL;
1364     ret = 1;
1365     goto done;
1366
1367  f_err:
1368     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1369  err:
1370     s->state = SSL_ST_ERR;
1371  done:
1372     EVP_PKEY_free(pkey);
1373     X509_free(x);
1374     sk_X509_pop_free(sk, X509_free);
1375     return (ret);
1376 }
1377
1378 int ssl3_get_key_exchange(SSL *s)
1379 {
1380 #ifndef OPENSSL_NO_RSA
1381     unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
1382 #endif
1383     EVP_MD_CTX md_ctx;
1384     unsigned char *param, *p;
1385     int al, j, ok;
1386     long i, param_len, n, alg_k, alg_a;
1387     EVP_PKEY *pkey = NULL;
1388     const EVP_MD *md = NULL;
1389 #ifndef OPENSSL_NO_RSA
1390     RSA *rsa = NULL;
1391 #endif
1392 #ifndef OPENSSL_NO_DH
1393     DH *dh = NULL;
1394 #endif
1395 #ifndef OPENSSL_NO_EC
1396     EC_KEY *ecdh = NULL;
1397     BN_CTX *bn_ctx = NULL;
1398     EC_POINT *srvr_ecpoint = NULL;
1399     int curve_nid = 0;
1400     int encoded_pt_len = 0;
1401 #endif
1402
1403     EVP_MD_CTX_init(&md_ctx);
1404
1405     /*
1406      * use same message size as in ssl3_get_certificate_request() as
1407      * ServerKeyExchange message may be skipped
1408      */
1409     n = s->method->ssl_get_message(s,
1410                                    SSL3_ST_CR_KEY_EXCH_A,
1411                                    SSL3_ST_CR_KEY_EXCH_B,
1412                                    -1, s->max_cert_list, &ok);
1413     if (!ok)
1414         return ((int)n);
1415
1416     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1417
1418     if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1419         /*
1420          * Can't skip server key exchange if this is an ephemeral
1421          * ciphersuite.
1422          */
1423         if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK)) {
1424             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1425             al = SSL_AD_UNEXPECTED_MESSAGE;
1426             goto f_err;
1427         }
1428
1429         s->s3->tmp.reuse_message = 1;
1430         return (1);
1431     }
1432
1433     param = p = (unsigned char *)s->init_msg;
1434
1435 #ifndef OPENSSL_NO_RSA
1436     RSA_free(s->s3->peer_rsa_tmp);
1437     s->s3->peer_rsa_tmp = NULL;
1438 #endif
1439 #ifndef OPENSSL_NO_DH
1440     DH_free(s->s3->peer_dh_tmp);
1441     s->s3->peer_dh_tmp = NULL;
1442 #endif
1443 #ifndef OPENSSL_NO_EC
1444     EC_KEY_free(s->s3->peer_ecdh_tmp);
1445     s->s3->peer_ecdh_tmp = NULL;
1446 #endif
1447
1448     /* Total length of the parameters including the length prefix */
1449     param_len = 0;
1450
1451     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1452
1453     al = SSL_AD_DECODE_ERROR;
1454
1455 #ifndef OPENSSL_NO_PSK
1456     /* PSK ciphersuites are preceded by an identity hint */
1457     if (alg_k & SSL_PSK) {
1458
1459         param_len = 2;
1460         if (param_len > n) {
1461             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1462             goto f_err;
1463         }
1464         n2s(p, i);
1465
1466         /*
1467          * Store PSK identity hint for later use, hint is used in
1468          * ssl3_send_client_key_exchange.  Assume that the maximum length of
1469          * a PSK identity hint can be as long as the maximum length of a PSK
1470          * identity.
1471          */
1472         if (i > PSK_MAX_IDENTITY_LEN) {
1473             al = SSL_AD_HANDSHAKE_FAILURE;
1474             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1475             goto f_err;
1476         }
1477         if (i > n - param_len) {
1478             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1479                    SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1480             goto f_err;
1481         }
1482         param_len += i;
1483
1484         OPENSSL_free(s->session->psk_identity_hint);
1485         if (i != 0) {
1486             s->session->psk_identity_hint = BUF_strndup((char *)p, i);
1487             if (s->session->psk_identity_hint == NULL) {
1488                 al = SSL_AD_HANDSHAKE_FAILURE;
1489                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1490                 goto f_err;
1491             }
1492         } else {
1493             s->session->psk_identity_hint = NULL;
1494         }
1495
1496         p += i;
1497         n -= param_len;
1498     }
1499
1500     /* Nothing else to do for plain PSK or RSAPSK */
1501     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1502     } else
1503 #endif                          /* !OPENSSL_NO_PSK */
1504 #ifndef OPENSSL_NO_SRP
1505     if (alg_k & SSL_kSRP) {
1506         param_len = 2;
1507         if (param_len > n) {
1508             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1509             goto f_err;
1510         }
1511         n2s(p, i);
1512
1513         if (i > n - param_len) {
1514             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_N_LENGTH);
1515             goto f_err;
1516         }
1517         param_len += i;
1518
1519         if ((s->srp_ctx.N = BN_bin2bn(p, i, NULL)) == NULL) {
1520             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1521             goto err;
1522         }
1523         p += i;
1524
1525         if (2 > n - param_len) {
1526             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1527             goto f_err;
1528         }
1529         param_len += 2;
1530
1531         n2s(p, i);
1532
1533         if (i > n - param_len) {
1534             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_G_LENGTH);
1535             goto f_err;
1536         }
1537         param_len += i;
1538
1539         if ((s->srp_ctx.g = BN_bin2bn(p, i, NULL)) == NULL) {
1540             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1541             goto err;
1542         }
1543         p += i;
1544
1545         if (1 > n - param_len) {
1546             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1547             goto f_err;
1548         }
1549         param_len += 1;
1550
1551         i = (unsigned int)(p[0]);
1552         p++;
1553
1554         if (i > n - param_len) {
1555             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_S_LENGTH);
1556             goto f_err;
1557         }
1558         param_len += i;
1559
1560         if ((s->srp_ctx.s = BN_bin2bn(p, i, NULL)) == NULL) {
1561             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1562             goto err;
1563         }
1564         p += i;
1565
1566         if (2 > n - param_len) {
1567             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1568             goto f_err;
1569         }
1570         param_len += 2;
1571
1572         n2s(p, i);
1573
1574         if (i > n - param_len) {
1575             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_B_LENGTH);
1576             goto f_err;
1577         }
1578         param_len += i;
1579
1580         if ((s->srp_ctx.B = BN_bin2bn(p, i, NULL)) == NULL) {
1581             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1582             goto err;
1583         }
1584         p += i;
1585         n -= param_len;
1586
1587         if (!srp_verify_server_param(s, &al)) {
1588             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1589             goto f_err;
1590         }
1591
1592 /* We must check if there is a certificate */
1593         if (alg_a & (SSL_aRSA|SSL_aDSS))
1594             pkey = X509_get_pubkey(s->session->peer);
1595     } else
1596 #endif                          /* !OPENSSL_NO_SRP */
1597 #ifndef OPENSSL_NO_RSA
1598     if (alg_k & SSL_kRSA) {
1599         /* Temporary RSA keys only allowed in export ciphersuites */
1600         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
1601             al = SSL_AD_UNEXPECTED_MESSAGE;
1602             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1603             goto f_err;
1604         }
1605         if ((rsa = RSA_new()) == NULL) {
1606             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1607             goto err;
1608         }
1609
1610         param_len = 2;
1611         if (param_len > n) {
1612             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1613             goto f_err;
1614         }
1615         n2s(p, i);
1616
1617         if (i > n - param_len) {
1618             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_MODULUS_LENGTH);
1619             goto f_err;
1620         }
1621         param_len += i;
1622
1623         if ((rsa->n = BN_bin2bn(p, i, rsa->n)) == 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_RSA_E_LENGTH);
1639             goto f_err;
1640         }
1641         param_len += i;
1642
1643         if ((rsa->e = BN_bin2bn(p, i, rsa->e)) == 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         /* this should be because we are using an export cipher */
1651         if (alg_a & SSL_aRSA)
1652             pkey = X509_get_pubkey(s->session->peer);
1653         else {
1654             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1655             goto err;
1656         }
1657
1658         if (EVP_PKEY_bits(pkey) <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
1659             al = SSL_AD_UNEXPECTED_MESSAGE;
1660             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1661             goto f_err;
1662         }
1663
1664         s->s3->peer_rsa_tmp = rsa;
1665         rsa = NULL;
1666     }
1667 #else                           /* OPENSSL_NO_RSA */
1668     if (0) ;
1669 #endif
1670 #ifndef OPENSSL_NO_DH
1671     else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1672         if ((dh = DH_new()) == NULL) {
1673             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
1674             goto err;
1675         }
1676
1677         param_len = 2;
1678         if (param_len > n) {
1679             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1680             goto f_err;
1681         }
1682         n2s(p, i);
1683
1684         if (i > n - param_len) {
1685             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_LENGTH);
1686             goto f_err;
1687         }
1688         param_len += i;
1689
1690         if ((dh->p = BN_bin2bn(p, i, NULL)) == NULL) {
1691             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1692             goto err;
1693         }
1694         p += i;
1695
1696         if (BN_is_zero(dh->p)) {
1697             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_VALUE);
1698             goto f_err;
1699         }
1700
1701
1702         if (2 > n - param_len) {
1703             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1704             goto f_err;
1705         }
1706         param_len += 2;
1707
1708         n2s(p, i);
1709
1710         if (i > n - param_len) {
1711             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_LENGTH);
1712             goto f_err;
1713         }
1714         param_len += i;
1715
1716         if ((dh->g = BN_bin2bn(p, i, NULL)) == NULL) {
1717             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1718             goto err;
1719         }
1720         p += i;
1721
1722         if (BN_is_zero(dh->g)) {
1723             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_VALUE);
1724             goto f_err;
1725         }
1726
1727         if (2 > n - param_len) {
1728             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1729             goto f_err;
1730         }
1731         param_len += 2;
1732
1733         n2s(p, i);
1734
1735         if (i > n - param_len) {
1736             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1737             goto f_err;
1738         }
1739         param_len += i;
1740
1741         if ((dh->pub_key = BN_bin2bn(p, i, NULL)) == NULL) {
1742             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1743             goto err;
1744         }
1745         p += i;
1746         n -= param_len;
1747
1748         if (BN_is_zero(dh->pub_key)) {
1749             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_VALUE);
1750             goto f_err;
1751         }
1752
1753         if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1754             al = SSL_AD_HANDSHAKE_FAILURE;
1755             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL);
1756             goto f_err;
1757         }
1758         if (alg_a & (SSL_aRSA|SSL_aDSS))
1759             pkey = X509_get_pubkey(s->session->peer);
1760         /* else anonymous DH, so no certificate or pkey. */
1761
1762         s->s3->peer_dh_tmp = dh;
1763         dh = NULL;
1764     }
1765 #endif                          /* !OPENSSL_NO_DH */
1766
1767 #ifndef OPENSSL_NO_EC
1768     else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1769         EC_GROUP *ngroup;
1770         const EC_GROUP *group;
1771
1772         if ((ecdh = EC_KEY_new()) == NULL) {
1773             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1774             goto err;
1775         }
1776
1777         /*
1778          * Extract elliptic curve parameters and the server's ephemeral ECDH
1779          * public key. Keep accumulating lengths of various components in
1780          * param_len and make sure it never exceeds n.
1781          */
1782
1783         /*
1784          * XXX: For now we only support named (not generic) curves and the
1785          * ECParameters in this case is just three bytes. We also need one
1786          * byte for the length of the encoded point
1787          */
1788         param_len = 4;
1789         if (param_len > n) {
1790             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1791             goto f_err;
1792         }
1793         /*
1794          * Check curve is one of our preferences, if not server has sent an
1795          * invalid curve. ECParameters is 3 bytes.
1796          */
1797         if (!tls1_check_curve(s, p, 3)) {
1798             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_CURVE);
1799             goto f_err;
1800         }
1801
1802         if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) {
1803             al = SSL_AD_INTERNAL_ERROR;
1804             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1805                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1806             goto f_err;
1807         }
1808
1809         ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1810         if (ngroup == NULL) {
1811             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1812             goto err;
1813         }
1814         if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1815             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1816             goto err;
1817         }
1818         EC_GROUP_free(ngroup);
1819
1820         group = EC_KEY_get0_group(ecdh);
1821
1822         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1823             (EC_GROUP_get_degree(group) > 163)) {
1824             al = SSL_AD_EXPORT_RESTRICTION;
1825             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1826                    SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1827             goto f_err;
1828         }
1829
1830         p += 3;
1831
1832         /* Next, get the encoded ECPoint */
1833         if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1834             ((bn_ctx = BN_CTX_new()) == NULL)) {
1835             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1836             goto err;
1837         }
1838
1839         encoded_pt_len = *p;    /* length of encoded point */
1840         p += 1;
1841
1842         if ((encoded_pt_len > n - param_len) ||
1843             (EC_POINT_oct2point(group, srvr_ecpoint,
1844                                 p, encoded_pt_len, bn_ctx) == 0)) {
1845             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1846             goto f_err;
1847         }
1848         param_len += encoded_pt_len;
1849
1850         n -= param_len;
1851         p += encoded_pt_len;
1852
1853         /*
1854          * The ECC/TLS specification does not mention the use of DSA to sign
1855          * ECParameters in the server key exchange message. We do support RSA
1856          * and ECDSA.
1857          */
1858         if (0) ;
1859 # ifndef OPENSSL_NO_RSA
1860         else if (alg_a & SSL_aRSA)
1861             pkey = X509_get_pubkey(s->session->peer);
1862 # endif
1863 # ifndef OPENSSL_NO_EC
1864         else if (alg_a & SSL_aECDSA)
1865             pkey = X509_get_pubkey(s->session->peer);
1866 # endif
1867         /* else anonymous ECDH, so no certificate or pkey. */
1868         EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1869         s->s3->peer_ecdh_tmp = ecdh;
1870         ecdh = NULL;
1871         BN_CTX_free(bn_ctx);
1872         bn_ctx = NULL;
1873         EC_POINT_free(srvr_ecpoint);
1874         srvr_ecpoint = NULL;
1875     } else if (alg_k) {
1876         al = SSL_AD_UNEXPECTED_MESSAGE;
1877         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1878         goto f_err;
1879     }
1880 #endif                          /* !OPENSSL_NO_EC */
1881
1882     /* p points to the next byte, there are 'n' bytes left */
1883
1884     /* if it was signed, check the signature */
1885     if (pkey != NULL) {
1886         if (SSL_USE_SIGALGS(s)) {
1887             int rv;
1888             if (2 > n) {
1889                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1890                 goto f_err;
1891             }
1892             rv = tls12_check_peer_sigalg(&md, s, p, pkey);
1893             if (rv == -1)
1894                 goto err;
1895             else if (rv == 0) {
1896                 goto f_err;
1897             }
1898 #ifdef SSL_DEBUG
1899             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1900 #endif
1901             p += 2;
1902             n -= 2;
1903         } else
1904             md = EVP_sha1();
1905
1906         if (2 > n) {
1907             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1908             goto f_err;
1909         }
1910         n2s(p, i);
1911         n -= 2;
1912         j = EVP_PKEY_size(pkey);
1913
1914         /*
1915          * Check signature length. If n is 0 then signature is empty
1916          */
1917         if ((i != n) || (n > j) || (n <= 0)) {
1918             /* wrong packet length */
1919             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1920             goto f_err;
1921         }
1922 #ifndef OPENSSL_NO_RSA
1923         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1924             int num;
1925             unsigned int size;
1926
1927             j = 0;
1928             q = md_buf;
1929             for (num = 2; num > 0; num--) {
1930                 EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1931                 EVP_DigestInit_ex(&md_ctx, (num == 2)
1932                                   ? s->ctx->md5 : s->ctx->sha1, NULL);
1933                 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1934                                  SSL3_RANDOM_SIZE);
1935                 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1936                                  SSL3_RANDOM_SIZE);
1937                 EVP_DigestUpdate(&md_ctx, param, param_len);
1938                 EVP_DigestFinal_ex(&md_ctx, q, &size);
1939                 q += size;
1940                 j += size;
1941             }
1942             i = RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa);
1943             if (i < 0) {
1944                 al = SSL_AD_DECRYPT_ERROR;
1945                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
1946                 goto f_err;
1947             }
1948             if (i == 0) {
1949                 /* bad signature */
1950                 al = SSL_AD_DECRYPT_ERROR;
1951                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1952                 goto f_err;
1953             }
1954         } else
1955 #endif
1956         {
1957             EVP_VerifyInit_ex(&md_ctx, md, NULL);
1958             EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1959                              SSL3_RANDOM_SIZE);
1960             EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1961                              SSL3_RANDOM_SIZE);
1962             EVP_VerifyUpdate(&md_ctx, param, param_len);
1963             if (EVP_VerifyFinal(&md_ctx, p, (int)n, pkey) <= 0) {
1964                 /* bad signature */
1965                 al = SSL_AD_DECRYPT_ERROR;
1966                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1967                 goto f_err;
1968             }
1969         }
1970     } else {
1971         /* aNULL, aSRP or PSK do not need public keys */
1972         if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_PSK)) {
1973             /* Might be wrong key type, check it */
1974             if (ssl3_check_cert_and_algorithm(s))
1975                 /* Otherwise this shouldn't happen */
1976                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1977             goto err;
1978         }
1979         /* still data left over */
1980         if (n != 0) {
1981             SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1982             goto f_err;
1983         }
1984     }
1985     EVP_PKEY_free(pkey);
1986     EVP_MD_CTX_cleanup(&md_ctx);
1987     return (1);
1988  f_err:
1989     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1990  err:
1991     EVP_PKEY_free(pkey);
1992 #ifndef OPENSSL_NO_RSA
1993     RSA_free(rsa);
1994 #endif
1995 #ifndef OPENSSL_NO_DH
1996     DH_free(dh);
1997 #endif
1998 #ifndef OPENSSL_NO_EC
1999     BN_CTX_free(bn_ctx);
2000     EC_POINT_free(srvr_ecpoint);
2001     EC_KEY_free(ecdh);
2002 #endif
2003     EVP_MD_CTX_cleanup(&md_ctx);
2004     s->state = SSL_ST_ERR;
2005     return (-1);
2006 }
2007
2008 int ssl3_get_certificate_request(SSL *s)
2009 {
2010     int ok, ret = 0;
2011     unsigned long n, nc, l;
2012     unsigned int llen, ctype_num, i;
2013     X509_NAME *xn = NULL;
2014     const unsigned char *p, *q;
2015     unsigned char *d;
2016     STACK_OF(X509_NAME) *ca_sk = NULL;
2017
2018     n = s->method->ssl_get_message(s,
2019                                    SSL3_ST_CR_CERT_REQ_A,
2020                                    SSL3_ST_CR_CERT_REQ_B,
2021                                    -1, s->max_cert_list, &ok);
2022
2023     if (!ok)
2024         return ((int)n);
2025
2026     s->s3->tmp.cert_req = 0;
2027
2028     if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
2029         s->s3->tmp.reuse_message = 1;
2030         /*
2031          * If we get here we don't need any cached handshake records as we
2032          * wont be doing client auth.
2033          */
2034         if (!ssl3_digest_cached_records(s, 0))
2035             goto err;
2036         return (1);
2037     }
2038
2039     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
2040         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2041         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
2042         goto err;
2043     }
2044
2045     /* TLS does not like anon-DH with client cert */
2046     if (s->version > SSL3_VERSION) {
2047         if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
2048             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2049             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2050                    SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
2051             goto err;
2052         }
2053     }
2054
2055     p = d = (unsigned char *)s->init_msg;
2056
2057     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
2058         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2059         goto err;
2060     }
2061
2062     /* get the certificate types */
2063     ctype_num = *(p++);
2064     OPENSSL_free(s->cert->ctypes);
2065     s->cert->ctypes = NULL;
2066     if (ctype_num > SSL3_CT_NUMBER) {
2067         /* If we exceed static buffer copy all to cert structure */
2068         s->cert->ctypes = OPENSSL_malloc(ctype_num);
2069         if (s->cert->ctypes == NULL) {
2070             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2071             goto err;
2072         }
2073         memcpy(s->cert->ctypes, p, ctype_num);
2074         s->cert->ctype_num = (size_t)ctype_num;
2075         ctype_num = SSL3_CT_NUMBER;
2076     }
2077     for (i = 0; i < ctype_num; i++)
2078         s->s3->tmp.ctype[i] = p[i];
2079     p += p[-1];
2080     if (SSL_USE_SIGALGS(s)) {
2081         n2s(p, llen);
2082         /*
2083          * Check we have enough room for signature algorithms and following
2084          * length value.
2085          */
2086         if ((unsigned long)(p - d + llen + 2) > n) {
2087             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2088             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2089                    SSL_R_DATA_LENGTH_TOO_LONG);
2090             goto err;
2091         }
2092         /* Clear certificate digests and validity flags */
2093         for (i = 0; i < SSL_PKEY_NUM; i++) {
2094             s->s3->tmp.md[i] = NULL;
2095             s->s3->tmp.valid_flags[i] = 0;
2096         }
2097         if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) {
2098             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2099             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2100                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2101             goto err;
2102         }
2103         if (!tls1_process_sigalgs(s)) {
2104             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2105             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2106             goto err;
2107         }
2108         p += llen;
2109     }
2110
2111     /* get the CA RDNs */
2112     n2s(p, llen);
2113
2114     if ((unsigned long)(p - d + llen) != n) {
2115         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2116         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2117         goto err;
2118     }
2119
2120     for (nc = 0; nc < llen;) {
2121         n2s(p, l);
2122         if ((l + nc + 2) > llen) {
2123             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2124             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2125             goto err;
2126         }
2127
2128         q = p;
2129
2130         if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
2131             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2132             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2133             goto err;
2134         }
2135
2136         if (q != (p + l)) {
2137             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2138             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2139                    SSL_R_CA_DN_LENGTH_MISMATCH);
2140             goto err;
2141         }
2142         if (!sk_X509_NAME_push(ca_sk, xn)) {
2143             SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2144             goto err;
2145         }
2146
2147         p += l;
2148         nc += l + 2;
2149     }
2150
2151     /* we should setup a certificate to return.... */
2152     s->s3->tmp.cert_req = 1;
2153     s->s3->tmp.ctype_num = ctype_num;
2154     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2155     s->s3->tmp.ca_names = ca_sk;
2156     ca_sk = NULL;
2157
2158     ret = 1;
2159     goto done;
2160  err:
2161     s->state = SSL_ST_ERR;
2162  done:
2163     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2164     return (ret);
2165 }
2166
2167 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2168 {
2169     return (X509_NAME_cmp(*a, *b));
2170 }
2171
2172 int ssl3_get_new_session_ticket(SSL *s)
2173 {
2174     int ok, al, ret = 0, ticklen;
2175     long n;
2176     const unsigned char *p;
2177     unsigned char *d;
2178
2179     n = s->method->ssl_get_message(s,
2180                                    SSL3_ST_CR_SESSION_TICKET_A,
2181                                    SSL3_ST_CR_SESSION_TICKET_B,
2182                                    SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
2183
2184     if (!ok)
2185         return ((int)n);
2186
2187     if (n < 6) {
2188         /* need at least ticket_lifetime_hint + ticket length */
2189         al = SSL_AD_DECODE_ERROR;
2190         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2191         goto f_err;
2192     }
2193
2194     p = d = (unsigned char *)s->init_msg;
2195
2196     if (s->session->session_id_length > 0) {
2197         int i = s->session_ctx->session_cache_mode;
2198         SSL_SESSION *new_sess;
2199         /*
2200          * We reused an existing session, so we need to replace it with a new
2201          * one
2202          */
2203         if (i & SSL_SESS_CACHE_CLIENT) {
2204             /*
2205              * Remove the old session from the cache
2206              */
2207             if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2208                 if (s->session_ctx->remove_session_cb != NULL)
2209                     s->session_ctx->remove_session_cb(s->session_ctx,
2210                                                       s->session);
2211             } else {
2212                 /* We carry on if this fails */
2213                 SSL_CTX_remove_session(s->session_ctx, s->session);
2214             }
2215         }
2216
2217         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2218             al = SSL_AD_INTERNAL_ERROR;
2219             SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2220             goto f_err;
2221         }
2222
2223         SSL_SESSION_free(s->session);
2224         s->session = new_sess;
2225     }
2226
2227     n2l(p, s->session->tlsext_tick_lifetime_hint);
2228     n2s(p, ticklen);
2229     /* ticket_lifetime_hint + ticket_length + ticket */
2230     if (ticklen + 6 != n) {
2231         al = SSL_AD_DECODE_ERROR;
2232         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2233         goto f_err;
2234     }
2235     OPENSSL_free(s->session->tlsext_tick);
2236     s->session->tlsext_ticklen = 0;
2237     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2238     if (!s->session->tlsext_tick) {
2239         SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2240         goto err;
2241     }
2242     memcpy(s->session->tlsext_tick, p, ticklen);
2243     s->session->tlsext_ticklen = ticklen;
2244     /*
2245      * There are two ways to detect a resumed ticket session. One is to set
2246      * an appropriate session ID and then the server must return a match in
2247      * ServerHello. This allows the normal client session ID matching to work
2248      * and we know much earlier that the ticket has been accepted. The
2249      * other way is to set zero length session ID when the ticket is
2250      * presented and rely on the handshake to determine session resumption.
2251      * We choose the former approach because this fits in with assumptions
2252      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2253      * SHA256 is disabled) hash of the ticket.
2254      */
2255     EVP_Digest(p, ticklen,
2256                s->session->session_id, &s->session->session_id_length,
2257                EVP_sha256(), NULL);
2258     ret = 1;
2259     return (ret);
2260  f_err:
2261     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2262  err:
2263     s->state = SSL_ST_ERR;
2264     return (-1);
2265 }
2266
2267 int ssl3_get_cert_status(SSL *s)
2268 {
2269     int ok, al;
2270     unsigned long resplen, n;
2271     const unsigned char *p;
2272
2273     n = s->method->ssl_get_message(s,
2274                                    SSL3_ST_CR_CERT_STATUS_A,
2275                                    SSL3_ST_CR_CERT_STATUS_B,
2276                                    SSL3_MT_CERTIFICATE_STATUS, 16384, &ok);
2277
2278     if (!ok)
2279         return ((int)n);
2280     if (n < 4) {
2281         /* need at least status type + length */
2282         al = SSL_AD_DECODE_ERROR;
2283         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2284         goto f_err;
2285     }
2286     p = (unsigned char *)s->init_msg;
2287     if (*p++ != TLSEXT_STATUSTYPE_ocsp) {
2288         al = SSL_AD_DECODE_ERROR;
2289         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2290         goto f_err;
2291     }
2292     n2l3(p, resplen);
2293     if (resplen + 4 != n) {
2294         al = SSL_AD_DECODE_ERROR;
2295         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2296         goto f_err;
2297     }
2298     OPENSSL_free(s->tlsext_ocsp_resp);
2299     s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2300     if (!s->tlsext_ocsp_resp) {
2301         al = SSL_AD_INTERNAL_ERROR;
2302         SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2303         goto f_err;
2304     }
2305     s->tlsext_ocsp_resplen = resplen;
2306     if (s->ctx->tlsext_status_cb) {
2307         int ret;
2308         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2309         if (ret == 0) {
2310             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2311             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
2312             goto f_err;
2313         }
2314         if (ret < 0) {
2315             al = SSL_AD_INTERNAL_ERROR;
2316             SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2317             goto f_err;
2318         }
2319     }
2320     return 1;
2321  f_err:
2322     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2323     s->state = SSL_ST_ERR;
2324     return (-1);
2325 }
2326
2327 int ssl3_get_server_done(SSL *s)
2328 {
2329     int ok, ret = 0;
2330     long n;
2331
2332     /* Second to last param should be very small, like 0 :-) */
2333     n = s->method->ssl_get_message(s,
2334                                    SSL3_ST_CR_SRVR_DONE_A,
2335                                    SSL3_ST_CR_SRVR_DONE_B,
2336                                    SSL3_MT_SERVER_DONE, 30, &ok);
2337
2338     if (!ok)
2339         return ((int)n);
2340     if (n > 0) {
2341         /* should contain no data */
2342         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2343         SSLerr(SSL_F_SSL3_GET_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2344         s->state = SSL_ST_ERR;
2345         return -1;
2346     }
2347     ret = 1;
2348     return (ret);
2349 }
2350
2351 int ssl3_send_client_key_exchange(SSL *s)
2352 {
2353     unsigned char *p;
2354     int n;
2355 #ifndef OPENSSL_NO_PSK
2356     size_t pskhdrlen = 0;
2357 #endif
2358     unsigned long alg_k;
2359 #ifndef OPENSSL_NO_RSA
2360     unsigned char *q;
2361     EVP_PKEY *pkey = NULL;
2362 #endif
2363 #ifndef OPENSSL_NO_EC
2364     EC_KEY *clnt_ecdh = NULL;
2365     const EC_POINT *srvr_ecpoint = NULL;
2366     EVP_PKEY *srvr_pub_pkey = NULL;
2367     unsigned char *encodedPoint = NULL;
2368     int encoded_pt_len = 0;
2369     BN_CTX *bn_ctx = NULL;
2370 #endif
2371     unsigned char *pms = NULL;
2372     size_t pmslen = 0;
2373     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2374
2375     if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
2376         p = ssl_handshake_start(s);
2377
2378
2379 #ifndef OPENSSL_NO_PSK
2380         if (alg_k & SSL_PSK) {
2381             int psk_err = 1;
2382             /*
2383              * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2384              * \0-terminated identity. The last byte is for us for simulating
2385              * strnlen.
2386              */
2387             char identity[PSK_MAX_IDENTITY_LEN + 1];
2388             size_t identitylen;
2389             unsigned char psk[PSK_MAX_PSK_LEN];
2390             size_t psklen;
2391
2392             if (s->psk_client_callback == NULL) {
2393                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2394                        SSL_R_PSK_NO_CLIENT_CB);
2395                 goto err;
2396             }
2397
2398             memset(identity, 0, sizeof(identity));
2399
2400             psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2401                                             identity, sizeof(identity) - 1,
2402                                             psk, sizeof(psk));
2403
2404             if (psklen > PSK_MAX_PSK_LEN) {
2405                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2406                        ERR_R_INTERNAL_ERROR);
2407                 goto psk_err;
2408             } else if (psklen == 0) {
2409                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2410                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2411                 goto psk_err;
2412             }
2413
2414             OPENSSL_free(s->s3->tmp.psk);
2415             s->s3->tmp.psk = BUF_memdup(psk, psklen);
2416             OPENSSL_cleanse(psk, psklen);
2417
2418             if (s->s3->tmp.psk == NULL) {
2419                 OPENSSL_cleanse(identity, sizeof(identity));
2420                 goto memerr;
2421             }
2422
2423             s->s3->tmp.psklen = psklen;
2424
2425             identitylen = strlen(identity);
2426             if (identitylen > PSK_MAX_IDENTITY_LEN) {
2427                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2428                        ERR_R_INTERNAL_ERROR);
2429                 goto psk_err;
2430             }
2431             OPENSSL_free(s->session->psk_identity);
2432             s->session->psk_identity = BUF_strdup(identity);
2433             if (s->session->psk_identity == NULL) {
2434                 OPENSSL_cleanse(identity, sizeof(identity));
2435                 goto memerr;
2436             }
2437
2438             s2n(identitylen, p);
2439             memcpy(p, identity, identitylen);
2440             pskhdrlen = 2 + identitylen;
2441             p += identitylen;
2442             psk_err = 0;
2443  psk_err:
2444             OPENSSL_cleanse(identity, sizeof(identity));
2445             if (psk_err != 0) {
2446                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2447                 goto err;
2448             }
2449         }
2450         if (alg_k & SSL_kPSK) {
2451             n = 0;
2452         } else
2453 #endif
2454
2455         /* Fool emacs indentation */
2456         if (0) {
2457         }
2458 #ifndef OPENSSL_NO_RSA
2459         else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2460             RSA *rsa;
2461             pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2462             pms = OPENSSL_malloc(pmslen);
2463             if (!pms)
2464                 goto memerr;
2465
2466             if (s->session->peer == NULL) {
2467                 /*
2468                  * We should always have a server certificate with SSL_kRSA.
2469                  */
2470                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2471                        ERR_R_INTERNAL_ERROR);
2472                 goto err;
2473             }
2474
2475             if (s->s3->peer_rsa_tmp != NULL)
2476                 rsa = s->s3->peer_rsa_tmp;
2477             else {
2478                 pkey = X509_get_pubkey(s->session->peer);
2479                 if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2480                     || (pkey->pkey.rsa == NULL)) {
2481                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2482                            ERR_R_INTERNAL_ERROR);
2483                     goto err;
2484                 }
2485                 rsa = pkey->pkey.rsa;
2486                 EVP_PKEY_free(pkey);
2487             }
2488
2489             pms[0] = s->client_version >> 8;
2490             pms[1] = s->client_version & 0xff;
2491             if (RAND_bytes(pms + 2, pmslen - 2) <= 0)
2492                 goto err;
2493
2494             q = p;
2495             /* Fix buf for TLS and beyond */
2496             if (s->version > SSL3_VERSION)
2497                 p += 2;
2498             n = RSA_public_encrypt(pmslen, pms, p, rsa, RSA_PKCS1_PADDING);
2499 # ifdef PKCS1_CHECK
2500             if (s->options & SSL_OP_PKCS1_CHECK_1)
2501                 p[1]++;
2502             if (s->options & SSL_OP_PKCS1_CHECK_2)
2503                 tmp_buf[0] = 0x70;
2504 # endif
2505             if (n <= 0) {
2506                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2507                        SSL_R_BAD_RSA_ENCRYPT);
2508                 goto err;
2509             }
2510
2511             /* Fix buf for TLS and beyond */
2512             if (s->version > SSL3_VERSION) {
2513                 s2n(n, q);
2514                 n += 2;
2515             }
2516         }
2517 #endif
2518 #ifndef OPENSSL_NO_DH
2519         else if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2520             DH *dh_srvr, *dh_clnt;
2521             if (s->s3->peer_dh_tmp != NULL)
2522                 dh_srvr = s->s3->peer_dh_tmp;
2523             else {
2524                 /* we get them from the cert */
2525                 EVP_PKEY *spkey = NULL;
2526                 dh_srvr = NULL;
2527                 spkey = X509_get_pubkey(s->session->peer);
2528                 if (spkey) {
2529                     dh_srvr = EVP_PKEY_get1_DH(spkey);
2530                     EVP_PKEY_free(spkey);
2531                 }
2532                 if (dh_srvr == NULL) {
2533                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2534                            ERR_R_INTERNAL_ERROR);
2535                     goto err;
2536                 }
2537             }
2538             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
2539                 /* Use client certificate key */
2540                 EVP_PKEY *clkey = s->cert->key->privatekey;
2541                 dh_clnt = NULL;
2542                 if (clkey)
2543                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2544                 if (dh_clnt == NULL) {
2545                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2546                            ERR_R_INTERNAL_ERROR);
2547                     goto err;
2548                 }
2549             } else {
2550                 /* generate a new random key */
2551                 if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2552                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2553                     goto err;
2554                 }
2555                 if (!DH_generate_key(dh_clnt)) {
2556                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2557                     DH_free(dh_clnt);
2558                     goto err;
2559                 }
2560             }
2561
2562             pmslen = DH_size(dh_clnt);
2563             pms = OPENSSL_malloc(pmslen);
2564             if (!pms)
2565                 goto memerr;
2566
2567             /*
2568              * use the 'p' output buffer for the DH key, but make sure to
2569              * clear it out afterwards
2570              */
2571
2572             n = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
2573             if (s->s3->peer_dh_tmp == NULL)
2574                 DH_free(dh_srvr);
2575
2576             if (n <= 0) {
2577                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2578                 DH_free(dh_clnt);
2579                 goto err;
2580             }
2581             pmslen = n;
2582
2583             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2584                 n = 0;
2585             else {
2586                 /* send off the data */
2587                 n = BN_num_bytes(dh_clnt->pub_key);
2588                 s2n(n, p);
2589                 BN_bn2bin(dh_clnt->pub_key, p);
2590                 n += 2;
2591             }
2592
2593             DH_free(dh_clnt);
2594         }
2595 #endif
2596
2597 #ifndef OPENSSL_NO_EC
2598         else if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2599             const EC_GROUP *srvr_group = NULL;
2600             EC_KEY *tkey;
2601             int ecdh_clnt_cert = 0;
2602             int field_size = 0;
2603             /*
2604              * Did we send out the client's ECDH share for use in premaster
2605              * computation as part of client certificate? If so, set
2606              * ecdh_clnt_cert to 1.
2607              */
2608             if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2609                 /*-
2610                  * XXX: For now, we do not support client
2611                  * authentication using ECDH certificates.
2612                  * To add such support, one needs to add
2613                  * code that checks for appropriate
2614                  * conditions and sets ecdh_clnt_cert to 1.
2615                  * For example, the cert have an ECC
2616                  * key on the same curve as the server's
2617                  * and the key should be authorized for
2618                  * key agreement.
2619                  *
2620                  * One also needs to add code in ssl3_connect
2621                  * to skip sending the certificate verify
2622                  * message.
2623                  *
2624                  * if ((s->cert->key->privatekey != NULL) &&
2625                  *     (s->cert->key->privatekey->type ==
2626                  *      EVP_PKEY_EC) && ...)
2627                  * ecdh_clnt_cert = 1;
2628                  */
2629             }
2630
2631             if (s->s3->peer_ecdh_tmp != NULL) {
2632                 tkey = s->s3->peer_ecdh_tmp;
2633             } else {
2634                 /* Get the Server Public Key from Cert */
2635                 srvr_pub_pkey = X509_get_pubkey(s->session->peer);
2636                 if ((srvr_pub_pkey == NULL)
2637                     || (srvr_pub_pkey->type != EVP_PKEY_EC)
2638                     || (srvr_pub_pkey->pkey.ec == NULL)) {
2639                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2640                            ERR_R_INTERNAL_ERROR);
2641                     goto err;
2642                 }
2643
2644                 tkey = srvr_pub_pkey->pkey.ec;
2645             }
2646
2647             srvr_group = EC_KEY_get0_group(tkey);
2648             srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2649
2650             if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2651                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2652                        ERR_R_INTERNAL_ERROR);
2653                 goto err;
2654             }
2655
2656             if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2657                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2658                        ERR_R_MALLOC_FAILURE);
2659                 goto err;
2660             }
2661
2662             if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2663                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2664                 goto err;
2665             }
2666             if (ecdh_clnt_cert) {
2667                 /*
2668                  * Reuse key info from our certificate We only need our
2669                  * private key to perform the ECDH computation.
2670                  */
2671                 const BIGNUM *priv_key;
2672                 tkey = s->cert->key->privatekey->pkey.ec;
2673                 priv_key = EC_KEY_get0_private_key(tkey);
2674                 if (priv_key == NULL) {
2675                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2676                            ERR_R_MALLOC_FAILURE);
2677                     goto err;
2678                 }
2679                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2680                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2681                     goto err;
2682                 }
2683             } else {
2684                 /* Generate a new ECDH key pair */
2685                 if (!(EC_KEY_generate_key(clnt_ecdh))) {
2686                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2687                            ERR_R_ECDH_LIB);
2688                     goto err;
2689                 }
2690             }
2691
2692             /*
2693              * use the 'p' output buffer for the ECDH key, but make sure to
2694              * clear it out afterwards
2695              */
2696
2697             field_size = EC_GROUP_get_degree(srvr_group);
2698             if (field_size <= 0) {
2699                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2700                 goto err;
2701             }
2702             pmslen = (field_size + 7) / 8;
2703             pms = OPENSSL_malloc(pmslen);
2704             if (!pms)
2705                 goto memerr;
2706             n = ECDH_compute_key(pms, pmslen, srvr_ecpoint, clnt_ecdh, NULL);
2707             if (n <= 0 || pmslen != (size_t)n) {
2708                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2709                 goto err;
2710             }
2711
2712             if (ecdh_clnt_cert) {
2713                 /* Send empty client key exch message */
2714                 n = 0;
2715             } else {
2716                 /*
2717                  * First check the size of encoding and allocate memory
2718                  * accordingly.
2719                  */
2720                 encoded_pt_len =
2721                     EC_POINT_point2oct(srvr_group,
2722                                        EC_KEY_get0_public_key(clnt_ecdh),
2723                                        POINT_CONVERSION_UNCOMPRESSED,
2724                                        NULL, 0, NULL);
2725
2726                 encodedPoint = (unsigned char *)
2727                     OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2728                 bn_ctx = BN_CTX_new();
2729                 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2730                     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2731                            ERR_R_MALLOC_FAILURE);
2732                     goto err;
2733                 }
2734
2735                 /* Encode the public key */
2736                 n = EC_POINT_point2oct(srvr_group,
2737                                        EC_KEY_get0_public_key(clnt_ecdh),
2738                                        POINT_CONVERSION_UNCOMPRESSED,
2739                                        encodedPoint, encoded_pt_len, bn_ctx);
2740
2741                 *p = n;         /* length of encoded point */
2742                 /* Encoded point will be copied here */
2743                 p += 1;
2744                 /* copy the point */
2745                 memcpy(p, encodedPoint, n);
2746                 /* increment n to account for length field */
2747                 n += 1;
2748             }
2749
2750             /* Free allocated memory */
2751             BN_CTX_free(bn_ctx);
2752             OPENSSL_free(encodedPoint);
2753             EC_KEY_free(clnt_ecdh);
2754             EVP_PKEY_free(srvr_pub_pkey);
2755         }
2756 #endif                          /* !OPENSSL_NO_EC */
2757         else if (alg_k & SSL_kGOST) {
2758             /* GOST key exchange message creation */
2759             EVP_PKEY_CTX *pkey_ctx;
2760             X509 *peer_cert;
2761             size_t msglen;
2762             unsigned int md_len;
2763             unsigned char shared_ukm[32], tmp[256];
2764             EVP_MD_CTX *ukm_hash;
2765             EVP_PKEY *pub_key;
2766
2767             pmslen = 32;
2768             pms = OPENSSL_malloc(pmslen);
2769             if (!pms)
2770                 goto memerr;
2771
2772             /*
2773              * Get server sertificate PKEY and create ctx from it
2774              */
2775             peer_cert = s->session->peer;
2776             if (!peer_cert) {
2777                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2778                        SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2779                 goto err;
2780             }
2781
2782             pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2783                                         X509_get_pubkey(peer_cert), NULL);
2784             /*
2785              * If we have send a certificate, and certificate key
2786              *
2787              * * parameters match those of server certificate, use
2788              * certificate key for key exchange
2789              */
2790
2791             /* Otherwise, generate ephemeral key pair */
2792
2793             EVP_PKEY_encrypt_init(pkey_ctx);
2794             /* Generate session key */
2795             if (RAND_bytes(pms, pmslen) <= 0) {
2796                 EVP_PKEY_CTX_free(pkey_ctx);
2797                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2798                        ERR_R_INTERNAL_ERROR);
2799                 goto err;
2800             };
2801             /*
2802              * If we have client certificate, use its secret as peer key
2803              */
2804             if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2805                 if (EVP_PKEY_derive_set_peer
2806                     (pkey_ctx, s->cert->key->privatekey) <= 0) {
2807                     /*
2808                      * If there was an error - just ignore it. Ephemeral key
2809                      * * would be used
2810                      */
2811                     ERR_clear_error();
2812                 }
2813             }
2814             /*
2815              * Compute shared IV and store it in algorithm-specific context
2816              * data
2817              */
2818             ukm_hash = EVP_MD_CTX_create();
2819             EVP_DigestInit(ukm_hash,
2820                            EVP_get_digestbynid(NID_id_GostR3411_94));
2821             EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2822                              SSL3_RANDOM_SIZE);
2823             EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2824                              SSL3_RANDOM_SIZE);
2825             EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2826             EVP_MD_CTX_destroy(ukm_hash);
2827             if (EVP_PKEY_CTX_ctrl
2828                 (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2829                  shared_ukm) < 0) {
2830                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2831                        SSL_R_LIBRARY_BUG);
2832                 goto err;
2833             }
2834             /* Make GOST keytransport blob message */
2835             /*
2836              * Encapsulate it into sequence
2837              */
2838             *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2839             msglen = 255;
2840             if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) < 0) {
2841                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2842                        SSL_R_LIBRARY_BUG);
2843                 goto err;
2844             }
2845             if (msglen >= 0x80) {
2846                 *(p++) = 0x81;
2847                 *(p++) = msglen & 0xff;
2848                 n = msglen + 3;
2849             } else {
2850                 *(p++) = msglen & 0xff;
2851                 n = msglen + 2;
2852             }
2853             memcpy(p, tmp, msglen);
2854             /* Check if pubkey from client certificate was used */
2855             if (EVP_PKEY_CTX_ctrl
2856                 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2857                 /* Set flag "skip certificate verify" */
2858                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2859             }
2860             EVP_PKEY_CTX_free(pkey_ctx);
2861             EVP_PKEY_free(pub_key);
2862
2863         }
2864 #ifndef OPENSSL_NO_SRP
2865         else if (alg_k & SSL_kSRP) {
2866             if (s->srp_ctx.A != NULL) {
2867                 /* send off the data */
2868                 n = BN_num_bytes(s->srp_ctx.A);
2869                 s2n(n, p);
2870                 BN_bn2bin(s->srp_ctx.A, p);
2871                 n += 2;
2872             } else {
2873                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2874                        ERR_R_INTERNAL_ERROR);
2875                 goto err;
2876             }
2877             OPENSSL_free(s->session->srp_username);
2878             s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2879             if (s->session->srp_username == NULL) {
2880                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2881                        ERR_R_MALLOC_FAILURE);
2882                 goto err;
2883             }
2884         }
2885 #endif
2886         else {
2887             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2888             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2889             goto err;
2890         }
2891
2892 #ifndef OPENSSL_NO_PSK
2893         n += pskhdrlen;
2894 #endif
2895
2896         if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
2897             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2898             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2899             goto err;
2900         }
2901
2902         s->state = SSL3_ST_CW_KEY_EXCH_B;
2903     }
2904
2905     /* SSL3_ST_CW_KEY_EXCH_B */
2906     n = ssl_do_write(s);
2907 #ifndef OPENSSL_NO_SRP
2908     /* Check for SRP */
2909     if (alg_k & SSL_kSRP) {
2910         /*
2911          * If everything written generate master key: no need to save PMS as
2912          * srp_generate_client_master_secret generates it internally.
2913          */
2914         if (n > 0) {
2915             if (!srp_generate_client_master_secret(s)) {
2916                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2917                        ERR_R_INTERNAL_ERROR);
2918                 goto err;
2919             }
2920         }
2921     } else
2922 #endif
2923         /* If we haven't written everything save PMS */
2924     if (n <= 0) {
2925         s->s3->tmp.pms = pms;
2926         s->s3->tmp.pmslen = pmslen;
2927     } else {
2928         /* If we don't have a PMS restore */
2929         if (pms == NULL) {
2930             pms = s->s3->tmp.pms;
2931             pmslen = s->s3->tmp.pmslen;
2932         }
2933         if (pms == NULL && !(alg_k & SSL_kPSK)) {
2934             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2935             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2936             goto err;
2937         }
2938         if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2939             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2940             SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2941             goto err;
2942         }
2943     }
2944     return n;
2945  memerr:
2946     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2947     SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2948  err:
2949     OPENSSL_clear_free(pms, pmslen);
2950     s->s3->tmp.pms = NULL;
2951 #ifndef OPENSSL_NO_EC
2952     BN_CTX_free(bn_ctx);
2953     OPENSSL_free(encodedPoint);
2954     EC_KEY_free(clnt_ecdh);
2955     EVP_PKEY_free(srvr_pub_pkey);
2956 #endif
2957 #ifndef OPENSSL_NO_PSK
2958     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2959     s->s3->tmp.psk = NULL;
2960 #endif
2961     s->state = SSL_ST_ERR;
2962     return (-1);
2963 }
2964
2965 int ssl3_send_client_verify(SSL *s)
2966 {
2967     unsigned char *p;
2968     unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2969     EVP_PKEY *pkey;
2970     EVP_PKEY_CTX *pctx = NULL;
2971     EVP_MD_CTX mctx;
2972     unsigned u = 0;
2973     unsigned long n;
2974     int j;
2975
2976     EVP_MD_CTX_init(&mctx);
2977
2978     if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
2979         p = ssl_handshake_start(s);
2980         pkey = s->cert->key->privatekey;
2981 /* Create context from key and test if sha1 is allowed as digest */
2982         pctx = EVP_PKEY_CTX_new(pkey, NULL);
2983         EVP_PKEY_sign_init(pctx);
2984         if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
2985             if (!SSL_USE_SIGALGS(s))
2986                 s->method->ssl3_enc->cert_verify_mac(s,
2987                                                      NID_sha1,
2988                                                      &(data
2989                                                        [MD5_DIGEST_LENGTH]));
2990         } else {
2991             ERR_clear_error();
2992         }
2993         /*
2994          * For TLS v1.2 send signature algorithm and signature using agreed
2995          * digest and cached handshake records.
2996          */
2997         if (SSL_USE_SIGALGS(s)) {
2998             long hdatalen = 0;
2999             void *hdata;
3000             const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
3001             hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3002             if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
3003                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3004                 goto err;
3005             }
3006             p += 2;
3007 #ifdef SSL_DEBUG
3008             fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3009                     EVP_MD_name(md));
3010 #endif
3011             if (!EVP_SignInit_ex(&mctx, md, NULL)
3012                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3013                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
3014                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
3015                 goto err;
3016             }
3017             s2n(u, p);
3018             n = u + 4;
3019             /* Digest cached records and discard handshake buffer */
3020             if (!ssl3_digest_cached_records(s, 0))
3021                 goto err;
3022         } else
3023 #ifndef OPENSSL_NO_RSA
3024         if (pkey->type == EVP_PKEY_RSA) {
3025             s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
3026             if (RSA_sign(NID_md5_sha1, data,
3027                          MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
3028                          &(p[2]), &u, pkey->pkey.rsa) <= 0) {
3029                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
3030                 goto err;
3031             }
3032             s2n(u, p);
3033             n = u + 2;
3034         } else
3035 #endif
3036 #ifndef OPENSSL_NO_DSA
3037         if (pkey->type == EVP_PKEY_DSA) {
3038             if (!DSA_sign(pkey->save_type,
3039                           &(data[MD5_DIGEST_LENGTH]),
3040                           SHA_DIGEST_LENGTH, &(p[2]),
3041                           (unsigned int *)&j, pkey->pkey.dsa)) {
3042                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
3043                 goto err;
3044             }
3045             s2n(j, p);
3046             n = j + 2;
3047         } else
3048 #endif
3049 #ifndef OPENSSL_NO_EC
3050         if (pkey->type == EVP_PKEY_EC) {
3051             if (!ECDSA_sign(pkey->save_type,
3052                             &(data[MD5_DIGEST_LENGTH]),
3053                             SHA_DIGEST_LENGTH, &(p[2]),
3054                             (unsigned int *)&j, pkey->pkey.ec)) {
3055                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
3056                 goto err;
3057             }
3058             s2n(j, p);
3059             n = j + 2;
3060         } else
3061 #endif
3062         if (pkey->type == NID_id_GostR3410_2001) {
3063             unsigned char signbuf[64];
3064             int i;
3065             size_t sigsize = 64;
3066             s->method->ssl3_enc->cert_verify_mac(s,
3067                                                  NID_id_GostR3411_94, data);
3068             if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3069                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3070                 goto err;
3071             }
3072             for (i = 63, j = 0; i >= 0; j++, i--) {
3073                 p[2 + j] = signbuf[i];
3074             }
3075             s2n(j, p);
3076             n = j + 2;
3077         } else {
3078             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3079             goto err;
3080         }
3081         if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
3082             SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3083             goto err;
3084         }
3085         s->state = SSL3_ST_CW_CERT_VRFY_B;
3086     }
3087     EVP_MD_CTX_cleanup(&mctx);
3088     EVP_PKEY_CTX_free(pctx);
3089     return ssl_do_write(s);
3090  err:
3091     EVP_MD_CTX_cleanup(&mctx);
3092     EVP_PKEY_CTX_free(pctx);
3093     s->state = SSL_ST_ERR;
3094     return (-1);
3095 }
3096
3097 /*
3098  * Check a certificate can be used for client authentication. Currently check
3099  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
3100  * certificates can be used and optionally checks suitability for Suite B.
3101  */
3102 static int ssl3_check_client_certificate(SSL *s)
3103 {
3104     unsigned long alg_k;
3105     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
3106         return 0;
3107     /* If no suitable signature algorithm can't use certificate */
3108     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
3109         return 0;
3110     /*
3111      * If strict mode check suitability of chain before using it. This also
3112      * adjusts suite B digest if necessary.
3113      */
3114     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3115         !tls1_check_chain(s, NULL, NULL, NULL, -2))
3116         return 0;
3117     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3118     /* See if we can use client certificate for fixed DH */
3119     if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3120         int i = s->session->peer_type;
3121         EVP_PKEY *clkey = NULL, *spkey = NULL;
3122         clkey = s->cert->key->privatekey;
3123         /* If client key not DH assume it can be used */
3124         if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
3125             return 1;
3126         if (i >= 0)
3127             spkey = X509_get_pubkey(s->session->peer);
3128         if (spkey) {
3129             /* Compare server and client parameters */
3130             i = EVP_PKEY_cmp_parameters(clkey, spkey);
3131             EVP_PKEY_free(spkey);
3132             if (i != 1)
3133                 return 0;
3134         }
3135         s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3136     }
3137     return 1;
3138 }
3139
3140 int ssl3_send_client_certificate(SSL *s)
3141 {
3142     X509 *x509 = NULL;
3143     EVP_PKEY *pkey = NULL;
3144     int i;
3145
3146     if (s->state == SSL3_ST_CW_CERT_A) {
3147         /* Let cert callback update client certificates if required */
3148         if (s->cert->cert_cb) {
3149             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
3150             if (i < 0) {
3151                 s->rwstate = SSL_X509_LOOKUP;
3152                 return -1;
3153             }
3154             if (i == 0) {
3155                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3156                 s->state = SSL_ST_ERR;
3157                 return 0;
3158             }
3159             s->rwstate = SSL_NOTHING;
3160         }
3161         if (ssl3_check_client_certificate(s))
3162             s->state = SSL3_ST_CW_CERT_C;
3163         else
3164             s->state = SSL3_ST_CW_CERT_B;
3165     }
3166
3167     /* We need to get a client cert */
3168     if (s->state == SSL3_ST_CW_CERT_B) {
3169         /*
3170          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3171          * return(-1); We then get retied later
3172          */
3173         i = 0;
3174         i = ssl_do_client_cert_cb(s, &x509, &pkey);
3175         if (i < 0) {
3176             s->rwstate = SSL_X509_LOOKUP;
3177             return (-1);
3178         }
3179         s->rwstate = SSL_NOTHING;
3180         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3181             s->state = SSL3_ST_CW_CERT_B;
3182             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3183                 i = 0;
3184         } else if (i == 1) {
3185             i = 0;
3186             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
3187                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3188         }
3189
3190         X509_free(x509);
3191         EVP_PKEY_free(pkey);
3192         if (i && !ssl3_check_client_certificate(s))
3193             i = 0;
3194         if (i == 0) {
3195             if (s->version == SSL3_VERSION) {
3196                 s->s3->tmp.cert_req = 0;
3197                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3198                 return (1);
3199             } else {
3200                 s->s3->tmp.cert_req = 2;
3201                 if (!ssl3_digest_cached_records(s, 0)) {
3202                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3203                     s->state = SSL_ST_ERR;
3204                     return 0;
3205                 }
3206             }
3207         }
3208
3209         /* Ok, we have a cert */
3210         s->state = SSL3_ST_CW_CERT_C;
3211     }
3212
3213     if (s->state == SSL3_ST_CW_CERT_C) {
3214         s->state = SSL3_ST_CW_CERT_D;
3215         if (!ssl3_output_cert_chain(s,
3216                                     (s->s3->tmp.cert_req ==
3217                                      2) ? NULL : s->cert->key)) {
3218             SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3219             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3220             s->state = SSL_ST_ERR;
3221             return 0;
3222         }
3223     }
3224     /* SSL3_ST_CW_CERT_D */
3225     return ssl_do_write(s);
3226 }
3227
3228 #define has_bits(i,m)   (((i)&(m)) == (m))
3229
3230 int ssl3_check_cert_and_algorithm(SSL *s)
3231 {
3232     int i, idx;
3233     long alg_k, alg_a;
3234     EVP_PKEY *pkey = NULL;
3235     int pkey_bits;
3236 #ifndef OPENSSL_NO_RSA
3237     RSA *rsa;
3238 #endif
3239 #ifndef OPENSSL_NO_DH
3240     DH *dh;
3241 #endif
3242     int al = SSL_AD_HANDSHAKE_FAILURE;
3243
3244     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3245     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3246
3247     /* we don't have a certificate */
3248     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
3249         return (1);
3250 #ifndef OPENSSL_NO_RSA
3251     rsa = s->s3->peer_rsa_tmp;
3252 #endif
3253 #ifndef OPENSSL_NO_DH
3254     dh = s->s3->peer_dh_tmp;
3255 #endif
3256
3257     /* This is the passed certificate */
3258
3259     idx = s->session->peer_type;
3260 #ifndef OPENSSL_NO_EC
3261     if (idx == SSL_PKEY_ECC) {
3262         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
3263             /* check failed */
3264             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3265             goto f_err;
3266         } else {
3267             return 1;
3268         }
3269     } else if (alg_a & SSL_aECDSA) {
3270         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3271                SSL_R_MISSING_ECDSA_SIGNING_CERT);
3272         goto f_err;
3273     } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
3274         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT);
3275         goto f_err;
3276     }
3277 #endif
3278     pkey = X509_get_pubkey(s->session->peer);
3279     pkey_bits = EVP_PKEY_bits(pkey);
3280     i = X509_certificate_type(s->session->peer, pkey);
3281     EVP_PKEY_free(pkey);
3282
3283     /* Check that we have a certificate if we require one */
3284     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3285         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3286                SSL_R_MISSING_RSA_SIGNING_CERT);
3287         goto f_err;
3288     }
3289 #ifndef OPENSSL_NO_DSA
3290     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3291         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3292                SSL_R_MISSING_DSA_SIGNING_CERT);
3293         goto f_err;
3294     }
3295 #endif
3296 #ifndef OPENSSL_NO_RSA
3297     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3298         if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3299             !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3300             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3301                    SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3302             goto f_err;
3303         } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
3304             if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3305                 if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3306                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3307                            SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3308                     goto f_err;
3309                 }
3310                 if (rsa != NULL) {
3311                     /* server key exchange is not allowed. */
3312                     al = SSL_AD_INTERNAL_ERROR;
3313                     SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3314                     goto f_err;
3315                 }
3316             }
3317         }
3318     }
3319 #endif
3320 #ifndef OPENSSL_NO_DH
3321     if ((alg_k & SSL_kDHE) && (dh == NULL)) {
3322         al = SSL_AD_INTERNAL_ERROR;
3323         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3324         goto f_err;
3325     } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
3326                !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3327         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3328                SSL_R_MISSING_DH_RSA_CERT);
3329         goto f_err;
3330     }
3331 # ifndef OPENSSL_NO_DSA
3332     else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
3333              !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3334         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3335                SSL_R_MISSING_DH_DSA_CERT);
3336         goto f_err;
3337     }
3338 # endif
3339 #endif
3340
3341     if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3342         pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3343 #ifndef OPENSSL_NO_RSA
3344         if (alg_k & SSL_kRSA) {
3345             if (rsa == NULL) {
3346                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3347                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3348                 goto f_err;
3349             } else if (RSA_bits(rsa) >
3350                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3351                 /* We have a temporary RSA key but it's too large. */
3352                 al = SSL_AD_EXPORT_RESTRICTION;
3353                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3354                        SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3355                 goto f_err;
3356             }
3357         } else
3358 #endif
3359 #ifndef OPENSSL_NO_DH
3360         if (alg_k & SSL_kDHE) {
3361             if (DH_bits(dh) >
3362                 SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3363                 /* We have a temporary DH key but it's too large. */
3364                 al = SSL_AD_EXPORT_RESTRICTION;
3365                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3366                        SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3367                 goto f_err;
3368             }
3369         } else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3370             /* The cert should have had an export DH key. */
3371             al = SSL_AD_EXPORT_RESTRICTION;
3372             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3373                    SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3374                 goto f_err;
3375         } else
3376 #endif
3377         {
3378             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3379                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3380             goto f_err;
3381         }
3382     }
3383     return (1);
3384  f_err:
3385     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3386     return (0);
3387 }
3388
3389 /*
3390  * Normally, we can tell if the server is resuming the session from
3391  * the session ID. EAP-FAST (RFC 4851), however, relies on the next server
3392  * message after the ServerHello to determine if the server is resuming.
3393  * Therefore, we allow EAP-FAST to peek ahead.
3394  * ssl3_check_change returns 1 if we are resuming from an external
3395  * pre-shared secret, we have a "ticket" and the next server message
3396  * is CCS; and 0 otherwise. It returns -1 upon an error.
3397  */
3398 static int ssl3_check_change(SSL *s)
3399 {
3400     int ok = 0;
3401
3402     if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
3403         !s->session->tlsext_tick)
3404         return 0;
3405
3406     /*
3407      * This function is called when we might get a Certificate message instead,
3408      * so permit appropriate message length.
3409      * We ignore the return value as we're only interested in the message type
3410      * and not its length.
3411      */
3412     s->method->ssl_get_message(s,
3413                                SSL3_ST_CR_CERT_A,
3414                                SSL3_ST_CR_CERT_B,
3415                                -1, s->max_cert_list, &ok);
3416
3417     if (!ok)
3418         return -1;
3419
3420     s->s3->tmp.reuse_message = 1;
3421
3422     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC)
3423         return 1;
3424
3425     return 0;
3426 }
3427
3428 #ifndef OPENSSL_NO_NEXTPROTONEG
3429 int ssl3_send_next_proto(SSL *s)
3430 {
3431     unsigned int len, padding_len;
3432     unsigned char *d;
3433
3434     if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
3435         len = s->next_proto_negotiated_len;
3436         padding_len = 32 - ((len + 2) % 32);
3437         d = (unsigned char *)s->init_buf->data;
3438         d[4] = len;
3439         memcpy(d + 5, s->next_proto_negotiated, len);
3440         d[5 + len] = padding_len;
3441         memset(d + 6 + len, 0, padding_len);
3442         *(d++) = SSL3_MT_NEXT_PROTO;
3443         l2n3(2 + len + padding_len, d);
3444         s->state = SSL3_ST_CW_NEXT_PROTO_B;
3445         s->init_num = 4 + 2 + len + padding_len;
3446         s->init_off = 0;
3447     }
3448
3449     return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3450 }
3451 #endif
3452
3453 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3454 {
3455     int i = 0;
3456 #ifndef OPENSSL_NO_ENGINE
3457     if (s->ctx->client_cert_engine) {
3458         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3459                                         SSL_get_client_CA_list(s),
3460                                         px509, ppkey, NULL, NULL, NULL);
3461         if (i != 0)
3462             return i;
3463     }
3464 #endif
3465     if (s->ctx->client_cert_cb)
3466         i = s->ctx->client_cert_cb(s, px509, ppkey);
3467     return i;
3468 }
3469
3470 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
3471                              unsigned char *p,
3472                              int (*put_cb) (const SSL_CIPHER *,
3473                                             unsigned char *))
3474 {
3475     int i, j = 0;
3476     SSL_CIPHER *c;
3477     unsigned char *q;
3478     int empty_reneg_info_scsv = !s->renegotiate;
3479     /* Set disabled masks for this session */
3480     ssl_set_client_disabled(s);
3481
3482     if (sk == NULL)
3483         return (0);
3484     q = p;
3485     if (put_cb == NULL)
3486         put_cb = s->method->put_cipher_by_char;
3487
3488     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3489         c = sk_SSL_CIPHER_value(sk, i);
3490         /* Skip disabled ciphers */
3491         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3492             continue;
3493 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3494         if (c->id == SSL3_CK_SCSV) {
3495             if (!empty_reneg_info_scsv)
3496                 continue;
3497             else
3498                 empty_reneg_info_scsv = 0;
3499         }
3500 #endif
3501         j = put_cb(c, p);
3502         p += j;
3503     }
3504     /*
3505      * If p == q, no ciphers; caller indicates an error. Otherwise, add
3506      * applicable SCSVs.
3507      */
3508     if (p != q) {
3509         if (empty_reneg_info_scsv) {
3510             static SSL_CIPHER scsv = {
3511                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3512             };
3513             j = put_cb(&scsv, p);
3514             p += j;
3515 #ifdef OPENSSL_RI_DEBUG
3516             fprintf(stderr,
3517                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
3518 #endif
3519         }
3520         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3521             static SSL_CIPHER scsv = {
3522                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3523             };
3524             j = put_cb(&scsv, p);
3525             p += j;
3526         }
3527     }
3528
3529     return (p - q);
3530 }