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