1/* $OpenBSD: ssl_clnt.c,v 1.165 2024/02/03 18:03:49 tb 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 <openssl/bn.h>
156#include <openssl/buffer.h>
157#include <openssl/curve25519.h>
158#include <openssl/dh.h>
159#include <openssl/evp.h>
160#include <openssl/md5.h>
161#include <openssl/objects.h>
162#include <openssl/opensslconf.h>
163
164#include "bytestring.h"
165#include "dtls_local.h"
166#include "ssl_local.h"
167#include "ssl_sigalgs.h"
168#include "ssl_tlsext.h"
169
170static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b);
171
172static int ssl3_send_client_hello(SSL *s);
173static int ssl3_get_dtls_hello_verify(SSL *s);
174static int ssl3_get_server_hello(SSL *s);
175static int ssl3_get_certificate_request(SSL *s);
176static int ssl3_get_new_session_ticket(SSL *s);
177static int ssl3_get_cert_status(SSL *s);
178static int ssl3_get_server_done(SSL *s);
179static int ssl3_send_client_verify(SSL *s);
180static int ssl3_send_client_certificate(SSL *s);
181static int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey);
182static int ssl3_send_client_key_exchange(SSL *s);
183static int ssl3_get_server_key_exchange(SSL *s);
184static int ssl3_get_server_certificate(SSL *s);
185static int ssl3_check_cert_and_algorithm(SSL *s);
186static int ssl3_check_finished(SSL *s);
187static int ssl3_send_client_change_cipher_spec(SSL *s);
188static int ssl3_send_client_finished(SSL *s);
189static int ssl3_get_server_finished(SSL *s);
190
191int
192ssl3_connect(SSL *s)
193{
194	int new_state, state, skip = 0;
195	int ret = -1;
196
197	ERR_clear_error();
198	errno = 0;
199
200	s->in_handshake++;
201	if (!SSL_in_init(s) || SSL_in_before(s))
202		SSL_clear(s);
203
204	for (;;) {
205		state = s->s3->hs.state;
206
207		switch (s->s3->hs.state) {
208		case SSL_ST_RENEGOTIATE:
209			s->renegotiate = 1;
210			s->s3->hs.state = SSL_ST_CONNECT;
211			s->ctx->stats.sess_connect_renegotiate++;
212			/* break */
213		case SSL_ST_BEFORE:
214		case SSL_ST_CONNECT:
215		case SSL_ST_BEFORE|SSL_ST_CONNECT:
216		case SSL_ST_OK|SSL_ST_CONNECT:
217
218			s->server = 0;
219
220			ssl_info_callback(s, SSL_CB_HANDSHAKE_START, 1);
221
222			if (!ssl_legacy_stack_version(s, s->version)) {
223				SSLerror(s, ERR_R_INTERNAL_ERROR);
224				ret = -1;
225				goto end;
226			}
227
228			if (!ssl_supported_tls_version_range(s,
229			    &s->s3->hs.our_min_tls_version,
230			    &s->s3->hs.our_max_tls_version)) {
231				SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
232				ret = -1;
233				goto end;
234			}
235
236			if (!ssl_security_version(s,
237			    s->s3->hs.our_min_tls_version)) {
238				SSLerror(s, SSL_R_VERSION_TOO_LOW);
239				ret = -1;
240				goto end;
241			}
242
243			if (!ssl3_setup_init_buffer(s)) {
244				ret = -1;
245				goto end;
246			}
247			if (!ssl3_setup_buffers(s)) {
248				ret = -1;
249				goto end;
250			}
251			if (!ssl_init_wbio_buffer(s, 0)) {
252				ret = -1;
253				goto end;
254			}
255
256			/* don't push the buffering BIO quite yet */
257
258			if (!tls1_transcript_init(s)) {
259				ret = -1;
260				goto end;
261			}
262
263			s->s3->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
264			s->ctx->stats.sess_connect++;
265			s->init_num = 0;
266
267			if (SSL_is_dtls(s)) {
268				/* mark client_random uninitialized */
269				memset(s->s3->client_random, 0,
270				    sizeof(s->s3->client_random));
271				s->d1->send_cookie = 0;
272				s->hit = 0;
273			}
274			break;
275
276		case SSL3_ST_CW_CLNT_HELLO_A:
277		case SSL3_ST_CW_CLNT_HELLO_B:
278			s->shutdown = 0;
279
280			if (SSL_is_dtls(s)) {
281				/* every DTLS ClientHello resets Finished MAC */
282				tls1_transcript_reset(s);
283
284				dtls1_start_timer(s);
285			}
286
287			ret = ssl3_send_client_hello(s);
288			if (ret <= 0)
289				goto end;
290
291			if (SSL_is_dtls(s) && s->d1->send_cookie) {
292				s->s3->hs.state = SSL3_ST_CW_FLUSH;
293				s->s3->hs.tls12.next_state = SSL3_ST_CR_SRVR_HELLO_A;
294			} else
295				s->s3->hs.state = SSL3_ST_CR_SRVR_HELLO_A;
296
297			s->init_num = 0;
298
299			/* turn on buffering for the next lot of output */
300			if (s->bbio != s->wbio)
301				s->wbio = BIO_push(s->bbio, s->wbio);
302
303			break;
304
305		case SSL3_ST_CR_SRVR_HELLO_A:
306		case SSL3_ST_CR_SRVR_HELLO_B:
307			ret = ssl3_get_server_hello(s);
308			if (ret <= 0)
309				goto end;
310
311			if (s->hit) {
312				s->s3->hs.state = SSL3_ST_CR_FINISHED_A;
313				if (!SSL_is_dtls(s)) {
314					if (s->tlsext_ticket_expected) {
315						/* receive renewed session ticket */
316						s->s3->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
317					}
318
319					/* No client certificate verification. */
320					tls1_transcript_free(s);
321				}
322			} else if (SSL_is_dtls(s)) {
323				s->s3->hs.state = DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
324			} else {
325				s->s3->hs.state = SSL3_ST_CR_CERT_A;
326			}
327			s->init_num = 0;
328			break;
329
330		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
331		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
332			ret = ssl3_get_dtls_hello_verify(s);
333			if (ret <= 0)
334				goto end;
335			dtls1_stop_timer(s);
336			if (s->d1->send_cookie) /* start again, with a cookie */
337				s->s3->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
338			else
339				s->s3->hs.state = SSL3_ST_CR_CERT_A;
340			s->init_num = 0;
341			break;
342
343		case SSL3_ST_CR_CERT_A:
344		case SSL3_ST_CR_CERT_B:
345			ret = ssl3_check_finished(s);
346			if (ret <= 0)
347				goto end;
348			if (ret == 2) {
349				s->hit = 1;
350				if (s->tlsext_ticket_expected)
351					s->s3->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
352				else
353					s->s3->hs.state = SSL3_ST_CR_FINISHED_A;
354				s->init_num = 0;
355				break;
356			}
357			/* Check if it is anon DH/ECDH. */
358			if (!(s->s3->hs.cipher->algorithm_auth &
359			    SSL_aNULL)) {
360				ret = ssl3_get_server_certificate(s);
361				if (ret <= 0)
362					goto end;
363				if (s->tlsext_status_expected)
364					s->s3->hs.state = SSL3_ST_CR_CERT_STATUS_A;
365				else
366					s->s3->hs.state = SSL3_ST_CR_KEY_EXCH_A;
367			} else {
368				skip = 1;
369				s->s3->hs.state = SSL3_ST_CR_KEY_EXCH_A;
370			}
371			s->init_num = 0;
372			break;
373
374		case SSL3_ST_CR_KEY_EXCH_A:
375		case SSL3_ST_CR_KEY_EXCH_B:
376			ret = ssl3_get_server_key_exchange(s);
377			if (ret <= 0)
378				goto end;
379			s->s3->hs.state = SSL3_ST_CR_CERT_REQ_A;
380			s->init_num = 0;
381
382			/*
383			 * At this point we check that we have the
384			 * required stuff from the server.
385			 */
386			if (!ssl3_check_cert_and_algorithm(s)) {
387				ret = -1;
388				goto end;
389			}
390			break;
391
392		case SSL3_ST_CR_CERT_REQ_A:
393		case SSL3_ST_CR_CERT_REQ_B:
394			ret = ssl3_get_certificate_request(s);
395			if (ret <= 0)
396				goto end;
397			s->s3->hs.state = SSL3_ST_CR_SRVR_DONE_A;
398			s->init_num = 0;
399			break;
400
401		case SSL3_ST_CR_SRVR_DONE_A:
402		case SSL3_ST_CR_SRVR_DONE_B:
403			ret = ssl3_get_server_done(s);
404			if (ret <= 0)
405				goto end;
406			if (SSL_is_dtls(s))
407				dtls1_stop_timer(s);
408			if (s->s3->hs.tls12.cert_request)
409				s->s3->hs.state = SSL3_ST_CW_CERT_A;
410			else
411				s->s3->hs.state = SSL3_ST_CW_KEY_EXCH_A;
412			s->init_num = 0;
413
414			break;
415
416		case SSL3_ST_CW_CERT_A:
417		case SSL3_ST_CW_CERT_B:
418		case SSL3_ST_CW_CERT_C:
419		case SSL3_ST_CW_CERT_D:
420			if (SSL_is_dtls(s))
421				dtls1_start_timer(s);
422			ret = ssl3_send_client_certificate(s);
423			if (ret <= 0)
424				goto end;
425			s->s3->hs.state = SSL3_ST_CW_KEY_EXCH_A;
426			s->init_num = 0;
427			break;
428
429		case SSL3_ST_CW_KEY_EXCH_A:
430		case SSL3_ST_CW_KEY_EXCH_B:
431			if (SSL_is_dtls(s))
432				dtls1_start_timer(s);
433			ret = ssl3_send_client_key_exchange(s);
434			if (ret <= 0)
435				goto end;
436			/*
437			 * EAY EAY EAY need to check for DH fix cert
438			 * sent back
439			 */
440			/*
441			 * For TLS, cert_req is set to 2, so a cert chain
442			 * of nothing is sent, but no verify packet is sent
443			 */
444			/*
445			 * XXX: For now, we do not support client
446			 * authentication in ECDH cipher suites with
447			 * ECDH (rather than ECDSA) certificates.
448			 * We need to skip the certificate verify
449			 * message when client's ECDH public key is sent
450			 * inside the client certificate.
451			 */
452			if (s->s3->hs.tls12.cert_request == 1) {
453				s->s3->hs.state = SSL3_ST_CW_CERT_VRFY_A;
454			} else {
455				s->s3->hs.state = SSL3_ST_CW_CHANGE_A;
456				s->s3->change_cipher_spec = 0;
457			}
458
459			s->init_num = 0;
460			break;
461
462		case SSL3_ST_CW_CERT_VRFY_A:
463		case SSL3_ST_CW_CERT_VRFY_B:
464			if (SSL_is_dtls(s))
465				dtls1_start_timer(s);
466			ret = ssl3_send_client_verify(s);
467			if (ret <= 0)
468				goto end;
469			s->s3->hs.state = SSL3_ST_CW_CHANGE_A;
470			s->init_num = 0;
471			s->s3->change_cipher_spec = 0;
472			break;
473
474		case SSL3_ST_CW_CHANGE_A:
475		case SSL3_ST_CW_CHANGE_B:
476			if (SSL_is_dtls(s) && !s->hit)
477				dtls1_start_timer(s);
478			ret = ssl3_send_client_change_cipher_spec(s);
479			if (ret <= 0)
480				goto end;
481
482			s->s3->hs.state = SSL3_ST_CW_FINISHED_A;
483			s->init_num = 0;
484			s->session->cipher = s->s3->hs.cipher;
485
486			if (!tls1_setup_key_block(s)) {
487				ret = -1;
488				goto end;
489			}
490			if (!tls1_change_write_cipher_state(s)) {
491				ret = -1;
492				goto end;
493			}
494			break;
495
496		case SSL3_ST_CW_FINISHED_A:
497		case SSL3_ST_CW_FINISHED_B:
498			if (SSL_is_dtls(s) && !s->hit)
499				dtls1_start_timer(s);
500			ret = ssl3_send_client_finished(s);
501			if (ret <= 0)
502				goto end;
503			if (!SSL_is_dtls(s))
504				s->s3->flags |= SSL3_FLAGS_CCS_OK;
505			s->s3->hs.state = SSL3_ST_CW_FLUSH;
506
507			/* clear flags */
508			if (s->hit) {
509				s->s3->hs.tls12.next_state = SSL_ST_OK;
510			} else {
511				/* Allow NewSessionTicket if ticket expected */
512				if (s->tlsext_ticket_expected)
513					s->s3->hs.tls12.next_state =
514					    SSL3_ST_CR_SESSION_TICKET_A;
515				else
516					s->s3->hs.tls12.next_state =
517					    SSL3_ST_CR_FINISHED_A;
518			}
519			s->init_num = 0;
520			break;
521
522		case SSL3_ST_CR_SESSION_TICKET_A:
523		case SSL3_ST_CR_SESSION_TICKET_B:
524			ret = ssl3_get_new_session_ticket(s);
525			if (ret <= 0)
526				goto end;
527			s->s3->hs.state = SSL3_ST_CR_FINISHED_A;
528			s->init_num = 0;
529			break;
530
531		case SSL3_ST_CR_CERT_STATUS_A:
532		case SSL3_ST_CR_CERT_STATUS_B:
533			ret = ssl3_get_cert_status(s);
534			if (ret <= 0)
535				goto end;
536			s->s3->hs.state = SSL3_ST_CR_KEY_EXCH_A;
537			s->init_num = 0;
538			break;
539
540		case SSL3_ST_CR_FINISHED_A:
541		case SSL3_ST_CR_FINISHED_B:
542			if (SSL_is_dtls(s))
543				s->d1->change_cipher_spec_ok = 1;
544			else
545				s->s3->flags |= SSL3_FLAGS_CCS_OK;
546			ret = ssl3_get_server_finished(s);
547			if (ret <= 0)
548				goto end;
549			if (SSL_is_dtls(s))
550				dtls1_stop_timer(s);
551
552			if (s->hit)
553				s->s3->hs.state = SSL3_ST_CW_CHANGE_A;
554			else
555				s->s3->hs.state = SSL_ST_OK;
556			s->init_num = 0;
557			break;
558
559		case SSL3_ST_CW_FLUSH:
560			s->rwstate = SSL_WRITING;
561			if (BIO_flush(s->wbio) <= 0) {
562				if (SSL_is_dtls(s)) {
563					/* If the write error was fatal, stop trying */
564					if (!BIO_should_retry(s->wbio)) {
565						s->rwstate = SSL_NOTHING;
566						s->s3->hs.state = s->s3->hs.tls12.next_state;
567					}
568				}
569				ret = -1;
570				goto end;
571			}
572			s->rwstate = SSL_NOTHING;
573			s->s3->hs.state = s->s3->hs.tls12.next_state;
574			break;
575
576		case SSL_ST_OK:
577			/* clean a few things up */
578			tls1_cleanup_key_block(s);
579
580			if (s->s3->handshake_transcript != NULL) {
581				SSLerror(s, ERR_R_INTERNAL_ERROR);
582				ret = -1;
583				goto end;
584			}
585
586			if (!SSL_is_dtls(s))
587				ssl3_release_init_buffer(s);
588
589			ssl_free_wbio_buffer(s);
590
591			s->init_num = 0;
592			s->renegotiate = 0;
593			s->new_session = 0;
594
595			ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
596			if (s->hit)
597				s->ctx->stats.sess_hit++;
598
599			ret = 1;
600			/* s->server=0; */
601			s->handshake_func = ssl3_connect;
602			s->ctx->stats.sess_connect_good++;
603
604			ssl_info_callback(s, SSL_CB_HANDSHAKE_DONE, 1);
605
606			if (SSL_is_dtls(s)) {
607				/* done with handshaking */
608				s->d1->handshake_read_seq = 0;
609				s->d1->next_handshake_write_seq = 0;
610			}
611
612			goto end;
613			/* break; */
614
615		default:
616			SSLerror(s, SSL_R_UNKNOWN_STATE);
617			ret = -1;
618			goto end;
619			/* break; */
620		}
621
622		/* did we do anything */
623		if (!s->s3->hs.tls12.reuse_message && !skip) {
624			if (s->s3->hs.state != state) {
625				new_state = s->s3->hs.state;
626				s->s3->hs.state = state;
627				ssl_info_callback(s, SSL_CB_CONNECT_LOOP, 1);
628				s->s3->hs.state = new_state;
629			}
630		}
631		skip = 0;
632	}
633
634 end:
635	s->in_handshake--;
636	ssl_info_callback(s, SSL_CB_CONNECT_EXIT, ret);
637
638	return (ret);
639}
640
641static int
642ssl3_send_client_hello(SSL *s)
643{
644	CBB cbb, client_hello, session_id, cookie, cipher_suites;
645	CBB compression_methods;
646	uint16_t max_version;
647	size_t sl;
648
649	memset(&cbb, 0, sizeof(cbb));
650
651	if (s->s3->hs.state == SSL3_ST_CW_CLNT_HELLO_A) {
652		SSL_SESSION *sess = s->session;
653
654		if (!ssl_max_supported_version(s, &max_version)) {
655			SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
656			return (-1);
657		}
658		s->version = max_version;
659
660		if (sess == NULL || sess->ssl_version != s->version ||
661		    (sess->session_id_length == 0 && sess->tlsext_tick == NULL) ||
662		    sess->not_resumable) {
663			if (!ssl_get_new_session(s, 0))
664				goto err;
665		}
666		/* else use the pre-loaded session */
667
668		/*
669		 * If a DTLS ClientHello message is being resent after a
670		 * HelloVerifyRequest, we must retain the original client
671		 * random value.
672		 */
673		if (!SSL_is_dtls(s) || s->d1->send_cookie == 0)
674			arc4random_buf(s->s3->client_random, SSL3_RANDOM_SIZE);
675
676		if (!ssl3_handshake_msg_start(s, &cbb, &client_hello,
677		    SSL3_MT_CLIENT_HELLO))
678			goto err;
679
680		if (!CBB_add_u16(&client_hello, s->version))
681			goto err;
682
683		/* Random stuff */
684		if (!CBB_add_bytes(&client_hello, s->s3->client_random,
685		    sizeof(s->s3->client_random)))
686			goto err;
687
688		/* Session ID */
689		if (!CBB_add_u8_length_prefixed(&client_hello, &session_id))
690			goto err;
691		if (!s->new_session &&
692		    s->session->session_id_length > 0) {
693			sl = s->session->session_id_length;
694			if (sl > sizeof(s->session->session_id)) {
695				SSLerror(s, ERR_R_INTERNAL_ERROR);
696				goto err;
697			}
698			if (!CBB_add_bytes(&session_id,
699			    s->session->session_id, sl))
700				goto err;
701		}
702
703		/* DTLS Cookie. */
704		if (SSL_is_dtls(s)) {
705			if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
706				SSLerror(s, ERR_R_INTERNAL_ERROR);
707				goto err;
708			}
709			if (!CBB_add_u8_length_prefixed(&client_hello, &cookie))
710				goto err;
711			if (!CBB_add_bytes(&cookie, s->d1->cookie,
712			    s->d1->cookie_len))
713				goto err;
714		}
715
716		/* Ciphers supported */
717		if (!CBB_add_u16_length_prefixed(&client_hello, &cipher_suites))
718			return 0;
719		if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s),
720		    &cipher_suites)) {
721			SSLerror(s, SSL_R_NO_CIPHERS_AVAILABLE);
722			goto err;
723		}
724
725		/* Add in compression methods (null) */
726		if (!CBB_add_u8_length_prefixed(&client_hello,
727		    &compression_methods))
728			goto err;
729		if (!CBB_add_u8(&compression_methods, 0))
730			goto err;
731
732		/* TLS extensions */
733		if (!tlsext_client_build(s, SSL_TLSEXT_MSG_CH, &client_hello)) {
734			SSLerror(s, ERR_R_INTERNAL_ERROR);
735			goto err;
736		}
737
738		if (!ssl3_handshake_msg_finish(s, &cbb))
739			goto err;
740
741		s->s3->hs.state = SSL3_ST_CW_CLNT_HELLO_B;
742	}
743
744	/* SSL3_ST_CW_CLNT_HELLO_B */
745	return (ssl3_handshake_write(s));
746
747 err:
748	CBB_cleanup(&cbb);
749
750	return (-1);
751}
752
753static int
754ssl3_get_dtls_hello_verify(SSL *s)
755{
756	CBS hello_verify_request, cookie;
757	size_t cookie_len;
758	uint16_t ssl_version;
759	int al, ret;
760
761	if ((ret = ssl3_get_message(s, DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
762	    DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B, -1, s->max_cert_list)) <= 0)
763		return ret;
764
765	if (s->s3->hs.tls12.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
766		s->d1->send_cookie = 0;
767		s->s3->hs.tls12.reuse_message = 1;
768		return (1);
769	}
770
771	if (s->init_num < 0)
772		goto decode_err;
773
774	CBS_init(&hello_verify_request, s->init_msg,
775	    s->init_num);
776
777	if (!CBS_get_u16(&hello_verify_request, &ssl_version))
778		goto decode_err;
779	if (!CBS_get_u8_length_prefixed(&hello_verify_request, &cookie))
780		goto decode_err;
781	if (CBS_len(&hello_verify_request) != 0)
782		goto decode_err;
783
784	/*
785	 * Per RFC 6347 section 4.2.1, the HelloVerifyRequest should always
786	 * contain DTLSv1.0 the version that is going to be negotiated.
787	 * Tolerate DTLSv1.2 just in case.
788	 */
789	if (ssl_version != DTLS1_VERSION && ssl_version != DTLS1_2_VERSION) {
790		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
791		s->version = (s->version & 0xff00) | (ssl_version & 0xff);
792		al = SSL_AD_PROTOCOL_VERSION;
793		goto fatal_err;
794	}
795
796	if (!CBS_write_bytes(&cookie, s->d1->cookie,
797	    sizeof(s->d1->cookie), &cookie_len)) {
798		s->d1->cookie_len = 0;
799		al = SSL_AD_ILLEGAL_PARAMETER;
800		goto fatal_err;
801	}
802	s->d1->cookie_len = cookie_len;
803	s->d1->send_cookie = 1;
804
805	return 1;
806
807 decode_err:
808	al = SSL_AD_DECODE_ERROR;
809 fatal_err:
810	ssl3_send_alert(s, SSL3_AL_FATAL, al);
811	return -1;
812}
813
814static int
815ssl3_get_server_hello(SSL *s)
816{
817	CBS cbs, server_random, session_id;
818	uint16_t server_version, cipher_suite;
819	uint8_t compression_method;
820	const SSL_CIPHER *cipher;
821	const SSL_METHOD *method;
822	int al, ret;
823
824	s->first_packet = 1;
825	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
826	    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000 /* ?? */)) <= 0)
827		return ret;
828	s->first_packet = 0;
829
830	if (s->init_num < 0)
831		goto decode_err;
832
833	CBS_init(&cbs, s->init_msg, s->init_num);
834
835	if (SSL_is_dtls(s)) {
836		if (s->s3->hs.tls12.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
837			if (s->d1->send_cookie == 0) {
838				s->s3->hs.tls12.reuse_message = 1;
839				return (1);
840			} else {
841				/* Already sent a cookie. */
842				al = SSL_AD_UNEXPECTED_MESSAGE;
843				SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
844				goto fatal_err;
845			}
846		}
847	}
848
849	if (s->s3->hs.tls12.message_type != SSL3_MT_SERVER_HELLO) {
850		al = SSL_AD_UNEXPECTED_MESSAGE;
851		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
852		goto fatal_err;
853	}
854
855	if (!CBS_get_u16(&cbs, &server_version))
856		goto decode_err;
857
858	if (!ssl_check_version_from_server(s, server_version)) {
859		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
860		s->version = (s->version & 0xff00) | (server_version & 0xff);
861		al = SSL_AD_PROTOCOL_VERSION;
862		goto fatal_err;
863	}
864	s->s3->hs.peer_legacy_version = server_version;
865	s->version = server_version;
866
867	s->s3->hs.negotiated_tls_version = ssl_tls_version(server_version);
868	if (s->s3->hs.negotiated_tls_version == 0) {
869		SSLerror(s, ERR_R_INTERNAL_ERROR);
870		goto err;
871	}
872
873	if ((method = ssl_get_method(server_version)) == NULL) {
874		SSLerror(s, ERR_R_INTERNAL_ERROR);
875		goto err;
876	}
877	s->method = method;
878
879	/* Server random. */
880	if (!CBS_get_bytes(&cbs, &server_random, SSL3_RANDOM_SIZE))
881		goto decode_err;
882	if (!CBS_write_bytes(&server_random, s->s3->server_random,
883	    sizeof(s->s3->server_random), NULL))
884		goto err;
885
886	if (s->s3->hs.our_max_tls_version >= TLS1_2_VERSION &&
887	    s->s3->hs.negotiated_tls_version < s->s3->hs.our_max_tls_version) {
888		/*
889		 * RFC 8446 section 4.1.3. We must not downgrade if the server
890		 * random value contains the TLS 1.2 or TLS 1.1 magical value.
891		 */
892		if (!CBS_skip(&server_random,
893		    CBS_len(&server_random) - sizeof(tls13_downgrade_12)))
894			goto err;
895		if (s->s3->hs.negotiated_tls_version == TLS1_2_VERSION &&
896		    CBS_mem_equal(&server_random, tls13_downgrade_12,
897		    sizeof(tls13_downgrade_12))) {
898			al = SSL_AD_ILLEGAL_PARAMETER;
899			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
900			goto fatal_err;
901		}
902		if (CBS_mem_equal(&server_random, tls13_downgrade_11,
903		    sizeof(tls13_downgrade_11))) {
904			al = SSL_AD_ILLEGAL_PARAMETER;
905			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
906			goto fatal_err;
907		}
908	}
909
910	/* Session ID. */
911	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
912		goto decode_err;
913
914	if (CBS_len(&session_id) > SSL3_SESSION_ID_SIZE) {
915		al = SSL_AD_ILLEGAL_PARAMETER;
916		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
917		goto fatal_err;
918	}
919
920	/* Cipher suite. */
921	if (!CBS_get_u16(&cbs, &cipher_suite))
922		goto decode_err;
923
924	/*
925	 * Check if we want to resume the session based on external
926	 * pre-shared secret.
927	 */
928	if (s->tls_session_secret_cb != NULL) {
929		SSL_CIPHER *pref_cipher = NULL;
930		int master_key_length = sizeof(s->session->master_key);
931
932		if (!s->tls_session_secret_cb(s,
933		    s->session->master_key, &master_key_length, NULL,
934		    &pref_cipher, s->tls_session_secret_cb_arg)) {
935			SSLerror(s, ERR_R_INTERNAL_ERROR);
936			goto err;
937		}
938		if (master_key_length <= 0) {
939			SSLerror(s, ERR_R_INTERNAL_ERROR);
940			goto err;
941		}
942		s->session->master_key_length = master_key_length;
943
944		if ((s->session->cipher = pref_cipher) == NULL)
945			s->session->cipher =
946			    ssl3_get_cipher_by_value(cipher_suite);
947		s->s3->flags |= SSL3_FLAGS_CCS_OK;
948	}
949
950	if (s->session->session_id_length != 0 &&
951	    CBS_mem_equal(&session_id, s->session->session_id,
952		s->session->session_id_length)) {
953		if (s->sid_ctx_length != s->session->sid_ctx_length ||
954		    timingsafe_memcmp(s->session->sid_ctx,
955		    s->sid_ctx, s->sid_ctx_length) != 0) {
956			/* actually a client application bug */
957			al = SSL_AD_ILLEGAL_PARAMETER;
958			SSLerror(s, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
959			goto fatal_err;
960		}
961		s->s3->flags |= SSL3_FLAGS_CCS_OK;
962		s->hit = 1;
963	} else {
964		/* a miss or crap from the other end */
965
966		/* If we were trying for session-id reuse, make a new
967		 * SSL_SESSION so we don't stuff up other people */
968		s->hit = 0;
969		if (s->session->session_id_length > 0) {
970			if (!ssl_get_new_session(s, 0)) {
971				al = SSL_AD_INTERNAL_ERROR;
972				goto fatal_err;
973			}
974		}
975
976		/*
977		 * XXX - improve the handling for the case where there is a
978		 * zero length session identifier.
979		 */
980		if (!CBS_write_bytes(&session_id, s->session->session_id,
981		    sizeof(s->session->session_id),
982		    &s->session->session_id_length))
983			goto err;
984
985		s->session->ssl_version = s->version;
986	}
987
988	if ((cipher = ssl3_get_cipher_by_value(cipher_suite)) == NULL) {
989		al = SSL_AD_ILLEGAL_PARAMETER;
990		SSLerror(s, SSL_R_UNKNOWN_CIPHER_RETURNED);
991		goto fatal_err;
992	}
993
994	/* TLS v1.2 only ciphersuites require v1.2 or later. */
995	if ((cipher->algorithm_ssl & SSL_TLSV1_2) &&
996	    s->s3->hs.negotiated_tls_version < TLS1_2_VERSION) {
997		al = SSL_AD_ILLEGAL_PARAMETER;
998		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
999		goto fatal_err;
1000	}
1001
1002	if (!ssl_cipher_in_list(SSL_get_ciphers(s), cipher)) {
1003		/* we did not say we would use this cipher */
1004		al = SSL_AD_ILLEGAL_PARAMETER;
1005		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
1006		goto fatal_err;
1007	}
1008
1009	/*
1010	 * Depending on the session caching (internal/external), the cipher
1011	 * and/or cipher_id values may not be set. Make sure that
1012	 * cipher_id is set and use it for comparison.
1013	 */
1014	if (s->session->cipher)
1015		s->session->cipher_id = s->session->cipher->id;
1016	if (s->hit && (s->session->cipher_id != cipher->id)) {
1017		al = SSL_AD_ILLEGAL_PARAMETER;
1018		SSLerror(s, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1019		goto fatal_err;
1020	}
1021	s->s3->hs.cipher = cipher;
1022
1023	if (!tls1_transcript_hash_init(s))
1024		goto err;
1025
1026	/*
1027	 * Don't digest cached records if no sigalgs: we may need them for
1028	 * client authentication.
1029	 */
1030	if (!SSL_USE_SIGALGS(s))
1031		tls1_transcript_free(s);
1032
1033	if (!CBS_get_u8(&cbs, &compression_method))
1034		goto decode_err;
1035
1036	if (compression_method != 0) {
1037		al = SSL_AD_ILLEGAL_PARAMETER;
1038		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1039		goto fatal_err;
1040	}
1041
1042	if (!tlsext_client_parse(s, SSL_TLSEXT_MSG_SH, &cbs, &al)) {
1043		SSLerror(s, SSL_R_PARSE_TLSEXT);
1044		goto fatal_err;
1045	}
1046
1047	if (CBS_len(&cbs) != 0)
1048		goto decode_err;
1049
1050	/*
1051	 * Determine if we need to see RI. Strictly speaking if we want to
1052	 * avoid an attack we should *always* see RI even on initial server
1053	 * hello because the client doesn't see any renegotiation during an
1054	 * attack. However this would mean we could not connect to any server
1055	 * which doesn't support RI so for the immediate future tolerate RI
1056	 * absence on initial connect only.
1057	 */
1058	if (!s->s3->renegotiate_seen &&
1059	    !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)) {
1060		al = SSL_AD_HANDSHAKE_FAILURE;
1061		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1062		goto fatal_err;
1063	}
1064
1065	if (ssl_check_serverhello_tlsext(s) <= 0) {
1066		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
1067		goto err;
1068	}
1069
1070	return (1);
1071
1072 decode_err:
1073	/* wrong packet length */
1074	al = SSL_AD_DECODE_ERROR;
1075	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1076 fatal_err:
1077	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1078 err:
1079	return (-1);
1080}
1081
1082static int
1083ssl3_get_server_certificate(SSL *s)
1084{
1085	CBS cbs, cert_list, cert_data;
1086	STACK_OF(X509) *certs = NULL;
1087	X509 *cert = NULL;
1088	const uint8_t *p;
1089	int al, ret;
1090
1091	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
1092	    SSL3_ST_CR_CERT_B, -1, s->max_cert_list)) <= 0)
1093		return ret;
1094
1095	ret = -1;
1096
1097	if (s->s3->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1098		s->s3->hs.tls12.reuse_message = 1;
1099		return (1);
1100	}
1101
1102	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
1103		al = SSL_AD_UNEXPECTED_MESSAGE;
1104		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1105		goto fatal_err;
1106	}
1107
1108	if ((certs = sk_X509_new_null()) == NULL) {
1109		SSLerror(s, ERR_R_MALLOC_FAILURE);
1110		goto err;
1111	}
1112
1113	if (s->init_num < 0)
1114		goto decode_err;
1115
1116	CBS_init(&cbs, s->init_msg, s->init_num);
1117
1118	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list))
1119		goto decode_err;
1120	if (CBS_len(&cbs) != 0)
1121		goto decode_err;
1122
1123	while (CBS_len(&cert_list) > 0) {
1124		if (!CBS_get_u24_length_prefixed(&cert_list, &cert_data))
1125			goto decode_err;
1126		p = CBS_data(&cert_data);
1127		if ((cert = d2i_X509(NULL, &p, CBS_len(&cert_data))) == NULL) {
1128			al = SSL_AD_BAD_CERTIFICATE;
1129			SSLerror(s, ERR_R_ASN1_LIB);
1130			goto fatal_err;
1131		}
1132		if (p != CBS_data(&cert_data) + CBS_len(&cert_data))
1133			goto decode_err;
1134		if (!sk_X509_push(certs, cert)) {
1135			SSLerror(s, ERR_R_MALLOC_FAILURE);
1136			goto err;
1137		}
1138		cert = NULL;
1139	}
1140
1141	/* A server must always provide a non-empty certificate list. */
1142	if (sk_X509_num(certs) < 1) {
1143		SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1144		goto decode_err;
1145	}
1146
1147	if (ssl_verify_cert_chain(s, certs) <= 0 &&
1148	    s->verify_mode != SSL_VERIFY_NONE) {
1149		al = ssl_verify_alarm_type(s->verify_result);
1150		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1151		goto fatal_err;
1152	}
1153	s->session->verify_result = s->verify_result;
1154	ERR_clear_error();
1155
1156	if (!tls_process_peer_certs(s, certs))
1157		goto err;
1158
1159	ret = 1;
1160
1161	if (0) {
1162 decode_err:
1163		/* wrong packet length */
1164		al = SSL_AD_DECODE_ERROR;
1165		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1166 fatal_err:
1167		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1168	}
1169 err:
1170	sk_X509_pop_free(certs, X509_free);
1171	X509_free(cert);
1172
1173	return (ret);
1174}
1175
1176static int
1177ssl3_get_server_kex_dhe(SSL *s, CBS *cbs)
1178{
1179	int decode_error, invalid_params, invalid_key;
1180	int nid = NID_dhKeyAgreement;
1181
1182	tls_key_share_free(s->s3->hs.key_share);
1183	if ((s->s3->hs.key_share = tls_key_share_new_nid(nid)) == NULL)
1184		goto err;
1185
1186	if (!tls_key_share_peer_params(s->s3->hs.key_share, cbs,
1187	    &decode_error, &invalid_params)) {
1188		if (decode_error) {
1189			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1190			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1191		}
1192		goto err;
1193	}
1194	if (!tls_key_share_peer_public(s->s3->hs.key_share, cbs,
1195	    &decode_error, &invalid_key)) {
1196		if (decode_error) {
1197			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1198			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1199		}
1200		goto err;
1201	}
1202
1203	if (invalid_params) {
1204		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1205		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1206		goto err;
1207	}
1208	if (invalid_key) {
1209		SSLerror(s, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1210		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1211		goto err;
1212	}
1213
1214	if (!tls_key_share_peer_security(s, s->s3->hs.key_share)) {
1215		SSLerror(s, SSL_R_DH_KEY_TOO_SMALL);
1216		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1217		return 0;
1218	}
1219
1220	return 1;
1221
1222 err:
1223	return 0;
1224}
1225
1226static int
1227ssl3_get_server_kex_ecdhe(SSL *s, CBS *cbs)
1228{
1229	uint8_t curve_type;
1230	uint16_t group_id;
1231	int decode_error;
1232	CBS public;
1233
1234	if (!CBS_get_u8(cbs, &curve_type))
1235		goto decode_err;
1236	if (!CBS_get_u16(cbs, &group_id))
1237		goto decode_err;
1238
1239	/* Only named curves are supported. */
1240	if (curve_type != NAMED_CURVE_TYPE) {
1241		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1242		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1243		goto err;
1244	}
1245
1246	if (!CBS_get_u8_length_prefixed(cbs, &public))
1247		goto decode_err;
1248
1249	/*
1250	 * Check that the group is one of our preferences - if it is not,
1251	 * the server has sent us an invalid group.
1252	 */
1253	if (!tls1_check_group(s, group_id)) {
1254		SSLerror(s, SSL_R_WRONG_CURVE);
1255		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1256		goto err;
1257	}
1258
1259	tls_key_share_free(s->s3->hs.key_share);
1260	if ((s->s3->hs.key_share = tls_key_share_new(group_id)) == NULL)
1261		goto err;
1262
1263	if (!tls_key_share_peer_public(s->s3->hs.key_share, &public,
1264	    &decode_error, NULL)) {
1265		if (decode_error)
1266			goto decode_err;
1267		goto err;
1268	}
1269
1270	return 1;
1271
1272 decode_err:
1273	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1274	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1275 err:
1276	return 0;
1277}
1278
1279static int
1280ssl3_get_server_key_exchange(SSL *s)
1281{
1282	CBB cbb;
1283	CBS cbs, params, signature;
1284	EVP_MD_CTX *md_ctx;
1285	unsigned char *signed_params = NULL;
1286	size_t signed_params_len;
1287	size_t params_len;
1288	long alg_k, alg_a;
1289	int al, ret;
1290
1291	memset(&cbb, 0, sizeof(cbb));
1292
1293	alg_k = s->s3->hs.cipher->algorithm_mkey;
1294	alg_a = s->s3->hs.cipher->algorithm_auth;
1295
1296	/*
1297	 * Use same message size as in ssl3_get_certificate_request()
1298	 * as ServerKeyExchange message may be skipped.
1299	 */
1300	if ((ret = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1301	    SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list)) <= 0)
1302		return ret;
1303
1304	if ((md_ctx = EVP_MD_CTX_new()) == NULL)
1305		goto err;
1306
1307	if (s->init_num < 0)
1308		goto err;
1309
1310	CBS_init(&cbs, s->init_msg, s->init_num);
1311
1312	if (s->s3->hs.tls12.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1313		/*
1314		 * Do not skip server key exchange if this cipher suite uses
1315		 * ephemeral keys.
1316		 */
1317		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1318			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1319			al = SSL_AD_UNEXPECTED_MESSAGE;
1320			goto fatal_err;
1321		}
1322
1323		s->s3->hs.tls12.reuse_message = 1;
1324		EVP_MD_CTX_free(md_ctx);
1325		return (1);
1326	}
1327
1328	if (!CBB_init(&cbb, 0))
1329		goto err;
1330	if (!CBB_add_bytes(&cbb, s->s3->client_random, SSL3_RANDOM_SIZE))
1331		goto err;
1332	if (!CBB_add_bytes(&cbb, s->s3->server_random, SSL3_RANDOM_SIZE))
1333		goto err;
1334
1335	CBS_dup(&cbs, &params);
1336
1337	if (alg_k & SSL_kDHE) {
1338		if (!ssl3_get_server_kex_dhe(s, &cbs))
1339			goto err;
1340	} else if (alg_k & SSL_kECDHE) {
1341		if (!ssl3_get_server_kex_ecdhe(s, &cbs))
1342			goto err;
1343	} else if (alg_k != 0) {
1344		al = SSL_AD_UNEXPECTED_MESSAGE;
1345		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1346		goto fatal_err;
1347	}
1348
1349	if ((params_len = CBS_offset(&cbs)) > CBS_len(&params))
1350		goto err;
1351	if (!CBB_add_bytes(&cbb, CBS_data(&params), params_len))
1352		goto err;
1353	if (!CBB_finish(&cbb, &signed_params, &signed_params_len))
1354		goto err;
1355
1356	/* if it was signed, check the signature */
1357	if ((alg_a & SSL_aNULL) == 0) {
1358		uint16_t sigalg_value = SIGALG_NONE;
1359		const struct ssl_sigalg *sigalg;
1360		EVP_PKEY_CTX *pctx;
1361		EVP_PKEY *pkey = NULL;
1362
1363		if ((alg_a & SSL_aRSA) != 0 &&
1364		    s->session->peer_cert_type == SSL_PKEY_RSA) {
1365			pkey = X509_get0_pubkey(s->session->peer_cert);
1366		} else if ((alg_a & SSL_aECDSA) != 0 &&
1367		    s->session->peer_cert_type == SSL_PKEY_ECC) {
1368			pkey = X509_get0_pubkey(s->session->peer_cert);
1369		}
1370		if (pkey == NULL) {
1371			al = SSL_AD_ILLEGAL_PARAMETER;
1372			SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1373			goto fatal_err;
1374		}
1375
1376		if (SSL_USE_SIGALGS(s)) {
1377			if (!CBS_get_u16(&cbs, &sigalg_value))
1378				goto decode_err;
1379		}
1380		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1381			goto decode_err;
1382		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1383			al = SSL_AD_DECODE_ERROR;
1384			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1385			goto fatal_err;
1386		}
1387
1388		if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1389		    sigalg_value)) == NULL) {
1390			al = SSL_AD_DECODE_ERROR;
1391			goto fatal_err;
1392		}
1393		s->s3->hs.peer_sigalg = sigalg;
1394
1395		if (!EVP_DigestVerifyInit(md_ctx, &pctx, sigalg->md(),
1396		    NULL, pkey))
1397			goto err;
1398		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1399		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1400		    RSA_PKCS1_PSS_PADDING) ||
1401		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1402			goto err;
1403		if (EVP_DigestVerify(md_ctx, CBS_data(&signature),
1404		    CBS_len(&signature), signed_params, signed_params_len) <= 0) {
1405			al = SSL_AD_DECRYPT_ERROR;
1406			SSLerror(s, SSL_R_BAD_SIGNATURE);
1407			goto fatal_err;
1408		}
1409	}
1410
1411	if (CBS_len(&cbs) != 0) {
1412		al = SSL_AD_DECODE_ERROR;
1413		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1414		goto fatal_err;
1415	}
1416
1417	EVP_MD_CTX_free(md_ctx);
1418	free(signed_params);
1419
1420	return (1);
1421
1422 decode_err:
1423	al = SSL_AD_DECODE_ERROR;
1424	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1425
1426 fatal_err:
1427	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1428
1429 err:
1430	CBB_cleanup(&cbb);
1431	EVP_MD_CTX_free(md_ctx);
1432	free(signed_params);
1433
1434	return (-1);
1435}
1436
1437static int
1438ssl3_get_certificate_request(SSL *s)
1439{
1440	CBS cert_request, cert_types, rdn_list;
1441	X509_NAME *xn = NULL;
1442	const unsigned char *q;
1443	STACK_OF(X509_NAME) *ca_sk = NULL;
1444	int ret;
1445
1446	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1447	    SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list)) <= 0)
1448		return ret;
1449
1450	ret = 0;
1451
1452	s->s3->hs.tls12.cert_request = 0;
1453
1454	if (s->s3->hs.tls12.message_type == SSL3_MT_SERVER_DONE) {
1455		s->s3->hs.tls12.reuse_message = 1;
1456		/*
1457		 * If we get here we don't need any cached handshake records
1458		 * as we wont be doing client auth.
1459		 */
1460		tls1_transcript_free(s);
1461		return (1);
1462	}
1463
1464	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1465		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1466		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1467		goto err;
1468	}
1469
1470	/* TLS does not like anon-DH with client cert */
1471	if (s->s3->hs.cipher->algorithm_auth & SSL_aNULL) {
1472		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1473		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1474		goto err;
1475	}
1476
1477	if (s->init_num < 0)
1478		goto decode_err;
1479	CBS_init(&cert_request, s->init_msg, s->init_num);
1480
1481	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1482		SSLerror(s, ERR_R_MALLOC_FAILURE);
1483		goto err;
1484	}
1485
1486	if (!CBS_get_u8_length_prefixed(&cert_request, &cert_types))
1487		goto decode_err;
1488
1489	if (SSL_USE_SIGALGS(s)) {
1490		CBS sigalgs;
1491
1492		if (CBS_len(&cert_request) < 2) {
1493			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1494			goto err;
1495		}
1496		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1497			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1498			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1499			goto err;
1500		}
1501		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1502			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1503			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1504			goto err;
1505		}
1506		if (!CBS_stow(&sigalgs, &s->s3->hs.sigalgs,
1507		    &s->s3->hs.sigalgs_len))
1508			goto err;
1509	}
1510
1511	/* get the CA RDNs */
1512	if (CBS_len(&cert_request) < 2) {
1513		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1514		goto err;
1515	}
1516
1517	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1518	    CBS_len(&cert_request) != 0) {
1519		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1520		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1521		goto err;
1522	}
1523
1524	while (CBS_len(&rdn_list) > 0) {
1525		CBS rdn;
1526
1527		if (CBS_len(&rdn_list) < 2) {
1528			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1529			goto err;
1530		}
1531
1532		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1533			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1534			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1535			goto err;
1536		}
1537
1538		q = CBS_data(&rdn);
1539		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1540			ssl3_send_alert(s, SSL3_AL_FATAL,
1541			    SSL_AD_DECODE_ERROR);
1542			SSLerror(s, ERR_R_ASN1_LIB);
1543			goto err;
1544		}
1545
1546		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1547			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1548			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1549			goto err;
1550		}
1551		if (!sk_X509_NAME_push(ca_sk, xn)) {
1552			SSLerror(s, ERR_R_MALLOC_FAILURE);
1553			goto err;
1554		}
1555		xn = NULL;	/* avoid free in err block */
1556	}
1557
1558	/* we should setup a certificate to return.... */
1559	s->s3->hs.tls12.cert_request = 1;
1560	sk_X509_NAME_pop_free(s->s3->hs.tls12.ca_names, X509_NAME_free);
1561	s->s3->hs.tls12.ca_names = ca_sk;
1562	ca_sk = NULL;
1563
1564	ret = 1;
1565	if (0) {
1566 decode_err:
1567		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1568	}
1569 err:
1570	X509_NAME_free(xn);
1571	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1572	return (ret);
1573}
1574
1575static int
1576ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1577{
1578	return (X509_NAME_cmp(*a, *b));
1579}
1580
1581static int
1582ssl3_get_new_session_ticket(SSL *s)
1583{
1584	uint32_t lifetime_hint;
1585	CBS cbs, session_ticket;
1586	unsigned int session_id_length = 0;
1587	int al, ret;
1588
1589	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1590	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384)) <= 0)
1591		return ret;
1592
1593	if (s->s3->hs.tls12.message_type == SSL3_MT_FINISHED) {
1594		s->s3->hs.tls12.reuse_message = 1;
1595		return (1);
1596	}
1597	if (s->s3->hs.tls12.message_type != SSL3_MT_NEWSESSION_TICKET) {
1598		al = SSL_AD_UNEXPECTED_MESSAGE;
1599		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1600		goto fatal_err;
1601	}
1602
1603	if (s->init_num < 0) {
1604		al = SSL_AD_DECODE_ERROR;
1605		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1606		goto fatal_err;
1607	}
1608
1609	CBS_init(&cbs, s->init_msg, s->init_num);
1610	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1611	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1612	    CBS_len(&cbs) != 0) {
1613		al = SSL_AD_DECODE_ERROR;
1614		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1615		goto fatal_err;
1616	}
1617	s->session->tlsext_tick_lifetime_hint = lifetime_hint;
1618
1619	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1620	    &s->session->tlsext_ticklen)) {
1621		SSLerror(s, ERR_R_MALLOC_FAILURE);
1622		goto err;
1623	}
1624
1625	/*
1626	 * There are two ways to detect a resumed ticket session.
1627	 * One is to set an appropriate session ID and then the server
1628	 * must return a match in ServerHello. This allows the normal
1629	 * client session ID matching to work and we know much
1630	 * earlier that the ticket has been accepted.
1631	 *
1632	 * The other way is to set zero length session ID when the
1633	 * ticket is presented and rely on the handshake to determine
1634	 * session resumption.
1635	 *
1636	 * We choose the former approach because this fits in with
1637	 * assumptions elsewhere in OpenSSL. The session ID is set
1638	 * to the SHA256 hash of the ticket.
1639	 */
1640	/* XXX - ensure this doesn't overflow session_id if hash is changed. */
1641	if (!EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1642	    s->session->session_id, &session_id_length, EVP_sha256(), NULL)) {
1643		al = SSL_AD_INTERNAL_ERROR;
1644		SSLerror(s, ERR_R_EVP_LIB);
1645		goto fatal_err;
1646	}
1647	s->session->session_id_length = session_id_length;
1648
1649	return (1);
1650
1651 fatal_err:
1652	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1653 err:
1654	return (-1);
1655}
1656
1657static int
1658ssl3_get_cert_status(SSL *s)
1659{
1660	CBS cert_status, response;
1661	uint8_t	status_type;
1662	int al, ret;
1663
1664	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1665	    SSL3_ST_CR_CERT_STATUS_B, -1, 16384)) <= 0)
1666		return ret;
1667
1668	if (s->s3->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1669		/*
1670		 * Tell the callback the server did not send us an OSCP
1671		 * response, and has decided to head directly to key exchange.
1672		 */
1673		if (s->ctx->tlsext_status_cb) {
1674			free(s->tlsext_ocsp_resp);
1675			s->tlsext_ocsp_resp = NULL;
1676			s->tlsext_ocsp_resp_len = 0;
1677
1678			ret = s->ctx->tlsext_status_cb(s,
1679			    s->ctx->tlsext_status_arg);
1680			if (ret == 0) {
1681				al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1682				SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1683				goto fatal_err;
1684			}
1685			if (ret < 0) {
1686				al = SSL_AD_INTERNAL_ERROR;
1687				SSLerror(s, ERR_R_MALLOC_FAILURE);
1688				goto fatal_err;
1689			}
1690		}
1691		s->s3->hs.tls12.reuse_message = 1;
1692		return (1);
1693	}
1694
1695	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE &&
1696	    s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1697		al = SSL_AD_UNEXPECTED_MESSAGE;
1698		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1699		goto fatal_err;
1700	}
1701
1702	if (s->init_num < 0) {
1703		/* need at least status type + length */
1704		al = SSL_AD_DECODE_ERROR;
1705		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1706		goto fatal_err;
1707	}
1708
1709	CBS_init(&cert_status, s->init_msg, s->init_num);
1710	if (!CBS_get_u8(&cert_status, &status_type) ||
1711	    CBS_len(&cert_status) < 3) {
1712		/* need at least status type + length */
1713		al = SSL_AD_DECODE_ERROR;
1714		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1715		goto fatal_err;
1716	}
1717
1718	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1719		al = SSL_AD_DECODE_ERROR;
1720		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1721		goto fatal_err;
1722	}
1723
1724	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1725	    CBS_len(&cert_status) != 0) {
1726		al = SSL_AD_DECODE_ERROR;
1727		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1728		goto fatal_err;
1729	}
1730
1731	if (!CBS_stow(&response, &s->tlsext_ocsp_resp,
1732	    &s->tlsext_ocsp_resp_len)) {
1733		al = SSL_AD_INTERNAL_ERROR;
1734		SSLerror(s, ERR_R_MALLOC_FAILURE);
1735		goto fatal_err;
1736	}
1737
1738	if (s->ctx->tlsext_status_cb) {
1739		ret = s->ctx->tlsext_status_cb(s,
1740		    s->ctx->tlsext_status_arg);
1741		if (ret == 0) {
1742			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1743			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1744			goto fatal_err;
1745		}
1746		if (ret < 0) {
1747			al = SSL_AD_INTERNAL_ERROR;
1748			SSLerror(s, ERR_R_MALLOC_FAILURE);
1749			goto fatal_err;
1750		}
1751	}
1752	return (1);
1753 fatal_err:
1754	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1755	return (-1);
1756}
1757
1758static int
1759ssl3_get_server_done(SSL *s)
1760{
1761	int ret;
1762
1763	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1764	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1765	    30 /* should be very small, like 0 :-) */)) <= 0)
1766		return ret;
1767
1768	if (s->init_num != 0) {
1769		/* should contain no data */
1770		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1771		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1772		return -1;
1773	}
1774
1775	return 1;
1776}
1777
1778static int
1779ssl3_send_client_kex_rsa(SSL *s, CBB *cbb)
1780{
1781	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1782	unsigned char *enc_pms = NULL;
1783	uint16_t max_legacy_version;
1784	EVP_PKEY *pkey;
1785	RSA *rsa;
1786	int ret = 0;
1787	int enc_len;
1788	CBB epms;
1789
1790	/*
1791	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1792	 */
1793
1794	pkey = X509_get0_pubkey(s->session->peer_cert);
1795	if (pkey == NULL || (rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
1796		SSLerror(s, ERR_R_INTERNAL_ERROR);
1797		goto err;
1798	}
1799
1800	/*
1801	 * Our maximum legacy protocol version - while RFC 5246 section 7.4.7.1
1802	 * says "The latest (newest) version supported by the client", if we're
1803	 * doing RSA key exchange then we have to presume that we're talking to
1804	 * a server that does not understand the supported versions extension
1805	 * and therefore our maximum version is that sent in the ClientHello.
1806	 */
1807	if (!ssl_max_legacy_version(s, &max_legacy_version))
1808		goto err;
1809	pms[0] = max_legacy_version >> 8;
1810	pms[1] = max_legacy_version & 0xff;
1811	arc4random_buf(&pms[2], sizeof(pms) - 2);
1812
1813	if ((enc_pms = malloc(RSA_size(rsa))) == NULL) {
1814		SSLerror(s, ERR_R_MALLOC_FAILURE);
1815		goto err;
1816	}
1817
1818	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, rsa,
1819	    RSA_PKCS1_PADDING);
1820	if (enc_len <= 0) {
1821		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1822		goto err;
1823	}
1824
1825	if (!CBB_add_u16_length_prefixed(cbb, &epms))
1826		goto err;
1827	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
1828		goto err;
1829	if (!CBB_flush(cbb))
1830		goto err;
1831
1832	if (!tls12_derive_master_secret(s, pms, sizeof(pms)))
1833		goto err;
1834
1835	ret = 1;
1836
1837 err:
1838	explicit_bzero(pms, sizeof(pms));
1839	free(enc_pms);
1840
1841	return ret;
1842}
1843
1844static int
1845ssl3_send_client_kex_dhe(SSL *s, CBB *cbb)
1846{
1847	uint8_t *key = NULL;
1848	size_t key_len = 0;
1849	int ret = 0;
1850
1851	/* Ensure that we have an ephemeral key from the server for DHE. */
1852	if (s->s3->hs.key_share == NULL) {
1853		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1854		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1855		goto err;
1856	}
1857
1858	if (!tls_key_share_generate(s->s3->hs.key_share))
1859		goto err;
1860	if (!tls_key_share_public(s->s3->hs.key_share, cbb))
1861		goto err;
1862	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1863		goto err;
1864
1865	if (!tls_key_share_peer_security(s, s->s3->hs.key_share)) {
1866		SSLerror(s, SSL_R_DH_KEY_TOO_SMALL);
1867		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1868		return 0;
1869	}
1870
1871	if (!tls12_derive_master_secret(s, key, key_len))
1872		goto err;
1873
1874	ret = 1;
1875
1876 err:
1877	freezero(key, key_len);
1878
1879	return ret;
1880}
1881
1882static int
1883ssl3_send_client_kex_ecdhe(SSL *s, CBB *cbb)
1884{
1885	uint8_t *key = NULL;
1886	size_t key_len = 0;
1887	CBB public;
1888	int ret = 0;
1889
1890	/* Ensure that we have an ephemeral key for ECDHE. */
1891	if (s->s3->hs.key_share == NULL) {
1892		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1893		SSLerror(s, ERR_R_INTERNAL_ERROR);
1894		goto err;
1895	}
1896
1897	if (!tls_key_share_generate(s->s3->hs.key_share))
1898		goto err;
1899
1900	if (!CBB_add_u8_length_prefixed(cbb, &public))
1901		return 0;
1902	if (!tls_key_share_public(s->s3->hs.key_share, &public))
1903		goto err;
1904	if (!CBB_flush(cbb))
1905		goto err;
1906
1907	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1908		goto err;
1909
1910	if (!tls12_derive_master_secret(s, key, key_len))
1911		goto err;
1912
1913	ret = 1;
1914
1915 err:
1916	freezero(key, key_len);
1917
1918	return ret;
1919}
1920
1921static int
1922ssl3_send_client_key_exchange(SSL *s)
1923{
1924	unsigned long alg_k;
1925	CBB cbb, kex;
1926
1927	memset(&cbb, 0, sizeof(cbb));
1928
1929	if (s->s3->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
1930		alg_k = s->s3->hs.cipher->algorithm_mkey;
1931
1932		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
1933		    SSL3_MT_CLIENT_KEY_EXCHANGE))
1934			goto err;
1935
1936		if (alg_k & SSL_kRSA) {
1937			if (!ssl3_send_client_kex_rsa(s, &kex))
1938				goto err;
1939		} else if (alg_k & SSL_kDHE) {
1940			if (!ssl3_send_client_kex_dhe(s, &kex))
1941				goto err;
1942		} else if (alg_k & SSL_kECDHE) {
1943			if (!ssl3_send_client_kex_ecdhe(s, &kex))
1944				goto err;
1945		} else {
1946			ssl3_send_alert(s, SSL3_AL_FATAL,
1947			    SSL_AD_HANDSHAKE_FAILURE);
1948			SSLerror(s, ERR_R_INTERNAL_ERROR);
1949			goto err;
1950		}
1951
1952		if (!ssl3_handshake_msg_finish(s, &cbb))
1953			goto err;
1954
1955		s->s3->hs.state = SSL3_ST_CW_KEY_EXCH_B;
1956	}
1957
1958	/* SSL3_ST_CW_KEY_EXCH_B */
1959	return (ssl3_handshake_write(s));
1960
1961 err:
1962	CBB_cleanup(&cbb);
1963
1964	return (-1);
1965}
1966
1967static int
1968ssl3_send_client_verify_sigalgs(SSL *s, EVP_PKEY *pkey,
1969    const struct ssl_sigalg *sigalg, CBB *cert_verify)
1970{
1971	CBB cbb_signature;
1972	EVP_PKEY_CTX *pctx = NULL;
1973	EVP_MD_CTX *mctx = NULL;
1974	const unsigned char *hdata;
1975	unsigned char *signature = NULL;
1976	size_t signature_len, hdata_len;
1977	int ret = 0;
1978
1979	if ((mctx = EVP_MD_CTX_new()) == NULL)
1980		goto err;
1981
1982	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
1983		SSLerror(s, ERR_R_INTERNAL_ERROR);
1984		goto err;
1985	}
1986	if (!EVP_DigestSignInit(mctx, &pctx, sigalg->md(), NULL, pkey)) {
1987		SSLerror(s, ERR_R_EVP_LIB);
1988		goto err;
1989	}
1990	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1991	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
1992	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
1993		SSLerror(s, ERR_R_EVP_LIB);
1994		goto err;
1995	}
1996	if (!EVP_DigestSign(mctx, NULL, &signature_len, hdata, hdata_len)) {
1997		SSLerror(s, ERR_R_EVP_LIB);
1998		goto err;
1999	}
2000	if ((signature = calloc(1, signature_len)) == NULL) {
2001		SSLerror(s, ERR_R_MALLOC_FAILURE);
2002		goto err;
2003	}
2004	if (!EVP_DigestSign(mctx, signature, &signature_len, hdata, hdata_len)) {
2005		SSLerror(s, ERR_R_EVP_LIB);
2006		goto err;
2007	}
2008
2009	if (!CBB_add_u16(cert_verify, sigalg->value))
2010		goto err;
2011	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2012		goto err;
2013	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2014		goto err;
2015	if (!CBB_flush(cert_verify))
2016		goto err;
2017
2018	ret = 1;
2019
2020 err:
2021	EVP_MD_CTX_free(mctx);
2022	free(signature);
2023	return ret;
2024}
2025
2026static int
2027ssl3_send_client_verify_rsa(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2028{
2029	CBB cbb_signature;
2030	RSA *rsa;
2031	unsigned char data[EVP_MAX_MD_SIZE];
2032	unsigned char *signature = NULL;
2033	unsigned int signature_len;
2034	size_t data_len;
2035	int ret = 0;
2036
2037	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2038		goto err;
2039	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2040		goto err;
2041	if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL)
2042		goto err;
2043	if (RSA_sign(NID_md5_sha1, data, data_len, signature, &signature_len,
2044	    rsa) <= 0 ) {
2045		SSLerror(s, ERR_R_RSA_LIB);
2046		goto err;
2047	}
2048
2049	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2050		goto err;
2051	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2052		goto err;
2053	if (!CBB_flush(cert_verify))
2054		goto err;
2055
2056	ret = 1;
2057 err:
2058	free(signature);
2059	return ret;
2060}
2061
2062static int
2063ssl3_send_client_verify_ec(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2064{
2065	CBB cbb_signature;
2066	EC_KEY *eckey;
2067	unsigned char data[EVP_MAX_MD_SIZE];
2068	unsigned char *signature = NULL;
2069	unsigned int signature_len;
2070	int ret = 0;
2071
2072	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2073		goto err;
2074	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2075		goto err;
2076	if ((eckey = EVP_PKEY_get0_EC_KEY(pkey)) == NULL)
2077		goto err;
2078	if (!ECDSA_sign(0, &data[MD5_DIGEST_LENGTH], SHA_DIGEST_LENGTH,
2079	    signature, &signature_len, eckey)) {
2080		SSLerror(s, ERR_R_ECDSA_LIB);
2081		goto err;
2082	}
2083
2084	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2085		goto err;
2086	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2087		goto err;
2088	if (!CBB_flush(cert_verify))
2089		goto err;
2090
2091	ret = 1;
2092 err:
2093	free(signature);
2094	return ret;
2095}
2096
2097static int
2098ssl3_send_client_verify(SSL *s)
2099{
2100	const struct ssl_sigalg *sigalg;
2101	CBB cbb, cert_verify;
2102	EVP_PKEY *pkey;
2103
2104	memset(&cbb, 0, sizeof(cbb));
2105
2106	if (s->s3->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2107		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2108		    SSL3_MT_CERTIFICATE_VERIFY))
2109			goto err;
2110
2111		pkey = s->cert->key->privatekey;
2112		if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2113			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2114			goto err;
2115		}
2116		s->s3->hs.our_sigalg = sigalg;
2117
2118		/*
2119		 * For TLS v1.2 send signature algorithm and signature using
2120		 * agreed digest and cached handshake records.
2121		 */
2122		if (SSL_USE_SIGALGS(s)) {
2123			if (!ssl3_send_client_verify_sigalgs(s, pkey, sigalg,
2124			    &cert_verify))
2125				goto err;
2126		} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
2127			if (!ssl3_send_client_verify_rsa(s, pkey, &cert_verify))
2128				goto err;
2129		} else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
2130			if (!ssl3_send_client_verify_ec(s, pkey, &cert_verify))
2131				goto err;
2132		} else {
2133			SSLerror(s, ERR_R_INTERNAL_ERROR);
2134			goto err;
2135		}
2136
2137		tls1_transcript_free(s);
2138
2139		if (!ssl3_handshake_msg_finish(s, &cbb))
2140			goto err;
2141
2142		s->s3->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2143	}
2144
2145	return (ssl3_handshake_write(s));
2146
2147 err:
2148	CBB_cleanup(&cbb);
2149
2150	return (-1);
2151}
2152
2153static int
2154ssl3_send_client_certificate(SSL *s)
2155{
2156	EVP_PKEY *pkey = NULL;
2157	X509 *x509 = NULL;
2158	CBB cbb, client_cert;
2159	int i;
2160
2161	memset(&cbb, 0, sizeof(cbb));
2162
2163	if (s->s3->hs.state == SSL3_ST_CW_CERT_A) {
2164		if (s->cert->key->x509 == NULL ||
2165		    s->cert->key->privatekey == NULL)
2166			s->s3->hs.state = SSL3_ST_CW_CERT_B;
2167		else
2168			s->s3->hs.state = SSL3_ST_CW_CERT_C;
2169	}
2170
2171	/* We need to get a client cert */
2172	if (s->s3->hs.state == SSL3_ST_CW_CERT_B) {
2173		/*
2174		 * If we get an error, we need to
2175		 * ssl->rwstate = SSL_X509_LOOKUP; return(-1);
2176		 * We then get retried later.
2177		 */
2178		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2179		if (i < 0) {
2180			s->rwstate = SSL_X509_LOOKUP;
2181			return (-1);
2182		}
2183		s->rwstate = SSL_NOTHING;
2184		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2185			s->s3->hs.state = SSL3_ST_CW_CERT_B;
2186			if (!SSL_use_certificate(s, x509) ||
2187			    !SSL_use_PrivateKey(s, pkey))
2188				i = 0;
2189		} else if (i == 1) {
2190			i = 0;
2191			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2192		}
2193
2194		X509_free(x509);
2195		EVP_PKEY_free(pkey);
2196		if (i == 0) {
2197			s->s3->hs.tls12.cert_request = 2;
2198
2199			/* There is no client certificate to verify. */
2200			tls1_transcript_free(s);
2201		}
2202
2203		/* Ok, we have a cert */
2204		s->s3->hs.state = SSL3_ST_CW_CERT_C;
2205	}
2206
2207	if (s->s3->hs.state == SSL3_ST_CW_CERT_C) {
2208		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2209		    SSL3_MT_CERTIFICATE))
2210			goto err;
2211		if (!ssl3_output_cert_chain(s, &client_cert,
2212		    (s->s3->hs.tls12.cert_request == 2) ? NULL : s->cert->key))
2213			goto err;
2214		if (!ssl3_handshake_msg_finish(s, &cbb))
2215			goto err;
2216
2217		s->s3->hs.state = SSL3_ST_CW_CERT_D;
2218	}
2219
2220	/* SSL3_ST_CW_CERT_D */
2221	return (ssl3_handshake_write(s));
2222
2223 err:
2224	CBB_cleanup(&cbb);
2225
2226	return (0);
2227}
2228
2229#define has_bits(i,m)	(((i)&(m)) == (m))
2230
2231static int
2232ssl3_check_cert_and_algorithm(SSL *s)
2233{
2234	long alg_k, alg_a;
2235	int nid = NID_undef;
2236	int i;
2237
2238	alg_k = s->s3->hs.cipher->algorithm_mkey;
2239	alg_a = s->s3->hs.cipher->algorithm_auth;
2240
2241	/* We don't have a certificate. */
2242	if (alg_a & SSL_aNULL)
2243		return (1);
2244
2245	if (s->s3->hs.key_share != NULL)
2246		nid = tls_key_share_nid(s->s3->hs.key_share);
2247
2248	/* This is the passed certificate. */
2249
2250	if (s->session->peer_cert_type == SSL_PKEY_ECC) {
2251		if (!ssl_check_srvr_ecc_cert_and_alg(s, s->session->peer_cert)) {
2252			SSLerror(s, SSL_R_BAD_ECC_CERT);
2253			goto fatal_err;
2254		}
2255		return (1);
2256	}
2257
2258	i = X509_certificate_type(s->session->peer_cert, NULL);
2259
2260	/* Check that we have a certificate if we require one. */
2261	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2262		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2263		goto fatal_err;
2264	}
2265	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2266		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2267		goto fatal_err;
2268	}
2269	if ((alg_k & SSL_kDHE) &&
2270	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (nid == NID_dhKeyAgreement))) {
2271		SSLerror(s, SSL_R_MISSING_DH_KEY);
2272		goto fatal_err;
2273	}
2274
2275	return (1);
2276
2277 fatal_err:
2278	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2279
2280	return (0);
2281}
2282
2283/*
2284 * Check to see if handshake is full or resumed. Usually this is just a
2285 * case of checking to see if a cache hit has occurred. In the case of
2286 * session tickets we have to check the next message to be sure.
2287 */
2288
2289static int
2290ssl3_check_finished(SSL *s)
2291{
2292	int ret;
2293
2294	/* If we have no ticket it cannot be a resumed session. */
2295	if (!s->session->tlsext_tick)
2296		return (1);
2297	/* this function is called when we really expect a Certificate
2298	 * message, so permit appropriate message length */
2299	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2300	    SSL3_ST_CR_CERT_B, -1, s->max_cert_list)) <= 0)
2301		return ret;
2302
2303	s->s3->hs.tls12.reuse_message = 1;
2304	if ((s->s3->hs.tls12.message_type == SSL3_MT_FINISHED) ||
2305	    (s->s3->hs.tls12.message_type == SSL3_MT_NEWSESSION_TICKET))
2306		return (2);
2307
2308	return (1);
2309}
2310
2311static int
2312ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2313{
2314	if (s->ctx->client_cert_cb == NULL)
2315		return 0;
2316
2317	return s->ctx->client_cert_cb(s, px509, ppkey);
2318}
2319
2320static int
2321ssl3_send_client_change_cipher_spec(SSL *s)
2322{
2323	size_t outlen;
2324	CBB cbb;
2325
2326	memset(&cbb, 0, sizeof(cbb));
2327
2328	if (s->s3->hs.state == SSL3_ST_CW_CHANGE_A) {
2329		if (!CBB_init_fixed(&cbb, s->init_buf->data,
2330		    s->init_buf->length))
2331			goto err;
2332		if (!CBB_add_u8(&cbb, SSL3_MT_CCS))
2333			goto err;
2334		if (!CBB_finish(&cbb, NULL, &outlen))
2335			goto err;
2336
2337		if (outlen > INT_MAX)
2338			goto err;
2339
2340		s->init_num = (int)outlen;
2341		s->init_off = 0;
2342
2343		if (SSL_is_dtls(s)) {
2344			s->d1->handshake_write_seq =
2345			    s->d1->next_handshake_write_seq;
2346			dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
2347			    s->d1->handshake_write_seq, 0, 0);
2348			dtls1_buffer_message(s, 1);
2349		}
2350
2351		s->s3->hs.state = SSL3_ST_CW_CHANGE_B;
2352	}
2353
2354	/* SSL3_ST_CW_CHANGE_B */
2355	return ssl3_record_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
2356
2357 err:
2358	CBB_cleanup(&cbb);
2359
2360	return -1;
2361}
2362
2363static int
2364ssl3_send_client_finished(SSL *s)
2365{
2366	CBB cbb, finished;
2367
2368	memset(&cbb, 0, sizeof(cbb));
2369
2370	if (s->s3->hs.state == SSL3_ST_CW_FINISHED_A) {
2371		if (!tls12_derive_finished(s))
2372			goto err;
2373
2374		/* Copy finished so we can use it for renegotiation checks. */
2375		memcpy(s->s3->previous_client_finished,
2376		    s->s3->hs.finished, s->s3->hs.finished_len);
2377		s->s3->previous_client_finished_len =
2378		    s->s3->hs.finished_len;
2379
2380		if (!ssl3_handshake_msg_start(s, &cbb, &finished,
2381		    SSL3_MT_FINISHED))
2382                        goto err;
2383		if (!CBB_add_bytes(&finished, s->s3->hs.finished,
2384		    s->s3->hs.finished_len))
2385			goto err;
2386		if (!ssl3_handshake_msg_finish(s, &cbb))
2387			goto err;
2388
2389		s->s3->hs.state = SSL3_ST_CW_FINISHED_B;
2390	}
2391
2392	return (ssl3_handshake_write(s));
2393
2394 err:
2395	CBB_cleanup(&cbb);
2396
2397	return (-1);
2398}
2399
2400static int
2401ssl3_get_server_finished(SSL *s)
2402{
2403	int al, md_len, ret;
2404	CBS cbs;
2405
2406	/* should actually be 36+4 :-) */
2407	if ((ret = ssl3_get_message(s, SSL3_ST_CR_FINISHED_A,
2408	    SSL3_ST_CR_FINISHED_B, SSL3_MT_FINISHED, 64)) <= 0)
2409		return ret;
2410
2411	/* If this occurs, we have missed a message */
2412	if (!s->s3->change_cipher_spec) {
2413		al = SSL_AD_UNEXPECTED_MESSAGE;
2414		SSLerror(s, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
2415		goto fatal_err;
2416	}
2417	s->s3->change_cipher_spec = 0;
2418
2419	md_len = TLS1_FINISH_MAC_LENGTH;
2420
2421	if (s->init_num < 0) {
2422		al = SSL_AD_DECODE_ERROR;
2423		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2424		goto fatal_err;
2425	}
2426
2427	CBS_init(&cbs, s->init_msg, s->init_num);
2428
2429	if (s->s3->hs.peer_finished_len != md_len ||
2430	    CBS_len(&cbs) != md_len) {
2431		al = SSL_AD_DECODE_ERROR;
2432		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2433		goto fatal_err;
2434	}
2435
2436	if (!CBS_mem_equal(&cbs, s->s3->hs.peer_finished, CBS_len(&cbs))) {
2437		al = SSL_AD_DECRYPT_ERROR;
2438		SSLerror(s, SSL_R_DIGEST_CHECK_FAILED);
2439		goto fatal_err;
2440	}
2441
2442	/* Copy finished so we can use it for renegotiation checks. */
2443	OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
2444	memcpy(s->s3->previous_server_finished,
2445	    s->s3->hs.peer_finished, md_len);
2446	s->s3->previous_server_finished_len = md_len;
2447
2448	return (1);
2449 fatal_err:
2450	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2451	return (0);
2452}
2453