GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/libssl/ssl_srvr.c Lines: 733 1205 60.8 %
Date: 2017-11-13 Branches: 386 851 45.4 %

Line Branch Exec Source
1
/* $OpenBSD: ssl_srvr.c,v 1.26 2017/10/12 15:52:50 jsing Exp $ */
2
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3
 * All rights reserved.
4
 *
5
 * This package is an SSL implementation written
6
 * by Eric Young (eay@cryptsoft.com).
7
 * The implementation was written so as to conform with Netscapes SSL.
8
 *
9
 * This library is free for commercial and non-commercial use as long as
10
 * the following conditions are aheared to.  The following conditions
11
 * apply to all code found in this distribution, be it the RC4, RSA,
12
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13
 * included with this distribution is covered by the same copyright terms
14
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15
 *
16
 * Copyright remains Eric Young's, and as such any Copyright notices in
17
 * the code are not to be removed.
18
 * If this package is used in a product, Eric Young should be given attribution
19
 * as the author of the parts of the library used.
20
 * This can be in the form of a textual message at program startup or
21
 * in documentation (online or textual) provided with the package.
22
 *
23
 * Redistribution and use in source and binary forms, with or without
24
 * modification, are permitted provided that the following conditions
25
 * are met:
26
 * 1. Redistributions of source code must retain the copyright
27
 *    notice, this list of conditions and the following disclaimer.
28
 * 2. Redistributions in binary form must reproduce the above copyright
29
 *    notice, this list of conditions and the following disclaimer in the
30
 *    documentation and/or other materials provided with the distribution.
31
 * 3. All advertising materials mentioning features or use of this software
32
 *    must display the following acknowledgement:
33
 *    "This product includes cryptographic software written by
34
 *     Eric Young (eay@cryptsoft.com)"
35
 *    The word 'cryptographic' can be left out if the rouines from the library
36
 *    being used are not cryptographic related :-).
37
 * 4. If you include any Windows specific code (or a derivative thereof) from
38
 *    the apps directory (application code) you must include an acknowledgement:
39
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40
 *
41
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51
 * SUCH DAMAGE.
52
 *
53
 * The licence and distribution terms for any publically available version or
54
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55
 * copied and put under another distribution licence
56
 * [including the GNU Public Licence.]
57
 */
58
/* ====================================================================
59
 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60
 *
61
 * Redistribution and use in source and binary forms, with or without
62
 * modification, are permitted provided that the following conditions
63
 * are met:
64
 *
65
 * 1. Redistributions of source code must retain the above copyright
66
 *    notice, this list of conditions and the following disclaimer.
67
 *
68
 * 2. Redistributions in binary form must reproduce the above copyright
69
 *    notice, this list of conditions and the following disclaimer in
70
 *    the documentation and/or other materials provided with the
71
 *    distribution.
72
 *
73
 * 3. All advertising materials mentioning features or use of this
74
 *    software must display the following acknowledgment:
75
 *    "This product includes software developed by the OpenSSL Project
76
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77
 *
78
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79
 *    endorse or promote products derived from this software without
80
 *    prior written permission. For written permission, please contact
81
 *    openssl-core@openssl.org.
82
 *
83
 * 5. Products derived from this software may not be called "OpenSSL"
84
 *    nor may "OpenSSL" appear in their names without prior written
85
 *    permission of the OpenSSL Project.
86
 *
87
 * 6. Redistributions of any form whatsoever must retain the following
88
 *    acknowledgment:
89
 *    "This product includes software developed by the OpenSSL Project
90
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91
 *
92
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103
 * OF THE POSSIBILITY OF SUCH DAMAGE.
104
 * ====================================================================
105
 *
106
 * This product includes cryptographic software written by Eric Young
107
 * (eay@cryptsoft.com).  This product includes software written by Tim
108
 * Hudson (tjh@cryptsoft.com).
109
 *
110
 */
111
/* ====================================================================
112
 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113
 *
114
 * Portions of the attached software ("Contribution") are developed by
115
 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116
 *
117
 * The Contribution is licensed pursuant to the OpenSSL open source
118
 * license provided above.
119
 *
120
 * ECC cipher suite support in OpenSSL originally written by
121
 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122
 *
123
 */
124
/* ====================================================================
125
 * Copyright 2005 Nokia. All rights reserved.
126
 *
127
 * The portions of the attached software ("Contribution") is developed by
128
 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129
 * license.
130
 *
131
 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132
 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133
 * support (see RFC 4279) to OpenSSL.
134
 *
135
 * No patent licenses or other rights except those expressly stated in
136
 * the OpenSSL open source license shall be deemed granted or received
137
 * expressly, by implication, estoppel, or otherwise.
138
 *
139
 * No assurances are provided by Nokia that the Contribution does not
140
 * infringe the patent or other intellectual property rights of any third
141
 * party or that the license provides you with all the necessary rights
142
 * to make use of the Contribution.
143
 *
144
 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145
 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146
 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147
 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148
 * OTHERWISE.
149
 */
