Fix DHE Null CKE vulnerability
[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 #ifndef OPENSSL_NO_SSL3_METHOD
174 static const SSL_METHOD *ssl3_get_server_method(int ver);
175
176 static const SSL_METHOD *ssl3_get_server_method(int ver)
177 {
178     if (ver == SSL3_VERSION)
179         return (SSLv3_server_method());
180     else
181         return (NULL);
182 }
183
184 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
185                          ssl3_accept,
186                          ssl_undefined_function, ssl3_get_server_method)
187 #endif
188 #ifndef OPENSSL_NO_SRP
189 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
190 {
191     int ret = SSL_ERROR_NONE;
192
193     *al = SSL_AD_UNRECOGNIZED_NAME;
194
195     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
196         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
197         if (s->srp_ctx.login == NULL) {
198             /*
199              * RFC 5054 says SHOULD reject, we do so if There is no srp
200              * login name
201              */
202             ret = SSL3_AL_FATAL;
203             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
204         } else {
205             ret = SSL_srp_server_param_with_username(s, al);
206         }
207     }
208     return ret;
209 }
210 #endif
211
212 int ssl3_accept(SSL *s)
213 {
214     BUF_MEM *buf;
215     unsigned long alg_k, Time = (unsigned long)time(NULL);
216     void (*cb) (const SSL *ssl, int type, int val) = NULL;
217     int ret = -1;
218     int new_state, state, skip = 0;
219
220     RAND_add(&Time, sizeof(Time), 0);
221     ERR_clear_error();
222     clear_sys_error();
223
224     if (s->info_callback != NULL)
225         cb = s->info_callback;
226     else if (s->ctx->info_callback != NULL)
227         cb = s->ctx->info_callback;
228
229     /* init things to blank */
230     s->in_handshake++;
231     if (!SSL_in_init(s) || SSL_in_before(s))
232         SSL_clear(s);
233
234     if (s->cert == NULL) {
235         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
236         return (-1);
237     }
238 #ifndef OPENSSL_NO_HEARTBEATS
239     /*
240      * If we're awaiting a HeartbeatResponse, pretend we already got and
241      * don't await it anymore, because Heartbeats don't make sense during
242      * handshakes anyway.
243      */
244     if (s->tlsext_hb_pending) {
245         s->tlsext_hb_pending = 0;
246         s->tlsext_hb_seq++;
247     }
248 #endif
249
250     for (;;) {
251         state = s->state;
252
253         switch (s->state) {
254         case SSL_ST_RENEGOTIATE:
255             s->renegotiate = 1;
256             /* s->state=SSL_ST_ACCEPT; */
257
258         case SSL_ST_BEFORE:
259         case SSL_ST_ACCEPT:
260         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
261         case SSL_ST_OK | SSL_ST_ACCEPT:
262
263             s->server = 1;
264             if (cb != NULL)
265                 cb(s, SSL_CB_HANDSHAKE_START, 1);
266
267             if ((s->version >> 8) != 3) {
268                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
269                 return -1;
270             }
271             s->type = SSL_ST_ACCEPT;
272
273             if (s->init_buf == NULL) {
274                 if ((buf = BUF_MEM_new()) == NULL) {
275                     ret = -1;
276                     goto end;
277                 }
278                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
279                     BUF_MEM_free(buf);
280                     ret = -1;
281                     goto end;
282                 }
283                 s->init_buf = buf;
284             }
285
286             if (!ssl3_setup_buffers(s)) {
287                 ret = -1;
288                 goto end;
289             }
290
291             s->init_num = 0;
292             s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
293             s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
294             /*
295              * Should have been reset by ssl3_get_finished, too.
296              */
297             s->s3->change_cipher_spec = 0;
298
299             if (s->state != SSL_ST_RENEGOTIATE) {
300                 /*
301                  * Ok, we now need to push on a buffering BIO so that the
302                  * output is sent in a way that TCP likes :-)
303                  */
304                 if (!ssl_init_wbio_buffer(s, 1)) {
305                     ret = -1;
306                     goto end;
307                 }
308
309                 ssl3_init_finished_mac(s);
310                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
311                 s->ctx->stats.sess_accept++;
312             } else if (!s->s3->send_connection_binding &&
313                        !(s->options &
314                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
315                 /*
316                  * Server attempting to renegotiate with client that doesn't
317                  * support secure renegotiation.
318                  */
319                 SSLerr(SSL_F_SSL3_ACCEPT,
320                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
321                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
322                 ret = -1;
323                 goto end;
324             } else {
325                 /*
326                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
327                  * HelloRequest
328                  */
329                 s->ctx->stats.sess_accept_renegotiate++;
330                 s->state = SSL3_ST_SW_HELLO_REQ_A;
331             }
332             break;
333
334         case SSL3_ST_SW_HELLO_REQ_A:
335         case SSL3_ST_SW_HELLO_REQ_B:
336
337             s->shutdown = 0;
338             ret = ssl3_send_hello_request(s);
339             if (ret <= 0)
340                 goto end;
341             s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
342             s->state = SSL3_ST_SW_FLUSH;
343             s->init_num = 0;
344
345             ssl3_init_finished_mac(s);
346             break;
347
348         case SSL3_ST_SW_HELLO_REQ_C:
349             s->state = SSL_ST_OK;
350             break;
351
352         case SSL3_ST_SR_CLNT_HELLO_A:
353         case SSL3_ST_SR_CLNT_HELLO_B:
354         case SSL3_ST_SR_CLNT_HELLO_C:
355
356             s->shutdown = 0;
357             ret = ssl3_get_client_hello(s);
358             if (ret <= 0)
359                 goto end;
360 #ifndef OPENSSL_NO_SRP
361             s->state = SSL3_ST_SR_CLNT_HELLO_D;
362         case SSL3_ST_SR_CLNT_HELLO_D:
363             {
364                 int al;
365                 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
366                     /*
367                      * callback indicates firther work to be done
368                      */
369                     s->rwstate = SSL_X509_LOOKUP;
370                     goto end;
371                 }
372                 if (ret != SSL_ERROR_NONE) {
373                     ssl3_send_alert(s, SSL3_AL_FATAL, al);
374                     /*
375                      * This is not really an error but the only means to for
376                      * a client to detect whether srp is supported.
377                      */
378                     if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
379                         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
380                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
381                     ret = -1;
382                     goto end;
383                 }
384             }
385 #endif
386
387             s->renegotiate = 2;
388             s->state = SSL3_ST_SW_SRVR_HELLO_A;
389             s->init_num = 0;
390             break;
391
392         case SSL3_ST_SW_SRVR_HELLO_A:
393         case SSL3_ST_SW_SRVR_HELLO_B:
394             ret = ssl3_send_server_hello(s);
395             if (ret <= 0)
396                 goto end;
397 #ifndef OPENSSL_NO_TLSEXT
398             if (s->hit) {
399                 if (s->tlsext_ticket_expected)
400                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
401                 else
402                     s->state = SSL3_ST_SW_CHANGE_A;
403             }
404 #else
405             if (s->hit)
406                 s->state = SSL3_ST_SW_CHANGE_A;
407 #endif
408             else
409                 s->state = SSL3_ST_SW_CERT_A;
410             s->init_num = 0;
411             break;
412
413         case SSL3_ST_SW_CERT_A:
414         case SSL3_ST_SW_CERT_B:
415             /* Check if it is anon DH or anon ECDH, */
416             /* normal PSK or KRB5 or SRP */
417             if (!
418                 (s->s3->tmp.
419                  new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
420                                                SSL_aSRP))
421 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
422                 ret = ssl3_send_server_certificate(s);
423                 if (ret <= 0)
424                     goto end;
425 #ifndef OPENSSL_NO_TLSEXT
426                 if (s->tlsext_status_expected)
427                     s->state = SSL3_ST_SW_CERT_STATUS_A;
428                 else
429                     s->state = SSL3_ST_SW_KEY_EXCH_A;
430             } else {
431                 skip = 1;
432                 s->state = SSL3_ST_SW_KEY_EXCH_A;
433             }
434 #else
435             } else
436                 skip = 1;
437
438             s->state = SSL3_ST_SW_KEY_EXCH_A;
439 #endif
440             s->init_num = 0;
441             break;
442
443         case SSL3_ST_SW_KEY_EXCH_A:
444         case SSL3_ST_SW_KEY_EXCH_B:
445             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
446
447             /*
448              * clear this, it may get reset by
449              * send_server_key_exchange
450              */
451             s->s3->tmp.use_rsa_tmp = 0;
452
453             /*
454              * only send if a DH key exchange, fortezza or RSA but we have a
455              * sign only certificate PSK: may send PSK identity hints For
456              * ECC ciphersuites, we send a serverKeyExchange message only if
457              * the cipher suite is either ECDH-anon or ECDHE. In other cases,
458              * the server certificate contains the server's public key for
459              * key exchange.
460              */
461             if (0
462                 /*
463                  * PSK: send ServerKeyExchange if PSK identity hint if
464                  * provided
465                  */
466 #ifndef OPENSSL_NO_PSK
467                 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
468 #endif
469 #ifndef OPENSSL_NO_SRP
470                 /* SRP: send ServerKeyExchange */
471                 || (alg_k & SSL_kSRP)
472 #endif
473                 || (alg_k & SSL_kEDH)
474                 || (alg_k & SSL_kEECDH)
475                 || ((alg_k & SSL_kRSA)
476                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
477                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
478                             && EVP_PKEY_size(s->cert->pkeys
479                                              [SSL_PKEY_RSA_ENC].privatekey) *
480                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
481                         )
482                     )
483                 )
484                 ) {
485                 ret = ssl3_send_server_key_exchange(s);
486                 if (ret <= 0)
487                     goto end;
488             } else
489                 skip = 1;
490
491             s->state = SSL3_ST_SW_CERT_REQ_A;
492             s->init_num = 0;
493             break;
494
495         case SSL3_ST_SW_CERT_REQ_A:
496         case SSL3_ST_SW_CERT_REQ_B:
497             if (                /* don't request cert unless asked for it: */
498                    !(s->verify_mode & SSL_VERIFY_PEER) ||
499                    /*
500                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
501                     * during re-negotiation:
502                     */
503                    ((s->session->peer != NULL) &&
504                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
505                    /*
506                     * never request cert in anonymous ciphersuites (see
507                     * section "Certificate request" in SSL 3 drafts and in
508                     * RFC 2246):
509                     */
510                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
511                     /*
512                      * ... except when the application insists on
513                      * verification (against the specs, but s3_clnt.c accepts
514                      * this for SSL 3)
515                      */
516                     !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
517                    /*
518                     * never request cert in Kerberos ciphersuites
519                     */
520                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
521                    /* don't request certificate for SRP auth */
522                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
523                    /*
524                     * With normal PSK Certificates and Certificate Requests
525                     * are omitted
526                     */
527                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
528                 /* no cert request */
529                 skip = 1;
530                 s->s3->tmp.cert_request = 0;
531                 s->state = SSL3_ST_SW_SRVR_DONE_A;
532                 if (s->s3->handshake_buffer)
533                     if (!ssl3_digest_cached_records(s))
534                         return -1;
535             } else {
536                 s->s3->tmp.cert_request = 1;
537                 ret = ssl3_send_certificate_request(s);
538                 if (ret <= 0)
539                     goto end;
540 #ifndef NETSCAPE_HANG_BUG
541                 s->state = SSL3_ST_SW_SRVR_DONE_A;
542 #else
543                 s->state = SSL3_ST_SW_FLUSH;
544                 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
545 #endif
546                 s->init_num = 0;
547             }
548             break;
549
550         case SSL3_ST_SW_SRVR_DONE_A:
551         case SSL3_ST_SW_SRVR_DONE_B:
552             ret = ssl3_send_server_done(s);
553             if (ret <= 0)
554                 goto end;
555             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
556             s->state = SSL3_ST_SW_FLUSH;
557             s->init_num = 0;
558             break;
559
560         case SSL3_ST_SW_FLUSH:
561
562             /*
563              * This code originally checked to see if any data was pending
564              * using BIO_CTRL_INFO and then flushed. This caused problems as
565              * documented in PR#1939. The proposed fix doesn't completely
566              * resolve this issue as buggy implementations of
567              * BIO_CTRL_PENDING still exist. So instead we just flush
568              * unconditionally.
569              */
570
571             s->rwstate = SSL_WRITING;
572             if (BIO_flush(s->wbio) <= 0) {
573                 ret = -1;
574                 goto end;
575             }
576             s->rwstate = SSL_NOTHING;
577
578             s->state = s->s3->tmp.next_state;
579             break;
580
581         case SSL3_ST_SR_CERT_A:
582         case SSL3_ST_SR_CERT_B:
583             if (s->s3->tmp.cert_request) {
584                 ret = ssl3_get_client_certificate(s);
585                 if (ret <= 0)
586                     goto end;
587             }
588             s->init_num = 0;
589             s->state = SSL3_ST_SR_KEY_EXCH_A;
590             break;
591
592         case SSL3_ST_SR_KEY_EXCH_A:
593         case SSL3_ST_SR_KEY_EXCH_B:
594             ret = ssl3_get_client_key_exchange(s);
595             if (ret <= 0)
596                 goto end;
597             if (ret == 2) {
598                 /*
599                  * For the ECDH ciphersuites when the client sends its ECDH
600                  * pub key in a certificate, the CertificateVerify message is
601                  * not sent. Also for GOST ciphersuites when the client uses
602                  * its key from the certificate for key exchange.
603                  */
604 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
605                 s->state = SSL3_ST_SR_FINISHED_A;
606 #else
607                 if (s->s3->next_proto_neg_seen)
608                     s->state = SSL3_ST_SR_NEXT_PROTO_A;
609                 else
610                     s->state = SSL3_ST_SR_FINISHED_A;
611 #endif
612                 s->init_num = 0;
613             } else if (SSL_USE_SIGALGS(s)) {
614                 s->state = SSL3_ST_SR_CERT_VRFY_A;
615                 s->init_num = 0;
616                 if (!s->session->peer)
617                     break;
618                 /*
619                  * For sigalgs freeze the handshake buffer at this point and
620                  * digest cached records.
621                  */
622                 if (!s->s3->handshake_buffer) {
623                     SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
624                     return -1;
625                 }
626                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
627                 if (!ssl3_digest_cached_records(s))
628                     return -1;
629             } else {
630                 int offset = 0;
631                 int dgst_num;
632
633                 s->state = SSL3_ST_SR_CERT_VRFY_A;
634                 s->init_num = 0;
635
636                 /*
637                  * We need to get hashes here so if there is a client cert,
638                  * it can be verified FIXME - digest processing for
639                  * CertificateVerify should be generalized. But it is next
640                  * step
641                  */
642                 if (s->s3->handshake_buffer)
643                     if (!ssl3_digest_cached_records(s))
644                         return -1;
645                 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
646                     if (s->s3->handshake_dgst[dgst_num]) {
647                         int dgst_size;
648
649                         s->method->ssl3_enc->cert_verify_mac(s,
650                                                              EVP_MD_CTX_type
651                                                              (s->
652                                                               s3->handshake_dgst
653                                                               [dgst_num]),
654                                                              &(s->s3->
655                                                                tmp.cert_verify_md
656                                                                [offset]));
657                         dgst_size =
658                             EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
659                         if (dgst_size < 0) {
660                             ret = -1;
661                             goto end;
662                         }
663                         offset += dgst_size;
664                     }
665             }
666             break;
667
668         case SSL3_ST_SR_CERT_VRFY_A:
669         case SSL3_ST_SR_CERT_VRFY_B:
670             /*
671              * This *should* be the first time we enable CCS, but be
672              * extra careful about surrounding code changes. We need
673              * to set this here because we don't know if we're
674              * expecting a CertificateVerify or not.
675              */
676             if (!s->s3->change_cipher_spec)
677                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
678             /* we should decide if we expected this one */
679             ret = ssl3_get_cert_verify(s);
680             if (ret <= 0)
681                 goto end;
682
683 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
684             s->state = SSL3_ST_SR_FINISHED_A;
685 #else
686             if (s->s3->next_proto_neg_seen)
687                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
688             else
689                 s->state = SSL3_ST_SR_FINISHED_A;
690 #endif
691             s->init_num = 0;
692             break;
693
694 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
695         case SSL3_ST_SR_NEXT_PROTO_A:
696         case SSL3_ST_SR_NEXT_PROTO_B:
697             /*
698              * Enable CCS for resumed handshakes with NPN.
699              * In a full handshake with NPN, we end up here through
700              * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
701              * already set. Receiving a CCS clears the flag, so make
702              * sure not to re-enable it to ban duplicates.
703              * s->s3->change_cipher_spec is set when a CCS is
704              * processed in s3_pkt.c, and remains set until
705              * the client's Finished message is read.
706              */
707             if (!s->s3->change_cipher_spec)
708                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
709
710             ret = ssl3_get_next_proto(s);
711             if (ret <= 0)
712                 goto end;
713             s->init_num = 0;
714             s->state = SSL3_ST_SR_FINISHED_A;
715             break;
716 #endif
717
718         case SSL3_ST_SR_FINISHED_A:
719         case SSL3_ST_SR_FINISHED_B:
720             /*
721              * Enable CCS for resumed handshakes without NPN.
722              * In a full handshake, we end up here through
723              * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
724              * already set. Receiving a CCS clears the flag, so make
725              * sure not to re-enable it to ban duplicates.
726              * s->s3->change_cipher_spec is set when a CCS is
727              * processed in s3_pkt.c, and remains set until
728              * the client's Finished message is read.
729              */
730             if (!s->s3->change_cipher_spec)
731                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
732             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
733                                     SSL3_ST_SR_FINISHED_B);
734             if (ret <= 0)
735                 goto end;
736             if (s->hit)
737                 s->state = SSL_ST_OK;
738 #ifndef OPENSSL_NO_TLSEXT
739             else if (s->tlsext_ticket_expected)
740                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
741 #endif
742             else
743                 s->state = SSL3_ST_SW_CHANGE_A;
744             s->init_num = 0;
745             break;
746
747 #ifndef OPENSSL_NO_TLSEXT
748         case SSL3_ST_SW_SESSION_TICKET_A:
749         case SSL3_ST_SW_SESSION_TICKET_B:
750             ret = ssl3_send_newsession_ticket(s);
751             if (ret <= 0)
752                 goto end;
753             s->state = SSL3_ST_SW_CHANGE_A;
754             s->init_num = 0;
755             break;
756
757         case SSL3_ST_SW_CERT_STATUS_A:
758         case SSL3_ST_SW_CERT_STATUS_B:
759             ret = ssl3_send_cert_status(s);
760             if (ret <= 0)
761                 goto end;
762             s->state = SSL3_ST_SW_KEY_EXCH_A;
763             s->init_num = 0;
764             break;
765
766 #endif
767
768         case SSL3_ST_SW_CHANGE_A:
769         case SSL3_ST_SW_CHANGE_B:
770
771             s->session->cipher = s->s3->tmp.new_cipher;
772             if (!s->method->ssl3_enc->setup_key_block(s)) {
773                 ret = -1;
774                 goto end;
775             }
776
777             ret = ssl3_send_change_cipher_spec(s,
778                                                SSL3_ST_SW_CHANGE_A,
779                                                SSL3_ST_SW_CHANGE_B);
780
781             if (ret <= 0)
782                 goto end;
783             s->state = SSL3_ST_SW_FINISHED_A;
784             s->init_num = 0;
785
786             if (!s->method->ssl3_enc->change_cipher_state(s,
787                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
788             {
789                 ret = -1;
790                 goto end;
791             }
792
793             break;
794
795         case SSL3_ST_SW_FINISHED_A:
796         case SSL3_ST_SW_FINISHED_B:
797             ret = ssl3_send_finished(s,
798                                      SSL3_ST_SW_FINISHED_A,
799                                      SSL3_ST_SW_FINISHED_B,
800                                      s->method->
801                                      ssl3_enc->server_finished_label,
802                                      s->method->
803                                      ssl3_enc->server_finished_label_len);
804             if (ret <= 0)
805                 goto end;
806             s->state = SSL3_ST_SW_FLUSH;
807             if (s->hit) {
808 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
809                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
810 #else
811                 if (s->s3->next_proto_neg_seen) {
812                     s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
813                 } else
814                     s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
815 #endif
816             } else
817                 s->s3->tmp.next_state = SSL_ST_OK;
818             s->init_num = 0;
819             break;
820
821         case SSL_ST_OK:
822             /* clean a few things up */
823             ssl3_cleanup_key_block(s);
824
825             BUF_MEM_free(s->init_buf);
826             s->init_buf = NULL;
827
828             /* remove buffering on output */
829             ssl_free_wbio_buffer(s);
830
831             s->init_num = 0;
832
833             if (s->renegotiate == 2) { /* skipped if we just sent a
834                                         * HelloRequest */
835                 s->renegotiate = 0;
836                 s->new_session = 0;
837
838                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
839
840                 s->ctx->stats.sess_accept_good++;
841                 /* s->server=1; */
842                 s->handshake_func = ssl3_accept;
843
844                 if (cb != NULL)
845                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
846             }
847
848             ret = 1;
849             goto end;
850             /* break; */
851
852         default:
853             SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
854             ret = -1;
855             goto end;
856             /* break; */
857         }
858
859         if (!s->s3->tmp.reuse_message && !skip) {
860             if (s->debug) {
861                 if ((ret = BIO_flush(s->wbio)) <= 0)
862                     goto end;
863             }
864
865             if ((cb != NULL) && (s->state != state)) {
866                 new_state = s->state;
867                 s->state = state;
868                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
869                 s->state = new_state;
870             }
871         }
872         skip = 0;
873     }
874  end:
875     /* BIO_flush(s->wbio); */
876
877     s->in_handshake--;
878     if (cb != NULL)
879         cb(s, SSL_CB_ACCEPT_EXIT, ret);
880     return (ret);
881 }
882
883 int ssl3_send_hello_request(SSL *s)
884 {
885
886     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
887         ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
888         s->state = SSL3_ST_SW_HELLO_REQ_B;
889     }
890
891     /* SSL3_ST_SW_HELLO_REQ_B */
892     return ssl_do_write(s);
893 }
894
895 int ssl3_get_client_hello(SSL *s)
896 {
897     int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
898     unsigned int cookie_len;
899     long n;
900     unsigned long id;
901     unsigned char *p, *d;
902     SSL_CIPHER *c;
903 #ifndef OPENSSL_NO_COMP
904     unsigned char *q;
905     SSL_COMP *comp = NULL;
906 #endif
907     STACK_OF(SSL_CIPHER) *ciphers = NULL;
908
909     if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
910         goto retry_cert;
911
912     /*
913      * We do this so that we will respond with our native type. If we are
914      * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
915      * switching should be handled by a different method. If we are SSLv3, we
916      * will respond with SSLv3, even if prompted with TLSv1.
917      */
918     if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
919         s->state = SSL3_ST_SR_CLNT_HELLO_B;
920     }
921     s->first_packet = 1;
922     n = s->method->ssl_get_message(s,
923                                    SSL3_ST_SR_CLNT_HELLO_B,
924                                    SSL3_ST_SR_CLNT_HELLO_C,
925                                    SSL3_MT_CLIENT_HELLO,
926                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
927
928     if (!ok)
929         return ((int)n);
930     s->first_packet = 0;
931     d = p = (unsigned char *)s->init_msg;
932
933     /*
934      * use version from inside client hello, not from record header (may
935      * differ: see RFC 2246, Appendix E, second paragraph)
936      */
937     s->client_version = (((int)p[0]) << 8) | (int)p[1];
938     p += 2;
939
940     if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
941                           s->method->version != DTLS_ANY_VERSION)
942         : (s->client_version < s->version)) {
943         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
944         if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
945             !s->enc_write_ctx && !s->write_hash) {
946             /*
947              * similar to ssl3_get_record, send alert using remote version
948              * number
949              */
950             s->version = s->client_version;
951         }
952         al = SSL_AD_PROTOCOL_VERSION;
953         goto f_err;
954     }
955
956     /*
957      * If we require cookies and this ClientHello doesn't contain one, just
958      * return since we do not want to allocate any memory yet. So check
959      * cookie length...
960      */
961     if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
962         unsigned int session_length, cookie_length;
963
964         session_length = *(p + SSL3_RANDOM_SIZE);
965         cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
966
967         if (cookie_length == 0)
968             return 1;
969     }
970
971     /* load the client random */
972     memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
973     p += SSL3_RANDOM_SIZE;
974
975     /* get the session-id */
976     j = *(p++);
977
978     s->hit = 0;
979     /*
980      * Versions before 0.9.7 always allow clients to resume sessions in
981      * renegotiation. 0.9.7 and later allow this by default, but optionally
982      * ignore resumption requests with flag
983      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
984      * than a change to default behavior so that applications relying on this
985      * for security won't even compile against older library versions).
986      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
987      * request renegotiation but not a new session (s->new_session remains
988      * unset): for servers, this essentially just means that the
989      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
990      */
991     if ((s->new_session
992          && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
993         if (!ssl_get_new_session(s, 1))
994             goto err;
995     } else {
996         i = ssl_get_prev_session(s, p, j, d + n);
997         /*
998          * Only resume if the session's version matches the negotiated
999          * version.
1000          * RFC 5246 does not provide much useful advice on resumption
1001          * with a different protocol version. It doesn't forbid it but
1002          * the sanity of such behaviour would be questionable.
1003          * In practice, clients do not accept a version mismatch and
1004          * will abort the handshake with an error.
1005          */
1006         if (i == 1 && s->version == s->session->ssl_version) { /* previous
1007                                                                 * session */
1008             s->hit = 1;
1009         } else if (i == -1)
1010             goto err;
1011         else {                  /* i == 0 */
1012
1013             if (!ssl_get_new_session(s, 1))
1014                 goto err;
1015         }
1016     }
1017
1018     p += j;
1019
1020     if (SSL_IS_DTLS(s)) {
1021         /* cookie stuff */
1022         cookie_len = *(p++);
1023
1024         /*
1025          * The ClientHello may contain a cookie even if the
1026          * HelloVerify message has not been sent--make sure that it
1027          * does not cause an overflow.
1028          */
1029         if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1030             /* too much data */
1031             al = SSL_AD_DECODE_ERROR;
1032             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1033             goto f_err;
1034         }
1035
1036         /* verify the cookie if appropriate option is set. */
1037         if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1038             memcpy(s->d1->rcvd_cookie, p, cookie_len);
1039
1040             if (s->ctx->app_verify_cookie_cb != NULL) {
1041                 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1042                                                  cookie_len) == 0) {
1043                     al = SSL_AD_HANDSHAKE_FAILURE;
1044                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1045                            SSL_R_COOKIE_MISMATCH);
1046                     goto f_err;
1047                 }
1048                 /* else cookie verification succeeded */
1049             }
1050             /* default verification */
1051             else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1052                             s->d1->cookie_len) != 0) {
1053                 al = SSL_AD_HANDSHAKE_FAILURE;
1054                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1055                 goto f_err;
1056             }
1057             /* Set to -2 so if successful we return 2 */
1058             ret = -2;
1059         }
1060
1061         p += cookie_len;
1062         if (s->method->version == DTLS_ANY_VERSION) {
1063             /* Select version to use */
1064             if (s->client_version <= DTLS1_2_VERSION &&
1065                 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1066                 s->version = DTLS1_2_VERSION;
1067                 s->method = DTLSv1_2_server_method();
1068             } else if (tls1_suiteb(s)) {
1069                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1070                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1071                 s->version = s->client_version;
1072                 al = SSL_AD_PROTOCOL_VERSION;
1073                 goto f_err;
1074             } else if (s->client_version <= DTLS1_VERSION &&
1075                        !(s->options & SSL_OP_NO_DTLSv1)) {
1076                 s->version = DTLS1_VERSION;
1077                 s->method = DTLSv1_server_method();
1078             } else {
1079                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1080                        SSL_R_WRONG_VERSION_NUMBER);
1081                 s->version = s->client_version;
1082                 al = SSL_AD_PROTOCOL_VERSION;
1083                 goto f_err;
1084             }
1085             s->session->ssl_version = s->version;
1086         }
1087     }
1088
1089     n2s(p, i);
1090     if ((i == 0) && (j != 0)) {
1091         /* we need a cipher if we are not resuming a session */
1092         al = SSL_AD_ILLEGAL_PARAMETER;
1093         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1094         goto f_err;
1095     }
1096     if ((p + i) >= (d + n)) {
1097         /* not enough data */
1098         al = SSL_AD_DECODE_ERROR;
1099         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1100         goto f_err;
1101     }
1102     if ((i > 0) && (ssl_bytes_to_cipher_list(s, p, i, &(ciphers))
1103                     == NULL)) {
1104         goto err;
1105     }
1106     p += i;
1107
1108     /* If it is a hit, check that the cipher is in the list */
1109     if ((s->hit) && (i > 0)) {
1110         j = 0;
1111         id = s->session->cipher->id;
1112
1113 #ifdef CIPHER_DEBUG
1114         fprintf(stderr, "client sent %d ciphers\n",
1115                 sk_SSL_CIPHER_num(ciphers));
1116 #endif
1117         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1118             c = sk_SSL_CIPHER_value(ciphers, i);
1119 #ifdef CIPHER_DEBUG
1120             fprintf(stderr, "client [%2d of %2d]:%s\n",
1121                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1122 #endif
1123             if (c->id == id) {
1124                 j = 1;
1125                 break;
1126             }
1127         }
1128         /*
1129          * Disabled because it can be used in a ciphersuite downgrade attack:
1130          * CVE-2010-4180.
1131          */
1132 #if 0
1133         if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1134             && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1135             /*
1136              * Special case as client bug workaround: the previously used
1137              * cipher may not be in the current list, the client instead
1138              * might be trying to continue using a cipher that before wasn't
1139              * chosen due to server preferences.  We'll have to reject the
1140              * connection if the cipher is not enabled, though.
1141              */
1142             c = sk_SSL_CIPHER_value(ciphers, 0);
1143             if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1144                 s->session->cipher = c;
1145                 j = 1;
1146             }
1147         }
1148 #endif
1149         if (j == 0) {
1150             /*
1151              * we need to have the cipher in the cipher list if we are asked
1152              * to reuse it
1153              */
1154             al = SSL_AD_ILLEGAL_PARAMETER;
1155             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1156                    SSL_R_REQUIRED_CIPHER_MISSING);
1157             goto f_err;
1158         }
1159     }
1160
1161     /* compression */
1162     i = *(p++);
1163     if ((p + i) > (d + n)) {
1164         /* not enough data */
1165         al = SSL_AD_DECODE_ERROR;
1166         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1167         goto f_err;
1168     }
1169 #ifndef OPENSSL_NO_COMP
1170     q = p;
1171 #endif
1172     for (j = 0; j < i; j++) {
1173         if (p[j] == 0)
1174             break;
1175     }
1176
1177     p += i;
1178     if (j >= i) {
1179         /* no compress */
1180         al = SSL_AD_DECODE_ERROR;
1181         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1182         goto f_err;
1183     }
1184 #ifndef OPENSSL_NO_TLSEXT
1185     /* TLS extensions */
1186     if (s->version >= SSL3_VERSION) {
1187         if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1188             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1189             goto err;
1190         }
1191     }
1192
1193     /*
1194      * Check if we want to use external pre-shared secret for this handshake
1195      * for not reused session only. We need to generate server_random before
1196      * calling tls_session_secret_cb in order to allow SessionTicket
1197      * processing to use it in key derivation.
1198      */
1199     {
1200         unsigned char *pos;
1201         pos = s->s3->server_random;
1202         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1203             goto f_err;
1204         }
1205     }
1206
1207     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1208         SSL_CIPHER *pref_cipher = NULL;
1209
1210         s->session->master_key_length = sizeof(s->session->master_key);
1211         if (s->tls_session_secret_cb(s, s->session->master_key,
1212                                      &s->session->master_key_length, ciphers,
1213                                      &pref_cipher,
1214                                      s->tls_session_secret_cb_arg)) {
1215             s->hit = 1;
1216             s->session->ciphers = ciphers;
1217             s->session->verify_result = X509_V_OK;
1218
1219             ciphers = NULL;
1220
1221             /* check if some cipher was preferred by call back */
1222             pref_cipher =
1223                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1224                                                                s->
1225                                                                session->ciphers,
1226                                                                SSL_get_ciphers
1227                                                                (s));
1228             if (pref_cipher == NULL) {
1229                 al = SSL_AD_HANDSHAKE_FAILURE;
1230                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1231                 goto f_err;
1232             }
1233
1234             s->session->cipher = pref_cipher;
1235
1236             if (s->cipher_list)
1237                 sk_SSL_CIPHER_free(s->cipher_list);
1238
1239             if (s->cipher_list_by_id)
1240                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1241
1242             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1243             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1244         }
1245     }
1246 #endif
1247
1248     /*
1249      * Worst case, we will use the NULL compression, but if we have other
1250      * options, we will now look for them.  We have i-1 compression
1251      * algorithms from the client, starting at q.
1252      */
1253     s->s3->tmp.new_compression = NULL;
1254 #ifndef OPENSSL_NO_COMP
1255     /* This only happens if we have a cache hit */
1256     if (s->session->compress_meth != 0) {
1257         int m, comp_id = s->session->compress_meth;
1258         /* Perform sanity checks on resumed compression algorithm */
1259         /* Can't disable compression */
1260         if (s->options & SSL_OP_NO_COMPRESSION) {
1261             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1262                    SSL_R_INCONSISTENT_COMPRESSION);
1263             goto f_err;
1264         }
1265         /* Look for resumed compression method */
1266         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1267             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1268             if (comp_id == comp->id) {
1269                 s->s3->tmp.new_compression = comp;
1270                 break;
1271             }
1272         }
1273         if (s->s3->tmp.new_compression == NULL) {
1274             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1275                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1276             goto f_err;
1277         }
1278         /* Look for resumed method in compression list */
1279         for (m = 0; m < i; m++) {
1280             if (q[m] == comp_id)
1281                 break;
1282         }
1283         if (m >= i) {
1284             al = SSL_AD_ILLEGAL_PARAMETER;
1285             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1286                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1287             goto f_err;
1288         }
1289     } else if (s->hit)
1290         comp = NULL;
1291     else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
1292         /* See if we have a match */
1293         int m, nn, o, v, done = 0;
1294
1295         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1296         for (m = 0; m < nn; m++) {
1297             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1298             v = comp->id;
1299             for (o = 0; o < i; o++) {
1300                 if (v == q[o]) {
1301                     done = 1;
1302                     break;
1303                 }
1304             }
1305             if (done)
1306                 break;
1307         }
1308         if (done)
1309             s->s3->tmp.new_compression = comp;
1310         else
1311             comp = NULL;
1312     }
1313 #else
1314     /*
1315      * If compression is disabled we'd better not try to resume a session
1316      * using compression.
1317      */
1318     if (s->session->compress_meth != 0) {
1319         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1320         goto f_err;
1321     }
1322 #endif
1323
1324     /*
1325      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1326      */
1327
1328     if (!s->hit) {
1329 #ifdef OPENSSL_NO_COMP
1330         s->session->compress_meth = 0;
1331 #else
1332         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1333 #endif
1334         if (s->session->ciphers != NULL)
1335             sk_SSL_CIPHER_free(s->session->ciphers);
1336         s->session->ciphers = ciphers;
1337         if (ciphers == NULL) {
1338             al = SSL_AD_ILLEGAL_PARAMETER;
1339             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_PASSED);
1340             goto f_err;
1341         }
1342         ciphers = NULL;
1343         if (!tls1_set_server_sigalgs(s)) {
1344             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1345             goto err;
1346         }
1347         /* Let cert callback update server certificates if required */
1348  retry_cert:
1349         if (s->cert->cert_cb) {
1350             int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1351             if (rv == 0) {
1352                 al = SSL_AD_INTERNAL_ERROR;
1353                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1354                 goto f_err;
1355             }
1356             if (rv < 0) {
1357                 s->rwstate = SSL_X509_LOOKUP;
1358                 return -1;
1359             }
1360             s->rwstate = SSL_NOTHING;
1361         }
1362         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1363
1364         if (c == NULL) {
1365             al = SSL_AD_HANDSHAKE_FAILURE;
1366             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1367             goto f_err;
1368         }
1369         s->s3->tmp.new_cipher = c;
1370     } else {
1371         /* Session-id reuse */
1372 #ifdef REUSE_CIPHER_BUG
1373         STACK_OF(SSL_CIPHER) *sk;
1374         SSL_CIPHER *nc = NULL;
1375         SSL_CIPHER *ec = NULL;
1376
1377         if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1378             sk = s->session->ciphers;
1379             for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1380                 c = sk_SSL_CIPHER_value(sk, i);
1381                 if (c->algorithm_enc & SSL_eNULL)
1382                     nc = c;
1383                 if (SSL_C_IS_EXPORT(c))
1384                     ec = c;
1385             }
1386             if (nc != NULL)
1387                 s->s3->tmp.new_cipher = nc;
1388             else if (ec != NULL)
1389                 s->s3->tmp.new_cipher = ec;
1390             else
1391                 s->s3->tmp.new_cipher = s->session->cipher;
1392         } else
1393 #endif
1394             s->s3->tmp.new_cipher = s->session->cipher;
1395     }
1396
1397     if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1398         if (!ssl3_digest_cached_records(s))
1399             goto f_err;
1400     }
1401
1402     /*-
1403     * we now have the following setup.
1404      * client_random
1405      * cipher_list          - our prefered list of ciphers
1406      * ciphers              - the clients prefered list of ciphers
1407      * compression          - basically ignored right now
1408      * ssl version is set   - sslv3
1409      * s->session           - The ssl session has been setup.
1410      * s->hit               - session reuse flag
1411      * s->tmp.new_cipher    - the new cipher to use.
1412      */
1413
1414     /* Handles TLS extensions that we couldn't check earlier */
1415     if (s->version >= SSL3_VERSION) {
1416         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1417             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1418             goto err;
1419         }
1420     }
1421
1422     if (ret < 0)
1423         ret = -ret;
1424     if (0) {
1425  f_err:
1426         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1427     }
1428  err:
1429     if (ciphers != NULL)
1430         sk_SSL_CIPHER_free(ciphers);
1431     return ret < 0 ? -1 : ret;
1432 }
1433
1434 int ssl3_send_server_hello(SSL *s)
1435 {
1436     unsigned char *buf;
1437     unsigned char *p, *d;
1438     int i, sl;
1439     int al = 0;
1440     unsigned long l;
1441
1442     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1443         buf = (unsigned char *)s->init_buf->data;
1444 #ifdef OPENSSL_NO_TLSEXT
1445         p = s->s3->server_random;
1446         if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1447             return -1;
1448 #endif
1449         /* Do the message type and length last */
1450         d = p = ssl_handshake_start(s);
1451
1452         *(p++) = s->version >> 8;
1453         *(p++) = s->version & 0xff;
1454
1455         /* Random stuff */
1456         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1457         p += SSL3_RANDOM_SIZE;
1458
1459         /*-
1460          * There are several cases for the session ID to send
1461          * back in the server hello:
1462          * - For session reuse from the session cache,
1463          *   we send back the old session ID.
1464          * - If stateless session reuse (using a session ticket)
1465          *   is successful, we send back the client's "session ID"
1466          *   (which doesn't actually identify the session).
1467          * - If it is a new session, we send back the new
1468          *   session ID.
1469          * - However, if we want the new session to be single-use,
1470          *   we send back a 0-length session ID.
1471          * s->hit is non-zero in either case of session reuse,
1472          * so the following won't overwrite an ID that we're supposed
1473          * to send back.
1474          */
1475         if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1476             && !s->hit)
1477             s->session->session_id_length = 0;
1478
1479         sl = s->session->session_id_length;
1480         if (sl > (int)sizeof(s->session->session_id)) {
1481             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1482             return -1;
1483         }
1484         *(p++) = sl;
1485         memcpy(p, s->session->session_id, sl);
1486         p += sl;
1487
1488         /* put the cipher */
1489         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1490         p += i;
1491
1492         /* put the compression method */
1493 #ifdef OPENSSL_NO_COMP
1494         *(p++) = 0;
1495 #else
1496         if (s->s3->tmp.new_compression == NULL)
1497             *(p++) = 0;
1498         else
1499             *(p++) = s->s3->tmp.new_compression->id;
1500 #endif
1501 #ifndef OPENSSL_NO_TLSEXT
1502         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1503             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1504             return -1;
1505         }
1506         if ((p =
1507              ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1508                                         &al)) == NULL) {
1509             ssl3_send_alert(s, SSL3_AL_FATAL, al);
1510             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1511             return -1;
1512         }
1513 #endif
1514         /* do the header */
1515         l = (p - d);
1516         ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1517         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1518     }
1519
1520     /* SSL3_ST_SW_SRVR_HELLO_B */
1521     return ssl_do_write(s);
1522 }
1523
1524 int ssl3_send_server_done(SSL *s)
1525 {
1526
1527     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1528         ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1529         s->state = SSL3_ST_SW_SRVR_DONE_B;
1530     }
1531
1532     /* SSL3_ST_SW_SRVR_DONE_B */
1533     return ssl_do_write(s);
1534 }
1535
1536 int ssl3_send_server_key_exchange(SSL *s)
1537 {
1538 #ifndef OPENSSL_NO_RSA
1539     unsigned char *q;
1540     int j, num;
1541     RSA *rsa;
1542     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1543     unsigned int u;
1544 #endif
1545 #ifndef OPENSSL_NO_DH
1546     DH *dh = NULL, *dhp;
1547 #endif
1548 #ifndef OPENSSL_NO_ECDH
1549     EC_KEY *ecdh = NULL, *ecdhp;
1550     unsigned char *encodedPoint = NULL;
1551     int encodedlen = 0;
1552     int curve_id = 0;
1553     BN_CTX *bn_ctx = NULL;
1554 #endif
1555     EVP_PKEY *pkey;
1556     const EVP_MD *md = NULL;
1557     unsigned char *p, *d;
1558     int al, i;
1559     unsigned long type;
1560     int n;
1561     CERT *cert;
1562     BIGNUM *r[4];
1563     int nr[4], kn;
1564     BUF_MEM *buf;
1565     EVP_MD_CTX md_ctx;
1566
1567     EVP_MD_CTX_init(&md_ctx);
1568     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1569         type = s->s3->tmp.new_cipher->algorithm_mkey;
1570         cert = s->cert;
1571
1572         buf = s->init_buf;
1573
1574         r[0] = r[1] = r[2] = r[3] = NULL;
1575         n = 0;
1576 #ifndef OPENSSL_NO_RSA
1577         if (type & SSL_kRSA) {
1578             rsa = cert->rsa_tmp;
1579             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1580                 rsa = s->cert->rsa_tmp_cb(s,
1581                                           SSL_C_IS_EXPORT(s->s3->
1582                                                           tmp.new_cipher),
1583                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1584                                                                   tmp.new_cipher));
1585                 if (rsa == NULL) {
1586                     al = SSL_AD_HANDSHAKE_FAILURE;
1587                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1588                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1589                     goto f_err;
1590                 }
1591                 RSA_up_ref(rsa);
1592                 cert->rsa_tmp = rsa;
1593             }
1594             if (rsa == NULL) {
1595                 al = SSL_AD_HANDSHAKE_FAILURE;
1596                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1597                        SSL_R_MISSING_TMP_RSA_KEY);
1598                 goto f_err;
1599             }
1600             r[0] = rsa->n;
1601             r[1] = rsa->e;
1602             s->s3->tmp.use_rsa_tmp = 1;
1603         } else
1604 #endif
1605 #ifndef OPENSSL_NO_DH
1606         if (type & SSL_kEDH) {
1607             dhp = cert->dh_tmp;
1608             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1609                 dhp = s->cert->dh_tmp_cb(s,
1610                                          SSL_C_IS_EXPORT(s->s3->
1611                                                          tmp.new_cipher),
1612                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1613                                                                  tmp.new_cipher));
1614             if (dhp == NULL) {
1615                 al = SSL_AD_HANDSHAKE_FAILURE;
1616                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1617                        SSL_R_MISSING_TMP_DH_KEY);
1618                 goto f_err;
1619             }
1620
1621             if (s->s3->tmp.dh != NULL) {
1622                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1623                        ERR_R_INTERNAL_ERROR);
1624                 goto err;
1625             }
1626
1627             if ((dh = DHparams_dup(dhp)) == NULL) {
1628                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1629                 goto err;
1630             }
1631
1632             s->s3->tmp.dh = dh;
1633             if ((dhp->pub_key == NULL ||
1634                  dhp->priv_key == NULL ||
1635                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1636                 if (!DH_generate_key(dh)) {
1637                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1638                     goto err;
1639                 }
1640             } else {
1641                 dh->pub_key = BN_dup(dhp->pub_key);
1642                 dh->priv_key = BN_dup(dhp->priv_key);
1643                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1644                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1645                     goto err;
1646                 }
1647             }
1648             r[0] = dh->p;
1649             r[1] = dh->g;
1650             r[2] = dh->pub_key;
1651         } else
1652 #endif
1653 #ifndef OPENSSL_NO_ECDH
1654         if (type & SSL_kEECDH) {
1655             const EC_GROUP *group;
1656
1657             ecdhp = cert->ecdh_tmp;
1658             if (s->cert->ecdh_tmp_auto) {
1659                 /* Get NID of appropriate shared curve */
1660                 int nid = tls1_shared_curve(s, -2);
1661                 if (nid != NID_undef)
1662                     ecdhp = EC_KEY_new_by_curve_name(nid);
1663             } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1664                 ecdhp = s->cert->ecdh_tmp_cb(s,
1665                                              SSL_C_IS_EXPORT(s->s3->
1666                                                              tmp.new_cipher),
1667                                              SSL_C_EXPORT_PKEYLENGTH(s->
1668                                                                      s3->tmp.new_cipher));
1669             }
1670             if (ecdhp == NULL) {
1671                 al = SSL_AD_HANDSHAKE_FAILURE;
1672                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1673                        SSL_R_MISSING_TMP_ECDH_KEY);
1674                 goto f_err;
1675             }
1676
1677             if (s->s3->tmp.ecdh != NULL) {
1678                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1679                        ERR_R_INTERNAL_ERROR);
1680                 goto err;
1681             }
1682
1683             /* Duplicate the ECDH structure. */
1684             if (ecdhp == NULL) {
1685                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1686                 goto err;
1687             }
1688             if (s->cert->ecdh_tmp_auto)
1689                 ecdh = ecdhp;
1690             else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1691                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1692                 goto err;
1693             }
1694
1695             s->s3->tmp.ecdh = ecdh;
1696             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1697                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1698                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1699                 if (!EC_KEY_generate_key(ecdh)) {
1700                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1701                            ERR_R_ECDH_LIB);
1702                     goto err;
1703                 }
1704             }
1705
1706             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1707                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1708                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1709                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1710                 goto err;
1711             }
1712
1713             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1714                 (EC_GROUP_get_degree(group) > 163)) {
1715                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1716                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1717                 goto err;
1718             }
1719
1720             /*
1721              * XXX: For now, we only support ephemeral ECDH keys over named
1722              * (not generic) curves. For supported named curves, curve_id is
1723              * non-zero.
1724              */
1725             if ((curve_id =
1726                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1727                 == 0) {
1728                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1729                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1730                 goto err;
1731             }
1732
1733             /*
1734              * Encode the public key. First check the size of encoding and
1735              * allocate memory accordingly.
1736              */
1737             encodedlen = EC_POINT_point2oct(group,
1738                                             EC_KEY_get0_public_key(ecdh),
1739                                             POINT_CONVERSION_UNCOMPRESSED,
1740                                             NULL, 0, NULL);
1741
1742             encodedPoint = (unsigned char *)
1743                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1744             bn_ctx = BN_CTX_new();
1745             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1746                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1747                        ERR_R_MALLOC_FAILURE);
1748                 goto err;
1749             }
1750
1751             encodedlen = EC_POINT_point2oct(group,
1752                                             EC_KEY_get0_public_key(ecdh),
1753                                             POINT_CONVERSION_UNCOMPRESSED,
1754                                             encodedPoint, encodedlen, bn_ctx);
1755
1756             if (encodedlen == 0) {
1757                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1758                 goto err;
1759             }
1760
1761             BN_CTX_free(bn_ctx);
1762             bn_ctx = NULL;
1763
1764             /*
1765              * XXX: For now, we only support named (not generic) curves in
1766              * ECDH ephemeral key exchanges. In this situation, we need four
1767              * additional bytes to encode the entire ServerECDHParams
1768              * structure.
1769              */
1770             n = 4 + encodedlen;
1771
1772             /*
1773              * We'll generate the serverKeyExchange message explicitly so we
1774              * can set these to NULLs
1775              */
1776             r[0] = NULL;
1777             r[1] = NULL;
1778             r[2] = NULL;
1779             r[3] = NULL;
1780         } else
1781 #endif                          /* !OPENSSL_NO_ECDH */
1782 #ifndef OPENSSL_NO_PSK
1783         if (type & SSL_kPSK) {
1784             /*
1785              * reserve size for record length and PSK identity hint
1786              */
1787             n += 2 + strlen(s->ctx->psk_identity_hint);
1788         } else
1789 #endif                          /* !OPENSSL_NO_PSK */
1790 #ifndef OPENSSL_NO_SRP
1791         if (type & SSL_kSRP) {
1792             if ((s->srp_ctx.N == NULL) ||
1793                 (s->srp_ctx.g == NULL) ||
1794                 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1795                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1796                        SSL_R_MISSING_SRP_PARAM);
1797                 goto err;
1798             }
1799             r[0] = s->srp_ctx.N;
1800             r[1] = s->srp_ctx.g;
1801             r[2] = s->srp_ctx.s;
1802             r[3] = s->srp_ctx.B;
1803         } else
1804 #endif
1805         {
1806             al = SSL_AD_HANDSHAKE_FAILURE;
1807             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1808                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1809             goto f_err;
1810         }
1811         for (i = 0; i < 4 && r[i] != NULL; i++) {
1812             nr[i] = BN_num_bytes(r[i]);
1813 #ifndef OPENSSL_NO_SRP
1814             if ((i == 2) && (type & SSL_kSRP))
1815                 n += 1 + nr[i];
1816             else
1817 #endif
1818                 n += 2 + nr[i];
1819         }
1820
1821         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1822             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1823             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1824                 == NULL) {
1825                 al = SSL_AD_DECODE_ERROR;
1826                 goto f_err;
1827             }
1828             kn = EVP_PKEY_size(pkey);
1829         } else {
1830             pkey = NULL;
1831             kn = 0;
1832         }
1833
1834         if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1835             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1836             goto err;
1837         }
1838         d = p = ssl_handshake_start(s);
1839
1840         for (i = 0; i < 4 && r[i] != NULL; i++) {
1841 #ifndef OPENSSL_NO_SRP
1842             if ((i == 2) && (type & SSL_kSRP)) {
1843                 *p = nr[i];
1844                 p++;
1845             } else
1846 #endif
1847                 s2n(nr[i], p);
1848             BN_bn2bin(r[i], p);
1849             p += nr[i];
1850         }
1851
1852 #ifndef OPENSSL_NO_ECDH
1853         if (type & SSL_kEECDH) {
1854             /*
1855              * XXX: For now, we only support named (not generic) curves. In
1856              * this situation, the serverKeyExchange message has: [1 byte
1857              * CurveType], [2 byte CurveName] [1 byte length of encoded
1858              * point], followed by the actual encoded point itself
1859              */
1860             *p = NAMED_CURVE_TYPE;
1861             p += 1;
1862             *p = 0;
1863             p += 1;
1864             *p = curve_id;
1865             p += 1;
1866             *p = encodedlen;
1867             p += 1;
1868             memcpy((unsigned char *)p,
1869                    (unsigned char *)encodedPoint, encodedlen);
1870             OPENSSL_free(encodedPoint);
1871             encodedPoint = NULL;
1872             p += encodedlen;
1873         }
1874 #endif
1875
1876 #ifndef OPENSSL_NO_PSK
1877         if (type & SSL_kPSK) {
1878             /* copy PSK identity hint */
1879             s2n(strlen(s->ctx->psk_identity_hint), p);
1880             strncpy((char *)p, s->ctx->psk_identity_hint,
1881                     strlen(s->ctx->psk_identity_hint));
1882             p += strlen(s->ctx->psk_identity_hint);
1883         }
1884 #endif
1885
1886         /* not anonymous */
1887         if (pkey != NULL) {
1888             /*
1889              * n is the length of the params, they start at &(d[4]) and p
1890              * points to the space at the end.
1891              */
1892 #ifndef OPENSSL_NO_RSA
1893             if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1894                 q = md_buf;
1895                 j = 0;
1896                 for (num = 2; num > 0; num--) {
1897                     EVP_MD_CTX_set_flags(&md_ctx,
1898                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1899                     EVP_DigestInit_ex(&md_ctx, (num == 2)
1900                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
1901                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1902                                      SSL3_RANDOM_SIZE);
1903                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1904                                      SSL3_RANDOM_SIZE);
1905                     EVP_DigestUpdate(&md_ctx, d, n);
1906                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1907                     q += i;
1908                     j += i;
1909                 }
1910                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1911                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1912                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1913                     goto err;
1914                 }
1915                 s2n(u, p);
1916                 n += u + 2;
1917             } else
1918 #endif
1919             if (md) {
1920                 /* send signature algorithm */
1921                 if (SSL_USE_SIGALGS(s)) {
1922                     if (!tls12_get_sigandhash(p, pkey, md)) {
1923                         /* Should never happen */
1924                         al = SSL_AD_INTERNAL_ERROR;
1925                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1926                                ERR_R_INTERNAL_ERROR);
1927                         goto f_err;
1928                     }
1929                     p += 2;
1930                 }
1931 #ifdef SSL_DEBUG
1932                 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1933 #endif
1934                 EVP_SignInit_ex(&md_ctx, md, NULL);
1935                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1936                                SSL3_RANDOM_SIZE);
1937                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1938                                SSL3_RANDOM_SIZE);
1939                 EVP_SignUpdate(&md_ctx, d, n);
1940                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1941                                    (unsigned int *)&i, pkey)) {
1942                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1943                     goto err;
1944                 }
1945                 s2n(i, p);
1946                 n += i + 2;
1947                 if (SSL_USE_SIGALGS(s))
1948                     n += 2;
1949             } else {
1950                 /* Is this error check actually needed? */
1951                 al = SSL_AD_HANDSHAKE_FAILURE;
1952                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1953                        SSL_R_UNKNOWN_PKEY_TYPE);
1954                 goto f_err;
1955             }
1956         }
1957
1958         ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1959     }
1960
1961     s->state = SSL3_ST_SW_KEY_EXCH_B;
1962     EVP_MD_CTX_cleanup(&md_ctx);
1963     return ssl_do_write(s);
1964  f_err:
1965     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1966  err:
1967 #ifndef OPENSSL_NO_ECDH
1968     if (encodedPoint != NULL)
1969         OPENSSL_free(encodedPoint);
1970     BN_CTX_free(bn_ctx);
1971 #endif
1972     EVP_MD_CTX_cleanup(&md_ctx);
1973     return (-1);
1974 }
1975
1976 int ssl3_send_certificate_request(SSL *s)
1977 {
1978     unsigned char *p, *d;
1979     int i, j, nl, off, n;
1980     STACK_OF(X509_NAME) *sk = NULL;
1981     X509_NAME *name;
1982     BUF_MEM *buf;
1983
1984     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
1985         buf = s->init_buf;
1986
1987         d = p = ssl_handshake_start(s);
1988
1989         /* get the list of acceptable cert types */
1990         p++;
1991         n = ssl3_get_req_cert_type(s, p);
1992         d[0] = n;
1993         p += n;
1994         n++;
1995
1996         if (SSL_USE_SIGALGS(s)) {
1997             const unsigned char *psigs;
1998             nl = tls12_get_psigalgs(s, &psigs);
1999             s2n(nl, p);
2000             memcpy(p, psigs, nl);
2001             p += nl;
2002             n += nl + 2;
2003         }
2004
2005         off = n;
2006         p += 2;
2007         n += 2;
2008
2009         sk = SSL_get_client_CA_list(s);
2010         nl = 0;
2011         if (sk != NULL) {
2012             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2013                 name = sk_X509_NAME_value(sk, i);
2014                 j = i2d_X509_NAME(name, NULL);
2015                 if (!BUF_MEM_grow_clean
2016                     (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2017                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2018                            ERR_R_BUF_LIB);
2019                     goto err;
2020                 }
2021                 p = ssl_handshake_start(s) + n;
2022                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
2023                     s2n(j, p);
2024                     i2d_X509_NAME(name, &p);
2025                     n += 2 + j;
2026                     nl += 2 + j;
2027                 } else {
2028                     d = p;
2029                     i2d_X509_NAME(name, &p);
2030                     j -= 2;
2031                     s2n(j, d);
2032                     j += 2;
2033                     n += j;
2034                     nl += j;
2035                 }
2036             }
2037         }
2038         /* else no CA names */
2039         p = ssl_handshake_start(s) + off;
2040         s2n(nl, p);
2041
2042         ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2043
2044 #ifdef NETSCAPE_HANG_BUG
2045         if (!SSL_IS_DTLS(s)) {
2046             if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
2047                 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
2048                 goto err;
2049             }
2050             p = (unsigned char *)s->init_buf->data + s->init_num;
2051             /* do the header */
2052             *(p++) = SSL3_MT_SERVER_DONE;
2053             *(p++) = 0;
2054             *(p++) = 0;
2055             *(p++) = 0;
2056             s->init_num += 4;
2057         }
2058 #endif
2059
2060         s->state = SSL3_ST_SW_CERT_REQ_B;
2061     }
2062
2063     /* SSL3_ST_SW_CERT_REQ_B */
2064     return ssl_do_write(s);
2065  err:
2066     return (-1);
2067 }
2068
2069 int ssl3_get_client_key_exchange(SSL *s)
2070 {
2071     int i, al, ok;
2072     long n;
2073     unsigned long alg_k;
2074     unsigned char *p;
2075 #ifndef OPENSSL_NO_RSA
2076     RSA *rsa = NULL;
2077     EVP_PKEY *pkey = NULL;
2078 #endif
2079 #ifndef OPENSSL_NO_DH
2080     BIGNUM *pub = NULL;
2081     DH *dh_srvr, *dh_clnt = NULL;
2082 #endif
2083 #ifndef OPENSSL_NO_KRB5
2084     KSSL_ERR kssl_err;
2085 #endif                          /* OPENSSL_NO_KRB5 */
2086
2087 #ifndef OPENSSL_NO_ECDH
2088     EC_KEY *srvr_ecdh = NULL;
2089     EVP_PKEY *clnt_pub_pkey = NULL;
2090     EC_POINT *clnt_ecpoint = NULL;
2091     BN_CTX *bn_ctx = NULL;
2092 #endif
2093
2094     n = s->method->ssl_get_message(s,
2095                                    SSL3_ST_SR_KEY_EXCH_A,
2096                                    SSL3_ST_SR_KEY_EXCH_B,
2097                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2098
2099     if (!ok)
2100         return ((int)n);
2101     p = (unsigned char *)s->init_msg;
2102
2103     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2104
2105 #ifndef OPENSSL_NO_RSA
2106     if (alg_k & SSL_kRSA) {
2107         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2108         int decrypt_len;
2109         unsigned char decrypt_good, version_good;
2110         size_t j;
2111
2112         /* FIX THIS UP EAY EAY EAY EAY */
2113         if (s->s3->tmp.use_rsa_tmp) {
2114             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2115                 rsa = s->cert->rsa_tmp;
2116             /*
2117              * Don't do a callback because rsa_tmp should be sent already
2118              */
2119             if (rsa == NULL) {
2120                 al = SSL_AD_HANDSHAKE_FAILURE;
2121                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2122                        SSL_R_MISSING_TMP_RSA_PKEY);
2123                 goto f_err;
2124
2125             }
2126         } else {
2127             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2128             if ((pkey == NULL) ||
2129                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2130                 al = SSL_AD_HANDSHAKE_FAILURE;
2131                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2132                        SSL_R_MISSING_RSA_CERTIFICATE);
2133                 goto f_err;
2134             }
2135             rsa = pkey->pkey.rsa;
2136         }
2137
2138         /* TLS and [incidentally] DTLS{0xFEFF} */
2139         if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2140             n2s(p, i);
2141             if (n != i + 2) {
2142                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2143                     al = SSL_AD_DECODE_ERROR;
2144                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2145                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2146                     goto f_err;
2147                 } else
2148                     p -= 2;
2149             } else
2150                 n = i;
2151         }
2152
2153         /*
2154          * Reject overly short RSA ciphertext because we want to be sure
2155          * that the buffer size makes it safe to iterate over the entire
2156          * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2157          * actual expected size is larger due to RSA padding, but the
2158          * bound is sufficient to be safe.
2159          */
2160         if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2161             al = SSL_AD_DECRYPT_ERROR;
2162             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2163                    SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2164             goto f_err;
2165         }
2166
2167         /*
2168          * We must not leak whether a decryption failure occurs because of
2169          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2170          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2171          * generates a random premaster secret for the case that the decrypt
2172          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2173          */
2174
2175         /*
2176          * should be RAND_bytes, but we cannot work around a failure.
2177          */
2178         if (RAND_pseudo_bytes(rand_premaster_secret,
2179                               sizeof(rand_premaster_secret)) <= 0)
2180             goto err;
2181         decrypt_len =
2182             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2183         ERR_clear_error();
2184
2185         /*
2186          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2187          * be 0xff if so and zero otherwise.
2188          */
2189         decrypt_good =
2190             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2191
2192         /*
2193          * If the version in the decrypted pre-master secret is correct then
2194          * version_good will be 0xff, otherwise it'll be zero. The
2195          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2196          * (http://eprint.iacr.org/2003/052/) exploits the version number
2197          * check as a "bad version oracle". Thus version checks are done in
2198          * constant time and are treated like any other decryption error.
2199          */
2200         version_good =
2201             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2202         version_good &=
2203             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2204
2205         /*
2206          * The premaster secret must contain the same version number as the
2207          * ClientHello to detect version rollback attacks (strangely, the
2208          * protocol does not offer such protection for DH ciphersuites).
2209          * However, buggy clients exist that send the negotiated protocol
2210          * version instead if the server does not support the requested
2211          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2212          * clients.
2213          */
2214         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2215             unsigned char workaround_good;
2216             workaround_good =
2217                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2218             workaround_good &=
2219                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2220             version_good |= workaround_good;
2221         }
2222
2223         /*
2224          * Both decryption and version must be good for decrypt_good to
2225          * remain non-zero (0xff).
2226          */
2227         decrypt_good &= version_good;
2228
2229         /*
2230          * Now copy rand_premaster_secret over from p using
2231          * decrypt_good_mask. If decryption failed, then p does not
2232          * contain valid plaintext, however, a check above guarantees
2233          * it is still sufficiently large to read from.
2234          */
2235         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2236             p[j] = constant_time_select_8(decrypt_good, p[j],
2237                                           rand_premaster_secret[j]);
2238         }
2239
2240         s->session->master_key_length =
2241             s->method->ssl3_enc->generate_master_secret(s,
2242                                                         s->
2243                                                         session->master_key,
2244                                                         p,
2245                                                         sizeof
2246                                                         (rand_premaster_secret));
2247         OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2248     } else
2249 #endif
2250 #ifndef OPENSSL_NO_DH
2251     if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2252         int idx = -1;
2253         EVP_PKEY *skey = NULL;
2254         if (n > 1) {
2255             n2s(p, i);
2256         } else {
2257             if (alg_k & SSL_kDHE) {
2258                 al = SSL_AD_HANDSHAKE_FAILURE;
2259                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2260                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2261                 goto f_err;
2262             }
2263             i = 0;
2264         }
2265         if (n && n != i + 2) {
2266             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2267                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2268                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2269                 goto err;
2270             } else {
2271                 p -= 2;
2272                 i = (int)n;
2273             }
2274         }
2275         if (alg_k & SSL_kDHr)
2276             idx = SSL_PKEY_DH_RSA;
2277         else if (alg_k & SSL_kDHd)
2278             idx = SSL_PKEY_DH_DSA;
2279         if (idx >= 0) {
2280             skey = s->cert->pkeys[idx].privatekey;
2281             if ((skey == NULL) ||
2282                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2283                 al = SSL_AD_HANDSHAKE_FAILURE;
2284                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2285                        SSL_R_MISSING_RSA_CERTIFICATE);
2286                 goto f_err;
2287             }
2288             dh_srvr = skey->pkey.dh;
2289         } else if (s->s3->tmp.dh == NULL) {
2290             al = SSL_AD_HANDSHAKE_FAILURE;
2291             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2292                    SSL_R_MISSING_TMP_DH_KEY);
2293             goto f_err;
2294         } else
2295             dh_srvr = s->s3->tmp.dh;
2296
2297         if (n == 0L) {
2298             /* Get pubkey from cert */
2299             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2300             if (clkey) {
2301                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2302                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2303             }
2304             if (dh_clnt == NULL) {
2305                 al = SSL_AD_HANDSHAKE_FAILURE;
2306                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2307                        SSL_R_MISSING_TMP_DH_KEY);
2308                 goto f_err;
2309             }
2310             EVP_PKEY_free(clkey);
2311             pub = dh_clnt->pub_key;
2312         } else
2313             pub = BN_bin2bn(p, i, NULL);
2314         if (pub == NULL) {
2315             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2316             goto err;
2317         }
2318
2319         i = DH_compute_key(p, pub, dh_srvr);
2320
2321         if (i <= 0) {
2322             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2323             BN_clear_free(pub);
2324             goto err;
2325         }
2326
2327         DH_free(s->s3->tmp.dh);
2328         s->s3->tmp.dh = NULL;
2329         if (dh_clnt)
2330             DH_free(dh_clnt);
2331         else
2332             BN_clear_free(pub);
2333         pub = NULL;
2334         s->session->master_key_length =
2335             s->method->ssl3_enc->generate_master_secret(s,
2336                                                         s->
2337                                                         session->master_key,
2338                                                         p, i);
2339         OPENSSL_cleanse(p, i);
2340         if (dh_clnt)
2341             return 2;
2342     } else
2343 #endif
2344 #ifndef OPENSSL_NO_KRB5
2345     if (alg_k & SSL_kKRB5) {
2346         krb5_error_code krb5rc;
2347         krb5_data enc_ticket;
2348         krb5_data authenticator;
2349         krb5_data enc_pms;
2350         KSSL_CTX *kssl_ctx = s->kssl_ctx;
2351         EVP_CIPHER_CTX ciph_ctx;
2352         const EVP_CIPHER *enc = NULL;
2353         unsigned char iv[EVP_MAX_IV_LENGTH];
2354         unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2355         int padl, outl;
2356         krb5_timestamp authtime = 0;
2357         krb5_ticket_times ttimes;
2358
2359         EVP_CIPHER_CTX_init(&ciph_ctx);
2360
2361         if (!kssl_ctx)
2362             kssl_ctx = kssl_ctx_new();
2363
2364         n2s(p, i);
2365         enc_ticket.length = i;
2366
2367         if (n < (long)(enc_ticket.length + 6)) {
2368             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2369                    SSL_R_DATA_LENGTH_TOO_LONG);
2370             goto err;
2371         }
2372
2373         enc_ticket.data = (char *)p;
2374         p += enc_ticket.length;
2375
2376         n2s(p, i);
2377         authenticator.length = i;
2378
2379         if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2380             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2381                    SSL_R_DATA_LENGTH_TOO_LONG);
2382             goto err;
2383         }
2384
2385         authenticator.data = (char *)p;
2386         p += authenticator.length;
2387
2388         n2s(p, i);
2389         enc_pms.length = i;
2390         enc_pms.data = (char *)p;
2391         p += enc_pms.length;
2392
2393         /*
2394          * Note that the length is checked again below, ** after decryption
2395          */
2396         if (enc_pms.length > sizeof pms) {
2397             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2398                    SSL_R_DATA_LENGTH_TOO_LONG);
2399             goto err;
2400         }
2401
2402         if (n != (long)(enc_ticket.length + authenticator.length +
2403                         enc_pms.length + 6)) {
2404             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2405                    SSL_R_DATA_LENGTH_TOO_LONG);
2406             goto err;
2407         }
2408
2409         if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2410                                     &kssl_err)) != 0) {
2411 # ifdef KSSL_DEBUG
2412             fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2413                     krb5rc, kssl_err.reason);
2414             if (kssl_err.text)
2415                 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2416 # endif                         /* KSSL_DEBUG */
2417             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2418             goto err;
2419         }
2420
2421         /*
2422          * Note: no authenticator is not considered an error, ** but will
2423          * return authtime == 0.
2424          */
2425         if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2426                                          &authtime, &kssl_err)) != 0) {
2427 # ifdef KSSL_DEBUG
2428             fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2429                     krb5rc, kssl_err.reason);
2430             if (kssl_err.text)
2431                 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2432 # endif                         /* KSSL_DEBUG */
2433             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2434             goto err;
2435         }
2436
2437         if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2438             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2439             goto err;
2440         }
2441 # ifdef KSSL_DEBUG
2442         kssl_ctx_show(kssl_ctx);
2443 # endif                         /* KSSL_DEBUG */
2444
2445         enc = kssl_map_enc(kssl_ctx->enctype);
2446         if (enc == NULL)
2447             goto err;
2448
2449         memset(iv, 0, sizeof iv); /* per RFC 1510 */
2450
2451         if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2452             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2453                    SSL_R_DECRYPTION_FAILED);
2454             goto err;
2455         }
2456         if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2457                                (unsigned char *)enc_pms.data, enc_pms.length))
2458         {
2459             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2460                    SSL_R_DECRYPTION_FAILED);
2461             goto err;
2462         }
2463         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2464             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2465                    SSL_R_DATA_LENGTH_TOO_LONG);
2466             goto err;
2467         }
2468         if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2469             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2470                    SSL_R_DECRYPTION_FAILED);
2471             goto err;
2472         }
2473         outl += padl;
2474         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2475             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2476                    SSL_R_DATA_LENGTH_TOO_LONG);
2477             goto err;
2478         }
2479         if (!((pms[0] == (s->client_version >> 8))
2480               && (pms[1] == (s->client_version & 0xff)))) {
2481             /*
2482              * The premaster secret must contain the same version number as
2483              * the ClientHello to detect version rollback attacks (strangely,
2484              * the protocol does not offer such protection for DH
2485              * ciphersuites). However, buggy clients exist that send random
2486              * bytes instead of the protocol version. If
2487              * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2488              * (Perhaps we should have a separate BUG value for the Kerberos
2489              * cipher)
2490              */
2491             if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2492                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2493                        SSL_AD_DECODE_ERROR);
2494                 goto err;
2495             }
2496         }
2497
2498         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2499
2500         s->session->master_key_length =
2501             s->method->ssl3_enc->generate_master_secret(s,
2502                                                         s->
2503                                                         session->master_key,
2504                                                         pms, outl);
2505
2506         if (kssl_ctx->client_princ) {
2507             size_t len = strlen(kssl_ctx->client_princ);
2508             if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2509                 s->session->krb5_client_princ_len = len;
2510                 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2511                        len);
2512             }
2513         }
2514
2515         /*- Was doing kssl_ctx_free() here,
2516          *  but it caused problems for apache.
2517          *  kssl_ctx = kssl_ctx_free(kssl_ctx);
2518          *  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2519          */
2520     } else
2521 #endif                          /* OPENSSL_NO_KRB5 */
2522
2523 #ifndef OPENSSL_NO_ECDH
2524     if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2525         int ret = 1;
2526         int field_size = 0;
2527         const EC_KEY *tkey;
2528         const EC_GROUP *group;
2529         const BIGNUM *priv_key;
2530
2531         /* initialize structures for server's ECDH key pair */
2532         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2533             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2534             goto err;
2535         }
2536
2537         /* Let's get server private key and group information */
2538         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2539             /* use the certificate */
2540             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2541         } else {
2542             /*
2543              * use the ephermeral values we saved when generating the
2544              * ServerKeyExchange msg.
2545              */
2546             tkey = s->s3->tmp.ecdh;
2547         }
2548
2549         group = EC_KEY_get0_group(tkey);
2550         priv_key = EC_KEY_get0_private_key(tkey);
2551
2552         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2553             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2554             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2555             goto err;
2556         }
2557
2558         /* Let's get client's public key */
2559         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2560             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2561             goto err;
2562         }
2563
2564         if (n == 0L) {
2565             /* Client Publickey was in Client Certificate */
2566
2567             if (alg_k & SSL_kEECDH) {
2568                 al = SSL_AD_HANDSHAKE_FAILURE;
2569                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2570                        SSL_R_MISSING_TMP_ECDH_KEY);
2571                 goto f_err;
2572             }
2573             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2574                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2575                 /*
2576                  * XXX: For now, we do not support client authentication
2577                  * using ECDH certificates so this branch (n == 0L) of the
2578                  * code is never executed. When that support is added, we
2579                  * ought to ensure the key received in the certificate is
2580                  * authorized for key agreement. ECDH_compute_key implicitly
2581                  * checks that the two ECDH shares are for the same group.
2582                  */
2583                 al = SSL_AD_HANDSHAKE_FAILURE;
2584                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2585                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2586                 goto f_err;
2587             }
2588
2589             if (EC_POINT_copy(clnt_ecpoint,
2590                               EC_KEY_get0_public_key(clnt_pub_pkey->
2591                                                      pkey.ec)) == 0) {
2592                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2593                 goto err;
2594             }
2595             ret = 2;            /* Skip certificate verify processing */
2596         } else {
2597             /*
2598              * Get client's public key from encoded point in the
2599              * ClientKeyExchange message.
2600              */
2601             if ((bn_ctx = BN_CTX_new()) == NULL) {
2602                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2603                        ERR_R_MALLOC_FAILURE);
2604                 goto err;
2605             }
2606
2607             /* Get encoded point length */
2608             i = *p;
2609             p += 1;
2610             if (n != 1 + i) {
2611                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2612                 goto err;
2613             }
2614             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2615                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2616                 goto err;
2617             }
2618             /*
2619              * p is pointing to somewhere in the buffer currently, so set it
2620              * to the start
2621              */
2622             p = (unsigned char *)s->init_buf->data;
2623         }
2624
2625         /* Compute the shared pre-master secret */
2626         field_size = EC_GROUP_get_degree(group);
2627         if (field_size <= 0) {
2628             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2629             goto err;
2630         }
2631         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2632                              NULL);
2633         if (i <= 0) {
2634             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2635             goto err;
2636         }
2637
2638         EVP_PKEY_free(clnt_pub_pkey);
2639         EC_POINT_free(clnt_ecpoint);
2640         EC_KEY_free(srvr_ecdh);
2641         BN_CTX_free(bn_ctx);
2642         EC_KEY_free(s->s3->tmp.ecdh);
2643         s->s3->tmp.ecdh = NULL;
2644
2645         /* Compute the master secret */
2646         s->session->master_key_length =
2647             s->method->ssl3_enc->generate_master_secret(s,
2648                                                         s->
2649                                                         session->master_key,
2650                                                         p, i);
2651
2652         OPENSSL_cleanse(p, i);
2653         return (ret);
2654     } else
2655 #endif
2656 #ifndef OPENSSL_NO_PSK
2657     if (alg_k & SSL_kPSK) {
2658         unsigned char *t = NULL;
2659         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2660         unsigned int pre_ms_len = 0, psk_len = 0;
2661         int psk_err = 1;
2662         char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2663
2664         al = SSL_AD_HANDSHAKE_FAILURE;
2665
2666         n2s(p, i);
2667         if (n != i + 2) {
2668             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2669             goto psk_err;
2670         }
2671         if (i > PSK_MAX_IDENTITY_LEN) {
2672             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2673                    SSL_R_DATA_LENGTH_TOO_LONG);
2674             goto psk_err;
2675         }
2676         if (s->psk_server_callback == NULL) {
2677             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2678                    SSL_R_PSK_NO_SERVER_CB);
2679             goto psk_err;
2680         }
2681
2682         /*
2683          * Create guaranteed NULL-terminated identity string for the callback
2684          */
2685         memcpy(tmp_id, p, i);
2686         memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2687         psk_len = s->psk_server_callback(s, tmp_id,
2688                                          psk_or_pre_ms,
2689                                          sizeof(psk_or_pre_ms));
2690         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2691
2692         if (psk_len > PSK_MAX_PSK_LEN) {
2693             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2694             goto psk_err;
2695         } else if (psk_len == 0) {
2696             /*
2697              * PSK related to the given identity not found
2698              */
2699             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2700                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2701             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2702             goto psk_err;
2703         }
2704
2705         /* create PSK pre_master_secret */
2706         pre_ms_len = 2 + psk_len + 2 + psk_len;
2707         t = psk_or_pre_ms;
2708         memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2709         s2n(psk_len, t);
2710         memset(t, 0, psk_len);
2711         t += psk_len;
2712         s2n(psk_len, t);
2713
2714         if (s->session->psk_identity != NULL)
2715             OPENSSL_free(s->session->psk_identity);
2716         s->session->psk_identity = BUF_strdup((char *)p);
2717         if (s->session->psk_identity == NULL) {
2718             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2719             goto psk_err;
2720         }
2721
2722         if (s->session->psk_identity_hint != NULL)
2723             OPENSSL_free(s->session->psk_identity_hint);
2724         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2725         if (s->ctx->psk_identity_hint != NULL &&
2726             s->session->psk_identity_hint == NULL) {
2727             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2728             goto psk_err;
2729         }
2730
2731         s->session->master_key_length =
2732             s->method->ssl3_enc->generate_master_secret(s,
2733                                                         s->
2734                                                         session->master_key,
2735                                                         psk_or_pre_ms,
2736                                                         pre_ms_len);
2737         psk_err = 0;
2738  psk_err:
2739         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2740         if (psk_err != 0)
2741             goto f_err;
2742     } else
2743 #endif
2744 #ifndef OPENSSL_NO_SRP
2745     if (alg_k & SSL_kSRP) {
2746         int param_len;
2747
2748         n2s(p, i);
2749         param_len = i + 2;
2750         if (param_len > n) {
2751             al = SSL_AD_DECODE_ERROR;
2752             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2753                    SSL_R_BAD_SRP_A_LENGTH);
2754             goto f_err;
2755         }
2756         if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
2757             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2758             goto err;
2759         }
2760         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2761             || BN_is_zero(s->srp_ctx.A)) {
2762             al = SSL_AD_ILLEGAL_PARAMETER;
2763             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2764                    SSL_R_BAD_SRP_PARAMETERS);
2765             goto f_err;
2766         }
2767         if (s->session->srp_username != NULL)
2768             OPENSSL_free(s->session->srp_username);
2769         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2770         if (s->session->srp_username == NULL) {
2771             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2772             goto err;
2773         }
2774
2775         if ((s->session->master_key_length =
2776              SRP_generate_server_master_secret(s,
2777                                                s->session->master_key)) < 0) {
2778             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2779             goto err;
2780         }
2781
2782         p += i;
2783     } else
2784 #endif                          /* OPENSSL_NO_SRP */
2785     if (alg_k & SSL_kGOST) {
2786         int ret = 0;
2787         EVP_PKEY_CTX *pkey_ctx;
2788         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2789         unsigned char premaster_secret[32], *start;
2790         size_t outlen = 32, inlen;
2791         unsigned long alg_a;
2792         int Ttag, Tclass;
2793         long Tlen;
2794
2795         /* Get our certificate private key */
2796         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2797         if (alg_a & SSL_aGOST94)
2798             pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2799         else if (alg_a & SSL_aGOST01)
2800             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2801
2802         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2803         EVP_PKEY_decrypt_init(pkey_ctx);
2804         /*
2805          * If client certificate is present and is of the same type, maybe
2806          * use it for key exchange.  Don't mind errors from
2807          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2808          * client certificate for authorization only.
2809          */
2810         client_pub_pkey = X509_get_pubkey(s->session->peer);
2811         if (client_pub_pkey) {
2812             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2813                 ERR_clear_error();
2814         }
2815         /* Decrypt session key */
2816         if (ASN1_get_object
2817             ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2818              n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2819             || Tclass != V_ASN1_UNIVERSAL) {
2820             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2821                    SSL_R_DECRYPTION_FAILED);
2822             goto gerr;
2823         }
2824         start = p;
2825         inlen = Tlen;
2826         if (EVP_PKEY_decrypt
2827             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2828             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2829                    SSL_R_DECRYPTION_FAILED);
2830             goto gerr;
2831         }
2832         /* Generate master secret */
2833         s->session->master_key_length =
2834             s->method->ssl3_enc->generate_master_secret(s,
2835                                                         s->
2836                                                         session->master_key,
2837                                                         premaster_secret, 32);
2838         /* Check if pubkey from client certificate was used */
2839         if (EVP_PKEY_CTX_ctrl
2840             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2841             ret = 2;
2842         else
2843             ret = 1;
2844  gerr:
2845         EVP_PKEY_free(client_pub_pkey);
2846         EVP_PKEY_CTX_free(pkey_ctx);
2847         if (ret)
2848             return ret;
2849         else
2850             goto err;
2851     } else {
2852         al = SSL_AD_HANDSHAKE_FAILURE;
2853         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2854         goto f_err;
2855     }
2856
2857     return (1);
2858  f_err:
2859     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2860 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2861  err:
2862 #endif
2863 #ifndef OPENSSL_NO_ECDH
2864     EVP_PKEY_free(clnt_pub_pkey);
2865     EC_POINT_free(clnt_ecpoint);
2866     if (srvr_ecdh != NULL)
2867         EC_KEY_free(srvr_ecdh);
2868     BN_CTX_free(bn_ctx);
2869 #endif
2870     return (-1);
2871 }
2872
2873 int ssl3_get_cert_verify(SSL *s)
2874 {
2875     EVP_PKEY *pkey = NULL;
2876     unsigned char *p;
2877     int al, ok, ret = 0;
2878     long n;
2879     int type = 0, i, j;
2880     X509 *peer;
2881     const EVP_MD *md = NULL;
2882     EVP_MD_CTX mctx;
2883     EVP_MD_CTX_init(&mctx);
2884
2885     n = s->method->ssl_get_message(s,
2886                                    SSL3_ST_SR_CERT_VRFY_A,
2887                                    SSL3_ST_SR_CERT_VRFY_B,
2888                                    -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2889
2890     if (!ok)
2891         return ((int)n);
2892
2893     if (s->session->peer != NULL) {
2894         peer = s->session->peer;
2895         pkey = X509_get_pubkey(peer);
2896         type = X509_certificate_type(peer, pkey);
2897     } else {
2898         peer = NULL;
2899         pkey = NULL;
2900     }
2901
2902     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2903         s->s3->tmp.reuse_message = 1;
2904         if (peer != NULL) {
2905             al = SSL_AD_UNEXPECTED_MESSAGE;
2906             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_MISSING_VERIFY_MESSAGE);
2907             goto f_err;
2908         }
2909         ret = 1;
2910         goto end;
2911     }
2912
2913     if (peer == NULL) {
2914         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_NO_CLIENT_CERT_RECEIVED);
2915         al = SSL_AD_UNEXPECTED_MESSAGE;
2916         goto f_err;
2917     }
2918
2919     if (!(type & EVP_PKT_SIGN)) {
2920         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2921                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2922         al = SSL_AD_ILLEGAL_PARAMETER;
2923         goto f_err;
2924     }
2925
2926     if (s->s3->change_cipher_spec) {
2927         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_CCS_RECEIVED_EARLY);
2928         al = SSL_AD_UNEXPECTED_MESSAGE;
2929         goto f_err;
2930     }
2931
2932     /* we now have a signature that we need to verify */
2933     p = (unsigned char *)s->init_msg;
2934     /* Check for broken implementations of GOST ciphersuites */
2935     /*
2936      * If key is GOST and n is exactly 64, it is bare signature without
2937      * length field
2938      */
2939     if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2940                     pkey->type == NID_id_GostR3410_2001)) {
2941         i = 64;
2942     } else {
2943         if (SSL_USE_SIGALGS(s)) {
2944             int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2945             if (rv == -1) {
2946                 al = SSL_AD_INTERNAL_ERROR;
2947                 goto f_err;
2948             } else if (rv == 0) {
2949                 al = SSL_AD_DECODE_ERROR;
2950                 goto f_err;
2951             }
2952 #ifdef SSL_DEBUG
2953             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2954 #endif
2955             p += 2;
2956             n -= 2;
2957         }
2958         n2s(p, i);
2959         n -= 2;
2960         if (i > n) {
2961             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2962             al = SSL_AD_DECODE_ERROR;
2963             goto f_err;
2964         }
2965     }
2966     j = EVP_PKEY_size(pkey);
2967     if ((i > j) || (n > j) || (n <= 0)) {
2968         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2969         al = SSL_AD_DECODE_ERROR;
2970         goto f_err;
2971     }
2972
2973     if (SSL_USE_SIGALGS(s)) {
2974         long hdatalen = 0;
2975         void *hdata;
2976         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2977         if (hdatalen <= 0) {
2978             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2979             al = SSL_AD_INTERNAL_ERROR;
2980             goto f_err;
2981         }
2982 #ifdef SSL_DEBUG
2983         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2984                 EVP_MD_name(md));
2985 #endif
2986         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2987             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2988             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2989             al = SSL_AD_INTERNAL_ERROR;
2990             goto f_err;
2991         }
2992
2993         if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2994             al = SSL_AD_DECRYPT_ERROR;
2995             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2996             goto f_err;
2997         }
2998     } else
2999 #ifndef OPENSSL_NO_RSA
3000     if (pkey->type == EVP_PKEY_RSA) {
3001         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3002                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3003                        pkey->pkey.rsa);
3004         if (i < 0) {
3005             al = SSL_AD_DECRYPT_ERROR;
3006             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3007             goto f_err;
3008         }
3009         if (i == 0) {
3010             al = SSL_AD_DECRYPT_ERROR;
3011             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3012             goto f_err;
3013         }
3014     } else
3015 #endif
3016 #ifndef OPENSSL_NO_DSA
3017     if (pkey->type == EVP_PKEY_DSA) {
3018         j = DSA_verify(pkey->save_type,
3019                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3020                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3021         if (j <= 0) {
3022             /* bad signature */
3023             al = SSL_AD_DECRYPT_ERROR;
3024             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3025             goto f_err;
3026         }
3027     } else
3028 #endif
3029 #ifndef OPENSSL_NO_ECDSA
3030     if (pkey->type == EVP_PKEY_EC) {
3031         j = ECDSA_verify(pkey->save_type,
3032                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3033                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3034         if (j <= 0) {
3035             /* bad signature */
3036             al = SSL_AD_DECRYPT_ERROR;
3037             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3038             goto f_err;
3039         }
3040     } else
3041 #endif
3042     if (pkey->type == NID_id_GostR3410_94
3043             || pkey->type == NID_id_GostR3410_2001) {
3044         unsigned char signature[64];
3045         int idx;
3046         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3047         EVP_PKEY_verify_init(pctx);
3048         if (i != 64) {
3049             fprintf(stderr, "GOST signature length is %d", i);
3050         }
3051         for (idx = 0; idx < 64; idx++) {
3052             signature[63 - idx] = p[idx];
3053         }
3054         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3055                             32);
3056         EVP_PKEY_CTX_free(pctx);
3057         if (j <= 0) {
3058             al = SSL_AD_DECRYPT_ERROR;
3059             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3060             goto f_err;
3061         }
3062     } else {
3063         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3064         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3065         goto f_err;
3066     }
3067
3068     ret = 1;
3069     if (0) {
3070  f_err:
3071         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3072     }
3073  end:
3074     if (s->s3->handshake_buffer) {
3075         BIO_free(s->s3->handshake_buffer);
3076         s->s3->handshake_buffer = NULL;
3077         s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3078     }
3079     EVP_MD_CTX_cleanup(&mctx);
3080     EVP_PKEY_free(pkey);
3081     return (ret);
3082 }
3083
3084 int ssl3_get_client_certificate(SSL *s)
3085 {
3086     int i, ok, al, ret = -1;
3087     X509 *x = NULL;
3088     unsigned long l, nc, llen, n;
3089     const unsigned char *p, *q;
3090     unsigned char *d;
3091     STACK_OF(X509) *sk = NULL;
3092
3093     n = s->method->ssl_get_message(s,
3094                                    SSL3_ST_SR_CERT_A,
3095                                    SSL3_ST_SR_CERT_B,
3096                                    -1, s->max_cert_list, &ok);
3097
3098     if (!ok)
3099         return ((int)n);
3100
3101     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3102         if ((s->verify_mode & SSL_VERIFY_PEER) &&
3103             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3104             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3105                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3106             al = SSL_AD_HANDSHAKE_FAILURE;
3107             goto f_err;
3108         }
3109         /*
3110          * If tls asked for a client cert, the client must return a 0 list
3111          */
3112         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3113             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3114                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3115             al = SSL_AD_UNEXPECTED_MESSAGE;
3116             goto f_err;
3117         }
3118         s->s3->tmp.reuse_message = 1;
3119         return (1);
3120     }
3121
3122     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3123         al = SSL_AD_UNEXPECTED_MESSAGE;
3124         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3125         goto f_err;
3126     }
3127     p = d = (unsigned char *)s->init_msg;
3128
3129     if ((sk = sk_X509_new_null()) == NULL) {
3130         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3131         goto err;
3132     }
3133
3134     n2l3(p, llen);
3135     if (llen + 3 != n) {
3136         al = SSL_AD_DECODE_ERROR;
3137         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3138         goto f_err;
3139     }
3140     for (nc = 0; nc < llen;) {
3141         n2l3(p, l);
3142         if ((l + nc + 3) > llen) {
3143             al = SSL_AD_DECODE_ERROR;
3144             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3145                    SSL_R_CERT_LENGTH_MISMATCH);
3146             goto f_err;
3147         }
3148
3149         q = p;
3150         x = d2i_X509(NULL, &p, l);
3151         if (x == NULL) {
3152             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3153             goto err;
3154         }
3155         if (p != (q + l)) {
3156             al = SSL_AD_DECODE_ERROR;
3157             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3158                    SSL_R_CERT_LENGTH_MISMATCH);
3159             goto f_err;
3160         }
3161         if (!sk_X509_push(sk, x)) {
3162             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3163             goto err;
3164         }
3165         x = NULL;
3166         nc += l + 3;
3167     }
3168
3169     if (sk_X509_num(sk) <= 0) {
3170         /* TLS does not mind 0 certs returned */
3171         if (s->version == SSL3_VERSION) {
3172             al = SSL_AD_HANDSHAKE_FAILURE;
3173             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3174                    SSL_R_NO_CERTIFICATES_RETURNED);
3175             goto f_err;
3176         }
3177         /* Fail for TLS only if we required a certificate */
3178         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3179                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3180             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3181                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3182             al = SSL_AD_HANDSHAKE_FAILURE;
3183             goto f_err;
3184         }
3185         /* No client certificate so digest cached records */
3186         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3187             al = SSL_AD_INTERNAL_ERROR;
3188             goto f_err;
3189         }
3190     } else {
3191         i = ssl_verify_cert_chain(s, sk);
3192         if (i <= 0) {
3193             al = ssl_verify_alarm_type(s->verify_result);
3194             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3195                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3196             goto f_err;
3197         }
3198     }
3199
3200     if (s->session->peer != NULL) /* This should not be needed */
3201         X509_free(s->session->peer);
3202     s->session->peer = sk_X509_shift(sk);
3203     s->session->verify_result = s->verify_result;
3204
3205     /*
3206      * With the current implementation, sess_cert will always be NULL when we
3207      * arrive here.
3208      */
3209     if (s->session->sess_cert == NULL) {
3210         s->session->sess_cert = ssl_sess_cert_new();
3211         if (s->session->sess_cert == NULL) {
3212             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3213             goto err;
3214         }
3215     }
3216     if (s->session->sess_cert->cert_chain != NULL)
3217         sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3218     s->session->sess_cert->cert_chain = sk;
3219     /*
3220      * Inconsistency alert: cert_chain does *not* include the peer's own
3221      * certificate, while we do include it in s3_clnt.c
3222      */
3223
3224     sk = NULL;
3225
3226     ret = 1;
3227     if (0) {
3228  f_err:
3229         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3230     }
3231  err:
3232     if (x != NULL)
3233         X509_free(x);
3234     if (sk != NULL)
3235         sk_X509_pop_free(sk, X509_free);
3236     return (ret);
3237 }
3238
3239 int ssl3_send_server_certificate(SSL *s)
3240 {
3241     CERT_PKEY *cpk;
3242
3243     if (s->state == SSL3_ST_SW_CERT_A) {
3244         cpk = ssl_get_server_send_pkey(s);
3245         if (cpk == NULL) {
3246             /* VRS: allow null cert if auth == KRB5 */
3247             if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3248                 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3249                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3250                        ERR_R_INTERNAL_ERROR);
3251                 return (0);
3252             }
3253         }
3254
3255         if (!ssl3_output_cert_chain(s, cpk)) {
3256             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3257             return (0);
3258         }
3259         s->state = SSL3_ST_SW_CERT_B;
3260     }
3261
3262     /* SSL3_ST_SW_CERT_B */
3263     return ssl_do_write(s);
3264 }
3265
3266 #ifndef OPENSSL_NO_TLSEXT
3267 /* send a new session ticket (not necessarily for a new session) */
3268 int ssl3_send_newsession_ticket(SSL *s)
3269 {
3270     unsigned char *senc = NULL;
3271     EVP_CIPHER_CTX ctx;
3272     HMAC_CTX hctx;
3273
3274     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3275         unsigned char *p, *macstart;
3276         const unsigned char *const_p;
3277         int len, slen_full, slen;
3278         SSL_SESSION *sess;
3279         unsigned int hlen;
3280         SSL_CTX *tctx = s->initial_ctx;
3281         unsigned char iv[EVP_MAX_IV_LENGTH];
3282         unsigned char key_name[16];
3283
3284         /* get session encoding length */
3285         slen_full = i2d_SSL_SESSION(s->session, NULL);
3286         /*
3287          * Some length values are 16 bits, so forget it if session is too
3288          * long
3289          */
3290         if (slen_full == 0 || slen_full > 0xFF00)
3291             return -1;
3292         senc = OPENSSL_malloc(slen_full);
3293         if (!senc)
3294             return -1;
3295
3296         EVP_CIPHER_CTX_init(&ctx);
3297         HMAC_CTX_init(&hctx);
3298
3299         p = senc;
3300         if (!i2d_SSL_SESSION(s->session, &p))
3301             goto err;
3302
3303         /*
3304          * create a fresh copy (not shared with other threads) to clean up
3305          */
3306         const_p = senc;
3307         sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3308         if (sess == NULL)
3309             goto err;
3310         sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3311
3312         slen = i2d_SSL_SESSION(sess, NULL);
3313         if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3314             SSL_SESSION_free(sess);
3315             goto err;
3316         }
3317         p = senc;
3318         if (!i2d_SSL_SESSION(sess, &p)) {
3319             SSL_SESSION_free(sess);
3320             goto err;
3321         }
3322         SSL_SESSION_free(sess);
3323
3324         /*-
3325          * Grow buffer if need be: the length calculation is as
3326          * follows handshake_header_length +
3327          * 4 (ticket lifetime hint) + 2 (ticket length) +
3328          * 16 (key name) + max_iv_len (iv length) +
3329          * session_length + max_enc_block_size (max encrypted session
3330          * length) + max_md_size (HMAC).
3331          */
3332         if (!BUF_MEM_grow(s->init_buf,
3333                           SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3334                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3335             goto err;
3336
3337         p = ssl_handshake_start(s);
3338         /*
3339          * Initialize HMAC and cipher contexts. If callback present it does
3340          * all the work otherwise use generated values from parent ctx.
3341          */
3342         if (tctx->tlsext_ticket_key_cb) {
3343             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3344                                            &hctx, 1) < 0)
3345                 goto err;
3346         } else {
3347             if (RAND_bytes(iv, 16) <= 0)
3348                 goto err;
3349             if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3350                                     tctx->tlsext_tick_aes_key, iv))
3351                 goto err;
3352             if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3353                               tlsext_tick_md(), NULL))
3354                 goto err;
3355             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3356         }
3357
3358         /*
3359          * Ticket lifetime hint (advisory only): We leave this unspecified
3360          * for resumed session (for simplicity), and guess that tickets for
3361          * new sessions will live as long as their sessions.
3362          */
3363         l2n(s->hit ? 0 : s->session->timeout, p);
3364
3365         /* Skip ticket length for now */
3366         p += 2;
3367         /* Output key name */
3368         macstart = p;
3369         memcpy(p, key_name, 16);
3370         p += 16;
3371         /* output IV */
3372         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3373         p += EVP_CIPHER_CTX_iv_length(&ctx);
3374         /* Encrypt session data */
3375         if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3376             goto err;
3377         p += len;
3378         if (!EVP_EncryptFinal(&ctx, p, &len))
3379             goto err;
3380         p += len;
3381
3382         if (!HMAC_Update(&hctx, macstart, p - macstart))
3383             goto err;
3384         if (!HMAC_Final(&hctx, p, &hlen))
3385             goto err;
3386
3387         EVP_CIPHER_CTX_cleanup(&ctx);
3388         HMAC_CTX_cleanup(&hctx);
3389
3390         p += hlen;
3391         /* Now write out lengths: p points to end of data written */
3392         /* Total length */
3393         len = p - ssl_handshake_start(s);
3394         ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3395         /* Skip ticket lifetime hint */
3396         p = ssl_handshake_start(s) + 4;
3397         s2n(len - 6, p);
3398         s->state = SSL3_ST_SW_SESSION_TICKET_B;
3399         OPENSSL_free(senc);
3400     }
3401
3402     /* SSL3_ST_SW_SESSION_TICKET_B */
3403     return ssl_do_write(s);
3404  err:
3405     if (senc)
3406         OPENSSL_free(senc);
3407     EVP_CIPHER_CTX_cleanup(&ctx);
3408     HMAC_CTX_cleanup(&hctx);
3409     return -1;
3410 }
3411
3412 int ssl3_send_cert_status(SSL *s)
3413 {
3414     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3415         unsigned char *p;
3416         /*-
3417          * Grow buffer if need be: the length calculation is as
3418          * follows 1 (message type) + 3 (message length) +
3419          * 1 (ocsp response type) + 3 (ocsp response length)
3420          * + (ocsp response)
3421          */
3422         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3423             return -1;
3424
3425         p = (unsigned char *)s->init_buf->data;
3426
3427         /* do the header */
3428         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3429         /* message length */
3430         l2n3(s->tlsext_ocsp_resplen + 4, p);
3431         /* status type */
3432         *(p++) = s->tlsext_status_type;
3433         /* length of OCSP response */
3434         l2n3(s->tlsext_ocsp_resplen, p);
3435         /* actual response */
3436         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3437         /* number of bytes to write */
3438         s->init_num = 8 + s->tlsext_ocsp_resplen;
3439         s->state = SSL3_ST_SW_CERT_STATUS_B;
3440         s->init_off = 0;
3441     }
3442
3443     /* SSL3_ST_SW_CERT_STATUS_B */
3444     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3445 }
3446
3447 # ifndef OPENSSL_NO_NEXTPROTONEG
3448 /*
3449  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3450  * It sets the next_proto member in s if found
3451  */
3452 int ssl3_get_next_proto(SSL *s)
3453 {
3454     int ok;
3455     int proto_len, padding_len;
3456     long n;
3457     const unsigned char *p;
3458
3459     /*
3460      * Clients cannot send a NextProtocol message if we didn't see the
3461      * extension in their ClientHello
3462      */
3463     if (!s->s3->next_proto_neg_seen) {
3464         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3465                SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3466         return -1;
3467     }
3468
3469     /* See the payload format below */
3470     n = s->method->ssl_get_message(s,
3471                                    SSL3_ST_SR_NEXT_PROTO_A,
3472                                    SSL3_ST_SR_NEXT_PROTO_B,
3473                                    SSL3_MT_NEXT_PROTO, 514, &ok);
3474
3475     if (!ok)
3476         return ((int)n);
3477
3478     /*
3479      * s->state doesn't reflect whether ChangeCipherSpec has been received in
3480      * this handshake, but s->s3->change_cipher_spec does (will be reset by
3481      * ssl3_get_finished).
3482      */
3483     if (!s->s3->change_cipher_spec) {
3484         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3485         return -1;
3486     }
3487
3488     if (n < 2)
3489         return 0;               /* The body must be > 1 bytes long */
3490
3491     p = (unsigned char *)s->init_msg;
3492
3493     /*-
3494      * The payload looks like:
3495      *   uint8 proto_len;
3496      *   uint8 proto[proto_len];
3497      *   uint8 padding_len;
3498      *   uint8 padding[padding_len];
3499      */
3500     proto_len = p[0];
3501     if (proto_len + 2 > s->init_num)
3502         return 0;
3503     padding_len = p[proto_len + 1];
3504     if (proto_len + padding_len + 2 != s->init_num)
3505         return 0;
3506
3507     s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3508     if (!s->next_proto_negotiated) {
3509         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3510         return 0;
3511     }
3512     memcpy(s->next_proto_negotiated, p + 1, proto_len);
3513     s->next_proto_negotiated_len = proto_len;
3514
3515     return 1;
3516 }
3517 # endif
3518
3519 #endif