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