150
151
#include <stdio.h>
152
153
#include "ssl_locl.h"
154
155
#include <openssl/bn.h>
156
#include <openssl/buffer.h>
157
#include <openssl/curve25519.h>
158
#include <openssl/evp.h>
159
#include <openssl/dh.h>
160
#ifndef OPENSSL_NO_GOST
161
#include <openssl/gost.h>
162
#endif
163
#include <openssl/hmac.h>
164
#include <openssl/md5.h>
165
#include <openssl/objects.h>
166
#include <openssl/x509.h>
167
168
#include "bytestring.h"
169
#include "ssl_tlsext.h"
170
171
int
172
ssl3_accept(SSL *s)
173
{
174
	void (*cb)(const SSL *ssl, int type, int val) = NULL;
175
	unsigned long alg_k;
176
	int ret = -1;
177
	int new_state, state, skip = 0;
178
	int listen;
179
180
7428
	ERR_clear_error();
181
3714
	errno = 0;
182
183
3714
	if (s->internal->info_callback != NULL)
184
		cb = s->internal->info_callback;
185
3714
	else if (s->ctx->internal->info_callback != NULL)
186
		cb = s->ctx->internal->info_callback;
187
188
3714
	if (SSL_IS_DTLS(s))
189
72
		listen = D1I(s)->listen;
190
191
	/* init things to blank */
192
3714
	s->internal->in_handshake++;
193

7428
	if (!SSL_in_init(s) || SSL_in_before(s))
194
198
		SSL_clear(s);
195
196
3714
	if (SSL_IS_DTLS(s))
197
72
		D1I(s)->listen = listen;
198
199
3714
	if (s->cert == NULL) {
200
		SSLerror(s, SSL_R_NO_CERTIFICATE_SET);
201
		ret = -1;
202
		goto end;
203
	}
204
205
6828
	for (;;) {
206
6828
		state = S3I(s)->hs.state;
207
208










6828
		switch (S3I(s)->hs.state) {
209
		case SSL_ST_RENEGOTIATE:
210
			s->internal->renegotiate = 1;
211
			/* S3I(s)->hs.state=SSL_ST_ACCEPT; */
212
213
		case SSL_ST_BEFORE:
214
		case SSL_ST_ACCEPT:
215
		case SSL_ST_BEFORE|SSL_ST_ACCEPT:
216
		case SSL_ST_OK|SSL_ST_ACCEPT:
217
198
			s->server = 1;
218
198
			if (cb != NULL)
219
				cb(s, SSL_CB_HANDSHAKE_START, 1);
220
221
198
			if (SSL_IS_DTLS(s)) {
222
36
				if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
223
					SSLerror(s, ERR_R_INTERNAL_ERROR);
224
					ret = -1;
225
					goto end;
226
				}
227
			} else {
228
162
				if ((s->version >> 8) != 3) {
229
					SSLerror(s, ERR_R_INTERNAL_ERROR);
230
					ret = -1;
231
					goto end;
232
				}
233
			}
234
198
			s->internal->type = SSL_ST_ACCEPT;
235
236
198
			if (!ssl3_setup_init_buffer(s)) {
237
				ret = -1;
238
				goto end;
239
			}
240
198
			if (!ssl3_setup_buffers(s)) {
241
				ret = -1;
242
				goto end;
243
			}
244
245
198
			s->internal->init_num = 0;
246
247
198
			if (S3I(s)->hs.state != SSL_ST_RENEGOTIATE) {
248
				/*
249
				 * Ok, we now need to push on a buffering BIO
250
				 * so that the output is sent in a way that
251
				 * TCP likes :-)
252
				 */
253
198
				if (!ssl_init_wbio_buffer(s, 1)) {
254
					ret = -1;
255
					goto end;
256
				}
257
198
				if (!tls1_init_finished_mac(s)) {
258
					ret = -1;
259
					goto end;
260
				}
261
262
198
				S3I(s)->hs.state = SSL3_ST_SR_CLNT_HELLO_A;
263
198
				s->ctx->internal->stats.sess_accept++;
264

198
			} else if (!SSL_IS_DTLS(s) && !S3I(s)->send_connection_binding) {
265
				/*
266
				 * Server attempting to renegotiate with
267
				 * client that doesn't support secure
268
				 * renegotiation.
269
				 */
270
				SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
271
				ssl3_send_alert(s, SSL3_AL_FATAL,
272
				    SSL_AD_HANDSHAKE_FAILURE);
273
				ret = -1;
274
				goto end;
275
			} else {
276
				/*
277
				 * S3I(s)->hs.state == SSL_ST_RENEGOTIATE,
278
				 * we will just send a HelloRequest.
279
				 */
280
				s->ctx->internal->stats.sess_accept_renegotiate++;
281
				S3I(s)->hs.state = SSL3_ST_SW_HELLO_REQ_A;
282
			}
283
			break;
284
285
		case SSL3_ST_SW_HELLO_REQ_A:
286
		case SSL3_ST_SW_HELLO_REQ_B:
287
			s->internal->shutdown = 0;
288
			if (SSL_IS_DTLS(s)) {
289
				dtls1_clear_record_buffer(s);
290
				dtls1_start_timer(s);
291
			}
292
			ret = ssl3_send_hello_request(s);
293
			if (ret <= 0)
294
				goto end;
295
			if (SSL_IS_DTLS(s))
296
				S3I(s)->hs.next_state = SSL3_ST_SR_CLNT_HELLO_A;
297
			else
298
				S3I(s)->hs.next_state = SSL3_ST_SW_HELLO_REQ_C;
299
			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
300
			s->internal->init_num = 0;
301
302
			if (!tls1_init_finished_mac(s)) {
303
				ret = -1;
304
				goto end;
305
			}
306
			break;
307
308
		case SSL3_ST_SW_HELLO_REQ_C:
309
			S3I(s)->hs.state = SSL_ST_OK;
310
			break;
311
312
		case SSL3_ST_SR_CLNT_HELLO_A:
313
		case SSL3_ST_SR_CLNT_HELLO_B:
314
		case SSL3_ST_SR_CLNT_HELLO_C:
315
774
			s->internal->shutdown = 0;
316
774
			if (SSL_IS_DTLS(s)) {
317
36
				ret = ssl3_get_client_hello(s);
318
36
				if (ret <= 0)
319
					goto end;
320
36
				dtls1_stop_timer(s);
321
322

72
				if (ret == 1 &&
323
36
				    (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
324
					S3I(s)->hs.state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A;
325
				else
326
					S3I(s)->hs.state = SSL3_ST_SW_SRVR_HELLO_A;
327
328
36
				s->internal->init_num = 0;
329
330
				/*
331
				 * Reflect ClientHello sequence to remain
332
				 * stateless while listening.
333
				 */
334
36
				if (listen) {
335
					memcpy(S3I(s)->write_sequence,
336
					    S3I(s)->read_sequence,
337
					    sizeof(S3I(s)->write_sequence));
338
				}
339
340
				/* If we're just listening, stop here */
341

36
				if (listen && S3I(s)->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
342
					ret = 2;
343
					D1I(s)->listen = 0;
344
					/*
345
					 * Set expected sequence numbers to
346
					 * continue the handshake.
347
					 */
348
					D1I(s)->handshake_read_seq = 2;
349
					D1I(s)->handshake_write_seq = 1;
350
					D1I(s)->next_handshake_write_seq = 1;
351
					goto end;
352
				}
353
			} else {
354
738
				if (s->internal->rwstate != SSL_X509_LOOKUP) {
355
738
					ret = ssl3_get_client_hello(s);
356
738
					if (ret <= 0)
357
						goto end;
358
				}
359
360
162
				s->internal->renegotiate = 2;
361
162
				S3I(s)->hs.state = SSL3_ST_SW_SRVR_HELLO_A;
362
162
				s->internal->init_num = 0;
363
			}
364
			break;
365
366
		case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A:
367
		case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B:
368
			ret = dtls1_send_hello_verify_request(s);
369
			if (ret <= 0)
370
				goto end;
371
			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
372
			S3I(s)->hs.next_state = SSL3_ST_SR_CLNT_HELLO_A;
373
374
			/* HelloVerifyRequest resets Finished MAC. */
375
			if (!tls1_init_finished_mac(s)) {
376
				ret = -1;
377
				goto end;
378
			}
379
			break;
380
381
		case SSL3_ST_SW_SRVR_HELLO_A:
382
		case SSL3_ST_SW_SRVR_HELLO_B:
383
198
			if (SSL_IS_DTLS(s)) {
384
36
				s->internal->renegotiate = 2;
385
36
				dtls1_start_timer(s);
386
36
			}
387
198
			ret = ssl3_send_server_hello(s);
388
198
			if (ret <= 0)
389
				goto end;
390
198
			if (s->internal->hit) {
391
				if (s->internal->tlsext_ticket_expected)
392
					S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_A;
393
				else
394
					S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
395
			} else {
396
198
				S3I(s)->hs.state = SSL3_ST_SW_CERT_A;
397
			}
398
198
			s->internal->init_num = 0;
399
198
			break;
400
401
		case SSL3_ST_SW_CERT_A:
402
		case SSL3_ST_SW_CERT_B:
403
			/* Check if it is anon DH or anon ECDH. */
404
198
			if (!(S3I(s)->hs.new_cipher->algorithm_auth &
405
			    SSL_aNULL)) {
406
168
				if (SSL_IS_DTLS(s))
407
36
					dtls1_start_timer(s);
408
168
				ret = ssl3_send_server_certificate(s);
409
168
				if (ret <= 0)
410
					goto end;
411
168
				if (s->internal->tlsext_status_expected)
412
					S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_A;
413
				else
414
					S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
415
168
			} else {
416
				skip = 1;
417
30
				S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
418
			}
419
198
			s->internal->init_num = 0;
420
198
			break;
421
422
		case SSL3_ST_SW_KEY_EXCH_A:
423
		case SSL3_ST_SW_KEY_EXCH_B:
424
198
			alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
425
426
			/*
427
			 * Only send if using a DH key exchange.
428
			 *
429
			 * For ECC ciphersuites, we send a ServerKeyExchange
430
			 * message only if the cipher suite is ECDHE. In other
431
			 * cases, the server certificate contains the server's
432
			 * public key for key exchange.
433
			 */
434
198
			if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
435
153
				if (SSL_IS_DTLS(s))
436
12
					dtls1_start_timer(s);
437
153
				ret = ssl3_send_server_key_exchange(s);
438
153
				if (ret <= 0)
439
					goto end;
440
			} else
441
				skip = 1;
442
443
198
			S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_A;
444
198
			s->internal->init_num = 0;
445
198
			break;
446
447
		case SSL3_ST_SW_CERT_REQ_A:
448
		case SSL3_ST_SW_CERT_REQ_B:
449
			/*
450
			 * Determine whether or not we need to request a
451
			 * certificate.
452
			 *
453
			 * Do not request a certificate if:
454
			 *
455
			 * - We did not ask for it (SSL_VERIFY_PEER is unset).
456
			 *
457
			 * - SSL_VERIFY_CLIENT_ONCE is set and we are
458
			 *   renegotiating.
459
			 *
460
			 * - We are using an anonymous ciphersuites
461
			 *   (see section "Certificate request" in SSL 3 drafts
462
			 *   and in RFC 2246) ... except when the application
463
			 *   insists on verification (against the specs, but
464
			 *   s3_clnt.c accepts this for SSL 3).
465
			 */
466

198
			if (!(s->verify_mode & SSL_VERIFY_PEER) ||
467
21
			    ((s->session->peer != NULL) &&
468
			     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
469
21
			    ((S3I(s)->hs.new_cipher->algorithm_auth &
470
21
			     SSL_aNULL) && !(s->verify_mode &
471
			     SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
472
				/* No cert request. */
473
				skip = 1;
474
177
				S3I(s)->tmp.cert_request = 0;
475
177
				S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_A;
476

324
				if (!SSL_IS_DTLS(s) && S3I(s)->handshake_buffer) {
477
					if (!tls1_digest_cached_records(s)) {
478
						ret = -1;
479
						goto end;
480
					}
481
				}
482
			} else {
483
21
				S3I(s)->tmp.cert_request = 1;
484
21
				if (SSL_IS_DTLS(s))
485
6
					dtls1_start_timer(s);
486
21
				ret = ssl3_send_certificate_request(s);
487
21
				if (ret <= 0)
488
					goto end;
489
21
				S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_A;
490
21
				s->internal->init_num = 0;
491
			}
492
			break;
493
494
		case SSL3_ST_SW_SRVR_DONE_A:
495
		case SSL3_ST_SW_SRVR_DONE_B:
496
198
			if (SSL_IS_DTLS(s))
497
36
				dtls1_start_timer(s);
498
198
			ret = ssl3_send_server_done(s);
499
198
			if (ret <= 0)
500
				goto end;
501
198
			S3I(s)->hs.next_state = SSL3_ST_SR_CERT_A;
502
198
			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
503
198
			s->internal->init_num = 0;
504
198
			break;
505
506
		case SSL3_ST_SW_FLUSH:
507
			/*
508
			 * This code originally checked to see if
509
			 * any data was pending using BIO_CTRL_INFO
510
			 * and then flushed. This caused problems
511
			 * as documented in PR#1939. The proposed
512
			 * fix doesn't completely resolve this issue
513
			 * as buggy implementations of BIO_CTRL_PENDING
514
			 * still exist. So instead we just flush
515
			 * unconditionally.
516
			 */
517
1122
			s->internal->rwstate = SSL_WRITING;
518
1122
			if (BIO_flush(s->wbio) <= 0) {
519
732
				if (SSL_IS_DTLS(s)) {
520
					/* If the write error was fatal, stop trying. */
521
					if (!BIO_should_retry(s->wbio)) {
522
						s->internal->rwstate = SSL_NOTHING;
523
						S3I(s)->hs.state = S3I(s)->hs.next_state;
524
					}
525
				}
526
				ret = -1;
527
732
				goto end;
528
			}
529
390
			s->internal->rwstate = SSL_NOTHING;
530
390
			S3I(s)->hs.state = S3I(s)->hs.next_state;
531
390
			break;
532
533
		case SSL3_ST_SR_CERT_A:
534
		case SSL3_ST_SR_CERT_B:
535
498
			if (S3I(s)->tmp.cert_request) {
536
321
				ret = ssl3_get_client_certificate(s);
537
321
				if (ret <= 0)
538
					goto end;
539
			}
540
198
			s->internal->init_num = 0;
541
198
			S3I(s)->hs.state = SSL3_ST_SR_KEY_EXCH_A;
542
198
			break;
543
544
		case SSL3_ST_SR_KEY_EXCH_A:
545
		case SSL3_ST_SR_KEY_EXCH_B:
546
1008
			ret = ssl3_get_client_key_exchange(s);
547
1008
			if (ret <= 0)
548
				goto end;
549
550
192
			if (SSL_IS_DTLS(s)) {
551
36
				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
552
36
				s->internal->init_num = 0;
553
36
			}
554
555
192
			alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
556
192
			if (ret == 2) {
557
				/*
558
				 * For the ECDH ciphersuites when
559
				 * the client sends its ECDH pub key in
560
				 * a certificate, the CertificateVerify
561
				 * message is not sent.
562
				 * Also for GOST ciphersuites when
563
				 * the client uses its key from the certificate
564
				 * for key exchange.
565
				 */
566
				S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
567
				s->internal->init_num = 0;
568

282
			} else if (SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) {
569
102
				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
570
102
				s->internal->init_num = 0;
571
102
				if (!s->session->peer)
572
					break;
573
				/*
574
				 * For sigalgs freeze the handshake buffer
575
				 * at this point and digest cached records.
576
				 */
577
15
				if (!S3I(s)->handshake_buffer) {
578
					SSLerror(s, ERR_R_INTERNAL_ERROR);
579
					ret = -1;
580
					goto end;
581
				}
582
15
				s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
583
15
				if (!tls1_digest_cached_records(s)) {
584
					ret = -1;
585
					goto end;
586
				}
587
			} else {
588
90
				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
589
90
				s->internal->init_num = 0;
590
591
				/*
592
				 * We need to get hashes here so if there is
593
				 * a client cert, it can be verified.
594
				 */
595
90
				if (S3I(s)->handshake_buffer) {
596
					if (!tls1_digest_cached_records(s)) {
597
						ret = -1;
598
						goto end;
599
					}
600
				}
601
90
				if (!tls1_handshake_hash_value(s,
602
90
				    S3I(s)->tmp.cert_verify_md,
603
				    sizeof(S3I(s)->tmp.cert_verify_md),
604
				    NULL)) {
605
					ret = -1;
606
					goto end;
607
				}
608
			}
609
			break;
610
611
		case SSL3_ST_SR_CERT_VRFY_A:
612
		case SSL3_ST_SR_CERT_VRFY_B:
613
1164
			if (SSL_IS_DTLS(s))
614
36
				D1I(s)->change_cipher_spec_ok = 1;
615
			else
616
1128
				s->s3->flags |= SSL3_FLAGS_CCS_OK;
617
618
			/* we should decide if we expected this one */
619
1164
			ret = ssl3_get_cert_verify(s);
620
1164
			if (ret <= 0)
621
				goto end;
622
192
			S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
623
192
			s->internal->init_num = 0;
624
192
			break;
625
626
		case SSL3_ST_SR_FINISHED_A:
627
		case SSL3_ST_SR_FINISHED_B:
628
318
			if (SSL_IS_DTLS(s))
629
36
				D1I(s)->change_cipher_spec_ok = 1;
630
			else
631
282
				s->s3->flags |= SSL3_FLAGS_CCS_OK;
632
318
			ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
633
			    SSL3_ST_SR_FINISHED_B);
634
318
			if (ret <= 0)
635
				goto end;
636
192
			if (SSL_IS_DTLS(s))
637
36
				dtls1_stop_timer(s);
638
192
			if (s->internal->hit)
639
				S3I(s)->hs.state = SSL_ST_OK;
640
192
			else if (s->internal->tlsext_ticket_expected)
641
				S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_A;
642
			else
643
				S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
644
192
			s->internal->init_num = 0;
645
192
			break;
646
647
		case SSL3_ST_SW_SESSION_TICKET_A:
648
		case SSL3_ST_SW_SESSION_TICKET_B:
649
180
			ret = ssl3_send_newsession_ticket(s);
650
180
			if (ret <= 0)
651
				goto end;
652
180
			S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
653
180
			s->internal->init_num = 0;
654
180
			break;
655
656
		case SSL3_ST_SW_CERT_STATUS_A:
657
		case SSL3_ST_SW_CERT_STATUS_B:
658
			ret = ssl3_send_cert_status(s);
659
			if (ret <= 0)
660
				goto end;
661
			S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
662
			s->internal->init_num = 0;
663
			break;
664
665
		case SSL3_ST_SW_CHANGE_A:
666
		case SSL3_ST_SW_CHANGE_B:
667
192
			s->session->cipher = S3I(s)->hs.new_cipher;
668
192
			if (!tls1_setup_key_block(s)) {
669
				ret = -1;
670
				goto end;
671
			}
672
673
192
			ret = ssl3_send_change_cipher_spec(s,
674
			    SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B);
675
192
			if (ret <= 0)
676
				goto end;
677
192
			S3I(s)->hs.state = SSL3_ST_SW_FINISHED_A;
678
192
			s->internal->init_num = 0;
679
680
192
			if (!tls1_change_cipher_state(s,
681
			    SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
682
				ret = -1;
683
				goto end;
684
			}
685
686
192
			if (SSL_IS_DTLS(s))
687
36
				dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
688
			break;
689
690
		case SSL3_ST_SW_FINISHED_A:
691
		case SSL3_ST_SW_FINISHED_B:
692
192
			ret = ssl3_send_finished(s,
693
			    SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
694
			    TLS_MD_SERVER_FINISH_CONST,
695
			    TLS_MD_SERVER_FINISH_CONST_SIZE);
696
192
			if (ret <= 0)
697
				goto end;
698
192
			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
699
192
			if (s->internal->hit)
700
				S3I(s)->hs.next_state = SSL3_ST_SR_FINISHED_A;
701
			else
702
				S3I(s)->hs.next_state = SSL_ST_OK;
703
192
			s->internal->init_num = 0;
704
192
			break;
705
706
		case SSL_ST_OK:
707
			/* clean a few things up */
708
192
			tls1_cleanup_key_block(s);
709
710
192
			if (!SSL_IS_DTLS(s)) {
711
156
				BUF_MEM_free(s->internal->init_buf);
712
156
				s->internal->init_buf = NULL;
713
156
			}
714
715
			/* remove buffering on output */
716
192
			ssl_free_wbio_buffer(s);
717
718
192
			s->internal->init_num = 0;
719
720
			/* Skipped if we just sent a HelloRequest. */
721
192
			if (s->internal->renegotiate == 2) {
722
192
				s->internal->renegotiate = 0;
723
192
				s->internal->new_session = 0;
724
725
192
				ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
726
727
192
				s->ctx->internal->stats.sess_accept_good++;
728
				/* s->server=1; */
729
192
				s->internal->handshake_func = ssl3_accept;
730
731
192
				if (cb != NULL)
732
					cb(s, SSL_CB_HANDSHAKE_DONE, 1);
733
			}
734
735
			ret = 1;
736
737
192
			if (SSL_IS_DTLS(s)) {
738
				/* Done handshaking, next message is client hello. */
739
36
				D1I(s)->handshake_read_seq = 0;
740
				/* Next message is server hello. */
741
36
				D1I(s)->handshake_write_seq = 0;
742
36
				D1I(s)->next_handshake_write_seq = 0;
743
36
			}
744
			goto end;
745
			/* break; */
746
747
		default:
748
			SSLerror(s, SSL_R_UNKNOWN_STATE);
749
			ret = -1;
750
			goto end;
751
			/* break; */
752
		}
753
754
3114
		if (!S3I(s)->tmp.reuse_message && !skip) {
755
2691
			if (s->internal->debug) {
756
				if ((ret = BIO_flush(s->wbio)) <= 0)
757
					goto end;
758
			}
759
760
761

2691
			if ((cb != NULL) && (S3I(s)->hs.state != state)) {
762
				new_state = S3I(s)->hs.state;
763
				S3I(s)->hs.state = state;
764
				cb(s, SSL_CB_ACCEPT_LOOP, 1);
765
				S3I(s)->hs.state = new_state;
766
			}
767
		}
768
		skip = 0;
769
	}
770
end:
771
	/* BIO_flush(s->wbio); */
772
3714
	s->internal->in_handshake--;
773
3714
	if (cb != NULL)
774
		cb(s, SSL_CB_ACCEPT_EXIT, ret);
775
776
3714
	return (ret);
777
}
778
779
int
780
ssl3_send_hello_request(SSL *s)
781
{
782
	CBB cbb, hello;
783
784
	memset(&cbb, 0, sizeof(cbb));
785
786
	if (S3I(s)->hs.state == SSL3_ST_SW_HELLO_REQ_A) {
787
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &hello,
788
		    SSL3_MT_HELLO_REQUEST))
789
			goto err;
790
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
791
			goto err;
792
793
		S3I(s)->hs.state = SSL3_ST_SW_HELLO_REQ_B;
794
	}
795
796
	/* SSL3_ST_SW_HELLO_REQ_B */
797
	return (ssl3_handshake_write(s));
798
799
 err:
800
	CBB_cleanup(&cbb);
801
802
	return (-1);
803
}
804
805
int
806
ssl3_get_client_hello(SSL *s)
807
{
808
1548
	CBS cbs, client_random, session_id, cookie, cipher_suites;
809
774
	CBS compression_methods;
810
774
	uint16_t client_version;
811
774
	uint8_t comp_method;
812
	int comp_null;
813
774
	int i, j, ok, al, ret = -1, cookie_valid = 0;
814
	long n;
815
	unsigned long id;
816
774
	unsigned char *p, *d;
817
	SSL_CIPHER *c;
818
	STACK_OF(SSL_CIPHER) *ciphers = NULL;
819
	unsigned long alg_k;
820
	const SSL_METHOD *method;
821
774
	uint16_t shared_version;
822
	unsigned char *end;
823
824
	/*
825
	 * We do this so that we will respond with our native type.
826
	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
827
	 * This down switching should be handled by a different method.
828
	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
829
	 * TLSv1.
830
	 */
831
774
	if (S3I(s)->hs.state == SSL3_ST_SR_CLNT_HELLO_A) {
832
198
		S3I(s)->hs.state = SSL3_ST_SR_CLNT_HELLO_B;
833
198
	}
834
835
774
	s->internal->first_packet = 1;
836
774
	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
837
	    SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
838
	    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
839
774
	if (!ok)
840
576
		return ((int)n);
841
198
	s->internal->first_packet = 0;
842
843
198
	if (n < 0)
844
		goto err;
845
846
198
	d = p = (unsigned char *)s->internal->init_msg;
847
198
	end = d + n;
848
849
198
	CBS_init(&cbs, s->internal->init_msg, n);
850
851
	/*
852
	 * Use version from inside client hello, not from record header.
853
	 * (may differ: see RFC 2246, Appendix E, second paragraph)
854
	 */
855
198
	if (!CBS_get_u16(&cbs, &client_version))
856
		goto truncated;
857
858
198
	if (ssl_max_shared_version(s, client_version, &shared_version) != 1) {
859
		SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
860
		if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
861
		    !s->internal->enc_write_ctx && !s->internal->write_hash) {
862
			/*
863
			 * Similar to ssl3_get_record, send alert using remote
864
			 * version number.
865
			 */
866
			s->version = s->client_version;
867
		}
868
		al = SSL_AD_PROTOCOL_VERSION;
869
		goto f_err;
870
	}
871
198
	s->client_version = client_version;
872
198
	s->version = shared_version;
873
874
198
	if ((method = tls1_get_server_method(shared_version)) == NULL)
875
36
		method = dtls1_get_server_method(shared_version);
876
198
	if (method == NULL) {
877
		SSLerror(s, ERR_R_INTERNAL_ERROR);
878
		goto err;
879
	}
880
198
	s->method = method;
881
882
198
	if (!CBS_get_bytes(&cbs, &client_random, SSL3_RANDOM_SIZE))
883
		goto truncated;
884
198
	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
885
		goto truncated;
886
887
	/*
888
	 * If we require cookies (DTLS) and this ClientHello doesn't
889
	 * contain one, just return since we do not want to
890
	 * allocate any memory yet. So check cookie length...
891
	 */
892
198
	if (SSL_IS_DTLS(s)) {
893
36
		if (!CBS_get_u8_length_prefixed(&cbs, &cookie))
894
			goto truncated;
895
36
		if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
896
			if (CBS_len(&cookie) == 0)
897
				return (1);
898
		}
899
	}
