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