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