900
901
198
	if (!CBS_write_bytes(&client_random, s->s3->client_random,
902
	    sizeof(s->s3->client_random), NULL))
903
		goto err;
904
905
198
	s->internal->hit = 0;
906
907
	/*
908
	 * Versions before 0.9.7 always allow clients to resume sessions in
909
	 * renegotiation. 0.9.7 and later allow this by default, but optionally
910
	 * ignore resumption requests with flag
911
	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
912
	 * rather than a change to default behavior so that applications
913
	 * relying on this for security won't even compile against older
914
	 * library versions).
915
	 *
916
	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
917
	 * to request renegotiation but not a new session (s->internal->new_session
918
	 * remains unset): for servers, this essentially just means that the
919
	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
920
	 * ignored.
921
	 */
922

198
	if ((s->internal->new_session && (s->internal->options &
923
	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
924
		if (!ssl_get_new_session(s, 1))
925
			goto err;
926
	} else {
927
		/* XXX - pass CBS through instead... */
928
198
		i = ssl_get_prev_session(s,
929
198
		    (unsigned char *)CBS_data(&session_id),
930
198
		    CBS_len(&session_id), end);
931
198
		if (i == 1) { /* previous session */
932
			s->internal->hit = 1;
933
198
		} else if (i == -1)
934
			goto err;
935
		else {
936
			/* i == 0 */
937
198
			if (!ssl_get_new_session(s, 1))
938
				goto err;
939
		}
940
	}
941
942
198
	if (SSL_IS_DTLS(s)) {
943
		/*
944
		 * The ClientHello may contain a cookie even if the HelloVerify
945
		 * message has not been sent - make sure that it does not cause
946
		 * an overflow.
947
		 */
948
36
		if (CBS_len(&cookie) > sizeof(D1I(s)->rcvd_cookie)) {
949
			al = SSL_AD_DECODE_ERROR;
950
			SSLerror(s, SSL_R_COOKIE_MISMATCH);
951
			goto f_err;
952
		}
953
954
		/* Verify the cookie if appropriate option is set. */
955

36
		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
956
		    CBS_len(&cookie) > 0) {
957
			size_t cookie_len;
958
959
			/* XXX - rcvd_cookie seems to only be used here... */
960
			if (!CBS_write_bytes(&cookie, D1I(s)->rcvd_cookie,
961
			    sizeof(D1I(s)->rcvd_cookie), &cookie_len))
962
				goto err;
963
964
			if (s->ctx->internal->app_verify_cookie_cb != NULL) {
965
				if (s->ctx->internal->app_verify_cookie_cb(s,
966
				    D1I(s)->rcvd_cookie, cookie_len) == 0) {
967
					al = SSL_AD_HANDSHAKE_FAILURE;
968
					SSLerror(s, SSL_R_COOKIE_MISMATCH);
969
					goto f_err;
970
				}
971
				/* else cookie verification succeeded */
972
			/* XXX - can d1->cookie_len > sizeof(rcvd_cookie) ? */
973
			} else if (timingsafe_memcmp(D1I(s)->rcvd_cookie,
974
			    D1I(s)->cookie, D1I(s)->cookie_len) != 0) {
975
				/* default verification */
976
				al = SSL_AD_HANDSHAKE_FAILURE;
977
				SSLerror(s, SSL_R_COOKIE_MISMATCH);
978
				goto f_err;
979
			}
980
			cookie_valid = 1;
981
		}
982
	}
983
984
198
	if (!CBS_get_u16_length_prefixed(&cbs, &cipher_suites))
985
		goto truncated;
986
987
	/* XXX - This logic seems wrong... */
988

198
	if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
989
		/* we need a cipher if we are not resuming a session */
990
		al = SSL_AD_ILLEGAL_PARAMETER;
991
		SSLerror(s, SSL_R_NO_CIPHERS_SPECIFIED);
992
		goto f_err;
993
	}
994
995
198
	if (CBS_len(&cipher_suites) > 0) {
996
396
		if ((ciphers = ssl_bytes_to_cipher_list(s,
997
198
		    &cipher_suites)) == NULL)
998
			goto err;
999
	}
1000
1001
	/* If it is a hit, check that the cipher is in the list */
1002
	/* XXX - CBS_len(&cipher_suites) will always be zero here... */
1003

198
	if (s->internal->hit && CBS_len(&cipher_suites) > 0) {
1004
		j = 0;
1005
		id = s->session->cipher->id;
1006
1007
		for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1008
			c = sk_SSL_CIPHER_value(ciphers, i);
1009
			if (c->id == id) {
1010
				j = 1;
1011
				break;
1012
			}
1013
		}
1014
		if (j == 0) {
1015
			/*
1016
			 * We need to have the cipher in the cipher
1017
			 * list if we are asked to reuse it
1018
			 */
1019
			al = SSL_AD_ILLEGAL_PARAMETER;
1020
			SSLerror(s, SSL_R_REQUIRED_CIPHER_MISSING);
1021
			goto f_err;
1022
		}
1023
	}
1024
1025
198
	if (!CBS_get_u8_length_prefixed(&cbs, &compression_methods))
1026
		goto truncated;
1027
1028
	comp_null = 0;
1029
792
	while (CBS_len(&compression_methods) > 0) {
1030
198
		if (!CBS_get_u8(&compression_methods, &comp_method))
1031
			goto truncated;
1032
198
		if (comp_method == 0)
1033
198
			comp_null = 1;
1034
	}
1035
198
	if (comp_null == 0) {
1036
		al = SSL_AD_DECODE_ERROR;
1037
		SSLerror(s, SSL_R_NO_COMPRESSION_SPECIFIED);
1038
		goto f_err;
1039
	}
