xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /* $OpenBSD: ssl_clnt.c,v 1.23 2018/02/08 11:30:30 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 <limits.h>
152 #include <stdint.h>
153 #include <stdio.h>
154 
155 #include "ssl_locl.h"
156 
157 #include <openssl/bn.h>
158 #include <openssl/buffer.h>
159 #include <openssl/curve25519.h>
160 #include <openssl/dh.h>
161 #include <openssl/evp.h>
162 #include <openssl/md5.h>
163 #include <openssl/objects.h>
164 
165 #ifndef OPENSSL_NO_ENGINE
166 #include <openssl/engine.h>
167 #endif
168 #ifndef OPENSSL_NO_GOST
169 #include <openssl/gost.h>
170 #endif
171 
172 #include "bytestring.h"
173 #include "ssl_tlsext.h"
174 
175 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b);
176 
177 int
178 ssl3_connect(SSL *s)
179 {
180 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
181 	int ret = -1;
182 	int new_state, state, skip = 0;
183 
184 	ERR_clear_error();
185 	errno = 0;
186 
187 	if (s->internal->info_callback != NULL)
188 		cb = s->internal->info_callback;
189 	else if (s->ctx->internal->info_callback != NULL)
190 		cb = s->ctx->internal->info_callback;
191 
192 	s->internal->in_handshake++;
193 	if (!SSL_in_init(s) || SSL_in_before(s))
194 		SSL_clear(s);
195 
196 	for (;;) {
197 		state = S3I(s)->hs.state;
198 
199 		switch (S3I(s)->hs.state) {
200 		case SSL_ST_RENEGOTIATE:
201 			s->internal->renegotiate = 1;
202 			S3I(s)->hs.state = SSL_ST_CONNECT;
203 			s->ctx->internal->stats.sess_connect_renegotiate++;
204 			/* break */
205 		case SSL_ST_BEFORE:
206 		case SSL_ST_CONNECT:
207 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
208 		case SSL_ST_OK|SSL_ST_CONNECT:
209 
210 			s->server = 0;
211 			if (cb != NULL)
212 				cb(s, SSL_CB_HANDSHAKE_START, 1);
213 
214 			if (SSL_IS_DTLS(s)) {
215 				if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
216 					SSLerror(s, ERR_R_INTERNAL_ERROR);
217 					ret = -1;
218 					goto end;
219 				}
220 			} else {
221 				if ((s->version & 0xff00) != 0x0300) {
222 					SSLerror(s, ERR_R_INTERNAL_ERROR);
223 					ret = -1;
224 					goto end;
225 				}
226 			}
227 
228 			/* s->version=SSL3_VERSION; */
229 			s->internal->type = SSL_ST_CONNECT;
230 
231 			if (!ssl3_setup_init_buffer(s)) {
232 				ret = -1;
233 				goto end;
234 			}
235 			if (!ssl3_setup_buffers(s)) {
236 				ret = -1;
237 				goto end;
238 			}
239 			if (!ssl_init_wbio_buffer(s, 0)) {
240 				ret = -1;
241 				goto end;
242 			}
243 
244 			/* don't push the buffering BIO quite yet */
245 
246 			if (!SSL_IS_DTLS(s)) {
247 				if (!tls1_init_finished_mac(s)) {
248 					ret = -1;
249 					goto end;
250 				}
251 			}
252 
253 			S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
254 			s->ctx->internal->stats.sess_connect++;
255 			s->internal->init_num = 0;
256 
257 			if (SSL_IS_DTLS(s)) {
258 				/* mark client_random uninitialized */
259 				memset(s->s3->client_random, 0,
260 				    sizeof(s->s3->client_random));
261 				D1I(s)->send_cookie = 0;
262 				s->internal->hit = 0;
263 			}
264 			break;
265 
266 		case SSL3_ST_CW_CLNT_HELLO_A:
267 		case SSL3_ST_CW_CLNT_HELLO_B:
268 			s->internal->shutdown = 0;
269 
270 			if (SSL_IS_DTLS(s)) {
271 				/* every DTLS ClientHello resets Finished MAC */
272 				if (!tls1_init_finished_mac(s)) {
273 					ret = -1;
274 					goto end;
275 				}
276 
277 				dtls1_start_timer(s);
278 			}
279 
280 			ret = ssl3_send_client_hello(s);
281 			if (ret <= 0)
282 				goto end;
283 
284 			if (SSL_IS_DTLS(s) && D1I(s)->send_cookie) {
285 				S3I(s)->hs.state = SSL3_ST_CW_FLUSH;
286 				S3I(s)->hs.next_state = SSL3_ST_CR_SRVR_HELLO_A;
287 			} else
288 				S3I(s)->hs.state = SSL3_ST_CR_SRVR_HELLO_A;
289 
290 			s->internal->init_num = 0;
291 
292 			/* turn on buffering for the next lot of output */
293 			if (s->bbio != s->wbio)
294 				s->wbio = BIO_push(s->bbio, s->wbio);
295 
296 			break;
297 
298 		case SSL3_ST_CR_SRVR_HELLO_A:
299 		case SSL3_ST_CR_SRVR_HELLO_B:
300 			ret = ssl3_get_server_hello(s);
301 			if (ret <= 0)
302 				goto end;
303 
304 			if (s->internal->hit) {
305 				S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
306 				if (!SSL_IS_DTLS(s)) {
307 					if (s->internal->tlsext_ticket_expected) {
308 						/* receive renewed session ticket */
309 						S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
310 					}
311 				}
312 			} else if (SSL_IS_DTLS(s)) {
313 				S3I(s)->hs.state = DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
314 			} else {
315 				S3I(s)->hs.state = SSL3_ST_CR_CERT_A;
316 			}
317 			s->internal->init_num = 0;
318 			break;
319 
320 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
321 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
322 			ret = dtls1_get_hello_verify(s);
323 			if (ret <= 0)
324 				goto end;
325 			dtls1_stop_timer(s);
326 			if (D1I(s)->send_cookie) /* start again, with a cookie */
327 				S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
328 			else
329 				S3I(s)->hs.state = SSL3_ST_CR_CERT_A;
330 			s->internal->init_num = 0;
331 			break;
332 
333 		case SSL3_ST_CR_CERT_A:
334 		case SSL3_ST_CR_CERT_B:
335 			ret = ssl3_check_finished(s);
336 			if (ret <= 0)
337 				goto end;
338 			if (ret == 2) {
339 				s->internal->hit = 1;
340 				if (s->internal->tlsext_ticket_expected)
341 					S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
342 				else
343 					S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
344 				s->internal->init_num = 0;
345 				break;
346 			}
347 			/* Check if it is anon DH/ECDH. */
348 			if (!(S3I(s)->hs.new_cipher->algorithm_auth &
349 			    SSL_aNULL)) {
350 				ret = ssl3_get_server_certificate(s);
351 				if (ret <= 0)
352 					goto end;
353 				if (s->internal->tlsext_status_expected)
354 					S3I(s)->hs.state = SSL3_ST_CR_CERT_STATUS_A;
355 				else
356 					S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
357 			} else {
358 				skip = 1;
359 				S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
360 			}
361 			s->internal->init_num = 0;
362 			break;
363 
364 		case SSL3_ST_CR_KEY_EXCH_A:
365 		case SSL3_ST_CR_KEY_EXCH_B:
366 			ret = ssl3_get_server_key_exchange(s);
367 			if (ret <= 0)
368 				goto end;
369 			S3I(s)->hs.state = SSL3_ST_CR_CERT_REQ_A;
370 			s->internal->init_num = 0;
371 
372 			/*
373 			 * At this point we check that we have the
374 			 * required stuff from the server.
375 			 */
376 			if (!ssl3_check_cert_and_algorithm(s)) {
377 				ret = -1;
378 				goto end;
379 			}
380 			break;
381 
382 		case SSL3_ST_CR_CERT_REQ_A:
383 		case SSL3_ST_CR_CERT_REQ_B:
384 			ret = ssl3_get_certificate_request(s);
385 			if (ret <= 0)
386 				goto end;
387 			S3I(s)->hs.state = SSL3_ST_CR_SRVR_DONE_A;
388 			s->internal->init_num = 0;
389 			break;
390 
391 		case SSL3_ST_CR_SRVR_DONE_A:
392 		case SSL3_ST_CR_SRVR_DONE_B:
393 			ret = ssl3_get_server_done(s);
394 			if (ret <= 0)
395 				goto end;
396 			if (SSL_IS_DTLS(s))
397 				dtls1_stop_timer(s);
398 			if (S3I(s)->tmp.cert_req)
399 				S3I(s)->hs.state = SSL3_ST_CW_CERT_A;
400 			else
401 				S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_A;
402 			s->internal->init_num = 0;
403 
404 			break;
405 
406 		case SSL3_ST_CW_CERT_A:
407 		case SSL3_ST_CW_CERT_B:
408 		case SSL3_ST_CW_CERT_C:
409 		case SSL3_ST_CW_CERT_D:
410 			if (SSL_IS_DTLS(s))
411 				dtls1_start_timer(s);
412 			ret = ssl3_send_client_certificate(s);
413 			if (ret <= 0)
414 				goto end;
415 			S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_A;
416 			s->internal->init_num = 0;
417 			break;
418 
419 		case SSL3_ST_CW_KEY_EXCH_A:
420 		case SSL3_ST_CW_KEY_EXCH_B:
421 			if (SSL_IS_DTLS(s))
422 				dtls1_start_timer(s);
423 			ret = ssl3_send_client_key_exchange(s);
424 			if (ret <= 0)
425 				goto end;
426 			/*
427 			 * EAY EAY EAY need to check for DH fix cert
428 			 * sent back
429 			 */
430 			/*
431 			 * For TLS, cert_req is set to 2, so a cert chain
432 			 * of nothing is sent, but no verify packet is sent
433 			 */
434 			/*
435 			 * XXX: For now, we do not support client
436 			 * authentication in ECDH cipher suites with
437 			 * ECDH (rather than ECDSA) certificates.
438 			 * We need to skip the certificate verify
439 			 * message when client's ECDH public key is sent
440 			 * inside the client certificate.
441 			 */
442 			if (S3I(s)->tmp.cert_req == 1) {
443 				S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_A;
444 			} else {
445 				S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
446 				S3I(s)->change_cipher_spec = 0;
447 			}
448 			if (!SSL_IS_DTLS(s)) {
449 				if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
450 					S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
451 					S3I(s)->change_cipher_spec = 0;
452 				}
453 			}
454 
455 			s->internal->init_num = 0;
456 			break;
457 
458 		case SSL3_ST_CW_CERT_VRFY_A:
459 		case SSL3_ST_CW_CERT_VRFY_B:
460 			if (SSL_IS_DTLS(s))
461 				dtls1_start_timer(s);
462 			ret = ssl3_send_client_verify(s);
463 			if (ret <= 0)
464 				goto end;
465 			S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
466 			s->internal->init_num = 0;
467 			S3I(s)->change_cipher_spec = 0;
468 			break;
469 
470 		case SSL3_ST_CW_CHANGE_A:
471 		case SSL3_ST_CW_CHANGE_B:
472 			if (SSL_IS_DTLS(s) && !s->internal->hit)
473 				dtls1_start_timer(s);
474 			ret = ssl3_send_change_cipher_spec(s,
475 			    SSL3_ST_CW_CHANGE_A, SSL3_ST_CW_CHANGE_B);
476 			if (ret <= 0)
477 				goto end;
478 
479 			S3I(s)->hs.state = SSL3_ST_CW_FINISHED_A;
480 			s->internal->init_num = 0;
481 
482 			s->session->cipher = S3I(s)->hs.new_cipher;
483 			if (!tls1_setup_key_block(s)) {
484 				ret = -1;
485 				goto end;
486 			}
487 
488 			if (!tls1_change_cipher_state(s,
489 			    SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
490 				ret = -1;
491 				goto end;
492 			}
493 
494 			if (SSL_IS_DTLS(s))
495 				dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
496 
497 			break;
498 
499 		case SSL3_ST_CW_FINISHED_A:
500 		case SSL3_ST_CW_FINISHED_B:
501 			if (SSL_IS_DTLS(s) && !s->internal->hit)
502 				dtls1_start_timer(s);
503 			ret = ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,
504 			    SSL3_ST_CW_FINISHED_B, TLS_MD_CLIENT_FINISH_CONST,
505 			    TLS_MD_CLIENT_FINISH_CONST_SIZE);
506 			if (ret <= 0)
507 				goto end;
508 			if (!SSL_IS_DTLS(s))
509 				s->s3->flags |= SSL3_FLAGS_CCS_OK;
510 			S3I(s)->hs.state = SSL3_ST_CW_FLUSH;
511 
512 			/* clear flags */
513 			s->s3->flags &= ~SSL3_FLAGS_POP_BUFFER;
514 			if (s->internal->hit) {
515 				S3I(s)->hs.next_state = SSL_ST_OK;
516 				if (s->s3->flags &
517 				    SSL3_FLAGS_DELAY_CLIENT_FINISHED) {
518 					S3I(s)->hs.state = SSL_ST_OK;
519 					s->s3->flags |= SSL3_FLAGS_POP_BUFFER;
520 					S3I(s)->delay_buf_pop_ret = 0;
521 				}
522 			} else {
523 				/* Allow NewSessionTicket if ticket expected */
524 				if (s->internal->tlsext_ticket_expected)
525 					S3I(s)->hs.next_state =
526 					    SSL3_ST_CR_SESSION_TICKET_A;
527 				else
528 					S3I(s)->hs.next_state =
529 					    SSL3_ST_CR_FINISHED_A;
530 			}
531 			s->internal->init_num = 0;
532 			break;
533 
534 		case SSL3_ST_CR_SESSION_TICKET_A:
535 		case SSL3_ST_CR_SESSION_TICKET_B:
536 			ret = ssl3_get_new_session_ticket(s);
537 			if (ret <= 0)
538 				goto end;
539 			S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
540 			s->internal->init_num = 0;
541 			break;
542 
543 		case SSL3_ST_CR_CERT_STATUS_A:
544 		case SSL3_ST_CR_CERT_STATUS_B:
545 			ret = ssl3_get_cert_status(s);
546 			if (ret <= 0)
547 				goto end;
548 			S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
549 			s->internal->init_num = 0;
550 			break;
551 
552 		case SSL3_ST_CR_FINISHED_A:
553 		case SSL3_ST_CR_FINISHED_B:
554 			if (SSL_IS_DTLS(s))
555 				D1I(s)->change_cipher_spec_ok = 1;
556 			else
557 				s->s3->flags |= SSL3_FLAGS_CCS_OK;
558 			ret = ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A,
559 			    SSL3_ST_CR_FINISHED_B);
560 			if (ret <= 0)
561 				goto end;
562 			if (SSL_IS_DTLS(s))
563 				dtls1_stop_timer(s);
564 
565 			if (s->internal->hit)
566 				S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
567 			else
568 				S3I(s)->hs.state = SSL_ST_OK;
569 			s->internal->init_num = 0;
570 			break;
571 
572 		case SSL3_ST_CW_FLUSH:
573 			s->internal->rwstate = SSL_WRITING;
574 			if (BIO_flush(s->wbio) <= 0) {
575 				if (SSL_IS_DTLS(s)) {
576 					/* If the write error was fatal, stop trying */
577 					if (!BIO_should_retry(s->wbio)) {
578 						s->internal->rwstate = SSL_NOTHING;
579 						S3I(s)->hs.state = S3I(s)->hs.next_state;
580 					}
581 				}
582 				ret = -1;
583 				goto end;
584 			}
585 			s->internal->rwstate = SSL_NOTHING;
586 			S3I(s)->hs.state = S3I(s)->hs.next_state;
587 			break;
588 
589 		case SSL_ST_OK:
590 			/* clean a few things up */
591 			tls1_cleanup_key_block(s);
592 
593 			if (!SSL_IS_DTLS(s)) {
594 				BUF_MEM_free(s->internal->init_buf);
595 				s->internal->init_buf = NULL;
596 			}
597 
598 			/*
599 			 * If we are not 'joining' the last two packets,
600 			 * remove the buffering now
601 			 */
602 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
603 				ssl_free_wbio_buffer(s);
604 			/* else do it later in ssl3_write */
605 
606 			s->internal->init_num = 0;
607 			s->internal->renegotiate = 0;
608 			s->internal->new_session = 0;
609 
610 			ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
611 			if (s->internal->hit)
612 				s->ctx->internal->stats.sess_hit++;
613 
614 			ret = 1;
615 			/* s->server=0; */
616 			s->internal->handshake_func = ssl3_connect;
617 			s->ctx->internal->stats.sess_connect_good++;
618 
619 			if (cb != NULL)
620 				cb(s, SSL_CB_HANDSHAKE_DONE, 1);
621 
622 			if (SSL_IS_DTLS(s)) {
623 				/* done with handshaking */
624 				D1I(s)->handshake_read_seq = 0;
625 				D1I(s)->next_handshake_write_seq = 0;
626 			}
627 
628 			goto end;
629 			/* break; */
630 
631 		default:
632 			SSLerror(s, SSL_R_UNKNOWN_STATE);
633 			ret = -1;
634 			goto end;
635 			/* break; */
636 		}
637 
638 		/* did we do anything */
639 		if (!S3I(s)->tmp.reuse_message && !skip) {
640 			if (s->internal->debug) {
641 				if ((ret = BIO_flush(s->wbio)) <= 0)
642 					goto end;
643 			}
644 
645 			if ((cb != NULL) && (S3I(s)->hs.state != state)) {
646 				new_state = S3I(s)->hs.state;
647 				S3I(s)->hs.state = state;
648 				cb(s, SSL_CB_CONNECT_LOOP, 1);
649 				S3I(s)->hs.state = new_state;
650 			}
651 		}
652 		skip = 0;
653 	}
654 
655 end:
656 	s->internal->in_handshake--;
657 	if (cb != NULL)
658 		cb(s, SSL_CB_CONNECT_EXIT, ret);
659 
660 	return (ret);
661 }
662 
663 int
664 ssl3_send_client_hello(SSL *s)
665 {
666 	CBB cbb, client_hello, session_id, cookie, cipher_suites;
667 	CBB compression_methods;
668 	uint16_t max_version;
669 	size_t sl;
670 
671 	memset(&cbb, 0, sizeof(cbb));
672 
673 	if (S3I(s)->hs.state == SSL3_ST_CW_CLNT_HELLO_A) {
674 		SSL_SESSION *sess = s->session;
675 
676 		if (ssl_supported_version_range(s, NULL, &max_version) != 1) {
677 			SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
678 			return (-1);
679 		}
680 		s->client_version = s->version = max_version;
681 
682 		if (sess == NULL ||
683 		    sess->ssl_version != s->version ||
684 		    (!sess->session_id_length && !sess->tlsext_tick) ||
685 		    sess->internal->not_resumable) {
686 			if (!ssl_get_new_session(s, 0))
687 				goto err;
688 		}
689 		/* else use the pre-loaded session */
690 
691 		/*
692 		 * If a DTLS ClientHello message is being resent after a
693 		 * HelloVerifyRequest, we must retain the original client
694 		 * random value.
695 		 */
696 		if (!SSL_IS_DTLS(s) || D1I(s)->send_cookie == 0)
697 			arc4random_buf(s->s3->client_random, SSL3_RANDOM_SIZE);
698 
699 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &client_hello,
700 		    SSL3_MT_CLIENT_HELLO))
701 			goto err;
702 
703 		/*
704 		 * Version indicates the negotiated version: for example from
705 		 * an SSLv2/v3 compatible client hello). The client_version
706 		 * field is the maximum version we permit and it is also
707 		 * used in RSA encrypted premaster secrets. Some servers can
708 		 * choke if we initially report a higher version then
709 		 * renegotiate to a lower one in the premaster secret. This
710 		 * didn't happen with TLS 1.0 as most servers supported it
711 		 * but it can with TLS 1.1 or later if the server only supports
712 		 * 1.0.
713 		 *
714 		 * Possible scenario with previous logic:
715 		 * 	1. Client hello indicates TLS 1.2
716 		 * 	2. Server hello says TLS 1.0
717 		 *	3. RSA encrypted premaster secret uses 1.2.
718 		 * 	4. Handhaked proceeds using TLS 1.0.
719 		 *	5. Server sends hello request to renegotiate.
720 		 *	6. Client hello indicates TLS v1.0 as we now
721 		 *	   know that is maximum server supports.
722 		 *	7. Server chokes on RSA encrypted premaster secret
723 		 *	   containing version 1.0.
724 		 *
725 		 * For interoperability it should be OK to always use the
726 		 * maximum version we support in client hello and then rely
727 		 * on the checking of version to ensure the servers isn't
728 		 * being inconsistent: for example initially negotiating with
729 		 * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
730 		 * client_version in client hello and not resetting it to
731 		 * the negotiated version.
732 		 */
733 		if (!CBB_add_u16(&client_hello, s->client_version))
734 			goto err;
735 
736 		/* Random stuff */
737 		if (!CBB_add_bytes(&client_hello, s->s3->client_random,
738 		    sizeof(s->s3->client_random)))
739 			goto err;
740 
741 		/* Session ID */
742 		if (!CBB_add_u8_length_prefixed(&client_hello, &session_id))
743 			goto err;
744 		if (!s->internal->new_session &&
745 		    s->session->session_id_length > 0) {
746 			sl = s->session->session_id_length;
747 			if (sl > sizeof(s->session->session_id)) {
748 				SSLerror(s, ERR_R_INTERNAL_ERROR);
749 				goto err;
750 			}
751 			if (!CBB_add_bytes(&session_id,
752 			    s->session->session_id, sl))
753 				goto err;
754 		}
755 
756 		/* DTLS Cookie. */
757 		if (SSL_IS_DTLS(s)) {
758 			if (D1I(s)->cookie_len > sizeof(D1I(s)->cookie)) {
759 				SSLerror(s, ERR_R_INTERNAL_ERROR);
760 				goto err;
761 			}
762 			if (!CBB_add_u8_length_prefixed(&client_hello, &cookie))
763 				goto err;
764 			if (!CBB_add_bytes(&cookie, D1I(s)->cookie,
765 			    D1I(s)->cookie_len))
766 				goto err;
767 		}
768 
769 		/* Ciphers supported */
770 		if (!CBB_add_u16_length_prefixed(&client_hello, &cipher_suites))
771 			return 0;
772 		if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s),
773 		    &cipher_suites)) {
774 			SSLerror(s, SSL_R_NO_CIPHERS_AVAILABLE);
775 			goto err;
776 		}
777 
778 		/* Add in compression methods (null) */
779 		if (!CBB_add_u8_length_prefixed(&client_hello,
780 		    &compression_methods))
781 			goto err;
782 		if (!CBB_add_u8(&compression_methods, 0))
783 			goto err;
784 
785 		/* TLS extensions */
786 		if (!tlsext_clienthello_build(s, &client_hello)) {
787 			SSLerror(s, ERR_R_INTERNAL_ERROR);
788 			goto err;
789 		}
790 
791 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
792 			goto err;
793 
794 		S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_B;
795 	}
796 
797 	/* SSL3_ST_CW_CLNT_HELLO_B */
798 	return (ssl3_handshake_write(s));
799 
800 err:
801 	CBB_cleanup(&cbb);
802 
803 	return (-1);
804 }
805 
806 int
807 ssl3_get_server_hello(SSL *s)
808 {
809 	CBS cbs, server_random, session_id;
810 	uint16_t server_version, cipher_suite;
811 	uint16_t min_version, max_version;
812 	uint8_t compression_method;
813 	STACK_OF(SSL_CIPHER) *sk;
814 	const SSL_CIPHER *cipher;
815 	const SSL_METHOD *method;
816 	unsigned long alg_k;
817 	size_t outlen;
818 	int i, al, ok;
819 	long n;
820 
821 	s->internal->first_packet = 1;
822 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
823 	    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok);
824 	if (!ok)
825 		return ((int)n);
826 	s->internal->first_packet = 0;
827 
828 	if (n < 0)
829 		goto truncated;
830 
831 	CBS_init(&cbs, s->internal->init_msg, n);
832 
833 	if (SSL_IS_DTLS(s)) {
834 		if (S3I(s)->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
835 			if (D1I(s)->send_cookie == 0) {
836 				S3I(s)->tmp.reuse_message = 1;
837 				return (1);
838 			} else {
839 				/* Already sent a cookie. */
840 				al = SSL_AD_UNEXPECTED_MESSAGE;
841 				SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
842 				goto f_err;
843 			}
844 		}
845 	}
846 
847 	if (S3I(s)->tmp.message_type != SSL3_MT_SERVER_HELLO) {
848 		al = SSL_AD_UNEXPECTED_MESSAGE;
849 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
850 		goto f_err;
851 	}
852 
853 	if (!CBS_get_u16(&cbs, &server_version))
854 		goto truncated;
855 
856 	if (ssl_supported_version_range(s, &min_version, &max_version) != 1) {
857 		SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
858 		goto err;
859 	}
860 
861 	if (server_version < min_version || server_version > max_version) {
862 		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
863 		s->version = (s->version & 0xff00) | (server_version & 0xff);
864 		al = SSL_AD_PROTOCOL_VERSION;
865 		goto f_err;
866 	}
867 	s->version = server_version;
868 
869 	if ((method = tls1_get_client_method(server_version)) == NULL)
870 		method = dtls1_get_client_method(server_version);
871 	if (method == NULL) {
872 		SSLerror(s, ERR_R_INTERNAL_ERROR);
873 		goto err;
874 	}
875 	s->method = method;
876 
877 	/* Server random. */
878 	if (!CBS_get_bytes(&cbs, &server_random, SSL3_RANDOM_SIZE))
879 		goto truncated;
880 	if (!CBS_write_bytes(&server_random, s->s3->server_random,
881 	    sizeof(s->s3->server_random), NULL))
882 		goto err;
883 
884 	/* Session ID. */
885 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
886 		goto truncated;
887 
888 	if ((CBS_len(&session_id) > sizeof(s->session->session_id)) ||
889 	    (CBS_len(&session_id) > SSL3_SESSION_ID_SIZE)) {
890 		al = SSL_AD_ILLEGAL_PARAMETER;
891 		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
892 		goto f_err;
893 	}
894 
895 	/* Cipher suite. */
896 	if (!CBS_get_u16(&cbs, &cipher_suite))
897 		goto truncated;
898 
899 	/*
900 	 * Check if we want to resume the session based on external
901 	 * pre-shared secret.
902 	 */
903 	if (s->internal->tls_session_secret_cb) {
904 		SSL_CIPHER *pref_cipher = NULL;
905 		s->session->master_key_length = sizeof(s->session->master_key);
906 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
907 		    &s->session->master_key_length, NULL, &pref_cipher,
908 		    s->internal->tls_session_secret_cb_arg)) {
909 			s->session->cipher = pref_cipher ? pref_cipher :
910 			    ssl3_get_cipher_by_value(cipher_suite);
911 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
912 		}
913 	}
914 
915 	if (s->session->session_id_length != 0 &&
916 	    CBS_mem_equal(&session_id, s->session->session_id,
917 		s->session->session_id_length)) {
918 		if (s->sid_ctx_length != s->session->sid_ctx_length ||
919 		    timingsafe_memcmp(s->session->sid_ctx,
920 		    s->sid_ctx, s->sid_ctx_length) != 0) {
921 			/* actually a client application bug */
922 			al = SSL_AD_ILLEGAL_PARAMETER;
923 			SSLerror(s, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
924 			goto f_err;
925 		}
926 		s->s3->flags |= SSL3_FLAGS_CCS_OK;
927 		s->internal->hit = 1;
928 	} else {
929 		/* a miss or crap from the other end */
930 
931 		/* If we were trying for session-id reuse, make a new
932 		 * SSL_SESSION so we don't stuff up other people */
933 		s->internal->hit = 0;
934 		if (s->session->session_id_length > 0) {
935 			if (!ssl_get_new_session(s, 0)) {
936 				al = SSL_AD_INTERNAL_ERROR;
937 				goto f_err;
938 			}
939 		}
940 
941 		/*
942 		 * XXX - improve the handling for the case where there is a
943 		 * zero length session identifier.
944 		 */
945 		if (!CBS_write_bytes(&session_id, s->session->session_id,
946 		    sizeof(s->session->session_id), &outlen))
947 			goto err;
948 		s->session->session_id_length = outlen;
949 
950 		s->session->ssl_version = s->version;
951 	}
952 
953 	if ((cipher = ssl3_get_cipher_by_value(cipher_suite)) == NULL) {
954 		al = SSL_AD_ILLEGAL_PARAMETER;
955 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_RETURNED);
956 		goto f_err;
957 	}
958 
959 	/* TLS v1.2 only ciphersuites require v1.2 or later. */
960 	if ((cipher->algorithm_ssl & SSL_TLSV1_2) &&
961 	    (TLS1_get_version(s) < TLS1_2_VERSION)) {
962 		al = SSL_AD_ILLEGAL_PARAMETER;
963 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
964 		goto f_err;
965 	}
966 
967 	sk = ssl_get_ciphers_by_id(s);
968 	i = sk_SSL_CIPHER_find(sk, cipher);
969 	if (i < 0) {
970 		/* we did not say we would use this cipher */
971 		al = SSL_AD_ILLEGAL_PARAMETER;
972 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
973 		goto f_err;
974 	}
975 
976 	/*
977 	 * Depending on the session caching (internal/external), the cipher
978 	 * and/or cipher_id values may not be set. Make sure that
979 	 * cipher_id is set and use it for comparison.
980 	 */
981 	if (s->session->cipher)
982 		s->session->cipher_id = s->session->cipher->id;
983 	if (s->internal->hit && (s->session->cipher_id != cipher->id)) {
984 		al = SSL_AD_ILLEGAL_PARAMETER;
985 		SSLerror(s, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
986 		goto f_err;
987 	}
988 	S3I(s)->hs.new_cipher = cipher;
989 
990 	if (!tls1_handshake_hash_init(s))
991 		goto err;
992 
993 	/*
994 	 * Don't digest cached records if no sigalgs: we may need them for
995 	 * client authentication.
996 	 */
997 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
998 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) &&
999 	    !tls1_digest_cached_records(s)) {
1000 		al = SSL_AD_INTERNAL_ERROR;
1001 		goto f_err;
1002 	}
1003 
1004 	if (!CBS_get_u8(&cbs, &compression_method))
1005 		goto truncated;
1006 
1007 	if (compression_method != 0) {
1008 		al = SSL_AD_ILLEGAL_PARAMETER;
1009 		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1010 		goto f_err;
1011 	}
1012 
1013 	if (!tlsext_serverhello_parse(s, &cbs, &al)) {
1014 		SSLerror(s, SSL_R_PARSE_TLSEXT);
1015 		goto f_err;
1016 	}
1017 
1018 	/*
1019 	 * Determine if we need to see RI. Strictly speaking if we want to
1020 	 * avoid an attack we should *always* see RI even on initial server
1021 	 * hello because the client doesn't see any renegotiation during an
1022 	 * attack. However this would mean we could not connect to any server
1023 	 * which doesn't support RI so for the immediate future tolerate RI
1024 	 * absence on initial connect only.
1025 	 */
1026 	if (!S3I(s)->renegotiate_seen &&
1027 	    !(s->internal->options & SSL_OP_LEGACY_SERVER_CONNECT)) {
1028 		al = SSL_AD_HANDSHAKE_FAILURE;
1029 		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1030 		goto f_err;
1031 	}
1032 
1033 	if (ssl_check_serverhello_tlsext(s) <= 0) {
1034 		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
1035 		goto err;
1036 	}
1037 
1038 	return (1);
1039 
1040 truncated:
1041 	/* wrong packet length */
1042 	al = SSL_AD_DECODE_ERROR;
1043 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1044 f_err:
1045 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1046 err:
1047 	return (-1);
1048 }
1049 
1050 int
1051 ssl3_get_server_certificate(SSL *s)
1052 {
1053 	int			 al, i, ok, ret = -1;
1054 	long			 n;
1055 	CBS			 cbs, cert_list;
1056 	X509			*x = NULL;
1057 	const unsigned char	*q;
1058 	STACK_OF(X509)		*sk = NULL;
1059 	SESS_CERT		*sc;
1060 	EVP_PKEY		*pkey = NULL;
1061 
1062 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_A,
1063 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
1064 
1065 	if (!ok)
1066 		return ((int)n);
1067 
1068 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1069 		S3I(s)->tmp.reuse_message = 1;
1070 		return (1);
1071 	}
1072 
1073 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
1074 		al = SSL_AD_UNEXPECTED_MESSAGE;
1075 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1076 		goto f_err;
1077 	}
1078 
1079 
1080 	if ((sk = sk_X509_new_null()) == NULL) {
1081 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1082 		goto err;
1083 	}
1084 
1085 	if (n < 0)
1086 		goto truncated;
1087 
1088 	CBS_init(&cbs, s->internal->init_msg, n);
1089 	if (CBS_len(&cbs) < 3)
1090 		goto truncated;
1091 
1092 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
1093 	    CBS_len(&cbs) != 0) {
1094 		al = SSL_AD_DECODE_ERROR;
1095 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1096 		goto f_err;
1097 	}
1098 
1099 	while (CBS_len(&cert_list) > 0) {
1100 		CBS cert;
1101 
1102 		if (CBS_len(&cert_list) < 3)
1103 			goto truncated;
1104 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1105 			al = SSL_AD_DECODE_ERROR;
1106 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1107 			goto f_err;
1108 		}
1109 
1110 		q = CBS_data(&cert);
1111 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1112 		if (x == NULL) {
1113 			al = SSL_AD_BAD_CERTIFICATE;
1114 			SSLerror(s, ERR_R_ASN1_LIB);
1115 			goto f_err;
1116 		}
1117 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1118 			al = SSL_AD_DECODE_ERROR;
1119 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1120 			goto f_err;
1121 		}
1122 		if (!sk_X509_push(sk, x)) {
1123 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1124 			goto err;
1125 		}
1126 		x = NULL;
1127 	}
1128 
1129 	i = ssl_verify_cert_chain(s, sk);
1130 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1131 		al = ssl_verify_alarm_type(s->verify_result);
1132 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1133 		goto f_err;
1134 
1135 	}
1136 	ERR_clear_error(); /* but we keep s->verify_result */
1137 
1138 	sc = ssl_sess_cert_new();
1139 	if (sc == NULL)
1140 		goto err;
1141 	ssl_sess_cert_free(SSI(s)->sess_cert);
1142 	SSI(s)->sess_cert = sc;
1143 
1144 	sc->cert_chain = sk;
1145 	/*
1146 	 * Inconsistency alert: cert_chain does include the peer's
1147 	 * certificate, which we don't include in s3_srvr.c
1148 	 */
1149 	x = sk_X509_value(sk, 0);
1150 	sk = NULL;
1151 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1152 
1153 	pkey = X509_get_pubkey(x);
1154 
1155 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1156 		x = NULL;
1157 		al = SSL3_AL_FATAL;
1158 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1159 		goto f_err;
1160 	}
1161 
1162 	i = ssl_cert_type(x, pkey);
1163 	if (i < 0) {
1164 		x = NULL;
1165 		al = SSL3_AL_FATAL;
1166 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1167 		goto f_err;
1168 	}
1169 
1170 	sc->peer_cert_type = i;
1171 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1172 	/*
1173 	 * Why would the following ever happen?
1174 	 * We just created sc a couple of lines ago.
1175 	 */
1176 	X509_free(sc->peer_pkeys[i].x509);
1177 	sc->peer_pkeys[i].x509 = x;
1178 	sc->peer_key = &(sc->peer_pkeys[i]);
1179 
1180 	X509_free(s->session->peer);
1181 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1182 	s->session->peer = x;
1183 	s->session->verify_result = s->verify_result;
1184 
1185 	x = NULL;
1186 	ret = 1;
1187 
1188 	if (0) {
1189 truncated:
1190 		/* wrong packet length */
1191 		al = SSL_AD_DECODE_ERROR;
1192 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1193 f_err:
1194 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1195 	}
1196 err:
1197 	EVP_PKEY_free(pkey);
1198 	X509_free(x);
1199 	sk_X509_pop_free(sk, X509_free);
1200 
1201 	return (ret);
1202 }
1203 
1204 static int
1205 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, unsigned char **pp, long *nn)
1206 {
1207 	CBS cbs, dhp, dhg, dhpk;
1208 	BN_CTX *bn_ctx = NULL;
1209 	SESS_CERT *sc = NULL;
1210 	DH *dh = NULL;
1211 	long alg_a;
1212 	int al;
1213 
1214 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1215 	sc = SSI(s)->sess_cert;
1216 
1217 	if (*nn < 0)
1218 		goto err;
1219 
1220 	CBS_init(&cbs, *pp, *nn);
1221 
1222 	if ((dh = DH_new()) == NULL) {
1223 		SSLerror(s, ERR_R_DH_LIB);
1224 		goto err;
1225 	}
1226 
1227 	if (!CBS_get_u16_length_prefixed(&cbs, &dhp))
1228 		goto truncated;
1229 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1230 		SSLerror(s, ERR_R_BN_LIB);
1231 		goto err;
1232 	}
1233 
1234 	if (!CBS_get_u16_length_prefixed(&cbs, &dhg))
1235 		goto truncated;
1236 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1237 		SSLerror(s, ERR_R_BN_LIB);
1238 		goto err;
1239 	}
1240 
1241 	if (!CBS_get_u16_length_prefixed(&cbs, &dhpk))
1242 		goto truncated;
1243 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1244 	    NULL)) == NULL) {
1245 		SSLerror(s, ERR_R_BN_LIB);
1246 		goto err;
1247 	}
1248 
1249 	/*
1250 	 * Check the strength of the DH key just constructed.
1251 	 * Discard keys weaker than 1024 bits.
1252 	 */
1253 	if (DH_size(dh) < 1024 / 8) {
1254 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1255 		goto err;
1256 	}
1257 
1258 	if (alg_a & SSL_aRSA)
1259 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1260 	else
1261 		/* XXX - Anonymous DH, so no certificate or pkey. */
1262 		*pkey = NULL;
1263 
1264 	sc->peer_dh_tmp = dh;
1265 
1266 	*nn = CBS_len(&cbs);
1267 	*pp = (unsigned char *)CBS_data(&cbs);
1268 
1269 	return (1);
1270 
1271  truncated:
1272 	al = SSL_AD_DECODE_ERROR;
1273 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1274 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1275 
1276  err:
1277 	DH_free(dh);
1278 	BN_CTX_free(bn_ctx);
1279 
1280 	return (-1);
1281 }
1282 
1283 static int
1284 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1285 {
1286 	const EC_GROUP *group;
1287 	EC_GROUP *ngroup = NULL;
1288 	EC_POINT *point = NULL;
1289 	BN_CTX *bn_ctx = NULL;
1290 	EC_KEY *ecdh = NULL;
1291 	int ret = -1;
1292 
1293 	/*
1294 	 * Extract the server's ephemeral ECDH public key.
1295 	 */
1296 
1297 	if ((ecdh = EC_KEY_new()) == NULL) {
1298 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1299 		goto err;
1300 	}
1301 
1302 	if ((ngroup = EC_GROUP_new_by_curve_name(nid)) == NULL) {
1303 		SSLerror(s, ERR_R_EC_LIB);
1304 		goto err;
1305 	}
1306 	if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1307 		SSLerror(s, ERR_R_EC_LIB);
1308 		goto err;
1309 	}
1310 
1311 	group = EC_KEY_get0_group(ecdh);
1312 
1313 	if ((point = EC_POINT_new(group)) == NULL ||
1314 	    (bn_ctx = BN_CTX_new()) == NULL) {
1315 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1316 		goto err;
1317 	}
1318 
1319 	if (EC_POINT_oct2point(group, point, CBS_data(public),
1320 	    CBS_len(public), bn_ctx) == 0) {
1321 		SSLerror(s, SSL_R_BAD_ECPOINT);
1322 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1323 		goto err;
1324 	}
1325 
1326 	EC_KEY_set_public_key(ecdh, point);
1327 	sc->peer_ecdh_tmp = ecdh;
1328 	ecdh = NULL;
1329 
1330 	ret = 1;
1331 
1332  err:
1333 	BN_CTX_free(bn_ctx);
1334 	EC_GROUP_free(ngroup);
1335 	EC_POINT_free(point);
1336 	EC_KEY_free(ecdh);
1337 
1338 	return (ret);
1339 }
1340 
1341 static int
1342 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1343 {
1344 	size_t outlen;
1345 
1346 	if (nid != NID_X25519) {
1347 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1348 		goto err;
1349 	}
1350 
1351 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1352 		SSLerror(s, SSL_R_BAD_ECPOINT);
1353 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1354 		goto err;
1355 	}
1356 
1357 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1358 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1359 		goto err;
1360 	}
1361 
1362 	return (1);
1363 
1364  err:
1365 	return (-1);
1366 }
1367 
1368 static int
1369 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, unsigned char **pp, long *nn)
1370 {
1371 	CBS cbs, public;
1372 	uint8_t curve_type;
1373 	uint16_t curve_id;
1374 	SESS_CERT *sc;
1375 	long alg_a;
1376 	int nid;
1377 	int al;
1378 
1379 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1380 	sc = SSI(s)->sess_cert;
1381 
1382 	if (*nn < 0)
1383 		goto err;
1384 
1385 	CBS_init(&cbs, *pp, *nn);
1386 
1387 	/* Only named curves are supported. */
1388 	if (!CBS_get_u8(&cbs, &curve_type) ||
1389 	    curve_type != NAMED_CURVE_TYPE ||
1390 	    !CBS_get_u16(&cbs, &curve_id)) {
1391 		al = SSL_AD_DECODE_ERROR;
1392 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1393 		goto f_err;
1394 	}
1395 
1396 	/*
1397 	 * Check that the curve is one of our preferences - if it is not,
1398 	 * the server has sent us an invalid curve.
1399 	 */
1400 	if (tls1_check_curve(s, curve_id) != 1) {
1401 		al = SSL_AD_DECODE_ERROR;
1402 		SSLerror(s, SSL_R_WRONG_CURVE);
1403 		goto f_err;
1404 	}
1405 
1406 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1407 		al = SSL_AD_INTERNAL_ERROR;
1408 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1409 		goto f_err;
1410 	}
1411 
1412 	if (!CBS_get_u8_length_prefixed(&cbs, &public))
1413 		goto truncated;
1414 
1415 	if (nid == NID_X25519) {
1416 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1417 			goto err;
1418 	} else {
1419 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1420 			goto err;
1421 	}
1422 
1423 	/*
1424 	 * The ECC/TLS specification does not mention the use of DSA to sign
1425 	 * ECParameters in the server key exchange message. We do support RSA
1426 	 * and ECDSA.
1427 	 */
1428 	if (alg_a & SSL_aRSA)
1429 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1430 	else if (alg_a & SSL_aECDSA)
1431 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1432 	else
1433 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1434 		*pkey = NULL;
1435 
1436 	*nn = CBS_len(&cbs);
1437 	*pp = (unsigned char *)CBS_data(&cbs);
1438 
1439 	return (1);
1440 
1441  truncated:
1442 	al = SSL_AD_DECODE_ERROR;
1443 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1444 
1445  f_err:
1446 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1447 
1448  err:
1449 	return (-1);
1450 }
1451 
1452 int
1453 ssl3_get_server_key_exchange(SSL *s)
1454 {
1455 	unsigned char	*q, md_buf[EVP_MAX_MD_SIZE*2];
1456 	EVP_MD_CTX	 md_ctx;
1457 	unsigned char	*param, *p;
1458 	int		 al, i, j, param_len, ok;
1459 	long		 n, alg_k, alg_a;
1460 	EVP_PKEY	*pkey = NULL;
1461 	const		 EVP_MD *md = NULL;
1462 	RSA		*rsa = NULL;
1463 
1464 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1465 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1466 
1467 	/*
1468 	 * Use same message size as in ssl3_get_certificate_request()
1469 	 * as ServerKeyExchange message may be skipped.
1470 	 */
1471 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1472 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1473 	if (!ok)
1474 		return ((int)n);
1475 
1476 	EVP_MD_CTX_init(&md_ctx);
1477 
1478 	if (S3I(s)->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1479 		/*
1480 		 * Do not skip server key exchange if this cipher suite uses
1481 		 * ephemeral keys.
1482 		 */
1483 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1484 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1485 			al = SSL_AD_UNEXPECTED_MESSAGE;
1486 			goto f_err;
1487 		}
1488 
1489 		S3I(s)->tmp.reuse_message = 1;
1490 		EVP_MD_CTX_cleanup(&md_ctx);
1491 		return (1);
1492 	}
1493 
1494 	if (SSI(s)->sess_cert != NULL) {
1495 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1496 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1497 
1498 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1499 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1500 
1501 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1502 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1503 	} else {
1504 		SSI(s)->sess_cert = ssl_sess_cert_new();
1505 		if (SSI(s)->sess_cert == NULL)
1506 			goto err;
1507 	}
1508 
1509 	param = p = (unsigned char *)s->internal->init_msg;
1510 	param_len = n;
1511 
1512 	if (alg_k & SSL_kDHE) {
1513 		if (ssl3_get_server_kex_dhe(s, &pkey, &p, &n) != 1)
1514 			goto err;
1515 	} else if (alg_k & SSL_kECDHE) {
1516 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &p, &n) != 1)
1517 			goto err;
1518 	} else if (alg_k != 0) {
1519 		al = SSL_AD_UNEXPECTED_MESSAGE;
1520 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1521 			goto f_err;
1522 	}
1523 
1524 	param_len = param_len - n;
1525 
1526 	/* if it was signed, check the signature */
1527 	if (pkey != NULL) {
1528 		if (SSL_USE_SIGALGS(s)) {
1529 			int sigalg = tls12_get_sigid(pkey);
1530 			/* Should never happen */
1531 			if (sigalg == -1) {
1532 				SSLerror(s, ERR_R_INTERNAL_ERROR);
1533 				goto err;
1534 			}
1535 			/*
1536 			 * Check key type is consistent
1537 			 * with signature
1538 			 */
1539 			if (2 > n)
1540 				goto truncated;
1541 			if (sigalg != (int)p[1]) {
1542 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
1543 				al = SSL_AD_DECODE_ERROR;
1544 				goto f_err;
1545 			}
1546 			md = tls12_get_hash(p[0]);
1547 			if (md == NULL) {
1548 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
1549 				al = SSL_AD_DECODE_ERROR;
1550 				goto f_err;
1551 			}
1552 			p += 2;
1553 			n -= 2;
1554 		} else
1555 			md = EVP_sha1();
1556 
1557 		if (2 > n)
1558 			goto truncated;
1559 		n2s(p, i);
1560 		n -= 2;
1561 		j = EVP_PKEY_size(pkey);
1562 
1563 		if (i != n || n > j) {
1564 			/* wrong packet length */
1565 			al = SSL_AD_DECODE_ERROR;
1566 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1567 			goto f_err;
1568 		}
1569 
1570 		if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1571 			j = 0;
1572 			q = md_buf;
1573 			if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(), NULL)) {
1574 				al = SSL_AD_INTERNAL_ERROR;
1575 				goto f_err;
1576 			}
1577 			EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1578 			    SSL3_RANDOM_SIZE);
1579 			EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1580 			    SSL3_RANDOM_SIZE);
1581 			EVP_DigestUpdate(&md_ctx, param, param_len);
1582 			EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1583 			q += i;
1584 			j += i;
1585 			i = RSA_verify(NID_md5_sha1, md_buf, j,
1586 			    p, n, pkey->pkey.rsa);
1587 			if (i < 0) {
1588 				al = SSL_AD_DECRYPT_ERROR;
1589 				SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
1590 				goto f_err;
1591 			}
1592 			if (i == 0) {
1593 				/* bad signature */
1594 				al = SSL_AD_DECRYPT_ERROR;
1595 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1596 				goto f_err;
1597 			}
1598 		} else {
1599 			EVP_VerifyInit_ex(&md_ctx, md, NULL);
1600 			EVP_VerifyUpdate(&md_ctx, s->s3->client_random,
1601 			    SSL3_RANDOM_SIZE);
1602 			EVP_VerifyUpdate(&md_ctx, s->s3->server_random,
1603 			    SSL3_RANDOM_SIZE);
1604 			EVP_VerifyUpdate(&md_ctx, param, param_len);
1605 			if (EVP_VerifyFinal(&md_ctx, p,(int)n, pkey) <= 0) {
1606 				/* bad signature */
1607 				al = SSL_AD_DECRYPT_ERROR;
1608 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1609 				goto f_err;
1610 			}
1611 		}
1612 	} else {
1613 		/* aNULL does not need public keys. */
1614 		if (!(alg_a & SSL_aNULL)) {
1615 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1616 			goto err;
1617 		}
1618 		/* still data left over */
1619 		if (n != 0) {
1620 			al = SSL_AD_DECODE_ERROR;
1621 			SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1622 			goto f_err;
1623 		}
1624 	}
1625 
1626 	EVP_PKEY_free(pkey);
1627 	EVP_MD_CTX_cleanup(&md_ctx);
1628 
1629 	return (1);
1630 
1631  truncated:
1632 	/* wrong packet length */
1633 	al = SSL_AD_DECODE_ERROR;
1634 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1635 
1636  f_err:
1637 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1638 
1639  err:
1640 	EVP_PKEY_free(pkey);
1641 	RSA_free(rsa);
1642 	EVP_MD_CTX_cleanup(&md_ctx);
1643 
1644 	return (-1);
1645 }
1646 
1647 int
1648 ssl3_get_certificate_request(SSL *s)
1649 {
1650 	int			 ok, ret = 0;
1651 	long		 	 n;
1652 	uint8_t			 ctype_num;
1653 	CBS			 cert_request, ctypes, rdn_list;
1654 	X509_NAME		*xn = NULL;
1655 	const unsigned char	*q;
1656 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1657 
1658 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1659 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1660 
1661 	if (!ok)
1662 		return ((int)n);
1663 
1664 	S3I(s)->tmp.cert_req = 0;
1665 
1666 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_DONE) {
1667 		S3I(s)->tmp.reuse_message = 1;
1668 		/*
1669 		 * If we get here we don't need any cached handshake records
1670 		 * as we wont be doing client auth.
1671 		 */
1672 		if (S3I(s)->handshake_buffer) {
1673 			if (!tls1_digest_cached_records(s))
1674 				goto err;
1675 		}
1676 		return (1);
1677 	}
1678 
1679 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1680 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1681 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1682 		goto err;
1683 	}
1684 
1685 	/* TLS does not like anon-DH with client cert */
1686 	if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
1687 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1688 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1689 		goto err;
1690 	}
1691 
1692 	if (n < 0)
1693 		goto truncated;
1694 	CBS_init(&cert_request, s->internal->init_msg, n);
1695 
1696 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1697 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1698 		goto err;
1699 	}
1700 
1701 	/* get the certificate types */
1702 	if (!CBS_get_u8(&cert_request, &ctype_num))
1703 		goto truncated;
1704 
1705 	if (ctype_num > SSL3_CT_NUMBER)
1706 		ctype_num = SSL3_CT_NUMBER;
1707 	if (!CBS_get_bytes(&cert_request, &ctypes, ctype_num) ||
1708 	    !CBS_write_bytes(&ctypes, (uint8_t *)S3I(s)->tmp.ctype,
1709 	    sizeof(S3I(s)->tmp.ctype), NULL)) {
1710 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1711 		goto err;
1712 	}
1713 
1714 	if (SSL_USE_SIGALGS(s)) {
1715 		CBS sigalgs;
1716 
1717 		if (CBS_len(&cert_request) < 2) {
1718 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1719 			goto err;
1720 		}
1721 
1722 		/* Check we have enough room for signature algorithms and
1723 		 * following length value.
1724 		 */
1725 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1726 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1727 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1728 			goto err;
1729 		}
1730 		if (!tls1_process_sigalgs(s, &sigalgs)) {
1731 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1732 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1733 			goto err;
1734 		}
1735 	}
1736 
1737 	/* get the CA RDNs */
1738 	if (CBS_len(&cert_request) < 2) {
1739 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1740 		goto err;
1741 	}
1742 
1743 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1744 	    CBS_len(&cert_request) != 0) {
1745 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1746 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1747 		goto err;
1748 	}
1749 
1750 	while (CBS_len(&rdn_list) > 0) {
1751 		CBS rdn;
1752 
1753 		if (CBS_len(&rdn_list) < 2) {
1754 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1755 			goto err;
1756 		}
1757 
1758 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1759 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1760 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1761 			goto err;
1762 		}
1763 
1764 		q = CBS_data(&rdn);
1765 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1766 			ssl3_send_alert(s, SSL3_AL_FATAL,
1767 			    SSL_AD_DECODE_ERROR);
1768 			SSLerror(s, ERR_R_ASN1_LIB);
1769 			goto err;
1770 		}
1771 
1772 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1773 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1774 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1775 			goto err;
1776 		}
1777 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1778 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1779 			goto err;
1780 		}
1781 		xn = NULL;	/* avoid free in err block */
1782 	}
1783 
1784 	/* we should setup a certificate to return.... */
1785 	S3I(s)->tmp.cert_req = 1;
1786 	S3I(s)->tmp.ctype_num = ctype_num;
1787 	sk_X509_NAME_pop_free(S3I(s)->tmp.ca_names, X509_NAME_free);
1788 	S3I(s)->tmp.ca_names = ca_sk;
1789 	ca_sk = NULL;
1790 
1791 	ret = 1;
1792 	if (0) {
1793 truncated:
1794 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1795 	}
1796 err:
1797 	X509_NAME_free(xn);
1798 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1799 	return (ret);
1800 }
1801 
1802 static int
1803 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1804 {
1805 	return (X509_NAME_cmp(*a, *b));
1806 }
1807 
1808 int
1809 ssl3_get_new_session_ticket(SSL *s)
1810 {
1811 	int			 ok, al, ret = 0;
1812 	uint32_t		 lifetime_hint;
1813 	long			 n;
1814 	CBS			 cbs, session_ticket;
1815 
1816 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1817 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1818 	if (!ok)
1819 		return ((int)n);
1820 
1821 	if (S3I(s)->tmp.message_type == SSL3_MT_FINISHED) {
1822 		S3I(s)->tmp.reuse_message = 1;
1823 		return (1);
1824 	}
1825 	if (S3I(s)->tmp.message_type != SSL3_MT_NEWSESSION_TICKET) {
1826 		al = SSL_AD_UNEXPECTED_MESSAGE;
1827 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1828 		goto f_err;
1829 	}
1830 
1831 	if (n < 0) {
1832 		al = SSL_AD_DECODE_ERROR;
1833 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1834 		goto f_err;
1835 	}
1836 
1837 	CBS_init(&cbs, s->internal->init_msg, n);
1838 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1839 #if UINT32_MAX > LONG_MAX
1840 	    lifetime_hint > LONG_MAX ||
1841 #endif
1842 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1843 	    CBS_len(&cbs) != 0) {
1844 		al = SSL_AD_DECODE_ERROR;
1845 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1846 		goto f_err;
1847 	}
1848 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1849 
1850 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1851 	    &s->session->tlsext_ticklen)) {
1852 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1853 		goto err;
1854 	}
1855 
1856 	/*
1857 	 * There are two ways to detect a resumed ticket sesion.
1858 	 * One is to set an appropriate session ID and then the server
1859 	 * must return a match in ServerHello. This allows the normal
1860 	 * client session ID matching to work and we know much
1861 	 * earlier that the ticket has been accepted.
1862 	 *
1863 	 * The other way is to set zero length session ID when the
1864 	 * ticket is presented and rely on the handshake to determine
1865 	 * session resumption.
1866 	 *
1867 	 * We choose the former approach because this fits in with
1868 	 * assumptions elsewhere in OpenSSL. The session ID is set
1869 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1870 	 * ticket.
1871 	 */
1872 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1873 	    s->session->session_id, &s->session->session_id_length,
1874 	    EVP_sha256(), NULL);
1875 	ret = 1;
1876 	return (ret);
1877 f_err:
1878 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1879 err:
1880 	return (-1);
1881 }
1882 
1883 int
1884 ssl3_get_cert_status(SSL *s)
1885 {
1886 	CBS			 cert_status, response;
1887 	size_t			 stow_len;
1888 	int			 ok, al;
1889 	long			 n;
1890 	uint8_t			 status_type;
1891 
1892 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1893 	    SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS,
1894 	    16384, &ok);
1895 
1896 	if (!ok)
1897 		return ((int)n);
1898 
1899 	if (n < 0) {
1900 		/* need at least status type + length */
1901 		al = SSL_AD_DECODE_ERROR;
1902 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1903 		goto f_err;
1904 	}
1905 
1906 	CBS_init(&cert_status, s->internal->init_msg, n);
1907 	if (!CBS_get_u8(&cert_status, &status_type) ||
1908 	    CBS_len(&cert_status) < 3) {
1909 		/* need at least status type + length */
1910 		al = SSL_AD_DECODE_ERROR;
1911 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1912 		goto f_err;
1913 	}
1914 
1915 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1916 		al = SSL_AD_DECODE_ERROR;
1917 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1918 		goto f_err;
1919 	}
1920 
1921 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1922 	    CBS_len(&cert_status) != 0) {
1923 		al = SSL_AD_DECODE_ERROR;
1924 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1925 		goto f_err;
1926 	}
1927 
1928 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1929 	    &stow_len) || stow_len > INT_MAX) {
1930 		s->internal->tlsext_ocsp_resplen = 0;
1931  		al = SSL_AD_INTERNAL_ERROR;
1932  		SSLerror(s, ERR_R_MALLOC_FAILURE);
1933  		goto f_err;
1934  	}
1935 	s->internal->tlsext_ocsp_resplen = (int)stow_len;
1936 
1937 	if (s->ctx->internal->tlsext_status_cb) {
1938 		int ret;
1939 		ret = s->ctx->internal->tlsext_status_cb(s,
1940 		    s->ctx->internal->tlsext_status_arg);
1941 		if (ret == 0) {
1942 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1943 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1944 			goto f_err;
1945 		}
1946 		if (ret < 0) {
1947 			al = SSL_AD_INTERNAL_ERROR;
1948 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1949 			goto f_err;
1950 		}
1951 	}
1952 	return (1);
1953 f_err:
1954 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1955 	return (-1);
1956 }
1957 
1958 int
1959 ssl3_get_server_done(SSL *s)
1960 {
1961 	int	ok, ret = 0;
1962 	long	n;
1963 
1964 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1965 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1966 	    30, /* should be very small, like 0 :-) */ &ok);
1967 
1968 	if (!ok)
1969 		return ((int)n);
1970 	if (n > 0) {
1971 		/* should contain no data */
1972 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1973 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1974 		return (-1);
1975 	}
1976 	ret = 1;
1977 	return (ret);
1978 }
1979 
1980 static int
1981 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1982 {
1983 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1984 	unsigned char *enc_pms = NULL;
1985 	EVP_PKEY *pkey = NULL;
1986 	int ret = -1;
1987 	int enc_len;
1988 	CBB epms;
1989 
1990 	/*
1991 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1992 	 */
1993 
1994 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1995 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1996 	    pkey->pkey.rsa == NULL) {
1997 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1998 		goto err;
1999 	}
2000 
2001 	pms[0] = s->client_version >> 8;
2002 	pms[1] = s->client_version & 0xff;
2003 	arc4random_buf(&pms[2], sizeof(pms) - 2);
2004 
2005 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
2006 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2007 		goto err;
2008 	}
2009 
2010 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
2011 	    RSA_PKCS1_PADDING);
2012 	if (enc_len <= 0) {
2013 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
2014 		goto err;
2015 	}
2016 
2017 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
2018 		goto err;
2019 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
2020 		goto err;
2021 	if (!CBB_flush(cbb))
2022 		goto err;
2023 
2024 	s->session->master_key_length =
2025 	    tls1_generate_master_secret(s,
2026 		s->session->master_key, pms, sizeof(pms));
2027 
2028 	ret = 1;
2029 
2030 err:
2031 	explicit_bzero(pms, sizeof(pms));
2032 	EVP_PKEY_free(pkey);
2033 	free(enc_pms);
2034 
2035 	return (ret);
2036 }
2037 
2038 static int
2039 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2040 {
2041 	DH *dh_srvr = NULL, *dh_clnt = NULL;
2042 	unsigned char *key = NULL;
2043 	int key_size = 0, key_len;
2044 	unsigned char *data;
2045 	int ret = -1;
2046 	CBB dh_Yc;
2047 
2048 	/* Ensure that we have an ephemeral key for DHE. */
2049 	if (sess_cert->peer_dh_tmp == NULL) {
2050 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2051 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2052 		goto err;
2053 	}
2054 	dh_srvr = sess_cert->peer_dh_tmp;
2055 
2056 	/* Generate a new random key. */
2057 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2058 		SSLerror(s, ERR_R_DH_LIB);
2059 		goto err;
2060 	}
2061 	if (!DH_generate_key(dh_clnt)) {
2062 		SSLerror(s, ERR_R_DH_LIB);
2063 		goto err;
2064 	}
2065 	key_size = DH_size(dh_clnt);
2066 	if ((key = malloc(key_size)) == NULL) {
2067 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2068 		goto err;
2069 	}
2070 	key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt);
2071 	if (key_len <= 0) {
2072 		SSLerror(s, ERR_R_DH_LIB);
2073 		goto err;
2074 	}
2075 
2076 	/* Generate master key from the result. */
2077 	s->session->master_key_length =
2078 	    tls1_generate_master_secret(s,
2079 		s->session->master_key, key, key_len);
2080 
2081 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2082 		goto err;
2083 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2084 		goto err;
2085 	BN_bn2bin(dh_clnt->pub_key, data);
2086 	if (!CBB_flush(cbb))
2087 		goto err;
2088 
2089 	ret = 1;
2090 
2091 err:
2092 	DH_free(dh_clnt);
2093 	freezero(key, key_size);
2094 
2095 	return (ret);
2096 }
2097 
2098 static int
2099 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2100 {
2101 	const EC_GROUP *group = NULL;
2102 	const EC_POINT *point = NULL;
2103 	EC_KEY *ecdh = NULL;
2104 	BN_CTX *bn_ctx = NULL;
2105 	unsigned char *key = NULL;
2106 	unsigned char *data;
2107 	size_t encoded_len;
2108 	int key_size = 0, key_len;
2109 	int ret = -1;
2110 	CBB ecpoint;
2111 
2112 	if ((group = EC_KEY_get0_group(sc->peer_ecdh_tmp)) == NULL ||
2113 	    (point = EC_KEY_get0_public_key(sc->peer_ecdh_tmp)) == NULL) {
2114 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2115 		goto err;
2116 	}
2117 
2118 	if ((ecdh = EC_KEY_new()) == NULL) {
2119 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2120 		goto err;
2121 	}
2122 
2123 	if (!EC_KEY_set_group(ecdh, group)) {
2124 		SSLerror(s, ERR_R_EC_LIB);
2125 		goto err;
2126 	}
2127 
2128 	/* Generate a new ECDH key pair. */
2129 	if (!(EC_KEY_generate_key(ecdh))) {
2130 		SSLerror(s, ERR_R_ECDH_LIB);
2131 		goto err;
2132 	}
2133 	if ((key_size = ECDH_size(ecdh)) <= 0) {
2134 		SSLerror(s, ERR_R_ECDH_LIB);
2135 		goto err;
2136 	}
2137 	if ((key = malloc(key_size)) == NULL) {
2138 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2139 	}
2140 	key_len = ECDH_compute_key(key, key_size, point, ecdh, NULL);
2141 	if (key_len <= 0) {
2142 		SSLerror(s, ERR_R_ECDH_LIB);
2143 		goto err;
2144 	}
2145 
2146 	/* Generate master key from the result. */
2147 	s->session->master_key_length =
2148 	    tls1_generate_master_secret(s,
2149 		s->session->master_key, key, key_len);
2150 
2151 	encoded_len = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2152 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
2153 	if (encoded_len == 0) {
2154 		SSLerror(s, ERR_R_ECDH_LIB);
2155 		goto err;
2156 	}
2157 
2158 	if ((bn_ctx = BN_CTX_new()) == NULL) {
2159 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2160 		goto err;
2161 	}
2162 
2163 	/* Encode the public key. */
2164 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2165 		goto err;
2166 	if (!CBB_add_space(&ecpoint, &data, encoded_len))
2167 		goto err;
2168 	if (EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2169 	    POINT_CONVERSION_UNCOMPRESSED, data, encoded_len,
2170 	    bn_ctx) == 0)
2171 		goto err;
2172 	if (!CBB_flush(cbb))
2173 		goto err;
2174 
2175 	ret = 1;
2176 
2177  err:
2178 	freezero(key, key_size);
2179 
2180 	BN_CTX_free(bn_ctx);
2181 	EC_KEY_free(ecdh);
2182 
2183 	return (ret);
2184 }
2185 
2186 static int
2187 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2188 {
2189 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2190 	int ret = -1;
2191 	CBB ecpoint;
2192 
2193 	/* Generate X25519 key pair and derive shared key. */
2194 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2195 		goto err;
2196 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2197 		goto err;
2198 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2199 		goto err;
2200 	X25519_keypair(public_key, private_key);
2201 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2202 		goto err;
2203 
2204 	/* Serialize the public key. */
2205 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2206 		goto err;
2207 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2208 		goto err;
2209 	if (!CBB_flush(cbb))
2210 		goto err;
2211 
2212 	/* Generate master key from the result. */
2213 	s->session->master_key_length =
2214 	    tls1_generate_master_secret(s,
2215 		s->session->master_key, shared_key, X25519_KEY_LENGTH);
2216 
2217 	ret = 1;
2218 
2219  err:
2220 	free(public_key);
2221 	freezero(private_key, X25519_KEY_LENGTH);
2222 	freezero(shared_key, X25519_KEY_LENGTH);
2223 
2224 	return (ret);
2225 }
2226 
2227 static int
2228 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2229 {
2230 	if (sc->peer_x25519_tmp != NULL) {
2231 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2232 			goto err;
2233 	} else if (sc->peer_ecdh_tmp != NULL) {
2234 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2235 			goto err;
2236 	} else {
2237 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2238 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2239 		goto err;
2240 	}
2241 
2242 	return (1);
2243 
2244  err:
2245 	return (-1);
2246 }
2247 
2248 static int
2249 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2250 {
2251 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2252 	EVP_PKEY *pub_key = NULL;
2253 	EVP_PKEY_CTX *pkey_ctx;
2254 	X509 *peer_cert;
2255 	size_t msglen;
2256 	unsigned int md_len;
2257 	EVP_MD_CTX *ukm_hash;
2258 	int ret = -1;
2259 	int nid;
2260 	CBB gostblob;
2261 
2262 	/* Get server sertificate PKEY and create ctx from it */
2263 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2264 	if (peer_cert == NULL) {
2265 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2266 		goto err;
2267 	}
2268 
2269 	pub_key = X509_get_pubkey(peer_cert);
2270 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2271 
2272 	/*
2273 	 * If we have send a certificate, and certificate key parameters match
2274 	 * those of server certificate, use certificate key for key exchange.
2275 	 * Otherwise, generate ephemeral key pair.
2276 	 */
2277 	EVP_PKEY_encrypt_init(pkey_ctx);
2278 
2279 	/* Generate session key. */
2280 	arc4random_buf(premaster_secret, 32);
2281 
2282 	/*
2283 	 * If we have client certificate, use its secret as peer key.
2284 	 */
2285 	if (S3I(s)->tmp.cert_req && s->cert->key->privatekey) {
2286 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2287 		    s->cert->key->privatekey) <=0) {
2288 			/*
2289 			 * If there was an error - just ignore it.
2290 			 * Ephemeral key would be used.
2291 			 */
2292 			ERR_clear_error();
2293 		}
2294 	}
2295 
2296 	/*
2297 	 * Compute shared IV and store it in algorithm-specific context data.
2298 	 */
2299 	ukm_hash = EVP_MD_CTX_create();
2300 	if (ukm_hash == NULL) {
2301 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2302 		goto err;
2303 	}
2304 
2305 	if (ssl_get_algorithm2(s) & SSL_HANDSHAKE_MAC_GOST94)
2306 		nid = NID_id_GostR3411_94;
2307 	else
2308 		nid = NID_id_tc26_gost3411_2012_256;
2309 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2310 		goto err;
2311 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2312 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2313 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2314 	EVP_MD_CTX_destroy(ukm_hash);
2315 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2316 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2317 		SSLerror(s, SSL_R_LIBRARY_BUG);
2318 		goto err;
2319 	}
2320 
2321 	/*
2322 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2323 	 */
2324 	msglen = 255;
2325 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2326 	    32) < 0) {
2327 		SSLerror(s, SSL_R_LIBRARY_BUG);
2328 		goto err;
2329 	}
2330 
2331 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2332 		goto err;
2333 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2334 		goto err;
2335 	if (!CBB_flush(cbb))
2336 		goto err;
2337 
2338 	/* Check if pubkey from client certificate was used. */
2339 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2340 	    NULL) > 0) {
2341 		/* Set flag "skip certificate verify". */
2342 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2343 	}
2344 	EVP_PKEY_CTX_free(pkey_ctx);
2345 	s->session->master_key_length =
2346 	    tls1_generate_master_secret(s,
2347 		s->session->master_key, premaster_secret, 32);
2348 
2349 	ret = 1;
2350 
2351  err:
2352 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2353 	EVP_PKEY_free(pub_key);
2354 
2355 	return (ret);
2356 }
2357 
2358 int
2359 ssl3_send_client_key_exchange(SSL *s)
2360 {
2361 	SESS_CERT *sess_cert;
2362 	unsigned long alg_k;
2363 	CBB cbb, kex;
2364 
2365 	memset(&cbb, 0, sizeof(cbb));
2366 
2367 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2368 		alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2369 
2370 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2371 			ssl3_send_alert(s, SSL3_AL_FATAL,
2372 			    SSL_AD_UNEXPECTED_MESSAGE);
2373 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2374 			goto err;
2375 		}
2376 
2377 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &kex,
2378 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2379 			goto err;
2380 
2381 		if (alg_k & SSL_kRSA) {
2382 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2383 				goto err;
2384 		} else if (alg_k & SSL_kDHE) {
2385 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2386 				goto err;
2387 		} else if (alg_k & SSL_kECDHE) {
2388 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2389 				goto err;
2390 		} else if (alg_k & SSL_kGOST) {
2391 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2392 				goto err;
2393 		} else {
2394 			ssl3_send_alert(s, SSL3_AL_FATAL,
2395 			    SSL_AD_HANDSHAKE_FAILURE);
2396 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2397 			goto err;
2398 		}
2399 
2400 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2401 			goto err;
2402 
2403 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2404 	}
2405 
2406 	/* SSL3_ST_CW_KEY_EXCH_B */
2407 	return (ssl3_handshake_write(s));
2408 
2409 err:
2410 	CBB_cleanup(&cbb);
2411 
2412 	return (-1);
2413 }
2414 
2415 int
2416 ssl3_send_client_verify(SSL *s)
2417 {
2418 	unsigned char	*p;
2419 	unsigned char	 data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2420 	EVP_PKEY	*pkey;
2421 	EVP_PKEY_CTX	*pctx = NULL;
2422 	EVP_MD_CTX	 mctx;
2423 	unsigned	 u = 0;
2424 	unsigned long	 n;
2425 	int		 j;
2426 
2427 	EVP_MD_CTX_init(&mctx);
2428 
2429 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2430 		p = ssl3_handshake_msg_start(s, SSL3_MT_CERTIFICATE_VERIFY);
2431 
2432 		/*
2433 		 * Create context from key and test if sha1 is allowed as
2434 		 * digest.
2435 		 */
2436 		pkey = s->cert->key->privatekey;
2437 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2438 		EVP_PKEY_sign_init(pctx);
2439 
2440 		/* XXX - is this needed? */
2441 		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) <= 0)
2442 			ERR_clear_error();
2443 
2444 		if (!SSL_USE_SIGALGS(s)) {
2445 			if (S3I(s)->handshake_buffer) {
2446 				if (!tls1_digest_cached_records(s))
2447 					goto err;
2448 			}
2449 			if (!tls1_handshake_hash_value(s, data, sizeof(data),
2450 			    NULL))
2451 				goto err;
2452 		}
2453 
2454 		/*
2455 		 * For TLS v1.2 send signature algorithm and signature
2456 		 * using agreed digest and cached handshake records.
2457 		 */
2458 		if (SSL_USE_SIGALGS(s)) {
2459 			long hdatalen = 0;
2460 			void *hdata;
2461 			const EVP_MD *md = s->cert->key->digest;
2462 			hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer,
2463 			    &hdata);
2464 			if (hdatalen <= 0 ||
2465 			    !tls12_get_sigandhash(p, pkey, md)) {
2466 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2467 				goto err;
2468 			}
2469 			p += 2;
2470 			if (!EVP_SignInit_ex(&mctx, md, NULL) ||
2471 			    !EVP_SignUpdate(&mctx, hdata, hdatalen) ||
2472 			    !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2473 				SSLerror(s, ERR_R_EVP_LIB);
2474 				goto err;
2475 			}
2476 			s2n(u, p);
2477 			n = u + 4;
2478 			if (!tls1_digest_cached_records(s))
2479 				goto err;
2480 		} else if (pkey->type == EVP_PKEY_RSA) {
2481 			if (RSA_sign(NID_md5_sha1, data,
2482 			    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, &(p[2]),
2483 			    &u, pkey->pkey.rsa) <= 0 ) {
2484 				SSLerror(s, ERR_R_RSA_LIB);
2485 				goto err;
2486 			}
2487 			s2n(u, p);
2488 			n = u + 2;
2489 		} else if (pkey->type == EVP_PKEY_EC) {
2490 			if (!ECDSA_sign(pkey->save_type,
2491 			    &(data[MD5_DIGEST_LENGTH]),
2492 			    SHA_DIGEST_LENGTH, &(p[2]),
2493 			    (unsigned int *)&j, pkey->pkey.ec)) {
2494 				SSLerror(s, ERR_R_ECDSA_LIB);
2495 				goto err;
2496 			}
2497 			s2n(j, p);
2498 			n = j + 2;
2499 #ifndef OPENSSL_NO_GOST
2500 		} else if (pkey->type == NID_id_GostR3410_94 ||
2501 			   pkey->type == NID_id_GostR3410_2001) {
2502 			unsigned char signbuf[128];
2503 			long hdatalen = 0;
2504 			void *hdata;
2505 			const EVP_MD *md;
2506 			int nid;
2507 			size_t sigsize;
2508 
2509 			hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2510 			if (hdatalen <= 0) {
2511 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2512 				goto err;
2513 			}
2514 			if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2515 			    !(md = EVP_get_digestbynid(nid))) {
2516 				SSLerror(s, ERR_R_EVP_LIB);
2517 				goto err;
2518 			}
2519 			if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2520 			    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2521 			    !EVP_DigestFinal(&mctx, signbuf, &u) ||
2522 			    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2523 			    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2524 					       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2525 					       GOST_SIG_FORMAT_RS_LE,
2526 					       NULL) <= 0) ||
2527 			    (EVP_PKEY_sign(pctx, &(p[2]), &sigsize,
2528 					   signbuf, u) <= 0)) {
2529 				SSLerror(s, ERR_R_EVP_LIB);
2530 				goto err;
2531 			}
2532 			if (!tls1_digest_cached_records(s))
2533 				goto err;
2534 			j = sigsize;
2535 			s2n(j, p);
2536 			n = j + 2;
2537 #endif
2538 		} else {
2539 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2540 			goto err;
2541 		}
2542 
2543 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2544 
2545 		ssl3_handshake_msg_finish(s, n);
2546 	}
2547 
2548 	EVP_MD_CTX_cleanup(&mctx);
2549 	EVP_PKEY_CTX_free(pctx);
2550 
2551 	return (ssl3_handshake_write(s));
2552 
2553 err:
2554 	EVP_MD_CTX_cleanup(&mctx);
2555 	EVP_PKEY_CTX_free(pctx);
2556 	return (-1);
2557 }
2558 
2559 int
2560 ssl3_send_client_certificate(SSL *s)
2561 {
2562 	EVP_PKEY *pkey = NULL;
2563 	X509 *x509 = NULL;
2564 	CBB cbb, client_cert;
2565 	int i;
2566 
2567 	memset(&cbb, 0, sizeof(cbb));
2568 
2569 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2570 		if ((s->cert == NULL) || (s->cert->key->x509 == NULL) ||
2571 		    (s->cert->key->privatekey == NULL))
2572 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2573 		else
2574 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2575 	}
2576 
2577 	/* We need to get a client cert */
2578 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2579 		/*
2580 		 * If we get an error, we need to
2581 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2582 		 * We then get retied later
2583 		 */
2584 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2585 		if (i < 0) {
2586 			s->internal->rwstate = SSL_X509_LOOKUP;
2587 			return (-1);
2588 		}
2589 		s->internal->rwstate = SSL_NOTHING;
2590 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2591 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2592 			if (!SSL_use_certificate(s, x509) ||
2593 			    !SSL_use_PrivateKey(s, pkey))
2594 				i = 0;
2595 		} else if (i == 1) {
2596 			i = 0;
2597 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2598 		}
2599 
2600 		X509_free(x509);
2601 		EVP_PKEY_free(pkey);
2602 		if (i == 0)
2603 			S3I(s)->tmp.cert_req = 2;
2604 
2605 		/* Ok, we have a cert */
2606 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2607 	}
2608 
2609 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2610 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &client_cert,
2611 		    SSL3_MT_CERTIFICATE))
2612 			goto err;
2613 		if (!ssl3_output_cert_chain(s, &client_cert,
2614 		    (S3I(s)->tmp.cert_req == 2) ? NULL : s->cert->key->x509))
2615 			goto err;
2616 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2617 			goto err;
2618 
2619 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2620 	}
2621 
2622 	/* SSL3_ST_CW_CERT_D */
2623 	return (ssl3_handshake_write(s));
2624 
2625  err:
2626 	CBB_cleanup(&cbb);
2627 
2628 	return (0);
2629 }
2630 
2631 #define has_bits(i,m)	(((i)&(m)) == (m))
2632 
2633 int
2634 ssl3_check_cert_and_algorithm(SSL *s)
2635 {
2636 	int		 i, idx;
2637 	long		 alg_k, alg_a;
2638 	EVP_PKEY	*pkey = NULL;
2639 	SESS_CERT	*sc;
2640 	DH		*dh;
2641 
2642 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2643 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2644 
2645 	/* We don't have a certificate. */
2646 	if (alg_a & SSL_aNULL)
2647 		return (1);
2648 
2649 	sc = SSI(s)->sess_cert;
2650 	if (sc == NULL) {
2651 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2652 		goto err;
2653 	}
2654 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2655 
2656 	/* This is the passed certificate. */
2657 
2658 	idx = sc->peer_cert_type;
2659 	if (idx == SSL_PKEY_ECC) {
2660 		if (ssl_check_srvr_ecc_cert_and_alg(
2661 		    sc->peer_pkeys[idx].x509, s) == 0) {
2662 			/* check failed */
2663 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2664 			goto f_err;
2665 		} else {
2666 			return (1);
2667 		}
2668 	}
2669 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2670 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2671 	EVP_PKEY_free(pkey);
2672 
2673 	/* Check that we have a certificate if we require one. */
2674 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2675 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2676 		goto f_err;
2677 	}
2678 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2679 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2680 		goto f_err;
2681 	}
2682 	if ((alg_k & SSL_kDHE) &&
2683 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2684 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2685 		goto f_err;
2686 	}
2687 
2688 	return (1);
2689 f_err:
2690 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2691 err:
2692 	return (0);
2693 }
2694 
2695 /*
2696  * Check to see if handshake is full or resumed. Usually this is just a
2697  * case of checking to see if a cache hit has occurred. In the case of
2698  * session tickets we have to check the next message to be sure.
2699  */
2700 
2701 int
2702 ssl3_check_finished(SSL *s)
2703 {
2704 	int	ok;
2705 	long	n;
2706 
2707 	/* If we have no ticket it cannot be a resumed session. */
2708 	if (!s->session->tlsext_tick)
2709 		return (1);
2710 	/* this function is called when we really expect a Certificate
2711 	 * message, so permit appropriate message length */
2712 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_A,
2713 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2714 	if (!ok)
2715 		return ((int)n);
2716 	S3I(s)->tmp.reuse_message = 1;
2717 	if ((S3I(s)->tmp.message_type == SSL3_MT_FINISHED) ||
2718 	    (S3I(s)->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2719 		return (2);
2720 
2721 	return (1);
2722 }
2723 
2724 int
2725 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2726 {
2727 	int	i = 0;
2728 
2729 #ifndef OPENSSL_NO_ENGINE
2730 	if (s->ctx->internal->client_cert_engine) {
2731 		i = ENGINE_load_ssl_client_cert(
2732 		    s->ctx->internal->client_cert_engine, s,
2733 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2734 		if (i != 0)
2735 			return (i);
2736 	}
2737 #endif
2738 	if (s->ctx->internal->client_cert_cb)
2739 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2740 	return (i);
2741 }
2742