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