1040
1041
198
	p = (unsigned char *)CBS_data(&cbs);
1042
1043
	/* TLS extensions*/
1044
198
	if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
1045
		/* 'al' set by ssl_parse_clienthello_tlsext */
1046
		SSLerror(s, SSL_R_PARSE_TLSEXT);
1047
		goto f_err;
1048
	}
1049
198
	if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1050
		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1051
		goto err;
1052
	}
1053
1054
	/*
1055
	 * Check if we want to use external pre-shared secret for this
1056
	 * handshake for not reused session only. We need to generate
1057
	 * server_random before calling tls_session_secret_cb in order to allow
1058
	 * SessionTicket processing to use it in key derivation.
1059
	 */
1060
198
	arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
1061
1062

396
	if (!s->internal->hit && s->internal->tls_session_secret_cb) {
1063
		SSL_CIPHER *pref_cipher = NULL;
1064
1065
		s->session->master_key_length = sizeof(s->session->master_key);
1066
		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
1067
		    &s->session->master_key_length, ciphers, &pref_cipher,
1068
		    s->internal->tls_session_secret_cb_arg)) {
1069
			s->internal->hit = 1;
1070
			s->session->ciphers = ciphers;
1071
			s->session->verify_result = X509_V_OK;
1072
1073
			ciphers = NULL;
1074
1075
			/* check if some cipher was preferred by call back */
1076
			pref_cipher = pref_cipher ? pref_cipher :
1077
			    ssl3_choose_cipher(s, s->session->ciphers,
1078
			    SSL_get_ciphers(s));
1079
			if (pref_cipher == NULL) {
1080
				al = SSL_AD_HANDSHAKE_FAILURE;
1081
				SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1082
				goto f_err;
1083
			}
1084
1085
			s->session->cipher = pref_cipher;
1086
1087
			sk_SSL_CIPHER_free(s->cipher_list);
1088
			sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
1089
1090
			s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1091
			s->internal->cipher_list_by_id =
1092
			    sk_SSL_CIPHER_dup(s->session->ciphers);
1093
		}
1094
	}
1095
1096
	/*
1097
	 * Given s->session->ciphers and SSL_get_ciphers, we must
1098
	 * pick a cipher
1099
	 */
1100
1101
198
	if (!s->internal->hit) {
1102
198
		sk_SSL_CIPHER_free(s->session->ciphers);
1103
198
		s->session->ciphers = ciphers;
1104
198
		if (ciphers == NULL) {
1105
			al = SSL_AD_ILLEGAL_PARAMETER;
1106
			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
1107
			goto f_err;
1108
		}
1109
		ciphers = NULL;
1110
396
		c = ssl3_choose_cipher(s, s->session->ciphers,
1111
198
		SSL_get_ciphers(s));
1112
1113
198
		if (c == NULL) {
1114
			al = SSL_AD_HANDSHAKE_FAILURE;
1115
			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1116
			goto f_err;
1117
		}
1118
		S3I(s)->hs.new_cipher = c;
1119
198
	} else {
1120
		S3I(s)->hs.new_cipher = s->session->cipher;
1121
	}
1122
1123
198
	if (!tls1_handshake_hash_init(s))
1124
		goto err;
1125
1126
198
	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1127

396
	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1128
105
	    !(s->verify_mode & SSL_VERIFY_PEER)) {
1129
183
		if (!tls1_digest_cached_records(s)) {
1130
			al = SSL_AD_INTERNAL_ERROR;
1131
			goto f_err;
1132
		}
1133
	}
1134
1135
	/*
1136
	 * We now have the following setup.
1137
	 * client_random
1138
	 * cipher_list 		- our prefered list of ciphers
1139
	 * ciphers 		- the clients prefered list of ciphers
1140
	 * compression		- basically ignored right now
1141
	 * ssl version is set	- sslv3
1142
	 * s->session		- The ssl session has been setup.
1143
	 * s->internal->hit		- session reuse flag
1144
	 * s->hs.new_cipher	- the new cipher to use.
1145
	 */
1146
1147
	/* Handles TLS extensions that we couldn't check earlier */
1148
198
	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1149
		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1150
		goto err;
1151
	}
1152
1153
198
	ret = cookie_valid ? 2 : 1;
1154
1155
198
	if (0) {
1156
truncated:
1157
		al = SSL_AD_DECODE_ERROR;
1158
		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1159
f_err:
1160
		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1161
	}
1162
err:
1163
198
	sk_SSL_CIPHER_free(ciphers);
1164
1165
198
	return (ret);
1166
774
}
1167
1168
int
1169
ssl3_send_server_hello(SSL *s)
1170
{
1171
396
	CBB cbb, server_hello, session_id;
1172
	size_t sl;
1173
1174
198
	memset(&cbb, 0, sizeof(cbb));
1175
1176
198
	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
1177
198
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &server_hello,
1178
		    SSL3_MT_SERVER_HELLO))
1179
			goto err;
1180
1181
198
		if (!CBB_add_u16(&server_hello, s->version))
1182
			goto err;
1183
198
		if (!CBB_add_bytes(&server_hello, s->s3->server_random,
1184
		    sizeof(s->s3->server_random)))
1185
			goto err;
1186
1187
		/*
1188
		 * There are several cases for the session ID to send
1189
		 * back in the server hello:
1190
		 *
1191
		 * - For session reuse from the session cache,
1192
		 *   we send back the old session ID.
1193
		 * - If stateless session reuse (using a session ticket)
1194
		 *   is successful, we send back the client's "session ID"
1195
		 *   (which doesn't actually identify the session).
1196
		 * - If it is a new session, we send back the new
1197
		 *   session ID.
1198
		 * - However, if we want the new session to be single-use,
1199
		 *   we send back a 0-length session ID.
1200
		 *
1201
		 * s->internal->hit is non-zero in either case of session reuse,
1202
		 * so the following won't overwrite an ID that we're supposed
1203
		 * to send back.
1204
		 */
1205
210
		if (!(s->ctx->internal->session_cache_mode & SSL_SESS_CACHE_SERVER)
1206
210
		    && !s->internal->hit)
1207
12
			s->session->session_id_length = 0;
1208
1209
198
		sl = s->session->session_id_length;
1210
198
		if (sl > sizeof(s->session->session_id)) {
1211
			SSLerror(s, ERR_R_INTERNAL_ERROR);
1212
			goto err;
1213
		}
1214
198
		if (!CBB_add_u8_length_prefixed(&server_hello, &session_id))
1215
			goto err;
1216
198
		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1217
			goto err;
1218
1219
		/* Cipher suite. */
1220
198
		if (!CBB_add_u16(&server_hello,
1221
198
		    ssl3_cipher_get_value(S3I(s)->hs.new_cipher)))
1222
			goto err;
1223
1224
		/* Compression method (null). */
1225
198
		if (!CBB_add_u8(&server_hello, 0))
1226
			goto err;
1227
1228
		/* TLS extensions */
1229
198
		if (!tlsext_serverhello_build(s, &server_hello)) {
1230
			SSLerror(s, ERR_R_INTERNAL_ERROR);
1231
			goto err;
1232
		}
1233
1234
198
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1235
			goto err;
1236
	}
1237
1238
	/* SSL3_ST_SW_SRVR_HELLO_B */
1239
198
	return (ssl3_handshake_write(s));
1240
1241
 err:
1242
	CBB_cleanup(&cbb);
1243
1244
	return (-1);
1245
198
}
1246
1247
int
1248
ssl3_send_server_done(SSL *s)
1249
{
1250
396
	CBB cbb, done;
1251
1252
198
	memset(&cbb, 0, sizeof(cbb));
1253
1254
198
	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_DONE_A) {
1255
198
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &done,
1256
		    SSL3_MT_SERVER_DONE))
1257
			goto err;
1258
198
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1259
			goto err;
1260
1261
198
		S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_B;
1262
198
	}
1263
1264
	/* SSL3_ST_SW_SRVR_DONE_B */
1265
198
	return (ssl3_handshake_write(s));
1266
1267
 err:
1268
	CBB_cleanup(&cbb);
1269
1270
	return (-1);
1271
198
}
1272
1273
int
1274
ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1275
{
1276
138
	CBB dh_p, dh_g, dh_Ys;
1277
	DH *dh = NULL, *dhp;
1278
69
	unsigned char *data;
1279
	int al;
1280
1281
69
	if (s->cert->dh_tmp_auto != 0) {
1282
6
		if ((dhp = ssl_get_auto_dh(s)) == NULL) {
1283
			al = SSL_AD_INTERNAL_ERROR;
1284
			SSLerror(s, ERR_R_INTERNAL_ERROR);
1285
			goto f_err;
1286
		}
1287
	} else
1288
63
		dhp = s->cert->dh_tmp;
1289
1290

69
	if (dhp == NULL && s->cert->dh_tmp_cb != NULL)
1291
		dhp = s->cert->dh_tmp_cb(s, 0,
1292
		    SSL_C_PKEYLENGTH(S3I(s)->hs.new_cipher));
1293
1294
69
	if (dhp == NULL) {
1295
		al = SSL_AD_HANDSHAKE_FAILURE;
1296
		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1297
		goto f_err;
1298
	}
1299
1300
69
	if (S3I(s)->tmp.dh != NULL) {
1301
		SSLerror(s, ERR_R_INTERNAL_ERROR);
1302
		goto err;
1303
	}
1304
1305
69
	if (s->cert->dh_tmp_auto != 0) {
1306
		dh = dhp;
1307
69
	} else if ((dh = DHparams_dup(dhp)) == NULL) {
1308
		SSLerror(s, ERR_R_DH_LIB);
1309
		goto err;
1310
	}
1311
69
	S3I(s)->tmp.dh = dh;
1312
69
	if (!DH_generate_key(dh)) {
1313
		SSLerror(s, ERR_R_DH_LIB);
1314
		goto err;
1315
	}
1316
1317
	/*
1318
	 * Serialize the DH parameters and public key.
1319
	 */
1320
69
	if (!CBB_add_u16_length_prefixed(cbb, &dh_p))
1321
		goto err;
1322
69
	if (!CBB_add_space(&dh_p, &data, BN_num_bytes(dh->p)))
1323
		goto err;
1324
69
	BN_bn2bin(dh->p, data);
1325
1326
69
	if (!CBB_add_u16_length_prefixed(cbb, &dh_g))
1327
		goto err;
1328
69
	if (!CBB_add_space(&dh_g, &data, BN_num_bytes(dh->g)))
1329
		goto err;
1330
69
	BN_bn2bin(dh->g, data);
1331
1332
69
	if (!CBB_add_u16_length_prefixed(cbb, &dh_Ys))
1333
		goto err;
1334
69
	if (!CBB_add_space(&dh_Ys, &data, BN_num_bytes(dh->pub_key)))
1335
		goto err;
1336
69
	BN_bn2bin(dh->pub_key, data);
1337
1338
69
	if (!CBB_flush(cbb))
1339
		goto err;
1340
1341
69
	return (1);
1342
1343
 f_err:
1344
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1345
 err:
1346
	return (-1);
1347
69
}
1348
1349
static int
1350
ssl3_send_server_kex_ecdhe_ecp(SSL *s, int nid, CBB *cbb)
1351
{
1352
	const EC_GROUP *group;
1353
	const EC_POINT *pubkey;
1354
138
	unsigned char *data;
1355
	int encoded_len = 0;
1356
	int curve_id = 0;
1357
	BN_CTX *bn_ctx = NULL;
1358
	EC_KEY *ecdh;
1359
69
	CBB ecpoint;
1360
	int al;
1361
1362
	/*
1363
	 * Only named curves are supported in ECDH ephemeral key exchanges.
1364
	 * For supported named curves, curve_id is non-zero.
1365
	 */
1366
69
	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1367
		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1368
		goto err;
1369
	}
1370
1371
69
	if (S3I(s)->tmp.ecdh != NULL) {
1372
		SSLerror(s, ERR_R_INTERNAL_ERROR);
1373
		goto err;
1374
	}
1375
1376
69
	if ((S3I(s)->tmp.ecdh = EC_KEY_new_by_curve_name(nid)) == NULL) {
1377
		al = SSL_AD_HANDSHAKE_FAILURE;
1378
		SSLerror(s, SSL_R_MISSING_TMP_ECDH_KEY);
1379
		goto f_err;
1380
	}
1381
69
	ecdh = S3I(s)->tmp.ecdh;
