Merge branch 'vendor/LIBRESSL'
[dragonfly.git] / crypto / libressl / ssl / s3_srvr.c
1 /* $OpenBSD: s3_srvr.c,v 1.125 2016/03/11 07:08:45 mmcc Exp $ */
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 #include <stdio.h>
152
153 #include "ssl_locl.h"
154
155 #include <openssl/bn.h>
156 #include <openssl/buffer.h>
157 #include <openssl/evp.h>
158 #include <openssl/dh.h>
159 #ifndef OPENSSL_NO_GOST
160 #include <openssl/gost.h>
161 #endif
162 #include <openssl/hmac.h>
163 #include <openssl/md5.h>
164 #include <openssl/objects.h>
165 #include <openssl/x509.h>
166
167 #include "bytestring.h"
168
169 int
170 ssl3_accept(SSL *s)
171 {
172         unsigned long alg_k;
173         void (*cb)(const SSL *ssl, int type, int val) = NULL;
174         int ret = -1;
175         int new_state, state, skip = 0;
176
177         ERR_clear_error();
178         errno = 0;
179
180         if (s->info_callback != NULL)
181                 cb = s->info_callback;
182         else if (s->ctx->info_callback != NULL)
183                 cb = s->ctx->info_callback;
184
185         /* init things to blank */
186         s->in_handshake++;
187         if (!SSL_in_init(s) || SSL_in_before(s))
188                 SSL_clear(s);
189
190         if (s->cert == NULL) {
191                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
192                 ret = -1;
193                 goto end;
194         }
195
196         for (;;) {
197                 state = s->state;
198
199                 switch (s->state) {
200                 case SSL_ST_RENEGOTIATE:
201                         s->renegotiate = 1;
202                         /* s->state=SSL_ST_ACCEPT; */
203
204                 case SSL_ST_BEFORE:
205                 case SSL_ST_ACCEPT:
206                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
207                 case SSL_ST_OK|SSL_ST_ACCEPT:
208
209                         s->server = 1;
210                         if (cb != NULL)
211                                 cb(s, SSL_CB_HANDSHAKE_START, 1);
212
213                         if ((s->version >> 8) != 3) {
214                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
215                                 ret = -1;
216                                 goto end;
217                         }
218                         s->type = SSL_ST_ACCEPT;
219
220                         if (!ssl3_setup_init_buffer(s)) {
221                                 ret = -1;
222                                 goto end;
223                         }
224                         if (!ssl3_setup_buffers(s)) {
225                                 ret = -1;
226                                 goto end;
227                         }
228
229                         s->init_num = 0;
230
231                         if (s->state != SSL_ST_RENEGOTIATE) {
232                                 /*
233                                  * Ok, we now need to push on a buffering BIO
234                                  * so that the output is sent in a way that
235                                  * TCP likes :-)
236                                  */
237                                 if (!ssl_init_wbio_buffer(s, 1)) {
238                                         ret = -1;
239                                         goto end;
240                                 }
241
242                                 if (!tls1_init_finished_mac(s)) {
243                                         ret = -1;
244                                         goto end;
245                                 }
246
247                                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
248                                 s->ctx->stats.sess_accept++;
249                         } else if (!s->s3->send_connection_binding) {
250                                 /*
251                                  * Server attempting to renegotiate with
252                                  * client that doesn't support secure
253                                  * renegotiation.
254                                  */
255                                 SSLerr(SSL_F_SSL3_ACCEPT,
256                                     SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
257                                 ssl3_send_alert(s, SSL3_AL_FATAL,
258                                     SSL_AD_HANDSHAKE_FAILURE);
259                                 ret = -1;
260                                 goto end;
261                         } else {
262                                 /*
263                                  * s->state == SSL_ST_RENEGOTIATE,
264                                  * we will just send a HelloRequest
265                                  */
266                                 s->ctx->stats.sess_accept_renegotiate++;
267                                 s->state = SSL3_ST_SW_HELLO_REQ_A;
268                         }
269                         break;
270
271                 case SSL3_ST_SW_HELLO_REQ_A:
272                 case SSL3_ST_SW_HELLO_REQ_B:
273
274                         s->shutdown = 0;
275                         ret = ssl3_send_hello_request(s);
276                         if (ret <= 0)
277                                 goto end;
278                         s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
279                         s->state = SSL3_ST_SW_FLUSH;
280                         s->init_num = 0;
281
282                         if (!tls1_init_finished_mac(s)) {
283                                 ret = -1;
284                                 goto end;
285                         }
286                         break;
287
288                 case SSL3_ST_SW_HELLO_REQ_C:
289                         s->state = SSL_ST_OK;
290                         break;
291
292                 case SSL3_ST_SR_CLNT_HELLO_A:
293                 case SSL3_ST_SR_CLNT_HELLO_B:
294                 case SSL3_ST_SR_CLNT_HELLO_C:
295
296                         s->shutdown = 0;
297                         if (s->rwstate != SSL_X509_LOOKUP) {
298                                 ret = ssl3_get_client_hello(s);
299                                 if (ret <= 0)
300                                         goto end;
301                         }
302
303                         s->renegotiate = 2;
304                         s->state = SSL3_ST_SW_SRVR_HELLO_A;
305                         s->init_num = 0;
306                         break;
307
308                 case SSL3_ST_SW_SRVR_HELLO_A:
309                 case SSL3_ST_SW_SRVR_HELLO_B:
310                         ret = ssl3_send_server_hello(s);
311                         if (ret <= 0)
312                                 goto end;
313                         if (s->hit) {
314                                 if (s->tlsext_ticket_expected)
315                                         s->state = SSL3_ST_SW_SESSION_TICKET_A;
316                                 else
317                                         s->state = SSL3_ST_SW_CHANGE_A;
318                         }
319                         else
320                                 s->state = SSL3_ST_SW_CERT_A;
321                         s->init_num = 0;
322                         break;
323
324                 case SSL3_ST_SW_CERT_A:
325                 case SSL3_ST_SW_CERT_B:
326                         /* Check if it is anon DH or anon ECDH. */
327                         if (!(s->s3->tmp.new_cipher->algorithm_auth &
328                             SSL_aNULL)) {
329                                 ret = ssl3_send_server_certificate(s);
330                                 if (ret <= 0)
331                                         goto end;
332                                 if (s->tlsext_status_expected)
333                                         s->state = SSL3_ST_SW_CERT_STATUS_A;
334                                 else
335                                         s->state = SSL3_ST_SW_KEY_EXCH_A;
336                         } else {
337                                 skip = 1;
338                                 s->state = SSL3_ST_SW_KEY_EXCH_A;
339                         }
340                         s->init_num = 0;
341                         break;
342
343                 case SSL3_ST_SW_KEY_EXCH_A:
344                 case SSL3_ST_SW_KEY_EXCH_B:
345                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
346
347                         /*
348                          * Only send if using a DH key exchange.
349                          *
350                          * For ECC ciphersuites, we send a ServerKeyExchange
351                          * message only if the cipher suite is ECDHE. In other
352                          * cases, the server certificate contains the server's
353                          * public key for key exchange.
354                          */
355                         if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
356                                 ret = ssl3_send_server_key_exchange(s);
357                                 if (ret <= 0)
358                                         goto end;
359                         } else
360                                 skip = 1;
361
362                         s->state = SSL3_ST_SW_CERT_REQ_A;
363                         s->init_num = 0;
364                         break;
365
366                 case SSL3_ST_SW_CERT_REQ_A:
367                 case SSL3_ST_SW_CERT_REQ_B:
368                         /*
369                          * Determine whether or not we need to request a
370                          * certificate.
371                          *
372                          * Do not request a certificate if:
373                          *
374                          * - We did not ask for it (SSL_VERIFY_PEER is unset).
375                          *
376                          * - SSL_VERIFY_CLIENT_ONCE is set and we are
377                          *   renegotiating.
378                          *
379                          * - We are using an anonymous ciphersuites
380                          *   (see section "Certificate request" in SSL 3 drafts
381                          *   and in RFC 2246) ... except when the application
382                          *   insists on verification (against the specs, but
383                          *   s3_clnt.c accepts this for SSL 3).
384                          */
385                         if (!(s->verify_mode & SSL_VERIFY_PEER) ||
386                             ((s->session->peer != NULL) &&
387                              (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
388                             ((s->s3->tmp.new_cipher->algorithm_auth &
389                              SSL_aNULL) && !(s->verify_mode &
390                              SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
391                                 /* No cert request */
392                                 skip = 1;
393                                 s->s3->tmp.cert_request = 0;
394                                 s->state = SSL3_ST_SW_SRVR_DONE_A;
395                                 if (s->s3->handshake_buffer) {
396                                         if (!tls1_digest_cached_records(s)) {
397                                                 ret = -1;
398                                                 goto end;
399                                         }
400                                 }
401                         } else {
402                                 s->s3->tmp.cert_request = 1;
403                                 ret = ssl3_send_certificate_request(s);
404                                 if (ret <= 0)
405                                         goto end;
406                                 s->state = SSL3_ST_SW_SRVR_DONE_A;
407                                 s->init_num = 0;
408                         }
409                         break;
410
411                 case SSL3_ST_SW_SRVR_DONE_A:
412                 case SSL3_ST_SW_SRVR_DONE_B:
413                         ret = ssl3_send_server_done(s);
414                         if (ret <= 0)
415                                 goto end;
416                         s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
417                         s->state = SSL3_ST_SW_FLUSH;
418                         s->init_num = 0;
419                         break;
420
421                 case SSL3_ST_SW_FLUSH:
422
423                         /*
424                          * This code originally checked to see if
425                          * any data was pending using BIO_CTRL_INFO
426                          * and then flushed. This caused problems
427                          * as documented in PR#1939. The proposed
428                          * fix doesn't completely resolve this issue
429                          * as buggy implementations of BIO_CTRL_PENDING
430                          * still exist. So instead we just flush
431                          * unconditionally.
432                          */
433
434                         s->rwstate = SSL_WRITING;
435                         if (BIO_flush(s->wbio) <= 0) {
436                                 ret = -1;
437                                 goto end;
438                         }
439                         s->rwstate = SSL_NOTHING;
440
441                         s->state = s->s3->tmp.next_state;
442                         break;
443
444                 case SSL3_ST_SR_CERT_A:
445                 case SSL3_ST_SR_CERT_B:
446                         if (s->s3->tmp.cert_request) {
447                                 ret = ssl3_get_client_certificate(s);
448                                 if (ret <= 0)
449                                         goto end;
450                         }
451                         s->init_num = 0;
452                         s->state = SSL3_ST_SR_KEY_EXCH_A;
453                         break;
454
455                 case SSL3_ST_SR_KEY_EXCH_A:
456                 case SSL3_ST_SR_KEY_EXCH_B:
457                         ret = ssl3_get_client_key_exchange(s);
458                         if (ret <= 0)
459                                 goto end;
460                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
461                         if (ret == 2) {
462                                 /*
463                                  * For the ECDH ciphersuites when
464                                  * the client sends its ECDH pub key in
465                                  * a certificate, the CertificateVerify
466                                  * message is not sent.
467                                  * Also for GOST ciphersuites when
468                                  * the client uses its key from the certificate
469                                  * for key exchange.
470                                  */
471                                 if (s->s3->next_proto_neg_seen)
472                                         s->state = SSL3_ST_SR_NEXT_PROTO_A;
473                                 else
474                                         s->state = SSL3_ST_SR_FINISHED_A;
475                                 s->init_num = 0;
476                         } else if (SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) {
477                                 s->state = SSL3_ST_SR_CERT_VRFY_A;
478                                 s->init_num = 0;
479                                 if (!s->session->peer)
480                                         break;
481                                 /*
482                                  * For sigalgs freeze the handshake buffer
483                                  * at this point and digest cached records.
484                                  */
485                                 if (!s->s3->handshake_buffer) {
486                                         SSLerr(SSL_F_SSL3_ACCEPT,
487                                             ERR_R_INTERNAL_ERROR);
488                                         ret = -1;
489                                         goto end;
490                                 }
491                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
492                                 if (!tls1_digest_cached_records(s)) {
493                                         ret = -1;
494                                         goto end;
495                                 }
496                         } else {
497                                 int offset = 0;
498                                 int dgst_num;
499
500                                 s->state = SSL3_ST_SR_CERT_VRFY_A;
501                                 s->init_num = 0;
502
503                                 /*
504                                  * We need to get hashes here so if there is
505                                  * a client cert, it can be verified
506                                  * FIXME - digest processing for
507                                  * CertificateVerify should be generalized.
508                                  * But it is next step
509                                  */
510                                 if (s->s3->handshake_buffer) {
511                                         if (!tls1_digest_cached_records(s)) {
512                                                 ret = -1;
513                                                 goto end;
514                                         }
515                                 }
516                                 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST;
517                                     dgst_num++)
518                                         if (s->s3->handshake_dgst[dgst_num]) {
519                                         int dgst_size;
520
521                                         s->method->ssl3_enc->cert_verify_mac(s,
522                                             EVP_MD_CTX_type(
523                                             s->s3->handshake_dgst[dgst_num]),
524                                             &(s->s3->tmp.cert_verify_md[offset]));
525                                         dgst_size = EVP_MD_CTX_size(
526                                             s->s3->handshake_dgst[dgst_num]);
527                                         if (dgst_size < 0) {
528                                                 ret = -1;
529                                                 goto end;
530                                         }
531                                         offset += dgst_size;
532                                 }
533                         }
534                         break;
535
536                 case SSL3_ST_SR_CERT_VRFY_A:
537                 case SSL3_ST_SR_CERT_VRFY_B:
538                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
539
540                         /* we should decide if we expected this one */
541                         ret = ssl3_get_cert_verify(s);
542                         if (ret <= 0)
543                                 goto end;
544
545                         if (s->s3->next_proto_neg_seen)
546                                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
547                         else
548                                 s->state = SSL3_ST_SR_FINISHED_A;
549                         s->init_num = 0;
550                         break;
551
552                 case SSL3_ST_SR_NEXT_PROTO_A:
553                 case SSL3_ST_SR_NEXT_PROTO_B:
554                         ret = ssl3_get_next_proto(s);
555                         if (ret <= 0)
556                                 goto end;
557                         s->init_num = 0;
558                         s->state = SSL3_ST_SR_FINISHED_A;
559                         break;
560
561                 case SSL3_ST_SR_FINISHED_A:
562                 case SSL3_ST_SR_FINISHED_B:
563                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
564                         ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
565                             SSL3_ST_SR_FINISHED_B);
566                         if (ret <= 0)
567                                 goto end;
568                         if (s->hit)
569                                 s->state = SSL_ST_OK;
570                         else if (s->tlsext_ticket_expected)
571                                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
572                         else
573                                 s->state = SSL3_ST_SW_CHANGE_A;
574                         s->init_num = 0;
575                         break;
576
577                 case SSL3_ST_SW_SESSION_TICKET_A:
578                 case SSL3_ST_SW_SESSION_TICKET_B:
579                         ret = ssl3_send_newsession_ticket(s);
580                         if (ret <= 0)
581                                 goto end;
582                         s->state = SSL3_ST_SW_CHANGE_A;
583                         s->init_num = 0;
584                         break;
585
586                 case SSL3_ST_SW_CERT_STATUS_A:
587                 case SSL3_ST_SW_CERT_STATUS_B:
588                         ret = ssl3_send_cert_status(s);
589                         if (ret <= 0)
590                                 goto end;
591                         s->state = SSL3_ST_SW_KEY_EXCH_A;
592                         s->init_num = 0;
593                         break;
594
595
596                 case SSL3_ST_SW_CHANGE_A:
597                 case SSL3_ST_SW_CHANGE_B:
598
599                         s->session->cipher = s->s3->tmp.new_cipher;
600                         if (!s->method->ssl3_enc->setup_key_block(s)) {
601                                 ret = -1;
602                                 goto end;
603                         }
604
605                         ret = ssl3_send_change_cipher_spec(s,
606                             SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B);
607
608                         if (ret <= 0)
609                                 goto end;
610                         s->state = SSL3_ST_SW_FINISHED_A;
611                         s->init_num = 0;
612
613                         if (!s->method->ssl3_enc->change_cipher_state(
614                             s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
615                                 ret = -1;
616                                 goto end;
617                         }
618
619                         break;
620
621                 case SSL3_ST_SW_FINISHED_A:
622                 case SSL3_ST_SW_FINISHED_B:
623                         ret = ssl3_send_finished(s,
624                         SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
625                         s->method->ssl3_enc->server_finished_label,
626                         s->method->ssl3_enc->server_finished_label_len);
627                         if (ret <= 0)
628                                 goto end;
629                         s->state = SSL3_ST_SW_FLUSH;
630                         if (s->hit) {
631                                 if (s->s3->next_proto_neg_seen) {
632                                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
633                                         s->s3->tmp.next_state =
634                                             SSL3_ST_SR_NEXT_PROTO_A;
635                                 } else
636                                         s->s3->tmp.next_state =
637                                             SSL3_ST_SR_FINISHED_A;
638                         } else
639                                 s->s3->tmp.next_state = SSL_ST_OK;
640                         s->init_num = 0;
641                         break;
642
643                 case SSL_ST_OK:
644                         /* clean a few things up */
645                         tls1_cleanup_key_block(s);
646
647                         BUF_MEM_free(s->init_buf);
648                         s->init_buf = NULL;
649
650                         /* remove buffering on output */
651                         ssl_free_wbio_buffer(s);
652
653                         s->init_num = 0;
654
655                         /* skipped if we just sent a HelloRequest */
656                         if (s->renegotiate == 2) {
657                                 s->renegotiate = 0;
658                                 s->new_session = 0;
659
660                                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
661
662                                 s->ctx->stats.sess_accept_good++;
663                                 /* s->server=1; */
664                                 s->handshake_func = ssl3_accept;
665
666                                 if (cb != NULL)
667                                         cb(s, SSL_CB_HANDSHAKE_DONE, 1);
668                         }
669
670                         ret = 1;
671                         goto end;
672                         /* break; */
673
674                 default:
675                         SSLerr(SSL_F_SSL3_ACCEPT,
676                             SSL_R_UNKNOWN_STATE);
677                         ret = -1;
678                         goto end;
679                         /* break; */
680                 }
681
682                 if (!s->s3->tmp.reuse_message && !skip) {
683                         if (s->debug) {
684                                 if ((ret = BIO_flush(s->wbio)) <= 0)
685                                         goto end;
686                         }
687
688
689                         if ((cb != NULL) && (s->state != state)) {
690                                 new_state = s->state;
691                                 s->state = state;
692                                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
693                                 s->state = new_state;
694                         }
695                 }
696                 skip = 0;
697         }
698 end:
699         /* BIO_flush(s->wbio); */
700
701         s->in_handshake--;
702         if (cb != NULL)
703                 cb(s, SSL_CB_ACCEPT_EXIT, ret);
704         return (ret);
705 }
706
707 int
708 ssl3_send_hello_request(SSL *s)
709 {
710         if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
711                 ssl3_handshake_msg_start(s, SSL3_MT_HELLO_REQUEST);
712                 ssl3_handshake_msg_finish(s, 0);
713
714                 s->state = SSL3_ST_SW_HELLO_REQ_B;
715         }
716
717         /* SSL3_ST_SW_HELLO_REQ_B */
718         return (ssl3_handshake_write(s));
719 }
720
721 int
722 ssl3_get_client_hello(SSL *s)
723 {
724         int i, j, ok, al, ret = -1;
725         unsigned int cookie_len;
726         long n;
727         unsigned long id;
728         unsigned char *p, *d;
729         SSL_CIPHER *c;
730         STACK_OF(SSL_CIPHER) *ciphers = NULL;
731         unsigned long alg_k;
732
733         /*
734          * We do this so that we will respond with our native type.
735          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
736          * This down switching should be handled by a different method.
737          * If we are SSLv3, we will respond with SSLv3, even if prompted with
738          * TLSv1.
739          */
740         if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
741                 s->state = SSL3_ST_SR_CLNT_HELLO_B;
742         }
743         s->first_packet = 1;
744         n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
745             SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
746             SSL3_RT_MAX_PLAIN_LENGTH, &ok);
747
748         if (!ok)
749                 return ((int)n);
750         s->first_packet = 0;
751         d = p = (unsigned char *)s->init_msg;
752
753         if (2 > n)
754                 goto truncated;
755         /*
756          * Use version from inside client hello, not from record header.
757          * (may differ: see RFC 2246, Appendix E, second paragraph)
758          */
759         s->client_version = (((int)p[0]) << 8)|(int)p[1];
760         p += 2;
761
762         if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
763             (s->version != DTLS1_VERSION && s->client_version < s->version)) {
764                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
765                     SSL_R_WRONG_VERSION_NUMBER);
766                 if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
767                         !s->enc_write_ctx && !s->write_hash) {
768                         /*
769                          * Similar to ssl3_get_record, send alert using remote
770                          * version number
771                          */
772                         s->version = s->client_version;
773                 }
774                 al = SSL_AD_PROTOCOL_VERSION;
775                 goto f_err;
776         }
777
778         /*
779          * If we require cookies and this ClientHello doesn't
780          * contain one, just return since we do not want to
781          * allocate any memory yet. So check cookie length...
782          */
783         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
784                 unsigned int session_length, cookie_length;
785
786                 session_length = *(p + SSL3_RANDOM_SIZE);
787                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
788
789                 if (cookie_length == 0)
790                         return (1);
791         }
792
793         if (p + SSL3_RANDOM_SIZE + 1 - d > n)
794                 goto truncated;
795
796         /* load the client random */
797         memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
798         p += SSL3_RANDOM_SIZE;
799
800         /* get the session-id */
801         j= *(p++);
802         if (p + j - d > n)
803                 goto truncated;
804
805         s->hit = 0;
806         /*
807          * Versions before 0.9.7 always allow clients to resume sessions in
808          * renegotiation. 0.9.7 and later allow this by default, but optionally
809          * ignore resumption requests with flag
810          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
811          * rather than a change to default behavior so that applications
812          * relying on this for security won't even compile against older
813          * library versions).
814          *
815          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
816          * to request renegotiation but not a new session (s->new_session
817          * remains unset): for servers, this essentially just means that the
818          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
819          * ignored.
820          */
821         if ((s->new_session && (s->options &
822             SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
823                 if (!ssl_get_new_session(s, 1))
824                         goto err;
825         } else {
826                 i = ssl_get_prev_session(s, p, j, d + n);
827                 if (i == 1) { /* previous session */
828                         s->hit = 1;
829                 } else if (i == -1)
830                         goto err;
831                 else {
832                         /* i == 0 */
833                         if (!ssl_get_new_session(s, 1))
834                                 goto err;
835                 }
836         }
837
838         p += j;
839
840         if (SSL_IS_DTLS(s)) {
841                 /* cookie stuff */
842                 if (p + 1 - d > n)
843                         goto truncated;
844                 cookie_len = *(p++);
845
846                 /*
847                  * The ClientHello may contain a cookie even if the
848                  * HelloVerify message has not been sent--make sure that it
849                  * does not cause an overflow.
850                  */
851                 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
852                         /* too much data */
853                         al = SSL_AD_DECODE_ERROR;
854                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
855                             SSL_R_COOKIE_MISMATCH);
856                         goto f_err;
857                 }
858
859                 if (p + cookie_len - d > n)
860                         goto truncated;
861
862                 /* verify the cookie if appropriate option is set. */
863                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
864                     cookie_len > 0) {
865                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
866
867                         if (s->ctx->app_verify_cookie_cb != NULL) {
868                                 if (s->ctx->app_verify_cookie_cb(s,
869                                     s->d1->rcvd_cookie, cookie_len) == 0) {
870                                         al = SSL_AD_HANDSHAKE_FAILURE;
871                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
872                                             SSL_R_COOKIE_MISMATCH);
873                                         goto f_err;
874                                 }
875                                 /* else cookie verification succeeded */
876                         } else if (timingsafe_memcmp(s->d1->rcvd_cookie, s->d1->cookie,
877                             s->d1->cookie_len) != 0) {
878                                 /* default verification */
879                                 al = SSL_AD_HANDSHAKE_FAILURE;
880                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
881                                     SSL_R_COOKIE_MISMATCH);
882                                 goto f_err;
883                         }
884
885                         ret = 2;
886                 }
887
888                 p += cookie_len;
889         }
890
891         if (p + 2 - d > n)
892                 goto truncated;
893         n2s(p, i);
894         if ((i == 0) && (j != 0)) {
895                 /* we need a cipher if we are not resuming a session */
896                 al = SSL_AD_ILLEGAL_PARAMETER;
897                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
898                     SSL_R_NO_CIPHERS_SPECIFIED);
899                 goto f_err;
900         }
901         if (p + i - d > n)
902                 goto truncated;
903         if (i > 0) {
904                 if ((ciphers = ssl_bytes_to_cipher_list(s, p, i)) == NULL)
905                         goto err;
906         }
907         p += i;
908
909         /* If it is a hit, check that the cipher is in the list */
910         if ((s->hit) && (i > 0)) {
911                 j = 0;
912                 id = s->session->cipher->id;
913
914                 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
915                         c = sk_SSL_CIPHER_value(ciphers, i);
916                         if (c->id == id) {
917                                 j = 1;
918                                 break;
919                         }
920                 }
921                 if (j == 0) {
922                         /*
923                          * We need to have the cipher in the cipher
924                          * list if we are asked to reuse it
925                          */
926                         al = SSL_AD_ILLEGAL_PARAMETER;
927                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
928                             SSL_R_REQUIRED_CIPHER_MISSING);
929                         goto f_err;
930                 }
931         }
932
933         /* compression */
934         if (p + 1 - d > n)
935                 goto truncated;
936         i= *(p++);
937         if (p + i - d > n)
938                 goto truncated;
939         for (j = 0; j < i; j++) {
940                 if (p[j] == 0)
941                         break;
942         }
943
944         p += i;
945         if (j >= i) {
946                 /* no compress */
947                 al = SSL_AD_DECODE_ERROR;
948                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
949                     SSL_R_NO_COMPRESSION_SPECIFIED);
950                 goto f_err;
951         }
952
953         /* TLS extensions*/
954         if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
955                 /* 'al' set by ssl_parse_clienthello_tlsext */
956                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
957                 goto f_err;
958         }
959         if (ssl_check_clienthello_tlsext_early(s) <= 0) {
960                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
961                     SSL_R_CLIENTHELLO_TLSEXT);
962                 goto err;
963         }
964
965         /*
966          * Check if we want to use external pre-shared secret for this
967          * handshake for not reused session only. We need to generate
968          * server_random before calling tls_session_secret_cb in order to allow
969          * SessionTicket processing to use it in key derivation.
970          */
971         arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
972
973         if (!s->hit && s->tls_session_secret_cb) {
974                 SSL_CIPHER *pref_cipher = NULL;
975
976                 s->session->master_key_length = sizeof(s->session->master_key);
977                 if (s->tls_session_secret_cb(s, s->session->master_key,
978                     &s->session->master_key_length, ciphers, &pref_cipher,
979                     s->tls_session_secret_cb_arg)) {
980                         s->hit = 1;
981                         s->session->ciphers = ciphers;
982                         s->session->verify_result = X509_V_OK;
983
984                         ciphers = NULL;
985
986                         /* check if some cipher was preferred by call back */
987                         pref_cipher = pref_cipher ? pref_cipher :
988                             ssl3_choose_cipher(s, s->session->ciphers,
989                             SSL_get_ciphers(s));
990                         if (pref_cipher == NULL) {
991                                 al = SSL_AD_HANDSHAKE_FAILURE;
992                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
993                                     SSL_R_NO_SHARED_CIPHER);
994                                 goto f_err;
995                         }
996
997                         s->session->cipher = pref_cipher;
998
999                         if (s->cipher_list)
1000                                 sk_SSL_CIPHER_free(s->cipher_list);
1001
1002                         if (s->cipher_list_by_id)
1003                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1004
1005                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1006                         s->cipher_list_by_id =
1007                             sk_SSL_CIPHER_dup(s->session->ciphers);
1008                 }
1009         }
1010
1011         /*
1012          * Given s->session->ciphers and SSL_get_ciphers, we must
1013          * pick a cipher
1014          */
1015
1016         if (!s->hit) {
1017                 if (s->session->ciphers != NULL)
1018                         sk_SSL_CIPHER_free(s->session->ciphers);
1019                 s->session->ciphers = ciphers;
1020                 if (ciphers == NULL) {
1021                         al = SSL_AD_ILLEGAL_PARAMETER;
1022                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1023                             SSL_R_NO_CIPHERS_PASSED);
1024                         goto f_err;
1025                 }
1026                 ciphers = NULL;
1027                 c = ssl3_choose_cipher(s, s->session->ciphers,
1028                 SSL_get_ciphers(s));
1029
1030                 if (c == NULL) {
1031                         al = SSL_AD_HANDSHAKE_FAILURE;
1032                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1033                             SSL_R_NO_SHARED_CIPHER);
1034                         goto f_err;
1035                 }
1036                 s->s3->tmp.new_cipher = c;
1037         } else {
1038                 s->s3->tmp.new_cipher = s->session->cipher;
1039         }
1040
1041         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1042         if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1043             !(s->verify_mode & SSL_VERIFY_PEER)) {
1044                 if (!tls1_digest_cached_records(s)) {
1045                         al = SSL_AD_INTERNAL_ERROR;
1046                         goto f_err;
1047                 }
1048         }
1049
1050         /*
1051          * We now have the following setup.
1052          * client_random
1053          * cipher_list          - our prefered list of ciphers
1054          * ciphers              - the clients prefered list of ciphers
1055          * compression          - basically ignored right now
1056          * ssl version is set   - sslv3
1057          * s->session           - The ssl session has been setup.
1058          * s->hit               - session reuse flag
1059          * s->tmp.new_cipher    - the new cipher to use.
1060          */
1061
1062         /* Handles TLS extensions that we couldn't check earlier */
1063         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1064                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1065                 goto err;
1066         }
1067
1068         if (ret < 0)
1069                 ret = 1;
1070         if (0) {
1071 truncated:
1072                 al = SSL_AD_DECODE_ERROR;
1073                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_BAD_PACKET_LENGTH);
1074 f_err:
1075                 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1076         }
1077 err:
1078         if (ciphers != NULL)
1079                 sk_SSL_CIPHER_free(ciphers);
1080         return (ret);
1081 }
1082
1083 int
1084 ssl3_send_server_hello(SSL *s)
1085 {
1086         unsigned char *bufend;
1087         unsigned char *p, *d;
1088         int sl;
1089
1090         if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1091                 d = p = ssl3_handshake_msg_start(s, SSL3_MT_SERVER_HELLO);
1092
1093                 *(p++) = s->version >> 8;
1094                 *(p++) = s->version & 0xff;
1095
1096                 /* Random stuff */
1097                 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1098                 p += SSL3_RANDOM_SIZE;
1099
1100                 /*
1101                  * There are several cases for the session ID to send
1102                  * back in the server hello:
1103                  *
1104                  * - For session reuse from the session cache,
1105                  *   we send back the old session ID.
1106                  * - If stateless session reuse (using a session ticket)
1107                  *   is successful, we send back the client's "session ID"
1108                  *   (which doesn't actually identify the session).
1109                  * - If it is a new session, we send back the new
1110                  *   session ID.
1111                  * - However, if we want the new session to be single-use,
1112                  *   we send back a 0-length session ID.
1113                  *
1114                  * s->hit is non-zero in either case of session reuse,
1115                  * so the following won't overwrite an ID that we're supposed
1116                  * to send back.
1117                  */
1118                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1119                     && !s->hit)
1120                         s->session->session_id_length = 0;
1121
1122                 sl = s->session->session_id_length;
1123                 if (sl > (int)sizeof(s->session->session_id)) {
1124                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,
1125                             ERR_R_INTERNAL_ERROR);
1126                         return (-1);
1127                 }
1128                 *(p++) = sl;
1129                 memcpy(p, s->session->session_id, sl);
1130                 p += sl;
1131
1132                 /* put the cipher */
1133                 s2n(ssl3_cipher_get_value(s->s3->tmp.new_cipher), p);
1134
1135                 /* put the compression method */
1136                 *(p++) = 0;
1137
1138                 bufend = (unsigned char *)s->init_buf->data +
1139                     SSL3_RT_MAX_PLAIN_LENGTH;
1140                 if ((p = ssl_add_serverhello_tlsext(s, p, bufend)) == NULL) {
1141                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,
1142                             ERR_R_INTERNAL_ERROR);
1143                         return (-1);
1144                 }
1145
1146                 ssl3_handshake_msg_finish(s, p - d);
1147         }
1148
1149         /* SSL3_ST_SW_SRVR_HELLO_B */
1150         return (ssl3_handshake_write(s));
1151 }
1152
1153 int
1154 ssl3_send_server_done(SSL *s)
1155 {
1156         if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1157                 ssl3_handshake_msg_start(s, SSL3_MT_SERVER_DONE);
1158                 ssl3_handshake_msg_finish(s, 0);
1159
1160                 s->state = SSL3_ST_SW_SRVR_DONE_B;
1161         }
1162
1163         /* SSL3_ST_SW_SRVR_DONE_B */
1164         return (ssl3_handshake_write(s));
1165 }
1166
1167 int
1168 ssl3_send_server_key_exchange(SSL *s)
1169 {
1170         unsigned char *q;
1171         int j, num;
1172         unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1173         unsigned int u;
1174         DH *dh = NULL, *dhp;
1175         EC_KEY *ecdh = NULL, *ecdhp;
1176         unsigned char *encodedPoint = NULL;
1177         int encodedlen = 0;
1178         int curve_id = 0;
1179         BN_CTX *bn_ctx = NULL;
1180
1181         EVP_PKEY *pkey;
1182         const EVP_MD *md = NULL;
1183         unsigned char *p, *d;
1184         int al, i;
1185         unsigned long type;
1186         int n;
1187         CERT *cert;
1188         BIGNUM *r[4];
1189         int nr[4], kn;
1190         BUF_MEM *buf;
1191         EVP_MD_CTX md_ctx;
1192
1193         EVP_MD_CTX_init(&md_ctx);
1194         if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1195                 type = s->s3->tmp.new_cipher->algorithm_mkey;
1196                 cert = s->cert;
1197
1198                 buf = s->init_buf;
1199
1200                 r[0] = r[1] = r[2] = r[3] = NULL;
1201                 n = 0;
1202                 if (type & SSL_kDHE) {
1203                         if (s->cert->dh_tmp_auto != 0) {
1204                                 if ((dhp = ssl_get_auto_dh(s)) == NULL) {
1205                                         al = SSL_AD_INTERNAL_ERROR;
1206                                         SSLerr(
1207                                             SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1208                                             ERR_R_INTERNAL_ERROR);
1209                                         goto f_err;
1210                                 }
1211                         } else
1212                                 dhp = cert->dh_tmp;
1213
1214                         if (dhp == NULL && s->cert->dh_tmp_cb != NULL)
1215                                 dhp = s->cert->dh_tmp_cb(s, 0,
1216                                     SSL_C_PKEYLENGTH(s->s3->tmp.new_cipher));
1217
1218                         if (dhp == NULL) {
1219                                 al = SSL_AD_HANDSHAKE_FAILURE;
1220                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1221                                     SSL_R_MISSING_TMP_DH_KEY);
1222                                 goto f_err;
1223                         }
1224
1225                         if (s->s3->tmp.dh != NULL) {
1226                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1227                                     ERR_R_INTERNAL_ERROR);
1228                                 goto err;
1229                         }
1230
1231                         if (s->cert->dh_tmp_auto != 0) {
1232                                 dh = dhp;
1233                         } else if ((dh = DHparams_dup(dhp)) == NULL) {
1234                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1235                                     ERR_R_DH_LIB);
1236                                 goto err;
1237                         }
1238                         s->s3->tmp.dh = dh;
1239                         if (!DH_generate_key(dh)) {
1240                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1241                                     ERR_R_DH_LIB);
1242                                 goto err;
1243                         }
1244                         r[0] = dh->p;
1245                         r[1] = dh->g;
1246                         r[2] = dh->pub_key;
1247                 } else if (type & SSL_kECDHE) {
1248                         const EC_GROUP *group;
1249
1250                         ecdhp = cert->ecdh_tmp;
1251                         if (s->cert->ecdh_tmp_auto != 0) {
1252                                 int nid = tls1_get_shared_curve(s);
1253                                 if (nid != NID_undef)
1254                                         ecdhp = EC_KEY_new_by_curve_name(nid);
1255                         } else if (ecdhp == NULL &&
1256                             s->cert->ecdh_tmp_cb != NULL) {
1257                                 ecdhp = s->cert->ecdh_tmp_cb(s, 0,
1258                                     SSL_C_PKEYLENGTH(s->s3->tmp.new_cipher));
1259                         }
1260                         if (ecdhp == NULL) {
1261                                 al = SSL_AD_HANDSHAKE_FAILURE;
1262                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1263                                     SSL_R_MISSING_TMP_ECDH_KEY);
1264                                 goto f_err;
1265                         }
1266
1267                         if (s->s3->tmp.ecdh != NULL) {
1268                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1269                                     ERR_R_INTERNAL_ERROR);
1270                                 goto err;
1271                         }
1272
1273                         /* Duplicate the ECDH structure. */
1274                         if (s->cert->ecdh_tmp_auto != 0) {
1275                                 ecdh = ecdhp;
1276                         } else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1277                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1278                                     ERR_R_ECDH_LIB);
1279                                 goto err;
1280                         }
1281                         s->s3->tmp.ecdh = ecdh;
1282
1283                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1284                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1285                             (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1286                                 if (!EC_KEY_generate_key(ecdh)) {
1287                                         SSLerr(
1288                                             SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1289                                             ERR_R_ECDH_LIB);
1290                                         goto err;
1291                                 }
1292                         }
1293
1294                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1295                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1296                             (EC_KEY_get0_private_key(ecdh) == NULL)) {
1297                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1298                                     ERR_R_ECDH_LIB);
1299                                 goto err;
1300                         }
1301
1302                         /*
1303                          * XXX: For now, we only support ephemeral ECDH
1304                          * keys over named (not generic) curves. For
1305                          * supported named curves, curve_id is non-zero.
1306                          */
1307                         if ((curve_id = tls1_ec_nid2curve_id(
1308                             EC_GROUP_get_curve_name(group))) == 0) {
1309                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1310                                     SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1311                                 goto err;
1312                         }
1313
1314                         /*
1315                          * Encode the public key.
1316                          * First check the size of encoding and
1317                          * allocate memory accordingly.
1318                          */
1319                         encodedlen = EC_POINT_point2oct(group,
1320                             EC_KEY_get0_public_key(ecdh),
1321                             POINT_CONVERSION_UNCOMPRESSED,
1322                             NULL, 0, NULL);
1323
1324                         encodedPoint = malloc(encodedlen);
1325
1326                         bn_ctx = BN_CTX_new();
1327                         if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1328                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1329                                     ERR_R_MALLOC_FAILURE);
1330                                 goto err;
1331                         }
1332
1333
1334                         encodedlen = EC_POINT_point2oct(group,
1335                             EC_KEY_get0_public_key(ecdh),
1336                             POINT_CONVERSION_UNCOMPRESSED,
1337                             encodedPoint, encodedlen, bn_ctx);
1338
1339                         if (encodedlen == 0) {
1340                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1341                                     ERR_R_ECDH_LIB);
1342                                 goto err;
1343                         }
1344
1345                         BN_CTX_free(bn_ctx);
1346                         bn_ctx = NULL;
1347
1348                         /*
1349                          * XXX: For now, we only support named (not
1350                          * generic) curves in ECDH ephemeral key exchanges.
1351                          * In this situation, we need four additional bytes
1352                          * to encode the entire ServerECDHParams
1353                          * structure.
1354                          */
1355                         n = 4 + encodedlen;
1356
1357                         /*
1358                          * We'll generate the serverKeyExchange message
1359                          * explicitly so we can set these to NULLs
1360                          */
1361                         r[0] = NULL;
1362                         r[1] = NULL;
1363                         r[2] = NULL;
1364                         r[3] = NULL;
1365                 } else
1366                 {
1367                         al = SSL_AD_HANDSHAKE_FAILURE;
1368                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1369                             SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1370                         goto f_err;
1371                 }
1372                 for (i = 0; i < 4 && r[i] != NULL; i++) {
1373                         nr[i] = BN_num_bytes(r[i]);
1374                         n += 2 + nr[i];
1375                 }
1376
1377                 if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)) {
1378                         if ((pkey = ssl_get_sign_pkey(
1379                             s, s->s3->tmp.new_cipher, &md)) == NULL) {
1380                                 al = SSL_AD_DECODE_ERROR;
1381                                 goto f_err;
1382                         }
1383                         kn = EVP_PKEY_size(pkey);
1384                 } else {
1385                         pkey = NULL;
1386                         kn = 0;
1387                 }
1388
1389                 if (!BUF_MEM_grow_clean(buf, ssl3_handshake_msg_hdr_len(s) +
1390                     n + kn)) {
1391                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1392                             ERR_LIB_BUF);
1393                         goto err;
1394                 }
1395
1396                 d = p = ssl3_handshake_msg_start(s,
1397                     SSL3_MT_SERVER_KEY_EXCHANGE);
1398
1399                 for (i = 0; i < 4 && r[i] != NULL; i++) {
1400                         s2n(nr[i], p);
1401                         BN_bn2bin(r[i], p);
1402                         p += nr[i];
1403                 }
1404
1405                 if (type & SSL_kECDHE) {
1406                         /*
1407                          * XXX: For now, we only support named (not generic)
1408                          * curves.
1409                          * In this situation, the serverKeyExchange message has:
1410                          * [1 byte CurveType], [2 byte CurveName]
1411                          * [1 byte length of encoded point], followed by
1412                          * the actual encoded point itself
1413                          */
1414                         *p = NAMED_CURVE_TYPE;
1415                         p += 1;
1416                         *p = 0;
1417                         p += 1;
1418                         *p = curve_id;
1419                         p += 1;
1420                         *p = encodedlen;
1421                         p += 1;
1422                         memcpy((unsigned char*)p,
1423                             (unsigned char *)encodedPoint, encodedlen);
1424                         free(encodedPoint);
1425                         encodedPoint = NULL;
1426                         p += encodedlen;
1427                 }
1428
1429
1430                 /* not anonymous */
1431                 if (pkey != NULL) {
1432                         /*
1433                          * n is the length of the params, they start at &(d[4])
1434                          * and p points to the space at the end.
1435                          */
1436                         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1437                                 q = md_buf;
1438                                 j = 0;
1439                                 for (num = 2; num > 0; num--) {
1440                                         if (!EVP_DigestInit_ex(&md_ctx,
1441                                             (num == 2) ? s->ctx->md5 :
1442                                             s->ctx->sha1, NULL))
1443                                                 goto err;
1444                                         EVP_DigestUpdate(&md_ctx,
1445                                             s->s3->client_random,
1446                                             SSL3_RANDOM_SIZE);
1447                                         EVP_DigestUpdate(&md_ctx,
1448                                             s->s3->server_random,
1449                                             SSL3_RANDOM_SIZE);
1450                                         EVP_DigestUpdate(&md_ctx, d, n);
1451                                         EVP_DigestFinal_ex(&md_ctx, q,
1452                                             (unsigned int *)&i);
1453                                         q += i;
1454                                         j += i;
1455                                 }
1456                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1457                                     &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1458                                         SSLerr(
1459                                             SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1460                                             ERR_LIB_RSA);
1461                                         goto err;
1462                                 }
1463                                 s2n(u, p);
1464                                 n += u + 2;
1465                         } else if (md) {
1466                                 /* Send signature algorithm. */
1467                                 if (SSL_USE_SIGALGS(s)) {
1468                                         if (!tls12_get_sigandhash(p, pkey, md)) {
1469                                                 /* Should never happen */
1470                                                 al = SSL_AD_INTERNAL_ERROR;
1471                                                 SSLerr(
1472                                                     SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1473                                                     ERR_R_INTERNAL_ERROR);
1474                                                 goto f_err;
1475                                         }
1476                                         p += 2;
1477                                 }
1478                                 EVP_SignInit_ex(&md_ctx, md, NULL);
1479                                 EVP_SignUpdate(&md_ctx,
1480                                     s->s3->client_random,
1481                                     SSL3_RANDOM_SIZE);
1482                                 EVP_SignUpdate(&md_ctx,
1483                                     s->s3->server_random,
1484                                     SSL3_RANDOM_SIZE);
1485                                 EVP_SignUpdate(&md_ctx, d, n);
1486                                 if (!EVP_SignFinal(&md_ctx, &p[2],
1487                                         (unsigned int *)&i, pkey)) {
1488                                         SSLerr(
1489                                             SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1490                                             ERR_LIB_EVP);
1491                                         goto err;
1492                                 }
1493                                 s2n(i, p);
1494                                 n += i + 2;
1495                                 if (SSL_USE_SIGALGS(s))
1496                                         n += 2;
1497                         } else {
1498                                 /* Is this error check actually needed? */
1499                                 al = SSL_AD_HANDSHAKE_FAILURE;
1500                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1501                                     SSL_R_UNKNOWN_PKEY_TYPE);
1502                                 goto f_err;
1503                         }
1504                 }
1505
1506                 ssl3_handshake_msg_finish(s, n);
1507         }
1508
1509         s->state = SSL3_ST_SW_KEY_EXCH_B;
1510         EVP_MD_CTX_cleanup(&md_ctx);
1511
1512         return (ssl3_handshake_write(s));
1513         
1514 f_err:
1515         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1516 err:
1517         free(encodedPoint);
1518         BN_CTX_free(bn_ctx);
1519         EVP_MD_CTX_cleanup(&md_ctx);
1520         return (-1);
1521 }
1522
1523 int
1524 ssl3_send_certificate_request(SSL *s)
1525 {
1526         unsigned char *p, *d;
1527         int i, j, nl, off, n;
1528         STACK_OF(X509_NAME) *sk = NULL;
1529         X509_NAME *name;
1530         BUF_MEM *buf;
1531
1532         if (s->state == SSL3_ST_SW_CERT_REQ_A) {
1533                 buf = s->init_buf;
1534
1535                 d = p = ssl3_handshake_msg_start(s,
1536                     SSL3_MT_CERTIFICATE_REQUEST);
1537
1538                 /* get the list of acceptable cert types */
1539                 p++;
1540                 n = ssl3_get_req_cert_type(s, p);
1541                 d[0] = n;
1542                 p += n;
1543                 n++;
1544
1545                 if (SSL_USE_SIGALGS(s)) {
1546                         nl = tls12_get_req_sig_algs(s, p + 2);
1547                         s2n(nl, p);
1548                         p += nl + 2;
1549                         n += nl + 2;
1550                 }
1551
1552                 off = n;
1553                 p += 2;
1554                 n += 2;
1555
1556                 sk = SSL_get_client_CA_list(s);
1557                 nl = 0;
1558                 if (sk != NULL) {
1559                         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1560                                 name = sk_X509_NAME_value(sk, i);
1561                                 j = i2d_X509_NAME(name, NULL);
1562                                 if (!BUF_MEM_grow_clean(buf,
1563                                     ssl3_handshake_msg_hdr_len(s) + n + j
1564                                     + 2)) {
1565                                         SSLerr(
1566                                             SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
1567                                             ERR_R_BUF_LIB);
1568                                         goto err;
1569                                 }
1570                                 p = ssl3_handshake_msg_start(s,
1571                                     SSL3_MT_CERTIFICATE_REQUEST) + n;
1572                                 s2n(j, p);
1573                                 i2d_X509_NAME(name, &p);
1574                                 n += 2 + j;
1575                                 nl += 2 + j;
1576                         }
1577                 }
1578                 /* else no CA names */
1579                 p = ssl3_handshake_msg_start(s,
1580                     SSL3_MT_CERTIFICATE_REQUEST) + off;
1581                 s2n(nl, p);
1582
1583                 ssl3_handshake_msg_finish(s, n);
1584
1585                 s->state = SSL3_ST_SW_CERT_REQ_B;
1586         }
1587
1588         /* SSL3_ST_SW_CERT_REQ_B */
1589         return (ssl3_handshake_write(s));
1590 err:
1591         return (-1);
1592 }
1593
1594 int
1595 ssl3_get_client_key_exchange(SSL *s)
1596 {
1597         int i, al, ok;
1598         long n;
1599         unsigned long alg_k;
1600         unsigned char *d, *p;
1601         RSA *rsa = NULL;
1602         EVP_PKEY *pkey = NULL;
1603         BIGNUM *pub = NULL;
1604         DH *dh_srvr;
1605
1606         EC_KEY *srvr_ecdh = NULL;
1607         EVP_PKEY *clnt_pub_pkey = NULL;
1608         EC_POINT *clnt_ecpoint = NULL;
1609         BN_CTX *bn_ctx = NULL;
1610
1611         /* 2048 maxlen is a guess.  How long a key does that permit? */
1612         n = s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
1613             SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
1614         if (!ok)
1615                 return ((int)n);
1616         d = p = (unsigned char *)s->init_msg;
1617
1618         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1619
1620         if (alg_k & SSL_kRSA) {
1621                 char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1622
1623                 arc4random_buf(fakekey, sizeof(fakekey));
1624                 fakekey[0] = s->client_version >> 8;
1625                 fakekey[1] = s->client_version & 0xff;
1626
1627                 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1628                 if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1629                     (pkey->pkey.rsa == NULL)) {
1630                         al = SSL_AD_HANDSHAKE_FAILURE;
1631                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1632                             SSL_R_MISSING_RSA_CERTIFICATE);
1633                         goto f_err;
1634                 }
1635                 rsa = pkey->pkey.rsa;
1636
1637                 if (2 > n)
1638                         goto truncated;
1639                 n2s(p, i);
1640                 if (n != i + 2) {
1641                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1642                             SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1643                         goto err;
1644                 } else
1645                         n = i;
1646
1647                 i = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1648
1649                 ERR_clear_error();
1650
1651                 al = -1;
1652
1653                 if (i != SSL_MAX_MASTER_KEY_LENGTH) {
1654                         al = SSL_AD_DECODE_ERROR;
1655                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
1656                 }
1657
1658                 if (p + 2 - d > n)      /* needed in the SSL3 case */
1659                         goto truncated;
1660                 if ((al == -1) && !((p[0] == (s->client_version >> 8)) &&
1661                     (p[1] == (s->client_version & 0xff)))) {
1662                         /*
1663                          * The premaster secret must contain the same version
1664                          * number as the ClientHello to detect version rollback
1665                          * attacks (strangely, the protocol does not offer such
1666                          * protection for DH ciphersuites).
1667                          * However, buggy clients exist that send the negotiated
1668                          * protocol version instead if the server does not
1669                          * support the requested protocol version.
1670                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1671                          * clients.
1672                          */
1673                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1674                             (p[0] == (s->version >> 8)) &&
1675                             (p[1] == (s->version & 0xff)))) {
1676                                 al = SSL_AD_DECODE_ERROR;
1677                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1678
1679                                 /*
1680                                  * The Klima-Pokorny-Rosa extension of
1681                                  * Bleichenbacher's attack
1682                                  * (http://eprint.iacr.org/2003/052/) exploits
1683                                  * the version number check as a "bad version
1684                                  * oracle" -- an alert would reveal that the
1685                                  * plaintext corresponding to some ciphertext
1686                                  * made up by the adversary is properly
1687                                  * formatted except that the version number is
1688                                  * wrong.
1689                                  * To avoid such attacks, we should treat this
1690                                  * just like any other decryption error.
1691                                  */
1692                         }
1693                 }
1694
1695                 if (al != -1) {
1696                         /*
1697                          * Some decryption failure -- use random value instead
1698                          * as countermeasure against Bleichenbacher's attack
1699                          * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1700                          * section 7.4.7.1).
1701                          */
1702                         i = SSL_MAX_MASTER_KEY_LENGTH;
1703                         p = fakekey;
1704                 }
1705
1706                 s->session->master_key_length =
1707                     s->method->ssl3_enc->generate_master_secret(s,
1708                     s->session->master_key,
1709                     p, i);
1710                 explicit_bzero(p, i);
1711         } else if (alg_k & SSL_kDHE) {
1712                 if (2 > n)
1713                         goto truncated;
1714                 n2s(p, i);
1715                 if (n != i + 2) {
1716                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1717                             SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1718                         goto err;
1719                 }
1720
1721                 if (n == 0L) {
1722                         /* the parameters are in the cert */
1723                         al = SSL_AD_HANDSHAKE_FAILURE;
1724                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1725                             SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1726                         goto f_err;
1727                 } else {
1728                         if (s->s3->tmp.dh == NULL) {
1729                                 al = SSL_AD_HANDSHAKE_FAILURE;
1730                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1731                                     SSL_R_MISSING_TMP_DH_KEY);
1732                                 goto f_err;
1733                         } else
1734                                 dh_srvr = s->s3->tmp.dh;
1735                 }
1736
1737                 pub = BN_bin2bn(p, i, NULL);
1738                 if (pub == NULL) {
1739                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1740                             SSL_R_BN_LIB);
1741                         goto err;
1742                 }
1743
1744                 i = DH_compute_key(p, pub, dh_srvr);
1745
1746                 if (i <= 0) {
1747                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1748                             ERR_R_DH_LIB);
1749                         BN_clear_free(pub);
1750                         goto err;
1751                 }
1752
1753                 DH_free(s->s3->tmp.dh);
1754                 s->s3->tmp.dh = NULL;
1755
1756                 BN_clear_free(pub);
1757                 pub = NULL;
1758                 s->session->master_key_length =
1759                     s->method->ssl3_enc->generate_master_secret(
1760                         s, s->session->master_key, p, i);
1761                 explicit_bzero(p, i);
1762         } else
1763
1764         if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) {
1765                 int ret = 1;
1766                 int key_size;
1767                 const EC_KEY   *tkey;
1768                 const EC_GROUP *group;
1769                 const BIGNUM *priv_key;
1770
1771                 /* Initialize structures for server's ECDH key pair. */
1772                 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1773                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1774                             ERR_R_MALLOC_FAILURE);
1775                         goto err;
1776                 }
1777
1778                 /* Let's get server private key and group information. */
1779                 if (alg_k & (SSL_kECDHr|SSL_kECDHe)) {
1780                         /* Use the certificate */
1781                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
1782                 } else {
1783                         /*
1784                          * Use the ephermeral values we saved when
1785                          * generating the ServerKeyExchange msg.
1786                          */
1787                         tkey = s->s3->tmp.ecdh;
1788                 }
1789
1790                 group = EC_KEY_get0_group(tkey);
1791                 priv_key = EC_KEY_get0_private_key(tkey);
1792
1793                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
1794                     !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1795                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1796                             ERR_R_EC_LIB);
1797                         goto err;
1798                 }
1799
1800                 /* Let's get client's public key */
1801                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1802                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1803                             ERR_R_MALLOC_FAILURE);
1804                         goto err;
1805                 }
1806
1807                 if (n == 0L) {
1808                         /* Client Publickey was in Client Certificate */
1809
1810                         if (alg_k & SSL_kECDHE) {
1811                                 al = SSL_AD_HANDSHAKE_FAILURE;
1812                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1813                                     SSL_R_MISSING_TMP_ECDH_KEY);
1814                                 goto f_err;
1815                         }
1816                         if (((clnt_pub_pkey = X509_get_pubkey(
1817                             s->session->peer)) == NULL) ||
1818                             (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1819                                 /*
1820                                  * XXX: For now, we do not support client
1821                                  * authentication using ECDH certificates
1822                                  * so this branch (n == 0L) of the code is
1823                                  * never executed. When that support is
1824                                  * added, we ought to ensure the key
1825                                  * received in the certificate is
1826                                  * authorized for key agreement.
1827                                  * ECDH_compute_key implicitly checks that
1828                                  * the two ECDH shares are for the same
1829                                  * group.
1830                                  */
1831                                 al = SSL_AD_HANDSHAKE_FAILURE;
1832                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1833                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1834                                 goto f_err;
1835                         }
1836
1837                         if (EC_POINT_copy(clnt_ecpoint,
1838                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec))
1839                             == 0) {
1840                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1841                                     ERR_R_EC_LIB);
1842                                 goto err;
1843                         }
1844                         ret = 2; /* Skip certificate verify processing */
1845                 } else {
1846                         /*
1847                          * Get client's public key from encoded point
1848                          * in the ClientKeyExchange message.
1849                          */
1850                         if ((bn_ctx = BN_CTX_new()) == NULL) {
1851                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1852                                     ERR_R_MALLOC_FAILURE);
1853                                 goto err;
1854                         }
1855
1856                         /* Get encoded point length */
1857                         i = *p;
1858
1859                         p += 1;
1860                         if (n != 1 + i) {
1861                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1862                                     ERR_R_EC_LIB);
1863                                 goto err;
1864                         }
1865                         if (EC_POINT_oct2point(group,
1866                                 clnt_ecpoint, p, i, bn_ctx) == 0) {
1867                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1868                                     ERR_R_EC_LIB);
1869                                 goto err;
1870                         }
1871                         /*
1872                          * p is pointing to somewhere in the buffer
1873                          * currently, so set it to the start.
1874                          */
1875                         p = (unsigned char *)s->init_buf->data;
1876                 }
1877
1878                 /* Compute the shared pre-master secret */
1879                 key_size = ECDH_size(srvr_ecdh);
1880                 if (key_size <= 0) {
1881                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1882                             ERR_R_ECDH_LIB);
1883                         goto err;
1884                 }
1885                 i = ECDH_compute_key(p, key_size, clnt_ecpoint, srvr_ecdh,
1886                     NULL);
1887                 if (i <= 0) {
1888                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1889                             ERR_R_ECDH_LIB);
1890                         goto err;
1891                 }
1892
1893                 EVP_PKEY_free(clnt_pub_pkey);
1894                 EC_POINT_free(clnt_ecpoint);
1895                 EC_KEY_free(srvr_ecdh);
1896                 BN_CTX_free(bn_ctx);
1897                 EC_KEY_free(s->s3->tmp.ecdh);
1898                 s->s3->tmp.ecdh = NULL;
1899
1900
1901                 /* Compute the master secret */
1902                 s->session->master_key_length = s->method->ssl3_enc-> \
1903                     generate_master_secret(s, s->session->master_key, p, i);
1904
1905                 explicit_bzero(p, i);
1906                 return (ret);
1907         } else
1908         if (alg_k & SSL_kGOST) {
1909                 int ret = 0;
1910                 EVP_PKEY_CTX *pkey_ctx;
1911                 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
1912                 unsigned char premaster_secret[32], *start;
1913                 size_t outlen = 32, inlen;
1914                 unsigned long alg_a;
1915                 int Ttag, Tclass;
1916                 long Tlen;
1917
1918                 /* Get our certificate private key*/
1919                 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1920                 if (alg_a & SSL_aGOST01)
1921                         pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
1922
1923                 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
1924                 EVP_PKEY_decrypt_init(pkey_ctx);
1925                 /*
1926                  * If client certificate is present and is of the same type,
1927                  * maybe use it for key exchange.
1928                  * Don't mind errors from EVP_PKEY_derive_set_peer, because
1929                  * it is completely valid to use a client certificate for
1930                  * authorization only.
1931                  */
1932                 client_pub_pkey = X509_get_pubkey(s->session->peer);
1933                 if (client_pub_pkey) {
1934                         if (EVP_PKEY_derive_set_peer(pkey_ctx,
1935                             client_pub_pkey) <= 0)
1936                                 ERR_clear_error();
1937                 }
1938                 if (2 > n)
1939                         goto truncated;
1940                 /* Decrypt session key */
1941                 if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag,
1942                     &Tclass, n) != V_ASN1_CONSTRUCTED ||
1943                     Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
1944                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1945                             SSL_R_DECRYPTION_FAILED);
1946                         goto gerr;
1947                 }
1948                 start = p;
1949                 inlen = Tlen;
1950                 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
1951                     start, inlen) <=0) {
1952                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1953                             SSL_R_DECRYPTION_FAILED);
1954                         goto gerr;
1955                 }
1956                 /* Generate master secret */
1957                 s->session->master_key_length =
1958                     s->method->ssl3_enc->generate_master_secret(
1959                     s, s->session->master_key, premaster_secret, 32);
1960                 /* Check if pubkey from client certificate was used */
1961                 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
1962                     EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
1963                         ret = 2;
1964                 else
1965                         ret = 1;
1966 gerr:
1967                 EVP_PKEY_free(client_pub_pkey);
1968                 EVP_PKEY_CTX_free(pkey_ctx);
1969                 if (ret)
1970                         return (ret);
1971                 else
1972                         goto err;
1973         } else {
1974                 al = SSL_AD_HANDSHAKE_FAILURE;
1975                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1976                     SSL_R_UNKNOWN_CIPHER_TYPE);
1977                 goto f_err;
1978         }
1979
1980         return (1);
1981 truncated:
1982         al = SSL_AD_DECODE_ERROR;
1983         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BAD_PACKET_LENGTH);
1984 f_err:
1985         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1986 err:
1987         EVP_PKEY_free(clnt_pub_pkey);
1988         EC_POINT_free(clnt_ecpoint);
1989         EC_KEY_free(srvr_ecdh);
1990         BN_CTX_free(bn_ctx);
1991         return (-1);
1992 }
1993
1994 int
1995 ssl3_get_cert_verify(SSL *s)
1996 {
1997         EVP_PKEY *pkey = NULL;
1998         unsigned char *p;
1999         int al, ok, ret = 0;
2000         long n;
2001         int type = 0, i, j;
2002         X509 *peer;
2003         const EVP_MD *md = NULL;
2004         EVP_MD_CTX mctx;
2005         EVP_MD_CTX_init(&mctx);
2006
2007         n = s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2008             SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2009         if (!ok)
2010                 return ((int)n);
2011
2012         if (s->session->peer != NULL) {
2013                 peer = s->session->peer;
2014                 pkey = X509_get_pubkey(peer);
2015                 type = X509_certificate_type(peer, pkey);
2016         } else {
2017                 peer = NULL;
2018                 pkey = NULL;
2019         }
2020
2021         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2022                 s->s3->tmp.reuse_message = 1;
2023                 if (peer != NULL) {
2024                         al = SSL_AD_UNEXPECTED_MESSAGE;
2025                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2026                             SSL_R_MISSING_VERIFY_MESSAGE);
2027                         goto f_err;
2028                 }
2029                 ret = 1;
2030                 goto end;
2031         }
2032
2033         if (peer == NULL) {
2034                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2035                     SSL_R_NO_CLIENT_CERT_RECEIVED);
2036                 al = SSL_AD_UNEXPECTED_MESSAGE;
2037                 goto f_err;
2038         }
2039
2040         if (!(type & EVP_PKT_SIGN)) {
2041                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2042                     SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2043                 al = SSL_AD_ILLEGAL_PARAMETER;
2044                 goto f_err;
2045         }
2046
2047         if (s->s3->change_cipher_spec) {
2048                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2049                     SSL_R_CCS_RECEIVED_EARLY);
2050                 al = SSL_AD_UNEXPECTED_MESSAGE;
2051                 goto f_err;
2052         }
2053
2054         /* we now have a signature that we need to verify */
2055         p = (unsigned char *)s->init_msg;
2056         /*
2057          * Check for broken implementations of GOST ciphersuites.
2058          *
2059          * If key is GOST and n is exactly 64, it is a bare
2060          * signature without length field.
2061          */
2062         if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2063             pkey->type == NID_id_GostR3410_2001) ) {
2064                 i = 64;
2065         } else {
2066                 if (SSL_USE_SIGALGS(s)) {
2067                         int sigalg = tls12_get_sigid(pkey);
2068                         /* Should never happen */
2069                         if (sigalg == -1) {
2070                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2071                                     ERR_R_INTERNAL_ERROR);
2072                                 al = SSL_AD_INTERNAL_ERROR;
2073                                 goto f_err;
2074                         }
2075                         if (2 > n)
2076                                 goto truncated;
2077                         /* Check key type is consistent with signature */
2078                         if (sigalg != (int)p[1]) {
2079                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2080                                     SSL_R_WRONG_SIGNATURE_TYPE);
2081                                 al = SSL_AD_DECODE_ERROR;
2082                                 goto f_err;
2083                         }
2084                         md = tls12_get_hash(p[0]);
2085                         if (md == NULL) {
2086                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2087                                     SSL_R_UNKNOWN_DIGEST);
2088                                 al = SSL_AD_DECODE_ERROR;
2089                                 goto f_err;
2090                         }
2091                         p += 2;
2092                         n -= 2;
2093                 }
2094                 if (2 > n)
2095                         goto truncated;
2096                 n2s(p, i);
2097                 n -= 2;
2098                 if (i > n)
2099                         goto truncated;
2100         }
2101         j = EVP_PKEY_size(pkey);
2102         if ((i > j) || (n > j) || (n <= 0)) {
2103                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2104                     SSL_R_WRONG_SIGNATURE_SIZE);
2105                 al = SSL_AD_DECODE_ERROR;
2106                 goto f_err;
2107         }
2108
2109         if (SSL_USE_SIGALGS(s)) {
2110                 long hdatalen = 0;
2111                 void *hdata;
2112                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2113                 if (hdatalen <= 0) {
2114                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2115                             ERR_R_INTERNAL_ERROR);
2116                         al = SSL_AD_INTERNAL_ERROR;
2117                         goto f_err;
2118                 }
2119                 if (!EVP_VerifyInit_ex(&mctx, md, NULL) ||
2120                     !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2121                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2122                             ERR_R_EVP_LIB);
2123                         al = SSL_AD_INTERNAL_ERROR;
2124                         goto f_err;
2125                 }
2126
2127                 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2128                         al = SSL_AD_DECRYPT_ERROR;
2129                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2130                             SSL_R_BAD_SIGNATURE);
2131                         goto f_err;
2132                 }
2133         } else
2134         if (pkey->type == EVP_PKEY_RSA) {
2135                 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2136                     MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2137                     pkey->pkey.rsa);
2138                 if (i < 0) {
2139                         al = SSL_AD_DECRYPT_ERROR;
2140                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2141                             SSL_R_BAD_RSA_DECRYPT);
2142                         goto f_err;
2143                 }
2144                 if (i == 0) {
2145                         al = SSL_AD_DECRYPT_ERROR;
2146                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2147                             SSL_R_BAD_RSA_SIGNATURE);
2148                         goto f_err;
2149                 }
2150         } else
2151         if (pkey->type == EVP_PKEY_DSA) {
2152                 j = DSA_verify(pkey->save_type,
2153                     &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2154                     SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2155                 if (j <= 0) {
2156                         /* bad signature */
2157                         al = SSL_AD_DECRYPT_ERROR;
2158                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2159                             SSL_R_BAD_DSA_SIGNATURE);
2160                         goto f_err;
2161                 }
2162         } else
2163         if (pkey->type == EVP_PKEY_EC) {
2164                 j = ECDSA_verify(pkey->save_type,
2165                     &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2166                     SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2167                 if (j <= 0) {
2168                         /* bad signature */
2169                         al = SSL_AD_DECRYPT_ERROR;
2170                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2171                             SSL_R_BAD_ECDSA_SIGNATURE);
2172                         goto f_err;
2173                 }
2174         } else
2175 #ifndef OPENSSL_NO_GOST
2176         if (pkey->type == NID_id_GostR3410_94 ||
2177             pkey->type == NID_id_GostR3410_2001) {
2178                 long hdatalen = 0;
2179                 void *hdata;
2180                 unsigned char signature[128];
2181                 unsigned int siglen = sizeof(signature);
2182                 int nid;
2183                 EVP_PKEY_CTX *pctx;
2184
2185                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2186                 if (hdatalen <= 0) {
2187                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2188                             ERR_R_INTERNAL_ERROR);
2189                         al = SSL_AD_INTERNAL_ERROR;
2190                         goto f_err;
2191                 }
2192                 if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2193                                 !(md = EVP_get_digestbynid(nid))) {
2194                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2195                                         ERR_R_EVP_LIB);
2196                         al = SSL_AD_INTERNAL_ERROR;
2197                         goto f_err;
2198                 }
2199                 pctx = EVP_PKEY_CTX_new(pkey, NULL);
2200                 if (!pctx) {
2201                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2202                             ERR_R_EVP_LIB);
2203                         al = SSL_AD_INTERNAL_ERROR;
2204                         goto f_err;
2205                 }
2206                 if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2207                     !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2208                     !EVP_DigestFinal(&mctx, signature, &siglen) ||
2209                     (EVP_PKEY_verify_init(pctx) <= 0) ||
2210                     (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2211                     (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2212                                        EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2213                                        GOST_SIG_FORMAT_RS_LE,
2214                                        NULL) <= 0)) {
2215                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2216                             ERR_R_EVP_LIB);
2217                         al = SSL_AD_INTERNAL_ERROR;
2218                         EVP_PKEY_CTX_free(pctx);
2219                         goto f_err;
2220                 }
2221
2222                 if (EVP_PKEY_verify(pctx, p, i, signature, siglen) <= 0) {
2223                         al = SSL_AD_DECRYPT_ERROR;
2224                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2225                             SSL_R_BAD_SIGNATURE);
2226                         EVP_PKEY_CTX_free(pctx);
2227                         goto f_err;
2228                 }
2229
2230                 EVP_PKEY_CTX_free(pctx);
2231         } else
2232 #endif
2233         {
2234                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2235                     ERR_R_INTERNAL_ERROR);
2236                 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2237                 goto f_err;
2238         }
2239
2240
2241         ret = 1;
2242         if (0) {
2243 truncated:
2244                 al = SSL_AD_DECODE_ERROR;
2245                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_PACKET_LENGTH);
2246 f_err:
2247                 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2248         }
2249 end:
2250         if (s->s3->handshake_buffer) {
2251                 BIO_free(s->s3->handshake_buffer);
2252                 s->s3->handshake_buffer = NULL;
2253                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2254         }
2255         EVP_MD_CTX_cleanup(&mctx);
2256         EVP_PKEY_free(pkey);
2257         return (ret);
2258 }
2259
2260 int
2261 ssl3_get_client_certificate(SSL *s)
2262 {
2263         CBS cbs, client_certs;
2264         int i, ok, al, ret = -1;
2265         X509 *x = NULL;
2266         long n;
2267         const unsigned char *q;
2268         STACK_OF(X509) *sk = NULL;
2269
2270         n = s->method->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2271             -1, s->max_cert_list, &ok);
2272
2273         if (!ok)
2274                 return ((int)n);
2275
2276         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2277                 if ((s->verify_mode & SSL_VERIFY_PEER) &&
2278                     (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2279                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2280                             SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2281                         al = SSL_AD_HANDSHAKE_FAILURE;
2282                         goto f_err;
2283                 }
2284                 /*
2285                  * If tls asked for a client cert,
2286                  * the client must return a 0 list.
2287                  */
2288                 if (s->s3->tmp.cert_request) {
2289                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2290                             SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2291                             );
2292                         al = SSL_AD_UNEXPECTED_MESSAGE;
2293                         goto f_err;
2294                 }
2295                 s->s3->tmp.reuse_message = 1;
2296                 return (1);
2297         }
2298
2299         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
2300                 al = SSL_AD_UNEXPECTED_MESSAGE;
2301                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2302                     SSL_R_WRONG_MESSAGE_TYPE);
2303                 goto f_err;
2304         }
2305
2306         if (n < 0)
2307                 goto truncated;
2308
2309         CBS_init(&cbs, s->init_msg, n);
2310
2311         if ((sk = sk_X509_new_null()) == NULL) {
2312                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2313                     ERR_R_MALLOC_FAILURE);
2314                 goto err;
2315         }
2316
2317         if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2318             CBS_len(&cbs) != 0)
2319                 goto truncated;
2320
2321         while (CBS_len(&client_certs) > 0) {
2322                 CBS cert;
2323
2324                 if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2325                         al = SSL_AD_DECODE_ERROR;
2326                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2327                             SSL_R_CERT_LENGTH_MISMATCH);
2328                         goto f_err;
2329                 }
2330
2331                 q = CBS_data(&cert);
2332                 x = d2i_X509(NULL, &q, CBS_len(&cert));
2333                 if (x == NULL) {
2334                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2335                             ERR_R_ASN1_LIB);
2336                         goto err;
2337                 }
2338                 if (q != CBS_data(&cert) + CBS_len(&cert)) {
2339                         al = SSL_AD_DECODE_ERROR;
2340                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2341                             SSL_R_CERT_LENGTH_MISMATCH);
2342                         goto f_err;
2343                 }
2344                 if (!sk_X509_push(sk, x)) {
2345                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2346                             ERR_R_MALLOC_FAILURE);
2347                         goto err;
2348                 }
2349                 x = NULL;
2350         }
2351
2352         if (sk_X509_num(sk) <= 0) {
2353                 /*
2354                  * TLS does not mind 0 certs returned.
2355                  * Fail for TLS only if we required a certificate.
2356                  */
2357                 if ((s->verify_mode & SSL_VERIFY_PEER) &&
2358                     (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2359                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2360                             SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2361                         al = SSL_AD_HANDSHAKE_FAILURE;
2362                         goto f_err;
2363                 }
2364                 /* No client certificate so digest cached records */
2365                 if (s->s3->handshake_buffer && !tls1_digest_cached_records(s)) {
2366                         al = SSL_AD_INTERNAL_ERROR;
2367                         goto f_err;
2368                 }
2369         } else {
2370                 i = ssl_verify_cert_chain(s, sk);
2371                 if (i <= 0) {
2372                         al = ssl_verify_alarm_type(s->verify_result);
2373                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2374                             SSL_R_NO_CERTIFICATE_RETURNED);
2375                         goto f_err;
2376                 }
2377         }
2378
2379         X509_free(s->session->peer);
2380         s->session->peer = sk_X509_shift(sk);
2381         s->session->verify_result = s->verify_result;
2382
2383         /*
2384          * With the current implementation, sess_cert will always be NULL
2385          * when we arrive here
2386          */
2387         if (s->session->sess_cert == NULL) {
2388                 s->session->sess_cert = ssl_sess_cert_new();
2389                 if (s->session->sess_cert == NULL) {
2390                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2391                             ERR_R_MALLOC_FAILURE);
2392                         goto err;
2393                 }
2394         }
2395         if (s->session->sess_cert->cert_chain != NULL)
2396                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2397         s->session->sess_cert->cert_chain = sk;
2398
2399         /*
2400          * Inconsistency alert: cert_chain does *not* include the
2401          * peer's own certificate, while we do include it in s3_clnt.c
2402          */
2403
2404         sk = NULL;
2405
2406         ret = 1;
2407         if (0) {
2408 truncated:
2409                 al = SSL_AD_DECODE_ERROR;
2410                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2411                     SSL_R_BAD_PACKET_LENGTH);
2412 f_err:
2413                 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2414         }
2415 err:
2416         X509_free(x);
2417         if (sk != NULL)
2418                 sk_X509_pop_free(sk, X509_free);
2419         return (ret);
2420 }
2421
2422 int
2423 ssl3_send_server_certificate(SSL *s)
2424 {
2425         unsigned long l;
2426         X509 *x;
2427
2428         if (s->state == SSL3_ST_SW_CERT_A) {
2429                 x = ssl_get_server_send_cert(s);
2430                 if (x == NULL) {
2431                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
2432                             ERR_R_INTERNAL_ERROR);
2433                         return (0);
2434                 }
2435
2436                 l = ssl3_output_cert_chain(s, x);
2437                 s->state = SSL3_ST_SW_CERT_B;
2438                 s->init_num = (int)l;
2439                 s->init_off = 0;
2440         }
2441
2442         /* SSL3_ST_SW_CERT_B */
2443         return (ssl3_handshake_write(s));
2444 }
2445
2446 /* send a new session ticket (not necessarily for a new session) */
2447 int
2448 ssl3_send_newsession_ticket(SSL *s)
2449 {
2450         if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
2451                 unsigned char *d, *p, *senc, *macstart;
2452                 const unsigned char *const_p;
2453                 int len, slen_full, slen;
2454                 SSL_SESSION *sess;
2455                 unsigned int hlen;
2456                 EVP_CIPHER_CTX ctx;
2457                 HMAC_CTX hctx;
2458                 SSL_CTX *tctx = s->initial_ctx;
2459                 unsigned char iv[EVP_MAX_IV_LENGTH];
2460                 unsigned char key_name[16];
2461
2462                 /* get session encoding length */
2463                 slen_full = i2d_SSL_SESSION(s->session, NULL);
2464                 /*
2465                  * Some length values are 16 bits, so forget it if session is
2466                  * too long
2467                  */
2468                 if (slen_full > 0xFF00)
2469                         return (-1);
2470                 senc = malloc(slen_full);
2471                 if (!senc)
2472                         return (-1);
2473                 p = senc;
2474                 i2d_SSL_SESSION(s->session, &p);
2475
2476                 /*
2477                  * Create a fresh copy (not shared with other threads) to
2478                  * clean up
2479                  */
2480                 const_p = senc;
2481                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2482                 if (sess == NULL) {
2483                         free(senc);
2484                         return (-1);
2485                 }
2486
2487                 /* ID is irrelevant for the ticket */
2488                 sess->session_id_length = 0;
2489
2490                 slen = i2d_SSL_SESSION(sess, NULL);
2491                 if (slen > slen_full) {
2492                         /* shouldn't ever happen */
2493                         free(senc);
2494                         return (-1);
2495                 }
2496                 p = senc;
2497                 i2d_SSL_SESSION(sess, &p);
2498                 SSL_SESSION_free(sess);
2499
2500                 /*
2501                  * Grow buffer if need be: the length calculation is as
2502                  * follows 1 (size of message name) + 3 (message length
2503                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2504                  * 16 (key name) + max_iv_len (iv length) +
2505                  * session_length + max_enc_block_size (max encrypted session
2506                  * length) + max_md_size (HMAC).
2507                  */
2508                 if (!BUF_MEM_grow(s->init_buf, ssl3_handshake_msg_hdr_len(s) +
2509                     22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2510                     EVP_MAX_MD_SIZE + slen)) {
2511                         free(senc);
2512                         return (-1);
2513                 }
2514
2515                 d = p = ssl3_handshake_msg_start(s, SSL3_MT_NEWSESSION_TICKET);
2516
2517                 EVP_CIPHER_CTX_init(&ctx);
2518                 HMAC_CTX_init(&hctx);
2519
2520                 /*
2521                  * Initialize HMAC and cipher contexts. If callback present
2522                  * it does all the work otherwise use generated values
2523                  * from parent ctx.
2524                  */
2525                 if (tctx->tlsext_ticket_key_cb) {
2526                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2527                             &hctx, 1) < 0) {
2528                                 free(senc);
2529                                 EVP_CIPHER_CTX_cleanup(&ctx);
2530                                 return (-1);
2531                         }
2532                 } else {
2533                         arc4random_buf(iv, 16);
2534                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2535                             tctx->tlsext_tick_aes_key, iv);
2536                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2537                             tlsext_tick_md(), NULL);
2538                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2539                 }
2540
2541                 /*
2542                  * Ticket lifetime hint (advisory only):
2543                  * We leave this unspecified for resumed session
2544                  * (for simplicity), and guess that tickets for new
2545                  * sessions will live as long as their sessions.
2546                  */
2547                 l2n(s->hit ? 0 : s->session->timeout, p);
2548
2549                 /* Skip ticket length for now */
2550                 p += 2;
2551                 /* Output key name */
2552                 macstart = p;
2553                 memcpy(p, key_name, 16);
2554                 p += 16;
2555                 /* output IV */
2556                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2557                 p += EVP_CIPHER_CTX_iv_length(&ctx);
2558                 /* Encrypt session data */
2559                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2560                 p += len;
2561                 EVP_EncryptFinal_ex(&ctx, p, &len);
2562                 p += len;
2563                 EVP_CIPHER_CTX_cleanup(&ctx);
2564
2565                 HMAC_Update(&hctx, macstart, p - macstart);
2566                 HMAC_Final(&hctx, p, &hlen);
2567                 HMAC_CTX_cleanup(&hctx);
2568                 p += hlen;
2569
2570                 /* Now write out lengths: p points to end of data written */
2571                 /* Total length */
2572                 len = p - d;
2573
2574                 /* Skip ticket lifetime hint. */
2575                 p = d + 4;
2576                 s2n(len - 6, p); /* Message length */
2577
2578                 ssl3_handshake_msg_finish(s, len);
2579
2580                 s->state = SSL3_ST_SW_SESSION_TICKET_B;
2581
2582                 free(senc);
2583         }
2584
2585         /* SSL3_ST_SW_SESSION_TICKET_B */
2586         return (ssl3_handshake_write(s));
2587 }
2588
2589 int
2590 ssl3_send_cert_status(SSL *s)
2591 {
2592         unsigned char *p;
2593
2594         if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
2595                 /*
2596                  * Grow buffer if need be: the length calculation is as
2597                  * follows 1 (message type) + 3 (message length) +
2598                  * 1 (ocsp response type) + 3 (ocsp response length)
2599                  * + (ocsp response)
2600                  */
2601                 if (!BUF_MEM_grow(s->init_buf, SSL3_HM_HEADER_LENGTH + 4 +
2602                     s->tlsext_ocsp_resplen))
2603                         return (-1);
2604
2605                 p = ssl3_handshake_msg_start(s, SSL3_MT_CERTIFICATE_STATUS);
2606
2607                 *(p++) = s->tlsext_status_type;
2608                 l2n3(s->tlsext_ocsp_resplen, p);
2609                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2610
2611                 ssl3_handshake_msg_finish(s, s->tlsext_ocsp_resplen + 4);
2612
2613                 s->state = SSL3_ST_SW_CERT_STATUS_B;
2614         }
2615
2616         /* SSL3_ST_SW_CERT_STATUS_B */
2617         return (ssl3_handshake_write(s));
2618 }
2619
2620 /*
2621  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
2622  * It sets the next_proto member in s if found
2623  */
2624 int
2625 ssl3_get_next_proto(SSL *s)
2626 {
2627         CBS cbs, proto, padding;
2628         int ok;
2629         long n;
2630         size_t len;
2631
2632         /*
2633          * Clients cannot send a NextProtocol message if we didn't see the
2634          * extension in their ClientHello
2635          */
2636         if (!s->s3->next_proto_neg_seen) {
2637                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
2638                     SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2639                 return (-1);
2640         }
2641
2642         /* 514 maxlen is enough for the payload format below */
2643         n = s->method->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A,
2644             SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO, 514, &ok);
2645         if (!ok)
2646                 return ((int)n);
2647
2648         /*
2649          * s->state doesn't reflect whether ChangeCipherSpec has been received
2650          * in this handshake, but s->s3->change_cipher_spec does (will be reset
2651          * by ssl3_get_finished).
2652          */
2653         if (!s->s3->change_cipher_spec) {
2654                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
2655                     SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2656                 return (-1);
2657         }
2658
2659         if (n < 2)
2660                 return (0);
2661         /* The body must be > 1 bytes long */
2662
2663         CBS_init(&cbs, s->init_msg, s->init_num);
2664
2665         /*
2666          * The payload looks like:
2667          *   uint8 proto_len;
2668          *   uint8 proto[proto_len];
2669          *   uint8 padding_len;
2670          *   uint8 padding[padding_len];
2671          */
2672         if (!CBS_get_u8_length_prefixed(&cbs, &proto) ||
2673             !CBS_get_u8_length_prefixed(&cbs, &padding) ||
2674             CBS_len(&cbs) != 0)
2675                 return 0;
2676
2677         /*
2678          * XXX We should not NULL it, but this matches old behavior of not
2679          * freeing before malloc.
2680          */
2681         s->next_proto_negotiated = NULL;
2682         s->next_proto_negotiated_len = 0;
2683
2684         if (!CBS_stow(&proto, &s->next_proto_negotiated, &len)) {
2685                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
2686                     ERR_R_MALLOC_FAILURE);
2687                 return (0);
2688         }
2689         s->next_proto_negotiated_len = (uint8_t)len;
2690
2691         return (1);
2692 }