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