1382
1383
69
	if (!EC_KEY_generate_key(ecdh)) {
1384
		SSLerror(s, ERR_R_ECDH_LIB);
1385
		goto err;
1386
	}
1387

138
	if ((group = EC_KEY_get0_group(ecdh)) == NULL ||
1388
69
	    (pubkey = EC_KEY_get0_public_key(ecdh)) == NULL ||
1389
69
	    EC_KEY_get0_private_key(ecdh) == NULL) {
1390
		SSLerror(s, ERR_R_ECDH_LIB);
1391
		goto err;
1392
	}
1393
1394
	/*
1395
	 * Encode the public key.
1396
	 */
1397
69
	encoded_len = EC_POINT_point2oct(group, pubkey,
1398
	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
1399
69
	if (encoded_len == 0) {
1400
		SSLerror(s, ERR_R_ECDH_LIB);
1401
		goto err;
1402
	}
1403
69
	if ((bn_ctx = BN_CTX_new()) == NULL) {
1404
		SSLerror(s, ERR_R_MALLOC_FAILURE);
1405
		goto err;
1406
	}
1407
1408
	/*
1409
	 * Only named curves are supported in ECDH ephemeral key exchanges.
1410
	 * In this case the ServerKeyExchange message has:
1411
	 * [1 byte CurveType], [2 byte CurveName]
1412
	 * [1 byte length of encoded point], followed by
1413
	 * the actual encoded point itself.
1414
	 */
1415
69
	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1416
		goto err;
1417
69
	if (!CBB_add_u16(cbb, curve_id))
1418
		goto err;
1419
69
	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1420
		goto err;
1421
69
	if (!CBB_add_space(&ecpoint, &data, encoded_len))
1422
		goto err;
1423
138
	if (EC_POINT_point2oct(group, pubkey, POINT_CONVERSION_UNCOMPRESSED,
1424
138
	    data, encoded_len, bn_ctx) == 0) {
1425
		SSLerror(s, ERR_R_ECDH_LIB);
1426
		goto err;
1427
	}
1428
69
	if (!CBB_flush(cbb))
1429
		goto err;
1430
1431
69
	BN_CTX_free(bn_ctx);
1432
1433
69
	return (1);
1434
1435
 f_err:
1436
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1437
 err:
1438
	BN_CTX_free(bn_ctx);
1439
1440
	return (-1);
1441
69
}
1442
1443
static int
1444
ssl3_send_server_kex_ecdhe_ecx(SSL *s, int nid, CBB *cbb)
1445
{
1446
	uint8_t *public_key = NULL;
1447
	int curve_id;
1448
30
	CBB ecpoint;
1449
	int ret = -1;
1450
1451
	/* Generate an X25519 key pair. */
1452
15
	if (S3I(s)->tmp.x25519 != NULL) {
1453
		SSLerror(s, ERR_R_INTERNAL_ERROR);
1454
		goto err;
1455
	}
1456
15
	if ((S3I(s)->tmp.x25519 = malloc(X25519_KEY_LENGTH)) == NULL)
1457
		goto err;
1458
15
	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
1459
		goto err;
1460
15
	X25519_keypair(public_key, S3I(s)->tmp.x25519);
1461
1462
	/* Serialize public key. */
1463
15
	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1464
		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1465
		goto err;
1466
	}
1467
1468
15
	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1469
		goto err;
1470
15
	if (!CBB_add_u16(cbb, curve_id))
1471
		goto err;
1472
15
	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1473
		goto err;
1474
15
	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
1475
		goto err;
1476
15
	if (!CBB_flush(cbb))
1477
		goto err;
1478
1479
15
	ret = 1;
1480
1481
 err:
1482
15
	free(public_key);
1483
1484
15
	return (ret);
1485
15
}
1486
1487
static int
1488
ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1489
{
1490
	int nid;
1491
1492
168
	nid = tls1_get_shared_curve(s);
1493
1494
84
	if (nid == NID_X25519)
1495
15
		return ssl3_send_server_kex_ecdhe_ecx(s, nid, cbb);
1496
1497
69
	return ssl3_send_server_kex_ecdhe_ecp(s, nid, cbb);
1498
84
}
1499
1500
int
1501
ssl3_send_server_key_exchange(SSL *s)
1502
{
1503
306
	CBB cbb;
1504
153
	unsigned char *params = NULL;
1505
153
	size_t params_len;
1506
	unsigned char *q;
1507
153
	unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1508
153
	unsigned int u;
1509
	EVP_PKEY *pkey;
1510
153
	const EVP_MD *md = NULL;
1511
	unsigned char *p, *d;
1512
153
	int al, i, j, n, kn;
1513
	unsigned long type;
1514
	BUF_MEM *buf;
1515
153
	EVP_MD_CTX md_ctx;
1516
1517
153
	memset(&cbb, 0, sizeof(cbb));
1518
1519
153
	EVP_MD_CTX_init(&md_ctx);
1520
153
	if (S3I(s)->hs.state == SSL3_ST_SW_KEY_EXCH_A) {
1521
153
		type = S3I(s)->hs.new_cipher->algorithm_mkey;
1522
1523
153
		buf = s->internal->init_buf;
1524
1525
153
		if (!CBB_init(&cbb, 0))
1526
			goto err;
1527
1528
153
		if (type & SSL_kDHE) {
1529
69
			if (ssl3_send_server_kex_dhe(s, &cbb) != 1)
1530
				goto err;
1531
84
		} else if (type & SSL_kECDHE) {
1532
84
			if (ssl3_send_server_kex_ecdhe(s, &cbb) != 1)
1533
				goto err;
1534
		} else {
1535
			al = SSL_AD_HANDSHAKE_FAILURE;
1536
			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1537
			goto f_err;
1538
		}
1539
1540
153
		if (!CBB_finish(&cbb, &params, &params_len))
1541
			goto err;
1542
1543
153
		if (!(S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL)) {
1544
246
			if ((pkey = ssl_get_sign_pkey(
1545
123
			    s, S3I(s)->hs.new_cipher, &md)) == NULL) {
1546
				al = SSL_AD_DECODE_ERROR;
1547
				goto f_err;
1548
			}
1549
123
			kn = EVP_PKEY_size(pkey);
1550
123
		} else {
1551
			pkey = NULL;
1552
			kn = 0;
1553
		}
1554
1555
459
		if (!BUF_MEM_grow_clean(buf, ssl3_handshake_msg_hdr_len(s) +
1556
306
		    params_len + kn)) {
1557
			SSLerror(s, ERR_LIB_BUF);
1558
			goto err;
1559
		}
1560
1561
153
		d = p = ssl3_handshake_msg_start(s,
1562
		    SSL3_MT_SERVER_KEY_EXCHANGE);
1563
1564
153
		memcpy(p, params, params_len);
1565
1566
153
		free(params);
1567
153
		params = NULL;
1568
1569
153
		n = params_len;
1570
153
		p += params_len;
1571
1572
		/* not anonymous */
1573
153
		if (pkey != NULL) {
1574
			/*
1575
			 * n is the length of the params, they start at &(d[4])
1576
			 * and p points to the space at the end.
1577
			 */
1578

246
			if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1579
39
				q = md_buf;
1580
				j = 0;
1581
39
				if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(),
1582
				    NULL))
1583
					goto err;
1584
39
				EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1585
				    SSL3_RANDOM_SIZE);
1586
39
				EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1587
				    SSL3_RANDOM_SIZE);
1588
39
				EVP_DigestUpdate(&md_ctx, d, n);
1589
39
				EVP_DigestFinal_ex(&md_ctx, q,
1590
				    (unsigned int *)&i);
1591
39
				q += i;
1592
				j += i;
1593
78
				if (RSA_sign(NID_md5_sha1, md_buf, j,
1594
78
				    &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1595
					SSLerror(s, ERR_R_RSA_LIB);
1596
					goto err;
1597
				}
1598
39
				s2n(u, p);
1599
39
				n += u + 2;
1600
123
			} else if (md) {
1601
				/* Send signature algorithm. */
1602
84
				if (SSL_USE_SIGALGS(s)) {
1603
84
					if (!tls12_get_sigandhash(p, pkey, md)) {
1604
						/* Should never happen */
1605
						al = SSL_AD_INTERNAL_ERROR;
1606
						SSLerror(s, ERR_R_INTERNAL_ERROR);
1607
						goto f_err;
1608
					}
1609
84
					p += 2;
1610
84
				}
1611
84
				EVP_SignInit_ex(&md_ctx, md, NULL);
1612
84
				EVP_SignUpdate(&md_ctx,
1613
				    s->s3->client_random,
1614
				    SSL3_RANDOM_SIZE);
1615
84
				EVP_SignUpdate(&md_ctx,
1616
				    s->s3->server_random,
1617
				    SSL3_RANDOM_SIZE);
1618
84
				EVP_SignUpdate(&md_ctx, d, n);
1619
84
				if (!EVP_SignFinal(&md_ctx, &p[2],
1620
					(unsigned int *)&i, pkey)) {
1621
					SSLerror(s, ERR_R_EVP_LIB);
1622
					goto err;
1623
				}
1624
84
				s2n(i, p);
1625
84
				n += i + 2;
1626
84
				if (SSL_USE_SIGALGS(s))
1627
84
					n += 2;
1628
			} else {
1629
				/* Is this error check actually needed? */
1630
				al = SSL_AD_HANDSHAKE_FAILURE;
1631
				SSLerror(s, SSL_R_UNKNOWN_PKEY_TYPE);
1632
				goto f_err;
1633
			}
1634
		}
1635
1636
153
		ssl3_handshake_msg_finish(s, n);
1637
153
	}
1638
1639
153
	S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1640
1641
153
	EVP_MD_CTX_cleanup(&md_ctx);
1642
1643
153
	return (ssl3_handshake_write(s));
1644
1645
 f_err:
1646
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1647
 err:
1648
	free(params);
1649
	EVP_MD_CTX_cleanup(&md_ctx);
1650
	CBB_cleanup(&cbb);
1651
1652
	return (-1);
1653
153
}
1654
1655
int
1656
ssl3_send_certificate_request(SSL *s)
1657
{
1658
42
	CBB cbb, cert_request, cert_types, sigalgs, cert_auth, dn;
1659
	STACK_OF(X509_NAME) *sk = NULL;
1660
	X509_NAME *name;
1661
	int i;
1662
1663
	/*
1664
	 * Certificate Request - RFC 5246 section 7.4.4.
1665
	 */
1666
1667
21
	memset(&cbb, 0, sizeof(cbb));
1668
1669
21
	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1670
21
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &cert_request,
1671
		    SSL3_MT_CERTIFICATE_REQUEST))
1672
			goto err;
1673
1674
21
		if (!CBB_add_u8_length_prefixed(&cert_request, &cert_types))
1675
			goto err;
1676
21
		if (!ssl3_get_req_cert_types(s, &cert_types))
1677
			goto err;
1678
1679
21
		if (SSL_USE_SIGALGS(s)) {
1680
15
			unsigned char *sigalgs_data;
1681
15
			size_t sigalgs_len;
1682
1683
15
			tls12_get_req_sig_algs(s, &sigalgs_data, &sigalgs_len);
1684
1685
15
			if (!CBB_add_u16_length_prefixed(&cert_request, &sigalgs))
1686
				goto err;
1687
15
			if (!CBB_add_bytes(&sigalgs, sigalgs_data, sigalgs_len))
1688
				goto err;
1689
45
		}
1690
1691
21
		if (!CBB_add_u16_length_prefixed(&cert_request, &cert_auth))
1692
			goto err;
1693
1694
21
		sk = SSL_get_client_CA_list(s);
1695
42
		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1696
			unsigned char *name_data;
1697
			size_t name_len;
1698
1699
			name = sk_X509_NAME_value(sk, i);
1700
			name_len = i2d_X509_NAME(name, NULL);
1701
1702
			if (!CBB_add_u16_length_prefixed(&cert_auth, &dn))
1703
				goto err;
1704
			if (!CBB_add_space(&dn, &name_data, name_len))
1705
				goto err;
1706
			if (i2d_X509_NAME(name, &name_data) != name_len)
1707
				goto err;
1708
		}
1709
1710
21
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1711
			goto err;
1712
1713
21
		S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_B;
1714
21
	}
1715
1716
	/* SSL3_ST_SW_CERT_REQ_B */
1717
21
	return (ssl3_handshake_write(s));
1718
1719
 err:
1720
	CBB_cleanup(&cbb);
1721
1722
	return (-1);
