Run util/openssl-format-source -v -c .
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.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-2005 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 #define REUSE_CIPHER_BUG
126 #define NETSCAPE_HANG_BUG
127
128 #include <stdio.h>
129 #include "ssl_locl.h"
130 #include "kssl_lcl.h"
131 #include "../crypto/constant_time_locl.h"
132 #include <openssl/buffer.h>
133 #include <openssl/rand.h>
134 #include <openssl/objects.h>
135 #include <openssl/evp.h>
136 #include <openssl/hmac.h>
137 #include <openssl/x509.h>
138 #ifndef OPENSSL_NO_DH
139 # include <openssl/dh.h>
140 #endif
141 #include <openssl/bn.h>
142 #ifndef OPENSSL_NO_KRB5
143 # include <openssl/krb5_asn.h>
144 #endif
145 #include <openssl/md5.h>
146
147 static SSL_METHOD *ssl3_get_server_method(int ver);
148 #ifndef OPENSSL_NO_ECDH
149 static int nid2curve_id(int nid);
150 #endif
151
152 static SSL_METHOD *ssl3_get_server_method(int ver)
153 {
154     if (ver == SSL3_VERSION)
155         return (SSLv3_server_method());
156     else
157         return (NULL);
158 }
159
160 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
161                          ssl3_accept,
162                          ssl_undefined_function, ssl3_get_server_method)
163
164 int ssl3_accept(SSL *s)
165 {
166     BUF_MEM *buf;
167     unsigned long l, Time = (unsigned long)time(NULL);
168     void (*cb) (const SSL *ssl, int type, int val) = NULL;
169     int ret = -1;
170     int new_state, state, skip = 0;
171
172     RAND_add(&Time, sizeof(Time), 0);
173     ERR_clear_error();
174     clear_sys_error();
175
176     if (s->info_callback != NULL)
177         cb = s->info_callback;
178     else if (s->ctx->info_callback != NULL)
179         cb = s->ctx->info_callback;
180
181     /* init things to blank */
182     s->in_handshake++;
183     if (!SSL_in_init(s) || SSL_in_before(s))
184         SSL_clear(s);
185
186     if (s->cert == NULL) {
187         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
188         return (-1);
189     }
190
191     for (;;) {
192         state = s->state;
193
194         switch (s->state) {
195         case SSL_ST_RENEGOTIATE:
196             s->new_session = 1;
197             /* s->state=SSL_ST_ACCEPT; */
198
199         case SSL_ST_BEFORE:
200         case SSL_ST_ACCEPT:
201         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
202         case SSL_ST_OK | SSL_ST_ACCEPT:
203
204             s->server = 1;
205             if (cb != NULL)
206                 cb(s, SSL_CB_HANDSHAKE_START, 1);
207
208             if ((s->version >> 8) != 3) {
209                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
210                 return -1;
211             }
212             s->type = SSL_ST_ACCEPT;
213
214             if (s->init_buf == NULL) {
215                 if ((buf = BUF_MEM_new()) == NULL) {
216                     ret = -1;
217                     goto end;
218                 }
219                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
220                     ret = -1;
221                     goto end;
222                 }
223                 s->init_buf = buf;
224             }
225
226             if (!ssl3_setup_buffers(s)) {
227                 ret = -1;
228                 goto end;
229             }
230
231             s->init_num = 0;
232             s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
233
234             if (s->state != SSL_ST_RENEGOTIATE) {
235                 /*
236                  * Ok, we now need to push on a buffering BIO so that the
237                  * output is sent in a way that TCP likes :-)
238                  */
239                 if (!ssl_init_wbio_buffer(s, 1)) {
240                     ret = -1;
241                     goto end;
242                 }
243
244                 ssl3_init_finished_mac(s);
245                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
246                 s->ctx->stats.sess_accept++;
247             } else if (!s->s3->send_connection_binding &&
248                        !(s->options &
249                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
250                 /*
251                  * Server attempting to renegotiate with client that doesn't
252                  * support secure renegotiation.
253                  */
254                 SSLerr(SSL_F_SSL3_ACCEPT,
255                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
256                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
257                 ret = -1;
258                 goto end;
259             } else {
260                 /*
261                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
262                  * HelloRequest
263                  */
264                 s->ctx->stats.sess_accept_renegotiate++;
265                 s->state = SSL3_ST_SW_HELLO_REQ_A;
266             }
267             break;
268
269         case SSL3_ST_SW_HELLO_REQ_A:
270         case SSL3_ST_SW_HELLO_REQ_B:
271
272             s->shutdown = 0;
273             ret = ssl3_send_hello_request(s);
274             if (ret <= 0)
275                 goto end;
276             s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
277             s->state = SSL3_ST_SW_FLUSH;
278             s->init_num = 0;
279
280             ssl3_init_finished_mac(s);
281             break;
282
283         case SSL3_ST_SW_HELLO_REQ_C:
284             s->state = SSL_ST_OK;
285             break;
286
287         case SSL3_ST_SR_CLNT_HELLO_A:
288         case SSL3_ST_SR_CLNT_HELLO_B:
289         case SSL3_ST_SR_CLNT_HELLO_C:
290
291             s->shutdown = 0;
292             ret = ssl3_get_client_hello(s);
293             if (ret <= 0)
294                 goto end;
295             s->new_session = 2;
296             s->state = SSL3_ST_SW_SRVR_HELLO_A;
297             s->init_num = 0;
298             break;
299
300         case SSL3_ST_SW_SRVR_HELLO_A:
301         case SSL3_ST_SW_SRVR_HELLO_B:
302             ret = ssl3_send_server_hello(s);
303             if (ret <= 0)
304                 goto end;
305 #ifndef OPENSSL_NO_TLSEXT
306             if (s->hit) {
307                 if (s->tlsext_ticket_expected)
308                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
309                 else
310                     s->state = SSL3_ST_SW_CHANGE_A;
311             }
312 #else
313             if (s->hit)
314                 s->state = SSL3_ST_SW_CHANGE_A;
315 #endif
316             else
317                 s->state = SSL3_ST_SW_CERT_A;
318             s->init_num = 0;
319             break;
320
321         case SSL3_ST_SW_CERT_A:
322         case SSL3_ST_SW_CERT_B:
323             /* Check if it is anon DH or anon ECDH or KRB5 */
324             if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL)
325                 && !(s->s3->tmp.new_cipher->algorithms & SSL_aKRB5)) {
326                 ret = ssl3_send_server_certificate(s);
327                 if (ret <= 0)
328                     goto end;
329 #ifndef OPENSSL_NO_TLSEXT
330                 if (s->tlsext_status_expected)
331                     s->state = SSL3_ST_SW_CERT_STATUS_A;
332                 else
333                     s->state = SSL3_ST_SW_KEY_EXCH_A;
334             } else {
335                 skip = 1;
336                 s->state = SSL3_ST_SW_KEY_EXCH_A;
337             }
338 #else
339             } else
340                 skip = 1;
341
342             s->state = SSL3_ST_SW_KEY_EXCH_A;
343 #endif
344             s->init_num = 0;
345             break;
346
347         case SSL3_ST_SW_KEY_EXCH_A:
348         case SSL3_ST_SW_KEY_EXCH_B:
349             l = s->s3->tmp.new_cipher->algorithms;
350
351             /*
352              * clear this, it may get reset by send_server_key_exchange
353              */
354             s->s3->tmp.use_rsa_tmp = 0;
355
356             /*
357              * only send if a DH key exchange, fortezza or RSA but we have a
358              * sign only certificate For ECC ciphersuites, we send a
359              * serverKeyExchange message only if the cipher suite is either
360              * ECDH-anon or ECDHE. In other cases, the server certificate
361              * contains the server's public key for key exchange.
362              */
363             if ((l & SSL_kECDHE)
364                 || (l & (SSL_DH | SSL_kFZA))
365                 || ((l & SSL_kRSA)
366                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
367                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
368                             && EVP_PKEY_size(s->cert->
369                                              pkeys
370                                              [SSL_PKEY_RSA_ENC].privatekey) *
371                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
372                         )
373                     )
374                 )
375                 ) {
376                 ret = ssl3_send_server_key_exchange(s);
377                 if (ret <= 0)
378                     goto end;
379             } else
380                 skip = 1;
381
382             s->state = SSL3_ST_SW_CERT_REQ_A;
383             s->init_num = 0;
384             break;
385
386         case SSL3_ST_SW_CERT_REQ_A:
387         case SSL3_ST_SW_CERT_REQ_B:
388             if (                /* don't request cert unless asked for it: */
389                    !(s->verify_mode & SSL_VERIFY_PEER) ||
390                    /*
391                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
392                     * during re-negotiation:
393                     */
394                    ((s->session->peer != NULL) &&
395                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
396                    /*
397                     * never request cert in anonymous ciphersuites (see
398                     * section "Certificate request" in SSL 3 drafts and in
399                     * RFC 2246):
400                     */
401                    ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
402                     /*
403                      * ... except when the application insists on
404                      * verification (against the specs, but s3_clnt.c accepts
405                      * this for SSL 3)
406                      */
407                     !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
408                    /*
409                     * never request cert in Kerberos ciphersuites
410                     */
411                    (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5)) {
412                 /* no cert request */
413                 skip = 1;
414                 s->s3->tmp.cert_request = 0;
415                 s->state = SSL3_ST_SW_SRVR_DONE_A;
416             } else {
417                 s->s3->tmp.cert_request = 1;
418                 ret = ssl3_send_certificate_request(s);
419                 if (ret <= 0)
420                     goto end;
421 #ifndef NETSCAPE_HANG_BUG
422                 s->state = SSL3_ST_SW_SRVR_DONE_A;
423 #else
424                 s->state = SSL3_ST_SW_FLUSH;
425                 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
426 #endif
427                 s->init_num = 0;
428             }
429             break;
430
431         case SSL3_ST_SW_SRVR_DONE_A:
432         case SSL3_ST_SW_SRVR_DONE_B:
433             ret = ssl3_send_server_done(s);
434             if (ret <= 0)
435                 goto end;
436             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
437             s->state = SSL3_ST_SW_FLUSH;
438             s->init_num = 0;
439             break;
440
441         case SSL3_ST_SW_FLUSH:
442
443             /*
444              * This code originally checked to see if any data was pending
445              * using BIO_CTRL_INFO and then flushed. This caused problems as
446              * documented in PR#1939. The proposed fix doesn't completely
447              * resolve this issue as buggy implementations of
448              * BIO_CTRL_PENDING still exist. So instead we just flush
449              * unconditionally.
450              */
451
452             s->rwstate = SSL_WRITING;
453             if (BIO_flush(s->wbio) <= 0) {
454                 ret = -1;
455                 goto end;
456             }
457             s->rwstate = SSL_NOTHING;
458
459             s->state = s->s3->tmp.next_state;
460             break;
461
462         case SSL3_ST_SR_CERT_A:
463         case SSL3_ST_SR_CERT_B:
464             /* Check for second client hello (MS SGC) */
465             ret = ssl3_check_client_hello(s);
466             if (ret <= 0)
467                 goto end;
468             if (ret == 2)
469                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
470             else {
471                 if (s->s3->tmp.cert_request) {
472                     ret = ssl3_get_client_certificate(s);
473                     if (ret <= 0)
474                         goto end;
475                 }
476                 s->init_num = 0;
477                 s->state = SSL3_ST_SR_KEY_EXCH_A;
478             }
479             break;
480
481         case SSL3_ST_SR_KEY_EXCH_A:
482         case SSL3_ST_SR_KEY_EXCH_B:
483             ret = ssl3_get_client_key_exchange(s);
484             if (ret <= 0)
485                 goto end;
486             if (ret == 2) {
487                 /*
488                  * For the ECDH ciphersuites when the client sends its ECDH
489                  * pub key in a certificate, the CertificateVerify message is
490                  * not sent.
491                  */
492                 s->state = SSL3_ST_SR_FINISHED_A;
493                 s->init_num = 0;
494             } else {
495                 s->state = SSL3_ST_SR_CERT_VRFY_A;
496                 s->init_num = 0;
497
498                 /*
499                  * We need to get hashes here so if there is a client cert,
500                  * it can be verified
501                  */
502                 s->method->ssl3_enc->cert_verify_mac(s,
503                                                      &(s->s3->finish_dgst1),
504                                                      &(s->s3->
505                                                        tmp.cert_verify_md
506                                                        [0]));
507                 s->method->ssl3_enc->cert_verify_mac(s,
508                                                      &(s->s3->finish_dgst2),
509                                                      &(s->s3->
510                                                        tmp.cert_verify_md
511                                                        [MD5_DIGEST_LENGTH]));
512             }
513             break;
514
515         case SSL3_ST_SR_CERT_VRFY_A:
516         case SSL3_ST_SR_CERT_VRFY_B:
517
518             s->s3->flags |= SSL3_FLAGS_CCS_OK;
519             /* we should decide if we expected this one */
520             ret = ssl3_get_cert_verify(s);
521             if (ret <= 0)
522                 goto end;
523
524             s->state = SSL3_ST_SR_FINISHED_A;
525             s->init_num = 0;
526             break;
527
528         case SSL3_ST_SR_FINISHED_A:
529         case SSL3_ST_SR_FINISHED_B:
530             s->s3->flags |= SSL3_FLAGS_CCS_OK;
531             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
532                                     SSL3_ST_SR_FINISHED_B);
533             if (ret <= 0)
534                 goto end;
535             if (s->hit)
536                 s->state = SSL_ST_OK;
537 #ifndef OPENSSL_NO_TLSEXT
538             else if (s->tlsext_ticket_expected)
539                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
540 #endif
541             else
542                 s->state = SSL3_ST_SW_CHANGE_A;
543             s->init_num = 0;
544             break;
545
546 #ifndef OPENSSL_NO_TLSEXT
547         case SSL3_ST_SW_SESSION_TICKET_A:
548         case SSL3_ST_SW_SESSION_TICKET_B:
549             ret = ssl3_send_newsession_ticket(s);
550             if (ret <= 0)
551                 goto end;
552             s->state = SSL3_ST_SW_CHANGE_A;
553             s->init_num = 0;
554             break;
555
556         case SSL3_ST_SW_CERT_STATUS_A:
557         case SSL3_ST_SW_CERT_STATUS_B:
558             ret = ssl3_send_cert_status(s);
559             if (ret <= 0)
560                 goto end;
561             s->state = SSL3_ST_SW_KEY_EXCH_A;
562             s->init_num = 0;
563             break;
564
565 #endif
566
567         case SSL3_ST_SW_CHANGE_A:
568         case SSL3_ST_SW_CHANGE_B:
569
570             s->session->cipher = s->s3->tmp.new_cipher;
571             if (!s->method->ssl3_enc->setup_key_block(s)) {
572                 ret = -1;
573                 goto end;
574             }
575
576             ret = ssl3_send_change_cipher_spec(s,
577                                                SSL3_ST_SW_CHANGE_A,
578                                                SSL3_ST_SW_CHANGE_B);
579
580             if (ret <= 0)
581                 goto end;
582             s->state = SSL3_ST_SW_FINISHED_A;
583             s->init_num = 0;
584
585             if (!s->method->ssl3_enc->change_cipher_state(s,
586                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
587             {
588                 ret = -1;
589                 goto end;
590             }
591
592             break;
593
594         case SSL3_ST_SW_FINISHED_A:
595         case SSL3_ST_SW_FINISHED_B:
596             ret = ssl3_send_finished(s,
597                                      SSL3_ST_SW_FINISHED_A,
598                                      SSL3_ST_SW_FINISHED_B,
599                                      s->method->
600                                      ssl3_enc->server_finished_label,
601                                      s->method->
602                                      ssl3_enc->server_finished_label_len);
603             if (ret <= 0)
604                 goto end;
605             s->state = SSL3_ST_SW_FLUSH;
606             if (s->hit)
607                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
608             else
609                 s->s3->tmp.next_state = SSL_ST_OK;
610             s->init_num = 0;
611             break;
612
613         case SSL_ST_OK:
614             /* clean a few things up */
615             ssl3_cleanup_key_block(s);
616
617             BUF_MEM_free(s->init_buf);
618             s->init_buf = NULL;
619
620             /* remove buffering on output */
621             ssl_free_wbio_buffer(s);
622
623             s->init_num = 0;
624
625             if (s->new_session == 2) { /* skipped if we just sent a
626                                         * HelloRequest */
627                 /*
628                  * actually not necessarily a 'new' session unless
629                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set
630                  */
631
632                 s->new_session = 0;
633
634                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
635
636                 s->ctx->stats.sess_accept_good++;
637                 /* s->server=1; */
638                 s->handshake_func = ssl3_accept;
639
640                 if (cb != NULL)
641                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
642             }
643
644             ret = 1;
645             goto end;
646             /* break; */
647
648         default:
649             SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
650             ret = -1;
651             goto end;
652             /* break; */
653         }
654
655         if (!s->s3->tmp.reuse_message && !skip) {
656             if (s->debug) {
657                 if ((ret = BIO_flush(s->wbio)) <= 0)
658                     goto end;
659             }
660
661             if ((cb != NULL) && (s->state != state)) {
662                 new_state = s->state;
663                 s->state = state;
664                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
665                 s->state = new_state;
666             }
667         }
668         skip = 0;
669     }
670  end:
671     /* BIO_flush(s->wbio); */
672
673     s->in_handshake--;
674     if (cb != NULL)
675         cb(s, SSL_CB_ACCEPT_EXIT, ret);
676     return (ret);
677 }
678
679 int ssl3_send_hello_request(SSL *s)
680 {
681     unsigned char *p;
682
683     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
684         p = (unsigned char *)s->init_buf->data;
685         *(p++) = SSL3_MT_HELLO_REQUEST;
686         *(p++) = 0;
687         *(p++) = 0;
688         *(p++) = 0;
689
690         s->state = SSL3_ST_SW_HELLO_REQ_B;
691         /* number of bytes to write */
692         s->init_num = 4;
693         s->init_off = 0;
694     }
695
696     /* SSL3_ST_SW_HELLO_REQ_B */
697     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
698 }
699
700 int ssl3_check_client_hello(SSL *s)
701 {
702     int ok;
703     long n;
704
705     /*
706      * this function is called when we really expect a Certificate message,
707      * so permit appropriate message length
708      */
709     n = s->method->ssl_get_message(s,
710                                    SSL3_ST_SR_CERT_A,
711                                    SSL3_ST_SR_CERT_B,
712                                    -1, s->max_cert_list, &ok);
713     if (!ok)
714         return ((int)n);
715     s->s3->tmp.reuse_message = 1;
716     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO) {
717         /*
718          * We only allow the client to restart the handshake once per
719          * negotiation.
720          */
721         if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE) {
722             SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO,
723                    SSL_R_MULTIPLE_SGC_RESTARTS);
724             return -1;
725         }
726         /*
727          * Throw away what we have done so far in the current handshake,
728          * which will now be aborted. (A full SSL_clear would be too much.)
729          */
730 #ifndef OPENSSL_NO_DH
731         if (s->s3->tmp.dh != NULL) {
732             DH_free(s->s3->tmp.dh);
733             s->s3->tmp.dh = NULL;
734         }
735 #endif
736 #ifndef OPENSSL_NO_ECDH
737         if (s->s3->tmp.ecdh != NULL) {
738             EC_KEY_free(s->s3->tmp.ecdh);
739             s->s3->tmp.ecdh = NULL;
740         }
741 #endif
742         s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
743         return 2;
744     }
745     return 1;
746 }
747
748 int ssl3_get_client_hello(SSL *s)
749 {
750     int i, j, ok, al, ret = -1;
751     unsigned int cookie_len;
752     long n;
753     unsigned long id;
754     unsigned char *p, *d, *q;
755     SSL_CIPHER *c;
756 #ifndef OPENSSL_NO_COMP
757     SSL_COMP *comp = NULL;
758 #endif
759     STACK_OF(SSL_CIPHER) *ciphers = NULL;
760
761     /*
762      * We do this so that we will respond with our native type. If we are
763      * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
764      * switching should be handled by a different method. If we are SSLv3, we
765      * will respond with SSLv3, even if prompted with TLSv1.
766      */
767     if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
768         s->state = SSL3_ST_SR_CLNT_HELLO_B;
769     }
770     s->first_packet = 1;
771     n = s->method->ssl_get_message(s,
772                                    SSL3_ST_SR_CLNT_HELLO_B,
773                                    SSL3_ST_SR_CLNT_HELLO_C,
774                                    SSL3_MT_CLIENT_HELLO,
775                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
776
777     if (!ok)
778         return ((int)n);
779     s->first_packet = 0;
780     d = p = (unsigned char *)s->init_msg;
781
782     /*
783      * use version from inside client hello, not from record header (may
784      * differ: see RFC 2246, Appendix E, second paragraph)
785      */
786     s->client_version = (((int)p[0]) << 8) | (int)p[1];
787     p += 2;
788
789     if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
790         (s->version != DTLS1_VERSION && s->client_version < s->version)) {
791         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
792         if ((s->client_version >> 8) == SSL3_VERSION_MAJOR) {
793             /*
794              * similar to ssl3_get_record, send alert using remote version
795              * number
796              */
797             s->version = s->client_version;
798         }
799         al = SSL_AD_PROTOCOL_VERSION;
800         goto f_err;
801     }
802
803     /*
804      * If we require cookies and this ClientHello doesn't contain one, just
805      * return since we do not want to allocate any memory yet. So check
806      * cookie length...
807      */
808     if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
809         unsigned int session_length, cookie_length;
810
811         session_length = *(p + SSL3_RANDOM_SIZE);
812         cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
813
814         if (cookie_length == 0)
815             return 1;
816     }
817
818     /* load the client random */
819     memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
820     p += SSL3_RANDOM_SIZE;
821
822     /* get the session-id */
823     j = *(p++);
824
825     s->hit = 0;
826     /*
827      * Versions before 0.9.7 always allow session reuse during renegotiation
828      * (i.e. when s->new_session is true), option
829      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7. Maybe
830      * this optional behaviour should always have been the default, but we
831      * cannot safely change the default behaviour (or new applications might
832      * be written that become totally unsecure when compiled with an earlier
833      * library version)
834      */
835     if ((s->new_session
836          && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
837         if (!ssl_get_new_session(s, 1))
838             goto err;
839     } else {
840         i = ssl_get_prev_session(s, p, j, d + n);
841         if (i == 1) {           /* previous session */
842             s->hit = 1;
843         } else if (i == -1)
844             goto err;
845         else {                  /* i == 0 */
846
847             if (!ssl_get_new_session(s, 1))
848                 goto err;
849         }
850     }
851
852     p += j;
853
854     if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
855         /* cookie stuff */
856         cookie_len = *(p++);
857
858         /*
859          * The ClientHello may contain a cookie even if the
860          * HelloVerify message has not been sent--make sure that it
861          * does not cause an overflow.
862          */
863         if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
864             /* too much data */
865             al = SSL_AD_DECODE_ERROR;
866             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
867             goto f_err;
868         }
869
870         /* verify the cookie if appropriate option is set. */
871         if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
872             memcpy(s->d1->rcvd_cookie, p, cookie_len);
873
874             if (s->ctx->app_verify_cookie_cb != NULL) {
875                 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
876                                                  cookie_len) == 0) {
877                     al = SSL_AD_HANDSHAKE_FAILURE;
878                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
879                            SSL_R_COOKIE_MISMATCH);
880                     goto f_err;
881                 }
882                 /* else cookie verification succeeded */
883             }
884             /* default verification */
885             else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
886                             s->d1->cookie_len) != 0) {
887                 al = SSL_AD_HANDSHAKE_FAILURE;
888                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
889                 goto f_err;
890             }
891
892             ret = 2;
893         }
894
895         p += cookie_len;
896     }
897
898     n2s(p, i);
899     if ((i == 0) && (j != 0)) {
900         /* we need a cipher if we are not resuming a session */
901         al = SSL_AD_ILLEGAL_PARAMETER;
902         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
903         goto f_err;
904     }
905     if ((p + i) >= (d + n)) {
906         /* not enough data */
907         al = SSL_AD_DECODE_ERROR;
908         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
909         goto f_err;
910     }
911     if ((i > 0) && (ssl_bytes_to_cipher_list(s, p, i, &(ciphers))
912                     == NULL)) {
913         goto err;
914     }
915     p += i;
916
917     /* If it is a hit, check that the cipher is in the list */
918     if ((s->hit) && (i > 0)) {
919         j = 0;
920         id = s->session->cipher->id;
921
922 #ifdef CIPHER_DEBUG
923         printf("client sent %d ciphers\n", sk_num(ciphers));
924 #endif
925         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
926             c = sk_SSL_CIPHER_value(ciphers, i);
927 #ifdef CIPHER_DEBUG
928             printf("client [%2d of %2d]:%s\n",
929                    i, sk_num(ciphers), SSL_CIPHER_get_name(c));
930 #endif
931             if (c->id == id) {
932                 j = 1;
933                 break;
934             }
935         }
936         /*
937          * Disabled because it can be used in a ciphersuite downgrade attack:
938          * CVE-2010-4180.
939          */
940 #if 0
941         if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
942             && (sk_SSL_CIPHER_num(ciphers) == 1)) {
943             /*
944              * Special case as client bug workaround: the previously used
945              * cipher may not be in the current list, the client instead
946              * might be trying to continue using a cipher that before wasn't
947              * chosen due to server preferences.  We'll have to reject the
948              * connection if the cipher is not enabled, though.
949              */
950             c = sk_SSL_CIPHER_value(ciphers, 0);
951             if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
952                 s->session->cipher = c;
953                 j = 1;
954             }
955         }
956 #endif
957         if (j == 0) {
958             /*
959              * we need to have the cipher in the cipher list if we are asked
960              * to reuse it
961              */
962             al = SSL_AD_ILLEGAL_PARAMETER;
963             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
964                    SSL_R_REQUIRED_CIPHER_MISSING);
965             goto f_err;
966         }
967     }
968
969     /* compression */
970     i = *(p++);
971     if ((p + i) > (d + n)) {
972         /* not enough data */
973         al = SSL_AD_DECODE_ERROR;
974         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
975         goto f_err;
976     }
977     q = p;
978     for (j = 0; j < i; j++) {
979         if (p[j] == 0)
980             break;
981     }
982
983     p += i;
984     if (j >= i) {
985         /* no compress */
986         al = SSL_AD_DECODE_ERROR;
987         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
988         goto f_err;
989     }
990 #ifndef OPENSSL_NO_TLSEXT
991     /* TLS extensions */
992     if (s->version >= SSL3_VERSION) {
993         if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
994             /* 'al' set by ssl_parse_clienthello_tlsext */
995             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
996             goto f_err;
997         }
998     }
999     if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1000         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1001         goto err;
1002     }
1003 #endif
1004     /*
1005      * Worst case, we will use the NULL compression, but if we have other
1006      * options, we will now look for them.  We have i-1 compression
1007      * algorithms from the client, starting at q.
1008      */
1009     s->s3->tmp.new_compression = NULL;
1010 #ifndef OPENSSL_NO_COMP
1011     if (s->ctx->comp_methods != NULL) {
1012         /* See if we have a match */
1013         int m, nn, o, v, done = 0;
1014
1015         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1016         for (m = 0; m < nn; m++) {
1017             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1018             v = comp->id;
1019             for (o = 0; o < i; o++) {
1020                 if (v == q[o]) {
1021                     done = 1;
1022                     break;
1023                 }
1024             }
1025             if (done)
1026                 break;
1027         }
1028         if (done)
1029             s->s3->tmp.new_compression = comp;
1030         else
1031             comp = NULL;
1032     }
1033 #endif
1034
1035     /* TLS does not mind if there is extra stuff */
1036 #if 0
1037     /*
1038      * SSL 3.0 does not mind either, so we should disable this test (was
1039      * enabled in 0.9.6d through 0.9.6j and 0.9.7 through 0.9.7b, in earlier
1040      * SSLeay/OpenSSL releases this test existed but was buggy)
1041      */
1042     if (s->version == SSL3_VERSION) {
1043         if (p < (d + n)) {
1044             /*
1045              * wrong number of bytes, there could be more to follow
1046              */
1047             al = SSL_AD_DECODE_ERROR;
1048             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1049             goto f_err;
1050         }
1051     }
1052 #endif
1053
1054     /*
1055      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1056      */
1057
1058     if (!s->hit) {
1059 #ifdef OPENSSL_NO_COMP
1060         s->session->compress_meth = 0;
1061 #else
1062         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1063 #endif
1064         if (s->session->ciphers != NULL)
1065             sk_SSL_CIPHER_free(s->session->ciphers);
1066         s->session->ciphers = ciphers;
1067         if (ciphers == NULL) {
1068             al = SSL_AD_ILLEGAL_PARAMETER;
1069             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_PASSED);
1070             goto f_err;
1071         }
1072         ciphers = NULL;
1073         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1074
1075         if (c == NULL) {
1076             al = SSL_AD_HANDSHAKE_FAILURE;
1077             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1078             goto f_err;
1079         }
1080         s->s3->tmp.new_cipher = c;
1081     } else {
1082         /* Session-id reuse */
1083 #ifdef REUSE_CIPHER_BUG
1084         STACK_OF(SSL_CIPHER) *sk;
1085         SSL_CIPHER *nc = NULL;
1086         SSL_CIPHER *ec = NULL;
1087
1088         if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1089             sk = s->session->ciphers;
1090             for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1091                 c = sk_SSL_CIPHER_value(sk, i);
1092                 if (c->algorithms & SSL_eNULL)
1093                     nc = c;
1094                 if (SSL_C_IS_EXPORT(c))
1095                     ec = c;
1096             }
1097             if (nc != NULL)
1098                 s->s3->tmp.new_cipher = nc;
1099             else if (ec != NULL)
1100                 s->s3->tmp.new_cipher = ec;
1101             else
1102                 s->s3->tmp.new_cipher = s->session->cipher;
1103         } else
1104 #endif
1105             s->s3->tmp.new_cipher = s->session->cipher;
1106     }
1107
1108         /*-
1109          * we now have the following setup.
1110          * client_random
1111          * cipher_list          - our prefered list of ciphers
1112          * ciphers              - the clients prefered list of ciphers
1113          * compression          - basically ignored right now
1114          * ssl version is set   - sslv3
1115          * s->session           - The ssl session has been setup.
1116          * s->hit               - session reuse flag
1117          * s->tmp.new_cipher    - the new cipher to use.
1118          */
1119
1120 #ifndef OPENSSL_NO_TLSEXT
1121     /* Handles TLS extensions that we couldn't check earlier */
1122     if (s->version >= SSL3_VERSION) {
1123         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1124             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1125             goto err;
1126         }
1127     }
1128 #endif
1129
1130     if (ret < 0)
1131         ret = 1;
1132     if (0) {
1133  f_err:
1134         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1135     }
1136  err:
1137     if (ciphers != NULL)
1138         sk_SSL_CIPHER_free(ciphers);
1139     return (ret);
1140 }
1141
1142 int ssl3_send_server_hello(SSL *s)
1143 {
1144     unsigned char *buf;
1145     unsigned char *p, *d;
1146     int i, sl;
1147     unsigned long l, Time;
1148
1149     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1150         buf = (unsigned char *)s->init_buf->data;
1151         p = s->s3->server_random;
1152         Time = (unsigned long)time(NULL); /* Time */
1153         l2n(Time, p);
1154         if (RAND_pseudo_bytes(p, SSL3_RANDOM_SIZE - 4) <= 0)
1155             return -1;
1156         /* Do the message type and length last */
1157         d = p = &(buf[4]);
1158
1159         *(p++) = s->version >> 8;
1160         *(p++) = s->version & 0xff;
1161
1162         /* Random stuff */
1163         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1164         p += SSL3_RANDOM_SIZE;
1165
1166         /*
1167          * now in theory we have 3 options to sending back the session id.
1168          * If it is a re-use, we send back the old session-id, if it is a new
1169          * session, we send back the new session-id or we send back a 0
1170          * length session-id if we want it to be single use. Currently I will
1171          * not implement the '0' length session-id 12-Jan-98 - I'll now
1172          * support the '0' length stuff. We also have an additional case
1173          * where stateless session resumption is successful: we always send
1174          * back the old session id. In this case s->hit is non zero: this can
1175          * only happen if stateless session resumption is succesful if session
1176          * caching is disabled so existing functionality is unaffected.
1177          */
1178         if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1179             && !s->hit)
1180             s->session->session_id_length = 0;
1181
1182         sl = s->session->session_id_length;
1183         if (sl > (int)sizeof(s->session->session_id)) {
1184             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1185             return -1;
1186         }
1187         *(p++) = sl;
1188         memcpy(p, s->session->session_id, sl);
1189         p += sl;
1190
1191         /* put the cipher */
1192         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1193         p += i;
1194
1195         /* put the compression method */
1196 #ifdef OPENSSL_NO_COMP
1197         *(p++) = 0;
1198 #else
1199         if (s->s3->tmp.new_compression == NULL)
1200             *(p++) = 0;
1201         else
1202             *(p++) = s->s3->tmp.new_compression->id;
1203 #endif
1204 #ifndef OPENSSL_NO_TLSEXT
1205         if ((p =
1206              ssl_add_serverhello_tlsext(s, p,
1207                                         buf + SSL3_RT_MAX_PLAIN_LENGTH)) ==
1208             NULL) {
1209             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1210             return -1;
1211         }
1212 #endif
1213         /* do the header */
1214         l = (p - d);
1215         d = buf;
1216         *(d++) = SSL3_MT_SERVER_HELLO;
1217         l2n3(l, d);
1218
1219         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1220         /* number of bytes to write */
1221         s->init_num = p - buf;
1222         s->init_off = 0;
1223     }
1224
1225     /* SSL3_ST_SW_SRVR_HELLO_B */
1226     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1227 }
1228
1229 int ssl3_send_server_done(SSL *s)
1230 {
1231     unsigned char *p;
1232
1233     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1234         p = (unsigned char *)s->init_buf->data;
1235
1236         /* do the header */
1237         *(p++) = SSL3_MT_SERVER_DONE;
1238         *(p++) = 0;
1239         *(p++) = 0;
1240         *(p++) = 0;
1241
1242         s->state = SSL3_ST_SW_SRVR_DONE_B;
1243         /* number of bytes to write */
1244         s->init_num = 4;
1245         s->init_off = 0;
1246     }
1247
1248     /* SSL3_ST_SW_SRVR_DONE_B */
1249     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1250 }
1251
1252 int ssl3_send_server_key_exchange(SSL *s)
1253 {
1254 #ifndef OPENSSL_NO_RSA
1255     unsigned char *q;
1256     int j, num;
1257     RSA *rsa;
1258     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1259     unsigned int u;
1260 #endif
1261 #ifndef OPENSSL_NO_DH
1262     DH *dh = NULL, *dhp;
1263 #endif
1264 #ifndef OPENSSL_NO_ECDH
1265     EC_KEY *ecdh = NULL, *ecdhp;
1266     unsigned char *encodedPoint = NULL;
1267     int encodedlen = 0;
1268     int curve_id = 0;
1269     BN_CTX *bn_ctx = NULL;
1270 #endif
1271     EVP_PKEY *pkey;
1272     unsigned char *p, *d;
1273     int al, i;
1274     unsigned long type;
1275     int n;
1276     CERT *cert;
1277     BIGNUM *r[4];
1278     int nr[4], kn;
1279     BUF_MEM *buf;
1280     EVP_MD_CTX md_ctx;
1281
1282     EVP_MD_CTX_init(&md_ctx);
1283     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1284         type = s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1285         cert = s->cert;
1286
1287         buf = s->init_buf;
1288
1289         r[0] = r[1] = r[2] = r[3] = NULL;
1290         n = 0;
1291 #ifndef OPENSSL_NO_RSA
1292         if (type & SSL_kRSA) {
1293             rsa = cert->rsa_tmp;
1294             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1295                 rsa = s->cert->rsa_tmp_cb(s,
1296                                           SSL_C_IS_EXPORT(s->s3->
1297                                                           tmp.new_cipher),
1298                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1299                                                                   tmp.new_cipher));
1300                 if (rsa == NULL) {
1301                     al = SSL_AD_HANDSHAKE_FAILURE;
1302                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1303                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1304                     goto f_err;
1305                 }
1306                 RSA_up_ref(rsa);
1307                 cert->rsa_tmp = rsa;
1308             }
1309             if (rsa == NULL) {
1310                 al = SSL_AD_HANDSHAKE_FAILURE;
1311                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1312                        SSL_R_MISSING_TMP_RSA_KEY);
1313                 goto f_err;
1314             }
1315             r[0] = rsa->n;
1316             r[1] = rsa->e;
1317             s->s3->tmp.use_rsa_tmp = 1;
1318         } else
1319 #endif
1320 #ifndef OPENSSL_NO_DH
1321         if (type & SSL_kEDH) {
1322             dhp = cert->dh_tmp;
1323             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1324                 dhp = s->cert->dh_tmp_cb(s,
1325                                          SSL_C_IS_EXPORT(s->s3->
1326                                                          tmp.new_cipher),
1327                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1328                                                                  tmp.new_cipher));
1329             if (dhp == NULL) {
1330                 al = SSL_AD_HANDSHAKE_FAILURE;
1331                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1332                        SSL_R_MISSING_TMP_DH_KEY);
1333                 goto f_err;
1334             }
1335
1336             if (s->s3->tmp.dh != NULL) {
1337                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1338                        ERR_R_INTERNAL_ERROR);
1339                 goto err;
1340             }
1341
1342             if ((dh = DHparams_dup(dhp)) == NULL) {
1343                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1344                 goto err;
1345             }
1346
1347             s->s3->tmp.dh = dh;
1348             if ((dhp->pub_key == NULL ||
1349                  dhp->priv_key == NULL ||
1350                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1351                 if (!DH_generate_key(dh)) {
1352                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1353                     goto err;
1354                 }
1355             } else {
1356                 dh->pub_key = BN_dup(dhp->pub_key);
1357                 dh->priv_key = BN_dup(dhp->priv_key);
1358                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1359                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1360                     goto err;
1361                 }
1362             }
1363             r[0] = dh->p;
1364             r[1] = dh->g;
1365             r[2] = dh->pub_key;
1366         } else
1367 #endif
1368 #ifndef OPENSSL_NO_ECDH
1369         if (type & SSL_kECDHE) {
1370             const EC_GROUP *group;
1371
1372             ecdhp = cert->ecdh_tmp;
1373             if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL)) {
1374                 ecdhp = s->cert->ecdh_tmp_cb(s,
1375                                              SSL_C_IS_EXPORT(s->s3->
1376                                                              tmp.new_cipher),
1377                                              SSL_C_EXPORT_PKEYLENGTH(s->
1378                                                                      s3->tmp.new_cipher));
1379             }
1380             if (ecdhp == NULL) {
1381                 al = SSL_AD_HANDSHAKE_FAILURE;
1382                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1383                        SSL_R_MISSING_TMP_ECDH_KEY);
1384                 goto f_err;
1385             }
1386
1387             if (s->s3->tmp.ecdh != NULL) {
1388                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1389                        ERR_R_INTERNAL_ERROR);
1390                 goto err;
1391             }
1392
1393             /* Duplicate the ECDH structure. */
1394             if (ecdhp == NULL) {
1395                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1396                 goto err;
1397             }
1398             if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1399                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1400                 goto err;
1401             }
1402
1403             s->s3->tmp.ecdh = ecdh;
1404             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1405                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1406                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1407                 if (!EC_KEY_generate_key(ecdh)) {
1408                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1409                            ERR_R_ECDH_LIB);
1410                     goto err;
1411                 }
1412             }
1413
1414             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1415                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1416                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1417                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1418                 goto err;
1419             }
1420
1421             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1422                 (EC_GROUP_get_degree(group) > 163)) {
1423                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1424                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1425                 goto err;
1426             }
1427
1428             /*
1429              * XXX: For now, we only support ephemeral ECDH keys over named
1430              * (not generic) curves. For supported named curves, curve_id is
1431              * non-zero.
1432              */
1433             if ((curve_id = nid2curve_id(EC_GROUP_get_curve_name(group)))
1434                 == 0) {
1435                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1436                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1437                 goto err;
1438             }
1439
1440             /*
1441              * Encode the public key. First check the size of encoding and
1442              * allocate memory accordingly.
1443              */
1444             encodedlen = EC_POINT_point2oct(group,
1445                                             EC_KEY_get0_public_key(ecdh),
1446                                             POINT_CONVERSION_UNCOMPRESSED,
1447                                             NULL, 0, NULL);
1448
1449             encodedPoint = (unsigned char *)
1450                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1451             bn_ctx = BN_CTX_new();
1452             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1453                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1454                        ERR_R_MALLOC_FAILURE);
1455                 goto err;
1456             }
1457
1458             encodedlen = EC_POINT_point2oct(group,
1459                                             EC_KEY_get0_public_key(ecdh),
1460                                             POINT_CONVERSION_UNCOMPRESSED,
1461                                             encodedPoint, encodedlen, bn_ctx);
1462
1463             if (encodedlen == 0) {
1464                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1465                 goto err;
1466             }
1467
1468             BN_CTX_free(bn_ctx);
1469             bn_ctx = NULL;
1470
1471             /*
1472              * XXX: For now, we only support named (not generic) curves in
1473              * ECDH ephemeral key exchanges. In this situation, we need four
1474              * additional bytes to encode the entire ServerECDHParams
1475              * structure.
1476              */
1477             n = 4 + encodedlen;
1478
1479             /*
1480              * We'll generate the serverKeyExchange message explicitly so we
1481              * can set these to NULLs
1482              */
1483             r[0] = NULL;
1484             r[1] = NULL;
1485             r[2] = NULL;
1486             r[3] = NULL;
1487         } else
1488 #endif                          /* !OPENSSL_NO_ECDH */
1489         {
1490             al = SSL_AD_HANDSHAKE_FAILURE;
1491             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1492                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1493             goto f_err;
1494         }
1495         for (i = 0; r[i] != NULL; i++) {
1496             nr[i] = BN_num_bytes(r[i]);
1497             n += 2 + nr[i];
1498         }
1499
1500         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL)) {
1501             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher))
1502                 == NULL) {
1503                 al = SSL_AD_DECODE_ERROR;
1504                 goto f_err;
1505             }
1506             kn = EVP_PKEY_size(pkey);
1507         } else {
1508             pkey = NULL;
1509             kn = 0;
1510         }
1511
1512         if (!BUF_MEM_grow_clean(buf, n + 4 + kn)) {
1513             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1514             goto err;
1515         }
1516         d = (unsigned char *)s->init_buf->data;
1517         p = &(d[4]);
1518
1519         for (i = 0; r[i] != NULL; i++) {
1520             s2n(nr[i], p);
1521             BN_bn2bin(r[i], p);
1522             p += nr[i];
1523         }
1524
1525 #ifndef OPENSSL_NO_ECDH
1526         if (type & SSL_kECDHE) {
1527             /*
1528              * XXX: For now, we only support named (not generic) curves. In
1529              * this situation, the serverKeyExchange message has: [1 byte
1530              * CurveType], [2 byte CurveName] [1 byte length of encoded
1531              * point], followed by the actual encoded point itself
1532              */
1533             *p = NAMED_CURVE_TYPE;
1534             p += 1;
1535             *p = 0;
1536             p += 1;
1537             *p = curve_id;
1538             p += 1;
1539             *p = encodedlen;
1540             p += 1;
1541             memcpy((unsigned char *)p,
1542                    (unsigned char *)encodedPoint, encodedlen);
1543             OPENSSL_free(encodedPoint);
1544             encodedPoint = NULL;
1545             p += encodedlen;
1546         }
1547 #endif
1548
1549         /* not anonymous */
1550         if (pkey != NULL) {
1551             /*
1552              * n is the length of the params, they start at &(d[4]) and p
1553              * points to the space at the end.
1554              */
1555 #ifndef OPENSSL_NO_RSA
1556             if (pkey->type == EVP_PKEY_RSA) {
1557                 q = md_buf;
1558                 j = 0;
1559                 for (num = 2; num > 0; num--) {
1560                     EVP_MD_CTX_set_flags(&md_ctx,
1561                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1562                     EVP_DigestInit_ex(&md_ctx, (num == 2)
1563                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
1564                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1565                                      SSL3_RANDOM_SIZE);
1566                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1567                                      SSL3_RANDOM_SIZE);
1568                     EVP_DigestUpdate(&md_ctx, &(d[4]), n);
1569                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1570                     q += i;
1571                     j += i;
1572                 }
1573                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1574                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1575                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1576                     goto err;
1577                 }
1578                 s2n(u, p);
1579                 n += u + 2;
1580             } else
1581 #endif
1582 #if !defined(OPENSSL_NO_DSA)
1583             if (pkey->type == EVP_PKEY_DSA) {
1584                 /* lets do DSS */
1585                 EVP_SignInit_ex(&md_ctx, EVP_dss1(), NULL);
1586                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1587                                SSL3_RANDOM_SIZE);
1588                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1589                                SSL3_RANDOM_SIZE);
1590                 EVP_SignUpdate(&md_ctx, &(d[4]), n);
1591                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1592                                    (unsigned int *)&i, pkey)) {
1593                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_DSA);
1594                     goto err;
1595                 }
1596                 s2n(i, p);
1597                 n += i + 2;
1598             } else
1599 #endif
1600 #if !defined(OPENSSL_NO_ECDSA)
1601             if (pkey->type == EVP_PKEY_EC) {
1602                 /* let's do ECDSA */
1603                 EVP_SignInit_ex(&md_ctx, EVP_ecdsa(), NULL);
1604                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1605                                SSL3_RANDOM_SIZE);
1606                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1607                                SSL3_RANDOM_SIZE);
1608                 EVP_SignUpdate(&md_ctx, &(d[4]), n);
1609                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1610                                    (unsigned int *)&i, pkey)) {
1611                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1612                            ERR_LIB_ECDSA);
1613                     goto err;
1614                 }
1615                 s2n(i, p);
1616                 n += i + 2;
1617             } else
1618 #endif
1619             {
1620                 /* Is this error check actually needed? */
1621                 al = SSL_AD_HANDSHAKE_FAILURE;
1622                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1623                        SSL_R_UNKNOWN_PKEY_TYPE);
1624                 goto f_err;
1625             }
1626         }
1627
1628         *(d++) = SSL3_MT_SERVER_KEY_EXCHANGE;
1629         l2n3(n, d);
1630
1631         /*
1632          * we should now have things packed up, so lets send it off
1633          */
1634         s->init_num = n + 4;
1635         s->init_off = 0;
1636     }
1637
1638     s->state = SSL3_ST_SW_KEY_EXCH_B;
1639     EVP_MD_CTX_cleanup(&md_ctx);
1640     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1641  f_err:
1642     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1643  err:
1644 #ifndef OPENSSL_NO_ECDH
1645     if (encodedPoint != NULL)
1646         OPENSSL_free(encodedPoint);
1647     BN_CTX_free(bn_ctx);
1648 #endif
1649     EVP_MD_CTX_cleanup(&md_ctx);
1650     return (-1);
1651 }
1652
1653 int ssl3_send_certificate_request(SSL *s)
1654 {
1655     unsigned char *p, *d;
1656     int i, j, nl, off, n;
1657     STACK_OF(X509_NAME) *sk = NULL;
1658     X509_NAME *name;
1659     BUF_MEM *buf;
1660
1661     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
1662         buf = s->init_buf;
1663
1664         d = p = (unsigned char *)&(buf->data[4]);
1665
1666         /* get the list of acceptable cert types */
1667         p++;
1668         n = ssl3_get_req_cert_type(s, p);
1669         d[0] = n;
1670         p += n;
1671         n++;
1672
1673         off = n;
1674         p += 2;
1675         n += 2;
1676
1677         sk = SSL_get_client_CA_list(s);
1678         nl = 0;
1679         if (sk != NULL) {
1680             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1681                 name = sk_X509_NAME_value(sk, i);
1682                 j = i2d_X509_NAME(name, NULL);
1683                 if (!BUF_MEM_grow_clean(buf, 4 + n + j + 2)) {
1684                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
1685                            ERR_R_BUF_LIB);
1686                     goto err;
1687                 }
1688                 p = (unsigned char *)&(buf->data[4 + n]);
1689                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
1690                     s2n(j, p);
1691                     i2d_X509_NAME(name, &p);
1692                     n += 2 + j;
1693                     nl += 2 + j;
1694                 } else {
1695                     d = p;
1696                     i2d_X509_NAME(name, &p);
1697                     j -= 2;
1698                     s2n(j, d);
1699                     j += 2;
1700                     n += j;
1701                     nl += j;
1702                 }
1703             }
1704         }
1705         /* else no CA names */
1706         p = (unsigned char *)&(buf->data[4 + off]);
1707         s2n(nl, p);
1708
1709         d = (unsigned char *)buf->data;
1710         *(d++) = SSL3_MT_CERTIFICATE_REQUEST;
1711         l2n3(n, d);
1712
1713         /*
1714          * we should now have things packed up, so lets send it off
1715          */
1716
1717         s->init_num = n + 4;
1718         s->init_off = 0;
1719 #ifdef NETSCAPE_HANG_BUG
1720         if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
1721             SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
1722             goto err;
1723         }
1724         p = (unsigned char *)s->init_buf->data + s->init_num;
1725
1726         /* do the header */
1727         *(p++) = SSL3_MT_SERVER_DONE;
1728         *(p++) = 0;
1729         *(p++) = 0;
1730         *(p++) = 0;
1731         s->init_num += 4;
1732 #endif
1733
1734         s->state = SSL3_ST_SW_CERT_REQ_B;
1735     }
1736
1737     /* SSL3_ST_SW_CERT_REQ_B */
1738     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1739  err:
1740     return (-1);
1741 }
1742
1743 int ssl3_get_client_key_exchange(SSL *s)
1744 {
1745     int i, al, ok;
1746     long n;
1747     unsigned long l;
1748     unsigned char *p;
1749 #ifndef OPENSSL_NO_RSA
1750     RSA *rsa = NULL;
1751     EVP_PKEY *pkey = NULL;
1752 #endif
1753 #ifndef OPENSSL_NO_DH
1754     BIGNUM *pub = NULL;
1755     DH *dh_srvr;
1756 #endif
1757 #ifndef OPENSSL_NO_KRB5
1758     KSSL_ERR kssl_err;
1759 #endif                          /* OPENSSL_NO_KRB5 */
1760
1761 #ifndef OPENSSL_NO_ECDH
1762     EC_KEY *srvr_ecdh = NULL;
1763     EVP_PKEY *clnt_pub_pkey = NULL;
1764     EC_POINT *clnt_ecpoint = NULL;
1765     BN_CTX *bn_ctx = NULL;
1766 #endif
1767
1768     n = s->method->ssl_get_message(s,
1769                                    SSL3_ST_SR_KEY_EXCH_A,
1770                                    SSL3_ST_SR_KEY_EXCH_B,
1771                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
1772
1773     if (!ok)
1774         return ((int)n);
1775     p = (unsigned char *)s->init_msg;
1776
1777     l = s->s3->tmp.new_cipher->algorithms;
1778
1779 #ifndef OPENSSL_NO_RSA
1780     if (l & SSL_kRSA) {
1781         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1782         int decrypt_len;
1783         unsigned char decrypt_good, version_good;
1784
1785         /* FIX THIS UP EAY EAY EAY EAY */
1786         if (s->s3->tmp.use_rsa_tmp) {
1787             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1788                 rsa = s->cert->rsa_tmp;
1789             /*
1790              * Don't do a callback because rsa_tmp should be sent already
1791              */
1792             if (rsa == NULL) {
1793                 al = SSL_AD_HANDSHAKE_FAILURE;
1794                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1795                        SSL_R_MISSING_TMP_RSA_PKEY);
1796                 goto f_err;
1797
1798             }
1799         } else {
1800             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1801             if ((pkey == NULL) ||
1802                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
1803                 al = SSL_AD_HANDSHAKE_FAILURE;
1804                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1805                        SSL_R_MISSING_RSA_CERTIFICATE);
1806                 goto f_err;
1807             }
1808             rsa = pkey->pkey.rsa;
1809         }
1810
1811         /* TLS and [incidentally] DTLS, including pre-0.9.8f */
1812         if (s->version > SSL3_VERSION && s->client_version != DTLS1_BAD_VER) {
1813             n2s(p, i);
1814             if (n != i + 2) {
1815                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
1816                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1817                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1818                     goto err;
1819                 } else
1820                     p -= 2;
1821             } else
1822                 n = i;
1823         }
1824
1825         /*
1826          * We must not leak whether a decryption failure occurs because of
1827          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
1828          * section 7.4.7.1). The code follows that advice of the TLS RFC and
1829          * generates a random premaster secret for the case that the decrypt
1830          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
1831          */
1832
1833         /*
1834          * should be RAND_bytes, but we cannot work around a failure.
1835          */
1836         if (RAND_pseudo_bytes(rand_premaster_secret,
1837                               sizeof(rand_premaster_secret)) <= 0)
1838             goto err;
1839         decrypt_len =
1840             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1841         ERR_clear_error();
1842
1843         /*
1844          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
1845          * be 0xff if so and zero otherwise.
1846          */
1847         decrypt_good =
1848             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
1849
1850         /*
1851          * If the version in the decrypted pre-master secret is correct then
1852          * version_good will be 0xff, otherwise it'll be zero. The
1853          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1854          * (http://eprint.iacr.org/2003/052/) exploits the version number
1855          * check as a "bad version oracle". Thus version checks are done in
1856          * constant time and are treated like any other decryption error.
1857          */
1858         version_good =
1859             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
1860         version_good &=
1861             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
1862
1863         /*
1864          * The premaster secret must contain the same version number as the
1865          * ClientHello to detect version rollback attacks (strangely, the
1866          * protocol does not offer such protection for DH ciphersuites).
1867          * However, buggy clients exist that send the negotiated protocol
1868          * version instead if the server does not support the requested
1869          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1870          * clients.
1871          */
1872         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
1873             unsigned char workaround_good;
1874             workaround_good =
1875                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
1876             workaround_good &=
1877                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
1878             version_good |= workaround_good;
1879         }
1880
1881         /*
1882          * Both decryption and version must be good for decrypt_good to
1883          * remain non-zero (0xff).
1884          */
1885         decrypt_good &= version_good;
1886
1887         /*
1888          * Now copy rand_premaster_secret over p using decrypt_good_mask.
1889          */
1890         for (i = 0; i < (int)sizeof(rand_premaster_secret); i++) {
1891             p[i] = constant_time_select_8(decrypt_good, p[i],
1892                                           rand_premaster_secret[i]);
1893         }
1894
1895         s->session->master_key_length =
1896             s->method->ssl3_enc->generate_master_secret(s,
1897                                                         s->
1898                                                         session->master_key,
1899                                                         p, i);
1900         OPENSSL_cleanse(p, i);
1901     } else
1902 #endif
1903 #ifndef OPENSSL_NO_DH
1904     if (l & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
1905         n2s(p, i);
1906         if (n != i + 2) {
1907             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
1908                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1909                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1910                 goto err;
1911             } else {
1912                 p -= 2;
1913                 i = (int)n;
1914             }
1915         }
1916
1917         if (n == 0L) {          /* the parameters are in the cert */
1918             al = SSL_AD_HANDSHAKE_FAILURE;
1919             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1920                    SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1921             goto f_err;
1922         } else {
1923             if (s->s3->tmp.dh == NULL) {
1924                 al = SSL_AD_HANDSHAKE_FAILURE;
1925                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1926                        SSL_R_MISSING_TMP_DH_KEY);
1927                 goto f_err;
1928             } else
1929                 dh_srvr = s->s3->tmp.dh;
1930         }
1931
1932         pub = BN_bin2bn(p, i, NULL);
1933         if (pub == NULL) {
1934             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
1935             goto err;
1936         }
1937
1938         i = DH_compute_key(p, pub, dh_srvr);
1939
1940         if (i <= 0) {
1941             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
1942             BN_clear_free(pub);
1943             goto err;
1944         }
1945
1946         DH_free(s->s3->tmp.dh);
1947         s->s3->tmp.dh = NULL;
1948
1949         BN_clear_free(pub);
1950         pub = NULL;
1951         s->session->master_key_length =
1952             s->method->ssl3_enc->generate_master_secret(s,
1953                                                         s->
1954                                                         session->master_key,
1955                                                         p, i);
1956         OPENSSL_cleanse(p, i);
1957     } else
1958 #endif
1959 #ifndef OPENSSL_NO_KRB5
1960     if (l & SSL_kKRB5) {
1961         krb5_error_code krb5rc;
1962         krb5_data enc_ticket;
1963         krb5_data authenticator;
1964         krb5_data enc_pms;
1965         KSSL_CTX *kssl_ctx = s->kssl_ctx;
1966         EVP_CIPHER_CTX ciph_ctx;
1967         EVP_CIPHER *enc = NULL;
1968         unsigned char iv[EVP_MAX_IV_LENGTH];
1969         unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
1970         int padl, outl;
1971         krb5_timestamp authtime = 0;
1972         krb5_ticket_times ttimes;
1973
1974         EVP_CIPHER_CTX_init(&ciph_ctx);
1975
1976         if (!kssl_ctx)
1977             kssl_ctx = kssl_ctx_new();
1978
1979         n2s(p, i);
1980         enc_ticket.length = i;
1981
1982         if (n < (int)enc_ticket.length + 6) {
1983             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1984                    SSL_R_DATA_LENGTH_TOO_LONG);
1985             goto err;
1986         }
1987
1988         enc_ticket.data = (char *)p;
1989         p += enc_ticket.length;
1990
1991         n2s(p, i);
1992         authenticator.length = i;
1993
1994         if (n < (int)(enc_ticket.length + authenticator.length) + 6) {
1995             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1996                    SSL_R_DATA_LENGTH_TOO_LONG);
1997             goto err;
1998         }
1999
2000         authenticator.data = (char *)p;
2001         p += authenticator.length;
2002
2003         n2s(p, i);
2004         enc_pms.length = i;
2005         enc_pms.data = (char *)p;
2006         p += enc_pms.length;
2007
2008         /*
2009          * Note that the length is checked again below, ** after decryption
2010          */
2011         if (enc_pms.length > sizeof pms) {
2012             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2013                    SSL_R_DATA_LENGTH_TOO_LONG);
2014             goto err;
2015         }
2016
2017         if (n != (long)(enc_ticket.length + authenticator.length +
2018                         enc_pms.length + 6)) {
2019             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2020                    SSL_R_DATA_LENGTH_TOO_LONG);
2021             goto err;
2022         }
2023
2024         if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2025                                     &kssl_err)) != 0) {
2026 # ifdef KSSL_DEBUG
2027             printf("kssl_sget_tkt rtn %d [%d]\n", krb5rc, kssl_err.reason);
2028             if (kssl_err.text)
2029                 printf("kssl_err text= %s\n", kssl_err.text);
2030 # endif                         /* KSSL_DEBUG */
2031             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2032             goto err;
2033         }
2034
2035         /*
2036          * Note: no authenticator is not considered an error, ** but will
2037          * return authtime == 0.
2038          */
2039         if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2040                                          &authtime, &kssl_err)) != 0) {
2041 # ifdef KSSL_DEBUG
2042             printf("kssl_check_authent rtn %d [%d]\n",
2043                    krb5rc, kssl_err.reason);
2044             if (kssl_err.text)
2045                 printf("kssl_err text= %s\n", kssl_err.text);
2046 # endif                         /* KSSL_DEBUG */
2047             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2048             goto err;
2049         }
2050
2051         if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2052             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2053             goto err;
2054         }
2055 # ifdef KSSL_DEBUG
2056         kssl_ctx_show(kssl_ctx);
2057 # endif                         /* KSSL_DEBUG */
2058
2059         enc = kssl_map_enc(kssl_ctx->enctype);
2060         if (enc == NULL)
2061             goto err;
2062
2063         memset(iv, 0, sizeof iv); /* per RFC 1510 */
2064
2065         if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2066             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2067                    SSL_R_DECRYPTION_FAILED);
2068             goto err;
2069         }
2070         if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2071                                (unsigned char *)enc_pms.data, enc_pms.length))
2072         {
2073             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2074                    SSL_R_DECRYPTION_FAILED);
2075             goto err;
2076         }
2077         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2078             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2079                    SSL_R_DATA_LENGTH_TOO_LONG);
2080             goto err;
2081         }
2082         if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2083             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2084                    SSL_R_DECRYPTION_FAILED);
2085             goto err;
2086         }
2087         outl += padl;
2088         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2089             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2090                    SSL_R_DATA_LENGTH_TOO_LONG);
2091             goto err;
2092         }
2093         if (!((pms[0] == (s->client_version >> 8))
2094               && (pms[1] == (s->client_version & 0xff)))) {
2095             /*
2096              * The premaster secret must contain the same version number as
2097              * the ClientHello to detect version rollback attacks (strangely,
2098              * the protocol does not offer such protection for DH
2099              * ciphersuites). However, buggy clients exist that send random
2100              * bytes instead of the protocol version. If
2101              * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2102              * (Perhaps we should have a separate BUG value for the Kerberos
2103              * cipher)
2104              */
2105             if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2106                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2107                        SSL_AD_DECODE_ERROR);
2108                 goto err;
2109             }
2110         }
2111
2112         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2113
2114         s->session->master_key_length =
2115             s->method->ssl3_enc->generate_master_secret(s,
2116                                                         s->
2117                                                         session->master_key,
2118                                                         pms, outl);
2119
2120         if (kssl_ctx->client_princ) {
2121             size_t len = strlen(kssl_ctx->client_princ);
2122             if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2123                 s->session->krb5_client_princ_len = len;
2124                 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2125                        len);
2126             }
2127         }
2128
2129                 /*- Was doing kssl_ctx_free() here,
2130                  *  but it caused problems for apache.
2131                  *  kssl_ctx = kssl_ctx_free(kssl_ctx);
2132                  *  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2133                  */
2134     } else
2135 #endif                          /* OPENSSL_NO_KRB5 */
2136
2137 #ifndef OPENSSL_NO_ECDH
2138     if ((l & SSL_kECDH) || (l & SSL_kECDHE)) {
2139         int ret = 1;
2140         int field_size = 0;
2141         const EC_KEY *tkey;
2142         const EC_GROUP *group;
2143         const BIGNUM *priv_key;
2144
2145         /* initialize structures for server's ECDH key pair */
2146         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2147             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2148             goto err;
2149         }
2150
2151         /* Let's get server private key and group information */
2152         if (l & SSL_kECDH) {
2153             /* use the certificate */
2154             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2155         } else {
2156             /*
2157              * use the ephermeral values we saved when generating the
2158              * ServerKeyExchange msg.
2159              */
2160             tkey = s->s3->tmp.ecdh;
2161         }
2162
2163         group = EC_KEY_get0_group(tkey);
2164         priv_key = EC_KEY_get0_private_key(tkey);
2165
2166         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2167             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2168             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2169             goto err;
2170         }
2171
2172         /* Let's get client's public key */
2173         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2174             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2175             goto err;
2176         }
2177
2178         if (n == 0L) {
2179             /* Client Publickey was in Client Certificate */
2180
2181             if (l & SSL_kECDHE) {
2182                 al = SSL_AD_HANDSHAKE_FAILURE;
2183                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2184                        SSL_R_MISSING_TMP_ECDH_KEY);
2185                 goto f_err;
2186             }
2187             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2188                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2189                 /*
2190                  * XXX: For now, we do not support client authentication
2191                  * using ECDH certificates so this branch (n == 0L) of the
2192                  * code is never executed. When that support is added, we
2193                  * ought to ensure the key received in the certificate is
2194                  * authorized for key agreement. ECDH_compute_key implicitly
2195                  * checks that the two ECDH shares are for the same group.
2196                  */
2197                 al = SSL_AD_HANDSHAKE_FAILURE;
2198                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2199                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2200                 goto f_err;
2201             }
2202
2203             if (EC_POINT_copy(clnt_ecpoint,
2204                               EC_KEY_get0_public_key(clnt_pub_pkey->
2205                                                      pkey.ec)) == 0) {
2206                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2207                 goto err;
2208             }
2209             ret = 2;            /* Skip certificate verify processing */
2210         } else {
2211             /*
2212              * Get client's public key from encoded point in the
2213              * ClientKeyExchange message.
2214              */
2215             if ((bn_ctx = BN_CTX_new()) == NULL) {
2216                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2217                        ERR_R_MALLOC_FAILURE);
2218                 goto err;
2219             }
2220
2221             /* Get encoded point length */
2222             i = *p;
2223             p += 1;
2224             if (n != 1 + i) {
2225                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2226                 goto err;
2227             }
2228             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2229                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2230                 goto err;
2231             }
2232             /*
2233              * p is pointing to somewhere in the buffer currently, so set it
2234              * to the start
2235              */
2236             p = (unsigned char *)s->init_buf->data;
2237         }
2238
2239         /* Compute the shared pre-master secret */
2240         field_size = EC_GROUP_get_degree(group);
2241         if (field_size <= 0) {
2242             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2243             goto err;
2244         }
2245         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2246                              NULL);
2247         if (i <= 0) {
2248             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2249             goto err;
2250         }
2251
2252         EVP_PKEY_free(clnt_pub_pkey);
2253         EC_POINT_free(clnt_ecpoint);
2254         if (srvr_ecdh != NULL)
2255             EC_KEY_free(srvr_ecdh);
2256         BN_CTX_free(bn_ctx);
2257
2258         /* Compute the master secret */
2259         s->session->master_key_length =
2260             s->method->ssl3_enc->generate_master_secret(s,
2261                                                         s->
2262                                                         session->master_key,
2263                                                         p, i);
2264
2265         OPENSSL_cleanse(p, i);
2266         return (ret);
2267     } else
2268 #endif
2269     {
2270         al = SSL_AD_HANDSHAKE_FAILURE;
2271         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2272         goto f_err;
2273     }
2274
2275     return (1);
2276  f_err:
2277     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2278 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH)
2279  err:
2280 #endif
2281 #ifndef OPENSSL_NO_ECDH
2282     EVP_PKEY_free(clnt_pub_pkey);
2283     EC_POINT_free(clnt_ecpoint);
2284     if (srvr_ecdh != NULL)
2285         EC_KEY_free(srvr_ecdh);
2286     BN_CTX_free(bn_ctx);
2287 #endif
2288     return (-1);
2289 }
2290
2291 int ssl3_get_cert_verify(SSL *s)
2292 {
2293     EVP_PKEY *pkey = NULL;
2294     unsigned char *p;
2295     int al, ok, ret = 0;
2296     long n;
2297     int type = 0, i, j;
2298     X509 *peer;
2299
2300     n = s->method->ssl_get_message(s,
2301                                    SSL3_ST_SR_CERT_VRFY_A,
2302                                    SSL3_ST_SR_CERT_VRFY_B,
2303                                    -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2304
2305     if (!ok)
2306         return ((int)n);
2307
2308     if (s->session->peer != NULL) {
2309         peer = s->session->peer;
2310         pkey = X509_get_pubkey(peer);
2311         type = X509_certificate_type(peer, pkey);
2312     } else {
2313         peer = NULL;
2314         pkey = NULL;
2315     }
2316
2317     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2318         s->s3->tmp.reuse_message = 1;
2319         if (peer != NULL) {
2320             al = SSL_AD_UNEXPECTED_MESSAGE;
2321             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_MISSING_VERIFY_MESSAGE);
2322             goto f_err;
2323         }
2324         ret = 1;
2325         goto end;
2326     }
2327
2328     if (peer == NULL) {
2329         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_NO_CLIENT_CERT_RECEIVED);
2330         al = SSL_AD_UNEXPECTED_MESSAGE;
2331         goto f_err;
2332     }
2333
2334     if (!(type & EVP_PKT_SIGN)) {
2335         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2336                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2337         al = SSL_AD_ILLEGAL_PARAMETER;
2338         goto f_err;
2339     }
2340
2341     if (s->s3->change_cipher_spec) {
2342         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_CCS_RECEIVED_EARLY);
2343         al = SSL_AD_UNEXPECTED_MESSAGE;
2344         goto f_err;
2345     }
2346
2347     /* we now have a signature that we need to verify */
2348     p = (unsigned char *)s->init_msg;
2349     n2s(p, i);
2350     n -= 2;
2351     if (i > n) {
2352         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2353         al = SSL_AD_DECODE_ERROR;
2354         goto f_err;
2355     }
2356
2357     j = EVP_PKEY_size(pkey);
2358     if ((i > j) || (n > j) || (n <= 0)) {
2359         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2360         al = SSL_AD_DECODE_ERROR;
2361         goto f_err;
2362     }
2363 #ifndef OPENSSL_NO_RSA
2364     if (pkey->type == EVP_PKEY_RSA) {
2365         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2366                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2367                        pkey->pkey.rsa);
2368         if (i < 0) {
2369             al = SSL_AD_DECRYPT_ERROR;
2370             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2371             goto f_err;
2372         }
2373         if (i == 0) {
2374             al = SSL_AD_DECRYPT_ERROR;
2375             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2376             goto f_err;
2377         }
2378     } else
2379 #endif
2380 #ifndef OPENSSL_NO_DSA
2381     if (pkey->type == EVP_PKEY_DSA) {
2382         j = DSA_verify(pkey->save_type,
2383                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2384                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2385         if (j <= 0) {
2386             /* bad signature */
2387             al = SSL_AD_DECRYPT_ERROR;
2388             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
2389             goto f_err;
2390         }
2391     } else
2392 #endif
2393 #ifndef OPENSSL_NO_ECDSA
2394     if (pkey->type == EVP_PKEY_EC) {
2395         j = ECDSA_verify(pkey->save_type,
2396                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2397                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2398         if (j <= 0) {
2399             /* bad signature */
2400             al = SSL_AD_DECRYPT_ERROR;
2401             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2402             goto f_err;
2403         }
2404     } else
2405 #endif
2406     {
2407         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2408         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2409         goto f_err;
2410     }
2411
2412     ret = 1;
2413     if (0) {
2414  f_err:
2415         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2416     }
2417  end:
2418     EVP_PKEY_free(pkey);
2419     return (ret);
2420 }
2421
2422 int ssl3_get_client_certificate(SSL *s)
2423 {
2424     int i, ok, al, ret = -1;
2425     X509 *x = NULL;
2426     unsigned long l, nc, llen, n;
2427     const unsigned char *p, *q;
2428     unsigned char *d;
2429     STACK_OF(X509) *sk = NULL;
2430
2431     n = s->method->ssl_get_message(s,
2432                                    SSL3_ST_SR_CERT_A,
2433                                    SSL3_ST_SR_CERT_B,
2434                                    -1, s->max_cert_list, &ok);
2435
2436     if (!ok)
2437         return ((int)n);
2438
2439     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2440         if ((s->verify_mode & SSL_VERIFY_PEER) &&
2441             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2442             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2443                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2444             al = SSL_AD_HANDSHAKE_FAILURE;
2445             goto f_err;
2446         }
2447         /*
2448          * If tls asked for a client cert, the client must return a 0 list
2449          */
2450         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
2451             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2452                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2453             al = SSL_AD_UNEXPECTED_MESSAGE;
2454             goto f_err;
2455         }
2456         s->s3->tmp.reuse_message = 1;
2457         return (1);
2458     }
2459
2460     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
2461         al = SSL_AD_UNEXPECTED_MESSAGE;
2462         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
2463         goto f_err;
2464     }
2465     p = d = (unsigned char *)s->init_msg;
2466
2467     if ((sk = sk_X509_new_null()) == NULL) {
2468         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2469         goto err;
2470     }
2471
2472     n2l3(p, llen);
2473     if (llen + 3 != n) {
2474         al = SSL_AD_DECODE_ERROR;
2475         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2476         goto f_err;
2477     }
2478     for (nc = 0; nc < llen;) {
2479         n2l3(p, l);
2480         if ((l + nc + 3) > llen) {
2481             al = SSL_AD_DECODE_ERROR;
2482             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2483                    SSL_R_CERT_LENGTH_MISMATCH);
2484             goto f_err;
2485         }
2486
2487         q = p;
2488         x = d2i_X509(NULL, &p, l);
2489         if (x == NULL) {
2490             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2491             goto err;
2492         }
2493         if (p != (q + l)) {
2494             al = SSL_AD_DECODE_ERROR;
2495             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2496                    SSL_R_CERT_LENGTH_MISMATCH);
2497             goto f_err;
2498         }
2499         if (!sk_X509_push(sk, x)) {
2500             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2501             goto err;
2502         }
2503         x = NULL;
2504         nc += l + 3;
2505     }
2506
2507     if (sk_X509_num(sk) <= 0) {
2508         /* TLS does not mind 0 certs returned */
2509         if (s->version == SSL3_VERSION) {
2510             al = SSL_AD_HANDSHAKE_FAILURE;
2511             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2512                    SSL_R_NO_CERTIFICATES_RETURNED);
2513             goto f_err;
2514         }
2515         /* Fail for TLS only if we required a certificate */
2516         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2517                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2518             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2519                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2520             al = SSL_AD_HANDSHAKE_FAILURE;
2521             goto f_err;
2522         }
2523     } else {
2524         i = ssl_verify_cert_chain(s, sk);
2525         if (i <= 0) {
2526             al = ssl_verify_alarm_type(s->verify_result);
2527             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2528                    SSL_R_NO_CERTIFICATE_RETURNED);
2529             goto f_err;
2530         }
2531     }
2532
2533     if (s->session->peer != NULL) /* This should not be needed */
2534         X509_free(s->session->peer);
2535     s->session->peer = sk_X509_shift(sk);
2536     s->session->verify_result = s->verify_result;
2537
2538     /*
2539      * With the current implementation, sess_cert will always be NULL when we
2540      * arrive here.
2541      */
2542     if (s->session->sess_cert == NULL) {
2543         s->session->sess_cert = ssl_sess_cert_new();
2544         if (s->session->sess_cert == NULL) {
2545             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2546             goto err;
2547         }
2548     }
2549     if (s->session->sess_cert->cert_chain != NULL)
2550         sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2551     s->session->sess_cert->cert_chain = sk;
2552     /*
2553      * Inconsistency alert: cert_chain does *not* include the peer's own
2554      * certificate, while we do include it in s3_clnt.c
2555      */
2556
2557     sk = NULL;
2558
2559     ret = 1;
2560     if (0) {
2561  f_err:
2562         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2563     }
2564  err:
2565     if (x != NULL)
2566         X509_free(x);
2567     if (sk != NULL)
2568         sk_X509_pop_free(sk, X509_free);
2569     return (ret);
2570 }
2571
2572 int ssl3_send_server_certificate(SSL *s)
2573 {
2574     unsigned long l;
2575     X509 *x;
2576
2577     if (s->state == SSL3_ST_SW_CERT_A) {
2578         x = ssl_get_server_send_cert(s);
2579         if (x == NULL &&
2580             /* VRS: allow null cert if auth == KRB5 */
2581             (s->s3->tmp.new_cipher->algorithms
2582              & (SSL_MKEY_MASK | SSL_AUTH_MASK))
2583             != (SSL_aKRB5 | SSL_kKRB5)) {
2584             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2585             return (0);
2586         }
2587
2588         l = ssl3_output_cert_chain(s, x);
2589         s->state = SSL3_ST_SW_CERT_B;
2590         s->init_num = (int)l;
2591         s->init_off = 0;
2592     }
2593
2594     /* SSL3_ST_SW_CERT_B */
2595     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
2596 }
2597
2598 #ifndef OPENSSL_NO_ECDH
2599 /* This is the complement of curve_id2nid in s3_clnt.c. */
2600 static int nid2curve_id(int nid)
2601 {
2602     /*
2603      * ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001) (no changes
2604      * in draft-ietf-tls-ecc-03.txt [June 2003])
2605      */
2606     switch (nid) {
2607     case NID_sect163k1:        /* sect163k1 (1) */
2608         return 1;
2609     case NID_sect163r1:        /* sect163r1 (2) */
2610         return 2;
2611     case NID_sect163r2:        /* sect163r2 (3) */
2612         return 3;
2613     case NID_sect193r1:        /* sect193r1 (4) */
2614         return 4;
2615     case NID_sect193r2:        /* sect193r2 (5) */
2616         return 5;
2617     case NID_sect233k1:        /* sect233k1 (6) */
2618         return 6;
2619     case NID_sect233r1:        /* sect233r1 (7) */
2620         return 7;
2621     case NID_sect239k1:        /* sect239k1 (8) */
2622         return 8;
2623     case NID_sect283k1:        /* sect283k1 (9) */
2624         return 9;
2625     case NID_sect283r1:        /* sect283r1 (10) */
2626         return 10;
2627     case NID_sect409k1:        /* sect409k1 (11) */
2628         return 11;
2629     case NID_sect409r1:        /* sect409r1 (12) */
2630         return 12;
2631     case NID_sect571k1:        /* sect571k1 (13) */
2632         return 13;
2633     case NID_sect571r1:        /* sect571r1 (14) */
2634         return 14;
2635     case NID_secp160k1:        /* secp160k1 (15) */
2636         return 15;
2637     case NID_secp160r1:        /* secp160r1 (16) */
2638         return 16;
2639     case NID_secp160r2:        /* secp160r2 (17) */
2640         return 17;
2641     case NID_secp192k1:        /* secp192k1 (18) */
2642         return 18;
2643     case NID_X9_62_prime192v1: /* secp192r1 (19) */
2644         return 19;
2645     case NID_secp224k1:        /* secp224k1 (20) */
2646         return 20;
2647     case NID_secp224r1:        /* secp224r1 (21) */
2648         return 21;
2649     case NID_secp256k1:        /* secp256k1 (22) */
2650         return 22;
2651     case NID_X9_62_prime256v1: /* secp256r1 (23) */
2652         return 23;
2653     case NID_secp384r1:        /* secp384r1 (24) */
2654         return 24;
2655     case NID_secp521r1:        /* secp521r1 (25) */
2656         return 25;
2657     default:
2658         return 0;
2659     }
2660 }
2661 #endif
2662 #ifndef OPENSSL_NO_TLSEXT
2663 int ssl3_send_newsession_ticket(SSL *s)
2664 {
2665     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
2666         unsigned char *p, *senc, *macstart;
2667         int len, slen;
2668         unsigned int hlen;
2669         EVP_CIPHER_CTX ctx;
2670         HMAC_CTX hctx;
2671         SSL_CTX *tctx = s->initial_ctx;
2672         unsigned char iv[EVP_MAX_IV_LENGTH];
2673         unsigned char key_name[16];
2674
2675         /* get session encoding length */
2676         slen = i2d_SSL_SESSION(s->session, NULL);
2677         /*
2678          * Some length values are 16 bits, so forget it if session is too
2679          * long
2680          */
2681         if (slen > 0xFF00)
2682             return -1;
2683                 /*-
2684                  * Grow buffer if need be: the length calculation is as
2685                  * follows 1 (size of message name) + 3 (message length
2686                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2687                  * 16 (key name) + max_iv_len (iv length) +
2688                  * session_length + max_enc_block_size (max encrypted session
2689                  * length) + max_md_size (HMAC).
2690                  */
2691         if (!BUF_MEM_grow(s->init_buf,
2692                           26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2693                           EVP_MAX_MD_SIZE + slen))
2694             return -1;
2695         senc = OPENSSL_malloc(slen);
2696         if (!senc)
2697             return -1;
2698         p = senc;
2699         i2d_SSL_SESSION(s->session, &p);
2700
2701         p = (unsigned char *)s->init_buf->data;
2702         /* do the header */
2703         *(p++) = SSL3_MT_NEWSESSION_TICKET;
2704         /* Skip message length for now */
2705         p += 3;
2706         EVP_CIPHER_CTX_init(&ctx);
2707         HMAC_CTX_init(&hctx);
2708         /*
2709          * Initialize HMAC and cipher contexts. If callback present it does
2710          * all the work otherwise use generated values from parent ctx.
2711          */
2712         if (tctx->tlsext_ticket_key_cb) {
2713             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2714                                            &hctx, 1) < 0) {
2715                 OPENSSL_free(senc);
2716                 return -1;
2717             }
2718         } else {
2719             RAND_pseudo_bytes(iv, 16);
2720             EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2721                                tctx->tlsext_tick_aes_key, iv);
2722             HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2723                          tlsext_tick_md(), NULL);
2724             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2725         }
2726         l2n(s->session->tlsext_tick_lifetime_hint, p);
2727         /* Skip ticket length for now */
2728         p += 2;
2729         /* Output key name */
2730         macstart = p;
2731         memcpy(p, key_name, 16);
2732         p += 16;
2733         /* output IV */
2734         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2735         p += EVP_CIPHER_CTX_iv_length(&ctx);
2736         /* Encrypt session data */
2737         EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2738         p += len;
2739         EVP_EncryptFinal(&ctx, p, &len);
2740         p += len;
2741         EVP_CIPHER_CTX_cleanup(&ctx);
2742
2743         HMAC_Update(&hctx, macstart, p - macstart);
2744         HMAC_Final(&hctx, p, &hlen);
2745         HMAC_CTX_cleanup(&hctx);
2746
2747         p += hlen;
2748         /* Now write out lengths: p points to end of data written */
2749         /* Total length */
2750         len = p - (unsigned char *)s->init_buf->data;
2751         p = (unsigned char *)s->init_buf->data + 1;
2752         l2n3(len - 4, p);       /* Message length */
2753         p += 4;
2754         s2n(len - 10, p);       /* Ticket length */
2755
2756         /* number of bytes to write */
2757         s->init_num = len;
2758         s->state = SSL3_ST_SW_SESSION_TICKET_B;
2759         s->init_off = 0;
2760         OPENSSL_free(senc);
2761     }
2762
2763     /* SSL3_ST_SW_SESSION_TICKET_B */
2764     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
2765 }
2766
2767 int ssl3_send_cert_status(SSL *s)
2768 {
2769     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
2770         unsigned char *p;
2771                 /*-
2772                  * Grow buffer if need be: the length calculation is as
2773                  * follows 1 (message type) + 3 (message length) +
2774                  * 1 (ocsp response type) + 3 (ocsp response length)
2775                  * + (ocsp response)
2776                  */
2777         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
2778             return -1;
2779
2780         p = (unsigned char *)s->init_buf->data;
2781
2782         /* do the header */
2783         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
2784         /* message length */
2785         l2n3(s->tlsext_ocsp_resplen + 4, p);
2786         /* status type */
2787         *(p++) = s->tlsext_status_type;
2788         /* length of OCSP response */
2789         l2n3(s->tlsext_ocsp_resplen, p);
2790         /* actual response */
2791         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2792         /* number of bytes to write */
2793         s->init_num = 8 + s->tlsext_ocsp_resplen;
2794         s->state = SSL3_ST_SW_CERT_STATUS_B;
2795         s->init_off = 0;
2796     }
2797
2798     /* SSL3_ST_SW_CERT_STATUS_B */
2799     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
2800 }
2801 #endif