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