1723
21
}
1724
1725
static int
1726
ssl3_get_client_kex_rsa(SSL *s, unsigned char *p, long n)
1727
{
1728
90
	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1729
	unsigned char *d;
1730
	RSA *rsa = NULL;
1731
	EVP_PKEY *pkey = NULL;
1732
	int i, al;
1733
1734
	d = p;
1735
1736
45
	arc4random_buf(fakekey, sizeof(fakekey));
1737
45
	fakekey[0] = s->client_version >> 8;
1738
45
	fakekey[1] = s->client_version & 0xff;
1739
1740
45
	pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1741

135
	if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1742
45
	    (pkey->pkey.rsa == NULL)) {
1743
		al = SSL_AD_HANDSHAKE_FAILURE;
1744
		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1745
		goto f_err;
1746
	}
1747
	rsa = pkey->pkey.rsa;
1748
1749
45
	if (2 > n)
1750
		goto truncated;
1751
45
	n2s(p, i);
1752
45
	if (n != i + 2) {
1753
		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1754
		goto err;
1755
	} else
1756
45
		n = i;
1757
1758
45
	i = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1759
1760
45
	ERR_clear_error();
1761
1762
	al = -1;
1763
1764
45
	if (i != SSL_MAX_MASTER_KEY_LENGTH) {
1765
		al = SSL_AD_DECODE_ERROR;
1766
		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1767
	}
1768
1769
45
	if (p - d + 2 > n)	/* needed in the SSL3 case */
1770
		goto truncated;
1771

135
	if ((al == -1) && !((p[0] == (s->client_version >> 8)) &&
1772
45
	    (p[1] == (s->client_version & 0xff)))) {
1773
		/*
1774
		 * The premaster secret must contain the same version
1775
		 * number as the ClientHello to detect version rollback
1776
		 * attacks (strangely, the protocol does not offer such
1777
		 * protection for DH ciphersuites).
1778
		 * However, buggy clients exist that send the negotiated
1779
		 * protocol version instead if the server does not
1780
		 * support the requested protocol version.
1781
		 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1782
		 * clients.
1783
		 */
1784
		if (!((s->internal->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1785
		    (p[0] == (s->version >> 8)) &&
1786
		    (p[1] == (s->version & 0xff)))) {
1787
			al = SSL_AD_DECODE_ERROR;
1788
			/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1789
1790
			/*
1791
			 * The Klima-Pokorny-Rosa extension of
1792
			 * Bleichenbacher's attack
1793
			 * (http://eprint.iacr.org/2003/052/) exploits
1794
			 * the version number check as a "bad version
1795
			 * oracle" -- an alert would reveal that the
1796
			 * plaintext corresponding to some ciphertext
1797
			 * made up by the adversary is properly
1798
			 * formatted except that the version number is
1799
			 * wrong.
1800
			 * To avoid such attacks, we should treat this
1801
			 * just like any other decryption error.
1802
			 */
1803
		}
1804
	}
1805
1806
45
	if (al != -1) {
1807
		/*
1808
		 * Some decryption failure -- use random value instead
1809
		 * as countermeasure against Bleichenbacher's attack
1810
		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1811
		 * section 7.4.7.1).
1812
		 */
1813
		i = SSL_MAX_MASTER_KEY_LENGTH;
1814
		p = fakekey;
1815
	}
1816
1817
45
	s->session->master_key_length =
1818
45
	    tls1_generate_master_secret(s,
1819
45
	        s->session->master_key, p, i);
1820
1821
45
	explicit_bzero(p, i);
1822
1823
45
	return (1);
1824
truncated:
1825
	al = SSL_AD_DECODE_ERROR;
1826
	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1827
f_err:
1828
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1829
err:
1830
	return (-1);
1831
45
}
1832
1833
static int
1834
ssl3_get_client_kex_dhe(SSL *s, unsigned char *p, long n)
1835
{
1836
	BIGNUM *bn = NULL;
1837
	int key_size, al;
1838
126
	CBS cbs, dh_Yc;
1839
	DH *dh;
1840
1841
63
	if (n < 0)
1842
		goto err;
1843
1844
63
	CBS_init(&cbs, p, n);
1845
1846
63
	if (!CBS_get_u16_length_prefixed(&cbs, &dh_Yc))
1847
		goto truncated;
1848
1849
63
	if (CBS_len(&cbs) != 0)
1850
		goto truncated;
1851
1852
63
	if (S3I(s)->tmp.dh == NULL) {
1853
		al = SSL_AD_HANDSHAKE_FAILURE;
1854
		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1855
		goto f_err;
1856
	}
1857
	dh = S3I(s)->tmp.dh;
1858
1859
63
	if ((bn = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL)) == NULL) {
1860
		SSLerror(s, SSL_R_BN_LIB);
1861
		goto err;
1862
	}
1863
1864
63
	key_size = DH_compute_key(p, bn, dh);
1865
63
	if (key_size <= 0) {
1866
		SSLerror(s, ERR_R_DH_LIB);
1867
		BN_clear_free(bn);
1868
		goto err;
1869
	}
1870
1871
63
	s->session->master_key_length =
1872
63
	    tls1_generate_master_secret(
1873
63
	        s, s->session->master_key, p, key_size);
1874
1875
63
	explicit_bzero(p, key_size);
1876
1877
63
	DH_free(S3I(s)->tmp.dh);
1878
63
	S3I(s)->tmp.dh = NULL;
1879
1880
63
	BN_clear_free(bn);
1881
1882
63
	return (1);
1883
1884
 truncated:
1885
	al = SSL_AD_DECODE_ERROR;
1886
	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1887
 f_err:
1888
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1889
 err:
1890
	return (-1);
1891
63
}
1892
1893
static int
1894
ssl3_get_client_kex_ecdhe_ecp(SSL *s, unsigned char *p, long n)
1895
{
1896
	EC_KEY *srvr_ecdh = NULL;
1897
	EVP_PKEY *clnt_pub_pkey = NULL;
1898
	EC_POINT *clnt_ecpoint = NULL;
1899
	BN_CTX *bn_ctx = NULL;
1900
	int i, al;
1901
1902
	int ret = 1;
1903
	int key_size;
1904
	const EC_KEY   *tkey;
1905
	const EC_GROUP *group;
1906
	const BIGNUM *priv_key;
1907
1908
	/* Initialize structures for server's ECDH key pair. */
1909
138
	if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1910
		SSLerror(s, ERR_R_MALLOC_FAILURE);
1911
		goto err;
1912
	}
1913
1914
	/*
1915
	 * Use the ephemeral values we saved when
1916
	 * generating the ServerKeyExchange message.
1917
	 */
1918
69
	tkey = S3I(s)->tmp.ecdh;
1919
1920
69
	group = EC_KEY_get0_group(tkey);
1921
69
	priv_key = EC_KEY_get0_private_key(tkey);
1922
1923

138
	if (!EC_KEY_set_group(srvr_ecdh, group) ||
1924
69
	    !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1925
		SSLerror(s, ERR_R_EC_LIB);
1926
		goto err;
1927
	}
1928
1929
	/* Let's get client's public key */
1930
69
	if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1931
		SSLerror(s, ERR_R_MALLOC_FAILURE);
1932
		goto err;
1933
	}
1934
1935
69
	if (n == 0L) {
1936
		/* Client Publickey was in Client Certificate */
1937
		if (((clnt_pub_pkey = X509_get_pubkey(
1938
		    s->session->peer)) == NULL) ||
1939
		    (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1940
			/*
1941
			 * XXX: For now, we do not support client
1942
			 * authentication using ECDH certificates
1943
			 * so this branch (n == 0L) of the code is
1944
			 * never executed. When that support is
1945
			 * added, we ought to ensure the key
1946
			 * received in the certificate is
1947
			 * authorized for key agreement.
1948
			 * ECDH_compute_key implicitly checks that
1949
			 * the two ECDH shares are for the same
1950
			 * group.
1951
			 */
1952
			al = SSL_AD_HANDSHAKE_FAILURE;
1953
			SSLerror(s, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1954
			goto f_err;
1955
		}
1956
1957
		if (EC_POINT_copy(clnt_ecpoint,
1958
		    EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec))
1959
		    == 0) {
1960
			SSLerror(s, ERR_R_EC_LIB);
1961
			goto err;
1962
		}
1963
		ret = 2; /* Skip certificate verify processing */
1964
	} else {
1965
		/*
1966
		 * Get client's public key from encoded point
1967
		 * in the ClientKeyExchange message.
1968
		 */
1969
69
		if ((bn_ctx = BN_CTX_new()) == NULL) {
1970
			SSLerror(s, ERR_R_MALLOC_FAILURE);
1971
			goto err;
1972
		}
1973
1974
		/* Get encoded point length */
1975
69
		i = *p;
1976
1977
69
		p += 1;
1978
69
		if (n != 1 + i) {
1979
			SSLerror(s, ERR_R_EC_LIB);
1980
			goto err;
1981
		}
1982
138
		if (EC_POINT_oct2point(group,
1983
138
			clnt_ecpoint, p, i, bn_ctx) == 0) {
1984
			SSLerror(s, ERR_R_EC_LIB);
1985
			goto err;
1986
		}
1987
		/*
1988
		 * p is pointing to somewhere in the buffer
1989
		 * currently, so set it to the start.
1990
		 */
1991
69
		p = (unsigned char *)s->internal->init_buf->data;
1992
	}
1993
1994
	/* Compute the shared pre-master secret */
1995
69
	key_size = ECDH_size(srvr_ecdh);
1996
69
	if (key_size <= 0) {
1997
		SSLerror(s, ERR_R_ECDH_LIB);
1998
		goto err;
1999
	}
2000
69
	i = ECDH_compute_key(p, key_size, clnt_ecpoint, srvr_ecdh,
2001
	    NULL);
2002
69
	if (i <= 0) {
2003
		SSLerror(s, ERR_R_ECDH_LIB);
2004
		goto err;
2005
	}
2006
2007
69
	EVP_PKEY_free(clnt_pub_pkey);
2008
69
	EC_POINT_free(clnt_ecpoint);
2009
69
	EC_KEY_free(srvr_ecdh);
2010
69
	BN_CTX_free(bn_ctx);
2011
69
	EC_KEY_free(S3I(s)->tmp.ecdh);
2012
69
	S3I(s)->tmp.ecdh = NULL;
2013
2014
	/* Compute the master secret */
2015
69
	s->session->master_key_length =
2016
69
	    tls1_generate_master_secret(
2017
69
		s, s->session->master_key, p, i);
2018
2019
69
	explicit_bzero(p, i);
2020
69
	return (ret);
2021
2022
 f_err:
2023
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2024
 err:
2025
	EVP_PKEY_free(clnt_pub_pkey);
2026
	EC_POINT_free(clnt_ecpoint);
2027
	EC_KEY_free(srvr_ecdh);
2028
	BN_CTX_free(bn_ctx);
2029
	return (-1);
2030
69
}
2031
2032
static int
2033
ssl3_get_client_kex_ecdhe_ecx(SSL *s, unsigned char *p, long n)
2034
{
2035
	uint8_t *shared_key = NULL;
2036
30
	CBS cbs, ecpoint;
2037
	int ret = -1;
2038
2039
15
	if (n < 0)
2040
		goto err;
2041
2042
15
	CBS_init(&cbs, p, n);
2043
15
	if (!CBS_get_u8_length_prefixed(&cbs, &ecpoint))
2044
		goto err;
2045
15
	if (CBS_len(&ecpoint) != X25519_KEY_LENGTH)
2046
		goto err;
2047
2048
15
	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2049
		goto err;
2050
15
	if (!X25519(shared_key, S3I(s)->tmp.x25519, CBS_data(&ecpoint)))
2051
		goto err;
2052
2053
15
	freezero(S3I(s)->tmp.x25519, X25519_KEY_LENGTH);
2054
15
	S3I(s)->tmp.x25519 = NULL;
2055
2056
15
	s->session->master_key_length =
2057
15
	    tls1_generate_master_secret(
2058
15
		s, s->session->master_key, shared_key, X25519_KEY_LENGTH);
2059
2060
15
	ret = 1;
2061
2062
 err:
2063
15
	freezero(shared_key, X25519_KEY_LENGTH);
2064
2065
15
	return (ret);
2066
15
}
2067
2068
static int
2069
ssl3_get_client_kex_ecdhe(SSL *s, unsigned char *p, long n)
2070
{
2071
168
        if (S3I(s)->tmp.x25519 != NULL)
2072
15
		return ssl3_get_client_kex_ecdhe_ecx(s, p, n);
2073
2074
69
	return ssl3_get_client_kex_ecdhe_ecp(s, p, n);
2075
84
}
2076
2077
static int
2078
ssl3_get_client_kex_gost(SSL *s, unsigned char *p, long n)
2079
{
2080
2081
	EVP_PKEY_CTX *pkey_ctx;
2082
	EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2083
	unsigned char premaster_secret[32], *start;
2084
	size_t outlen = 32, inlen;
2085
	unsigned long alg_a;
2086
	int Ttag, Tclass;
2087
	long Tlen;
2088
	int al;
2089
	int ret = 0;
2090
2091
	/* Get our certificate private key*/
2092
	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2093
	if (alg_a & SSL_aGOST01)
2094
		pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2095
2096
	pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2097
	EVP_PKEY_decrypt_init(pkey_ctx);
2098
	/*
2099
	 * If client certificate is present and is of the same type,
2100
	 * maybe use it for key exchange.
2101
	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
2102
	 * it is completely valid to use a client certificate for
2103
	 * authorization only.
2104
	 */
2105
	client_pub_pkey = X509_get_pubkey(s->session->peer);
2106
	if (client_pub_pkey) {
2107
		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2108
		    client_pub_pkey) <= 0)
