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