2109
			ERR_clear_error();
2110
	}
2111
	if (2 > n)
2112
		goto truncated;
2113
	/* Decrypt session key */
2114
	if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag,
2115
	    &Tclass, n) != V_ASN1_CONSTRUCTED ||
2116
	    Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
2117
		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2118
		goto gerr;
2119
	}
2120
	start = p;
2121
	inlen = Tlen;
2122
	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
2123
	    start, inlen) <=0) {
2124
		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2125
		goto gerr;
2126
	}
2127
	/* Generate master secret */
2128
	s->session->master_key_length =
2129
	    tls1_generate_master_secret(
2130
		s, s->session->master_key, premaster_secret, 32);
2131
	/* Check if pubkey from client certificate was used */
2132
	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
2133
	    EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2134
		ret = 2;
2135
	else
2136
		ret = 1;
2137
 gerr:
2138
	EVP_PKEY_free(client_pub_pkey);
2139
	EVP_PKEY_CTX_free(pkey_ctx);
2140
	if (ret)
2141
		return (ret);
2142
	else
2143
		goto err;
2144
2145
 truncated:
2146
	al = SSL_AD_DECODE_ERROR;
2147
	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2148
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2149
 err:
2150
	return (-1);
2151
}
2152
2153
int
2154
ssl3_get_client_key_exchange(SSL *s)
2155
{
2156
	unsigned long alg_k;
2157
	unsigned char *p;
2158
2016
	int al, ok;
2159
	long n;
2160
2161
	/* 2048 maxlen is a guess.  How long a key does that permit? */
2162
1008
	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
2163
	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2164
1008
	if (!ok)
2165
816
		return ((int)n);
2166
2167
192
	p = (unsigned char *)s->internal->init_msg;
2168
2169
192
	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2170
2171
192
	if (alg_k & SSL_kRSA) {
2172
45
		if (ssl3_get_client_kex_rsa(s, p, n) != 1)
2173
			goto err;
2174
147
	} else if (alg_k & SSL_kDHE) {
2175
63
		if (ssl3_get_client_kex_dhe(s, p, n) != 1)
2176
			goto err;
2177
84
	} else if (alg_k & SSL_kECDHE) {
2178
84
		if (ssl3_get_client_kex_ecdhe(s, p, n) != 1)
2179
			goto err;
2180
	} else if (alg_k & SSL_kGOST) {
2181
		if (ssl3_get_client_kex_gost(s, p, n) != 1)
2182
			goto err;
2183
	} else {
2184
		al = SSL_AD_HANDSHAKE_FAILURE;
2185
		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
2186
		goto f_err;
2187
	}
2188
2189
192
	return (1);
2190
2191
 f_err:
2192
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2193
 err:
2194
	return (-1);
2195
1008
}
2196
2197
int
2198
ssl3_get_cert_verify(SSL *s)
2199
{
2200
	EVP_PKEY *pkey = NULL;
2201
	unsigned char *p;
2202
2328
	int al, ok, ret = 0;
2203
	long n;
2204
	int type = 0, i, j;
2205
	X509 *peer;
2206
	const EVP_MD *md = NULL;
2207
1164
	EVP_MD_CTX mctx;
2208
1164
	EVP_MD_CTX_init(&mctx);
2209
2210
1164
	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2211
	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2212
1164
	if (!ok)
2213
972
		return ((int)n);
2214
2215
192
	if (s->session->peer != NULL) {
2216
		peer = s->session->peer;
2217
21
		pkey = X509_get_pubkey(peer);
2218
21
		type = X509_certificate_type(peer, pkey);
2219
21
	} else {
2220
		peer = NULL;
2221
		pkey = NULL;
2222
	}
2223
2224
192
	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2225
171
		S3I(s)->tmp.reuse_message = 1;
2226
171
		if (peer != NULL) {
2227
			al = SSL_AD_UNEXPECTED_MESSAGE;
2228
			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
2229
			goto f_err;
2230
		}
2231
		ret = 1;
2232
171
		goto end;
2233
	}
2234
2235
21
	if (peer == NULL) {
2236
		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
2237
		al = SSL_AD_UNEXPECTED_MESSAGE;
2238
		goto f_err;
2239
	}
2240
2241
21
	if (!(type & EVP_PKT_SIGN)) {
2242
		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2243
		al = SSL_AD_ILLEGAL_PARAMETER;
2244
		goto f_err;
2245
	}
2246
2247
21
	if (S3I(s)->change_cipher_spec) {
2248
		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2249
		al = SSL_AD_UNEXPECTED_MESSAGE;
2250
		goto f_err;
2251
	}
2252
2253
	/* we now have a signature that we need to verify */
2254
21
	p = (unsigned char *)s->internal->init_msg;
2255
	/*
2256
	 * Check for broken implementations of GOST ciphersuites.
2257
	 *
2258
	 * If key is GOST and n is exactly 64, it is a bare
2259
	 * signature without length field.
2260
	 */
2261

21
	if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2262
	    pkey->type == NID_id_GostR3410_2001) ) {
2263
		i = 64;
2264
	} else {
2265
21
		if (SSL_USE_SIGALGS(s)) {
2266
15
			int sigalg = tls12_get_sigid(pkey);
2267
			/* Should never happen */
2268
15
			if (sigalg == -1) {
2269
				SSLerror(s, ERR_R_INTERNAL_ERROR);
2270
				al = SSL_AD_INTERNAL_ERROR;
2271
				goto f_err;
2272
			}
2273
15
			if (2 > n)
2274
				goto truncated;
2275
			/* Check key type is consistent with signature */
2276
15
			if (sigalg != (int)p[1]) {
2277
				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
2278
				al = SSL_AD_DECODE_ERROR;
2279
				goto f_err;
2280
			}
2281
15
			md = tls12_get_hash(p[0]);
2282
15
			if (md == NULL) {
2283
				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
2284
				al = SSL_AD_DECODE_ERROR;
2285
				goto f_err;
2286
			}
2287
15
			p += 2;
2288
15
			n -= 2;
2289

15
		}
2290
21
		if (2 > n)
2291
			goto truncated;
2292
21
		n2s(p, i);
2293
21
		n -= 2;
2294
21
		if (i > n)
2295
			goto truncated;
2296
	}
2297
21
	j = EVP_PKEY_size(pkey);
2298

42
	if ((i > j) || (n > j) || (n <= 0)) {
2299
		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2300
		al = SSL_AD_DECODE_ERROR;
2301
		goto f_err;
2302
	}
2303
2304
21
	if (SSL_USE_SIGALGS(s)) {
2305
		long hdatalen = 0;
2306
15
		void *hdata;
2307
15
		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2308
15
		if (hdatalen <= 0) {
2309
			SSLerror(s, ERR_R_INTERNAL_ERROR);
2310
			al = SSL_AD_INTERNAL_ERROR;
2311
			goto f_err;
2312
		}
2313

30
		if (!EVP_VerifyInit_ex(&mctx, md, NULL) ||
2314
15
		    !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2315
			SSLerror(s, ERR_R_EVP_LIB);
2316
			al = SSL_AD_INTERNAL_ERROR;
2317
			goto f_err;
2318
		}
2319
2320
15
		if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2321
			al = SSL_AD_DECRYPT_ERROR;
2322
			SSLerror(s, SSL_R_BAD_SIGNATURE);
2323
			goto f_err;
2324
		}
2325
45
	} else
2326
6
	if (pkey->type == EVP_PKEY_RSA) {
2327
12
		i = RSA_verify(NID_md5_sha1, S3I(s)->tmp.cert_verify_md,
2328
		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2329
6
		    pkey->pkey.rsa);
2330
6
		if (i < 0) {
2331
			al = SSL_AD_DECRYPT_ERROR;
2332
			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2333
			goto f_err;
2334
		}
2335
6
		if (i == 0) {
2336
			al = SSL_AD_DECRYPT_ERROR;
2337
			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2338
			goto f_err;
2339
		}
2340
	} else
2341
	if (pkey->type == EVP_PKEY_EC) {
2342
		j = ECDSA_verify(pkey->save_type,
2343
		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2344
		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2345
		if (j <= 0) {
2346
			/* bad signature */
2347
			al = SSL_AD_DECRYPT_ERROR;
2348
			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2349
			goto f_err;
2350
		}
2351
	} else
2352
#ifndef OPENSSL_NO_GOST
2353
	if (pkey->type == NID_id_GostR3410_94 ||
2354
	    pkey->type == NID_id_GostR3410_2001) {
2355
		long hdatalen = 0;
2356
		void *hdata;
2357
		unsigned char signature[128];
2358
		unsigned int siglen = sizeof(signature);
2359
		int nid;
2360
		EVP_PKEY_CTX *pctx;
2361
2362
		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2363
		if (hdatalen <= 0) {
2364
			SSLerror(s, ERR_R_INTERNAL_ERROR);
2365
			al = SSL_AD_INTERNAL_ERROR;
2366
			goto f_err;
2367
		}
2368
		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2369
				!(md = EVP_get_digestbynid(nid))) {
2370
			SSLerror(s, ERR_R_EVP_LIB);
2371
			al = SSL_AD_INTERNAL_ERROR;
2372
			goto f_err;
2373
		}
2374
		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2375
		if (!pctx) {
2376
			SSLerror(s, ERR_R_EVP_LIB);
2377
			al = SSL_AD_INTERNAL_ERROR;
2378
			goto f_err;
2379
		}
2380
		if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2381
		    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2382
		    !EVP_DigestFinal(&mctx, signature, &siglen) ||
2383
		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2384
		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2385
		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2386
				       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2387
				       GOST_SIG_FORMAT_RS_LE,
2388
				       NULL) <= 0)) {
2389
			SSLerror(s, ERR_R_EVP_LIB);
2390
			al = SSL_AD_INTERNAL_ERROR;
2391
			EVP_PKEY_CTX_free(pctx);
2392
			goto f_err;
2393
		}
2394
2395
		if (EVP_PKEY_verify(pctx, p, i, signature, siglen) <= 0) {
2396
			al = SSL_AD_DECRYPT_ERROR;
2397
			SSLerror(s, SSL_R_BAD_SIGNATURE);
2398
			EVP_PKEY_CTX_free(pctx);
2399
			goto f_err;
2400
		}
2401
2402
		EVP_PKEY_CTX_free(pctx);
2403
	} else
2404
#endif
2405
	{
2406
		SSLerror(s, ERR_R_INTERNAL_ERROR);
2407
		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2408
		goto f_err;
2409
	}
2410
2411
2412
	ret = 1;
2413
21
	if (0) {
2414
truncated:
2415
		al = SSL_AD_DECODE_ERROR;
2416
		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2417
f_err:
2418
		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2419
	}
2420
end:
2421
192
	if (S3I(s)->handshake_buffer) {
2422
15
		BIO_free(S3I(s)->handshake_buffer);
2423
15
		S3I(s)->handshake_buffer = NULL;
2424
15
		s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2425
15
	}
2426
192
	EVP_MD_CTX_cleanup(&mctx);
2427
192
	EVP_PKEY_free(pkey);
2428
192
	return (ret);
2429
1164
}
2430
2431
int
2432
ssl3_get_client_certificate(SSL *s)
2433
{
2434
642
	CBS cbs, client_certs;
2435
321
	int i, ok, al, ret = -1;
2436
	X509 *x = NULL;
2437
	long n;
2438
321
	const unsigned char *q;
2439
	STACK_OF(X509) *sk = NULL;
2440
2441
642
	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2442
321
	    -1, s->internal->max_cert_list, &ok);
2443
2444
321
	if (!ok)
2445
300
		return ((int)n);
2446
2447
21
	if (S3I(s)->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2448
		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2449
		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2450
		    	SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2451
			al = SSL_AD_HANDSHAKE_FAILURE;
2452
			goto f_err;
2453
		}
2454
		/*
2455
		 * If tls asked for a client cert,
2456
		 * the client must return a 0 list.
2457
		 */
2458
		if (S3I(s)->tmp.cert_request) {
2459
			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2460
			    );
2461
			al = SSL_AD_UNEXPECTED_MESSAGE;
2462
			goto f_err;
2463
		}
2464
		S3I(s)->tmp.reuse_message = 1;
2465
		return (1);
2466
	}
2467
2468
21
	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
2469
		al = SSL_AD_UNEXPECTED_MESSAGE;
2470
		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2471
		goto f_err;
2472
	}
2473
2474
21
	if (n < 0)
2475
		goto truncated;
2476
2477
21
	CBS_init(&cbs, s->internal->init_msg, n);
2478
2479
21
	if ((sk = sk_X509_new_null()) == NULL) {
2480
		SSLerror(s, ERR_R_MALLOC_FAILURE);
2481
		goto err;
2482
	}
2483
2484

42
	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2485
21
	    CBS_len(&cbs) != 0)
2486
		goto truncated;
2487
2488
168
	while (CBS_len(&client_certs) > 0) {
2489
63
		CBS cert;
2490
2491
63
		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2492
			al = SSL_AD_DECODE_ERROR;
2493
			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2494
			goto f_err;
2495
		}
2496
2497
63
		q = CBS_data(&cert);
2498
63
		x = d2i_X509(NULL, &q, CBS_len(&cert));
2499
63
		if (x == NULL) {
2500
			SSLerror(s, ERR_R_ASN1_LIB);
2501
			goto err;
2502
		}
2503
63
		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2504
			al = SSL_AD_DECODE_ERROR;
2505
			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2506
			goto f_err;
2507
		}
2508
63
		if (!sk_X509_push(sk, x)) {
2509
			SSLerror(s, ERR_R_MALLOC_FAILURE);
2510
			goto err;
2511
		}
2512
		x = NULL;
2513

168
	}
2514
2515
21
	if (sk_X509_num(sk) <= 0) {
2516
		/*
2517
		 * TLS does not mind 0 certs returned.
2518
		 * Fail for TLS only if we required a certificate.
2519
		 */
2520
		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2521
		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2522
			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2523
			al = SSL_AD_HANDSHAKE_FAILURE;
2524
			goto f_err;
2525
		}
2526
		/* No client certificate so digest cached records */
2527
		if (S3I(s)->handshake_buffer && !tls1_digest_cached_records(s)) {
2528
			al = SSL_AD_INTERNAL_ERROR;
2529
			goto f_err;
2530
		}
2531
	} else {
2532
21
		i = ssl_verify_cert_chain(s, sk);
2533
21
		if (i <= 0) {
2534
			al = ssl_verify_alarm_type(s->verify_result);
2535
			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2536
			goto f_err;
2537
		}
2538
	}
2539
2540
21
	X509_free(s->session->peer);
2541
21
	s->session->peer = sk_X509_shift(sk);
2542
21
	s->session->verify_result = s->verify_result;
2543
2544
	/*
2545
	 * With the current implementation, sess_cert will always be NULL
2546
	 * when we arrive here
2547
	 */
2548
21
	if (SSI(s)->sess_cert == NULL) {
2549
21
		SSI(s)->sess_cert = ssl_sess_cert_new();
2550
21
		if (SSI(s)->sess_cert == NULL) {
2551
			SSLerror(s, ERR_R_MALLOC_FAILURE);
2552
			goto err;
2553
		}
2554
	}
2555
21
	sk_X509_pop_free(SSI(s)->sess_cert->cert_chain, X509_free);
2556
21
	SSI(s)->sess_cert->cert_chain = sk;
2557
2558
	/*
2559
	 * Inconsistency alert: cert_chain does *not* include the
2560
	 * peer's own certificate, while we do include it in s3_clnt.c
2561
	 */
2562
2563
	sk = NULL;
2564
2565
	ret = 1;
2566
21
	if (0) {
2567
truncated:
2568
		al = SSL_AD_DECODE_ERROR;
2569
		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2570
f_err:
2571
		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2572
	}
2573
err:
2574
21
	X509_free(x);
2575
21
	sk_X509_pop_free(sk, X509_free);
2576
2577
21
	return (ret);
2578
321
}
2579
2580
int
2581
ssl3_send_server_certificate(SSL *s)
2582
{
2583
336
	CBB cbb, server_cert;
2584
	X509 *x;
2585
2586
	/*
2587
	 * Server Certificate - RFC 5246, section 7.4.2.
2588
	 */
2589
2590
168
	memset(&cbb, 0, sizeof(cbb));
2591
2592
168
	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_A) {
2593
168
		if ((x = ssl_get_server_send_cert(s)) == NULL) {
2594
			SSLerror(s, ERR_R_INTERNAL_ERROR);
2595
			return (0);
2596
		}
2597
2598
168
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &server_cert,
2599
		    SSL3_MT_CERTIFICATE))
2600
			goto err;
2601
168
		if (!ssl3_output_cert_chain(s, &server_cert, x))
2602
			goto err;
2603
168
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2604
			goto err;
2605
2606
168
		S3I(s)->hs.state = SSL3_ST_SW_CERT_B;
2607
168
	}
2608
2609
	/* SSL3_ST_SW_CERT_B */
2610
168
	return (ssl3_handshake_write(s));
2611
2612
 err:
2613
	CBB_cleanup(&cbb);
2614
2615
	return (0);
2616
168
}
2617
2618
/* send a new session ticket (not necessarily for a new session) */
2619
int
2620
ssl3_send_newsession_ticket(SSL *s)
2621
{
2622
360
	unsigned char *d, *p, *macstart;
2623
	unsigned char *senc = NULL;
2624
180
	const unsigned char *const_p;
2625
180
	int len, slen_full, slen;
2626
	SSL_SESSION *sess;
2627
180
	unsigned int hlen;
2628
180
	EVP_CIPHER_CTX ctx;
2629
180
	HMAC_CTX hctx;
2630
180
	SSL_CTX *tctx = s->initial_ctx;
2631
180
	unsigned char iv[EVP_MAX_IV_LENGTH];
2632
180
	unsigned char key_name[16];
2633
2634
180
	if (S3I(s)->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2635
		/* get session encoding length */
2636
180
		slen_full = i2d_SSL_SESSION(s->session, NULL);
2637
		/*
2638
		 * Some length values are 16 bits, so forget it if session is
2639
 		 * too long
2640
 		 */
2641
180
		if (slen_full > 0xFF00)
2642
			goto err;
2643
180
		senc = malloc(slen_full);
2644
180
		if (!senc)
2645
			goto err;
2646
180
		p = senc;
2647
180
		i2d_SSL_SESSION(s->session, &p);
2648
2649
		/*
2650
		 * Create a fresh copy (not shared with other threads) to
2651
		 * clean up
2652
		 */
2653
180
		const_p = senc;
2654
180
		sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2655
180
		if (sess == NULL)
2656
			goto err;
2657
2658
		/* ID is irrelevant for the ticket */
2659
180
		sess->session_id_length = 0;
2660
2661
180
		slen = i2d_SSL_SESSION(sess, NULL);
2662
180
		if (slen > slen_full) {
2663
			/* shouldn't ever happen */
2664
			goto err;
2665
		}
2666
180
		p = senc;
2667
180
		i2d_SSL_SESSION(sess, &p);
2668
180
		SSL_SESSION_free(sess);
2669
2670
		/*
2671
		 * Grow buffer if need be: the length calculation is as
2672
 		 * follows 1 (size of message name) + 3 (message length
2673
 		 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2674
 		 * 16 (key name) + max_iv_len (iv length) +
2675
 		 * session_length + max_enc_block_size (max encrypted session
2676
 		 * length) + max_md_size (HMAC).
2677
 		 */
2678
360
		if (!BUF_MEM_grow(s->internal->init_buf, ssl3_handshake_msg_hdr_len(s) +
2679
180
		    22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2680
180
		    EVP_MAX_MD_SIZE + slen))
2681
			goto err;
2682
2683
180
		d = p = ssl3_handshake_msg_start(s, SSL3_MT_NEWSESSION_TICKET);
2684
2685
180
		EVP_CIPHER_CTX_init(&ctx);
2686
180
		HMAC_CTX_init(&hctx);
2687
2688
		/*
2689
		 * Initialize HMAC and cipher contexts. If callback present
2690
		 * it does all the work otherwise use generated values
2691
		 * from parent ctx.
2692
		 */
2693
180
		if (tctx->internal->tlsext_ticket_key_cb) {
2694
			if (tctx->internal->tlsext_ticket_key_cb(s,
2695
			    key_name, iv, &ctx, &hctx, 1) < 0) {
2696
				EVP_CIPHER_CTX_cleanup(&ctx);
2697
				goto err;
2698
			}
2699
		} else {
2700
180
			arc4random_buf(iv, 16);
2701
360
			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2702
180
			    tctx->internal->tlsext_tick_aes_key, iv);
2703
360
			HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
2704
180
			    16, tlsext_tick_md(), NULL);
2705
180
			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2706
		}
2707
2708
		/*
2709
		 * Ticket lifetime hint (advisory only):
2710
		 * We leave this unspecified for resumed session
2711
		 * (for simplicity), and guess that tickets for new
2712
		 * sessions will live as long as their sessions.
2713
		 */
2714


1620
		l2n(s->internal->hit ? 0 : s->session->timeout, p);
2715
2716
		/* Skip ticket length for now */
2717
180
		p += 2;
2718
		/* Output key name */
2719
		macstart = p;
2720
180
		memcpy(p, key_name, 16);
2721
180
		p += 16;
2722
		/* output IV */
2723
180
		memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2724
180
		p += EVP_CIPHER_CTX_iv_length(&ctx);
2725
		/* Encrypt session data */
2726
180
		EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2727
180
		p += len;
2728
180
		EVP_EncryptFinal_ex(&ctx, p, &len);
2729
180
		p += len;
2730
180
		EVP_CIPHER_CTX_cleanup(&ctx);
2731
2732
180
		HMAC_Update(&hctx, macstart, p - macstart);
2733
180
		HMAC_Final(&hctx, p, &hlen);
2734
180
		HMAC_CTX_cleanup(&hctx);
2735
180
		p += hlen;
2736
2737
		/* Now write out lengths: p points to end of data written */
2738
		/* Total length */
2739
180
		len = p - d;
2740
2741
		/* Skip ticket lifetime hint. */
2742
180
		p = d + 4;
2743
180
		s2n(len - 6, p); /* Message length */
2744
2745
180
		ssl3_handshake_msg_finish(s, len);
2746
2747
180
		S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2748
2749
180
		freezero(senc, slen_full);
2750
180
	}
2751
2752
	/* SSL3_ST_SW_SESSION_TICKET_B */
2753
180
	return (ssl3_handshake_write(s));
2754
2755
 err:
2756
	freezero(senc, slen_full);
2757
2758
	return (-1);
2759
180
}
2760
2761
int
2762
ssl3_send_cert_status(SSL *s)
2763
{
2764
	CBB cbb, certstatus, ocspresp;
2765
2766
	memset(&cbb, 0, sizeof(cbb));
2767
2768
	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2769
		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &certstatus,
2770
		    SSL3_MT_CERTIFICATE_STATUS))
2771
			goto err;
2772
		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2773
			goto err;
2774
		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2775
			goto err;
2776
		if (!CBB_add_bytes(&ocspresp, s->internal->tlsext_ocsp_resp,
2777
		    s->internal->tlsext_ocsp_resplen))
2778
			goto err;
2779
		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2780
			goto err;
2781
2782
		S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2783
	}
2784
2785
	/* SSL3_ST_SW_CERT_STATUS_B */
2786
	return (ssl3_handshake_write(s));
2787
2788
 err:
2789
	CBB_cleanup(&cbb);
2790
2791
	return (-1);
2792
}