1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
108 *
109 */
110 /* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112 *
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115 *
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
118 *
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121 *
122 */
123 /* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
125 *
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128 * license.
129 *
130 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132 * support (see RFC 4279) to OpenSSL.
133 *
134 * No patent licenses or other rights except those expressly stated in
135 * the OpenSSL open source license shall be deemed granted or received
136 * expressly, by implication, estoppel, or otherwise.
137 *
138 * No assurances are provided by Nokia that the Contribution does not
139 * infringe the patent or other intellectual property rights of any third
140 * party or that the license provides you with all the necessary rights
141 * to make use of the Contribution.
142 *
143 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147 * OTHERWISE. */
148
149 #include <openssl/ssl.h>
150
151 #include <assert.h>
152 #include <string.h>
153
154 #include <openssl/bn.h>
155 #include <openssl/buf.h>
156 #include <openssl/bytestring.h>
157 #include <openssl/cipher.h>
158 #include <openssl/dh.h>
159 #include <openssl/ec.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/err.h>
162 #include <openssl/evp.h>
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/mem.h>
166 #include <openssl/nid.h>
167 #include <openssl/rand.h>
168 #include <openssl/x509.h>
169
170 #include "internal.h"
171 #include "../crypto/internal.h"
172
173
174 static int ssl3_process_client_hello(SSL_HANDSHAKE *hs);
175 static int ssl3_select_certificate(SSL_HANDSHAKE *hs);
176 static int ssl3_select_parameters(SSL_HANDSHAKE *hs);
177 static int ssl3_send_server_hello(SSL_HANDSHAKE *hs);
178 static int ssl3_send_server_certificate(SSL_HANDSHAKE *hs);
179 static int ssl3_send_certificate_status(SSL_HANDSHAKE *hs);
180 static int ssl3_send_server_key_exchange(SSL_HANDSHAKE *hs);
181 static int ssl3_send_certificate_request(SSL_HANDSHAKE *hs);
182 static int ssl3_send_server_hello_done(SSL_HANDSHAKE *hs);
183 static int ssl3_get_client_certificate(SSL_HANDSHAKE *hs);
184 static int ssl3_get_client_key_exchange(SSL_HANDSHAKE *hs);
185 static int ssl3_get_cert_verify(SSL_HANDSHAKE *hs);
186 static int ssl3_get_next_proto(SSL_HANDSHAKE *hs);
187 static int ssl3_get_channel_id(SSL_HANDSHAKE *hs);
188 static int ssl3_send_new_session_ticket(SSL_HANDSHAKE *hs);
189
190 static struct CRYPTO_STATIC_MUTEX g_v2clienthello_lock =
191 CRYPTO_STATIC_MUTEX_INIT;
192 static uint64_t g_v2clienthello_count = 0;
193
SSL_get_v2clienthello_count(void)194 uint64_t SSL_get_v2clienthello_count(void) {
195 CRYPTO_STATIC_MUTEX_lock_read(&g_v2clienthello_lock);
196 uint64_t ret = g_v2clienthello_count;
197 CRYPTO_STATIC_MUTEX_unlock_read(&g_v2clienthello_lock);
198 return ret;
199 }
200
ssl3_accept(SSL_HANDSHAKE * hs)201 int ssl3_accept(SSL_HANDSHAKE *hs) {
202 SSL *const ssl = hs->ssl;
203 uint32_t alg_a;
204 int ret = -1;
205
206 assert(ssl->handshake_func == ssl3_accept);
207 assert(ssl->server);
208
209 for (;;) {
210 int state = hs->state;
211
212 switch (hs->state) {
213 case SSL_ST_INIT:
214 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
215 hs->state = SSL3_ST_SR_CLNT_HELLO_A;
216 break;
217
218 case SSL3_ST_SR_CLNT_HELLO_A:
219 ret = ssl->method->ssl_get_message(ssl);
220 if (ret <= 0) {
221 goto end;
222 }
223 hs->state = SSL3_ST_SR_CLNT_HELLO_B;
224 break;
225
226 case SSL3_ST_SR_CLNT_HELLO_B:
227 ret = ssl3_process_client_hello(hs);
228 if (ret <= 0) {
229 goto end;
230 }
231 hs->state = SSL3_ST_SR_CLNT_HELLO_C;
232 break;
233
234 case SSL3_ST_SR_CLNT_HELLO_C:
235 ret = ssl3_select_certificate(hs);
236 if (ret <= 0) {
237 goto end;
238 }
239 if (hs->state != SSL_ST_TLS13) {
240 hs->state = SSL3_ST_SR_CLNT_HELLO_D;
241 }
242 break;
243
244 case SSL3_ST_SR_CLNT_HELLO_D:
245 ret = ssl3_select_parameters(hs);
246 if (ret <= 0) {
247 goto end;
248 }
249 ssl->method->received_flight(ssl);
250 hs->state = SSL3_ST_SW_SRVR_HELLO_A;
251 break;
252
253 case SSL3_ST_SW_SRVR_HELLO_A:
254 ret = ssl3_send_server_hello(hs);
255 if (ret <= 0) {
256 goto end;
257 }
258 if (ssl->session != NULL) {
259 hs->state = SSL3_ST_SW_SESSION_TICKET_A;
260 } else {
261 hs->state = SSL3_ST_SW_CERT_A;
262 }
263 break;
264
265 case SSL3_ST_SW_CERT_A:
266 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
267 ret = ssl3_send_server_certificate(hs);
268 if (ret <= 0) {
269 goto end;
270 }
271 }
272 hs->state = SSL3_ST_SW_CERT_STATUS_A;
273 break;
274
275 case SSL3_ST_SW_CERT_STATUS_A:
276 if (hs->certificate_status_expected) {
277 ret = ssl3_send_certificate_status(hs);
278 if (ret <= 0) {
279 goto end;
280 }
281 }
282 hs->state = SSL3_ST_SW_KEY_EXCH_A;
283 break;
284
285 case SSL3_ST_SW_KEY_EXCH_A:
286 case SSL3_ST_SW_KEY_EXCH_B:
287 alg_a = hs->new_cipher->algorithm_auth;
288
289 /* PSK ciphers send ServerKeyExchange if there is an identity hint. */
290 if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
291 ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
292 ret = ssl3_send_server_key_exchange(hs);
293 if (ret <= 0) {
294 goto end;
295 }
296 }
297
298 hs->state = SSL3_ST_SW_CERT_REQ_A;
299 break;
300
301 case SSL3_ST_SW_CERT_REQ_A:
302 if (hs->cert_request) {
303 ret = ssl3_send_certificate_request(hs);
304 if (ret <= 0) {
305 goto end;
306 }
307 }
308 hs->state = SSL3_ST_SW_SRVR_DONE_A;
309 break;
310
311 case SSL3_ST_SW_SRVR_DONE_A:
312 ret = ssl3_send_server_hello_done(hs);
313 if (ret <= 0) {
314 goto end;
315 }
316 hs->next_state = SSL3_ST_SR_CERT_A;
317 hs->state = SSL3_ST_SW_FLUSH;
318 break;
319
320 case SSL3_ST_SR_CERT_A:
321 if (hs->cert_request) {
322 ret = ssl3_get_client_certificate(hs);
323 if (ret <= 0) {
324 goto end;
325 }
326 }
327 hs->state = SSL3_ST_SR_KEY_EXCH_A;
328 break;
329
330 case SSL3_ST_SR_KEY_EXCH_A:
331 case SSL3_ST_SR_KEY_EXCH_B:
332 ret = ssl3_get_client_key_exchange(hs);
333 if (ret <= 0) {
334 goto end;
335 }
336 hs->state = SSL3_ST_SR_CERT_VRFY_A;
337 break;
338
339 case SSL3_ST_SR_CERT_VRFY_A:
340 ret = ssl3_get_cert_verify(hs);
341 if (ret <= 0) {
342 goto end;
343 }
344
345 hs->state = SSL3_ST_SR_CHANGE;
346 break;
347
348 case SSL3_ST_SR_CHANGE:
349 ret = ssl->method->read_change_cipher_spec(ssl);
350 if (ret <= 0) {
351 goto end;
352 }
353
354 if (!tls1_change_cipher_state(hs, SSL3_CHANGE_CIPHER_SERVER_READ)) {
355 ret = -1;
356 goto end;
357 }
358
359 hs->state = SSL3_ST_SR_NEXT_PROTO_A;
360 break;
361
362 case SSL3_ST_SR_NEXT_PROTO_A:
363 if (hs->next_proto_neg_seen) {
364 ret = ssl3_get_next_proto(hs);
365 if (ret <= 0) {
366 goto end;
367 }
368 }
369 hs->state = SSL3_ST_SR_CHANNEL_ID_A;
370 break;
371
372 case SSL3_ST_SR_CHANNEL_ID_A:
373 if (ssl->s3->tlsext_channel_id_valid) {
374 ret = ssl3_get_channel_id(hs);
375 if (ret <= 0) {
376 goto end;
377 }
378 }
379 hs->state = SSL3_ST_SR_FINISHED_A;
380 break;
381
382 case SSL3_ST_SR_FINISHED_A:
383 ret = ssl3_get_finished(hs);
384 if (ret <= 0) {
385 goto end;
386 }
387
388 ssl->method->received_flight(ssl);
389 if (ssl->session != NULL) {
390 hs->state = SSL_ST_OK;
391 } else {
392 hs->state = SSL3_ST_SW_SESSION_TICKET_A;
393 }
394
395 /* If this is a full handshake with ChannelID then record the handshake
396 * hashes in |hs->new_session| in case we need them to verify a
397 * ChannelID signature on a resumption of this session in the future. */
398 if (ssl->session == NULL && ssl->s3->tlsext_channel_id_valid) {
399 ret = tls1_record_handshake_hashes_for_channel_id(hs);
400 if (ret <= 0) {
401 goto end;
402 }
403 }
404 break;
405
406 case SSL3_ST_SW_SESSION_TICKET_A:
407 if (hs->ticket_expected) {
408 ret = ssl3_send_new_session_ticket(hs);
409 if (ret <= 0) {
410 goto end;
411 }
412 }
413 hs->state = SSL3_ST_SW_CHANGE;
414 break;
415
416 case SSL3_ST_SW_CHANGE:
417 if (!ssl->method->add_change_cipher_spec(ssl) ||
418 !tls1_change_cipher_state(hs, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
419 ret = -1;
420 goto end;
421 }
422
423 hs->state = SSL3_ST_SW_FINISHED_A;
424 break;
425
426 case SSL3_ST_SW_FINISHED_A:
427 ret = ssl3_send_finished(hs);
428 if (ret <= 0) {
429 goto end;
430 }
431 hs->state = SSL3_ST_SW_FLUSH;
432 if (ssl->session != NULL) {
433 hs->next_state = SSL3_ST_SR_CHANGE;
434 } else {
435 hs->next_state = SSL_ST_OK;
436 }
437 break;
438
439 case SSL3_ST_SW_FLUSH:
440 ret = ssl->method->flush_flight(ssl);
441 if (ret <= 0) {
442 goto end;
443 }
444
445 hs->state = hs->next_state;
446 if (hs->state != SSL_ST_OK) {
447 ssl->method->expect_flight(ssl);
448 }
449 break;
450
451 case SSL_ST_TLS13: {
452 int early_return = 0;
453 ret = tls13_handshake(hs, &early_return);
454 if (ret <= 0) {
455 goto end;
456 }
457
458 if (early_return) {
459 ret = 1;
460 goto end;
461 }
462
463 hs->state = SSL_ST_OK;
464 break;
465 }
466
467 case SSL_ST_OK:
468 ssl->method->release_current_message(ssl, 1 /* free_buffer */);
469
470 /* If we aren't retaining peer certificates then we can discard it
471 * now. */
472 if (hs->new_session != NULL &&
473 ssl->retain_only_sha256_of_client_certs) {
474 sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
475 hs->new_session->certs = NULL;
476 ssl->ctx->x509_method->session_clear(hs->new_session);
477 }
478
479 SSL_SESSION_free(ssl->s3->established_session);
480 if (ssl->session != NULL) {
481 SSL_SESSION_up_ref(ssl->session);
482 ssl->s3->established_session = ssl->session;
483 } else {
484 ssl->s3->established_session = hs->new_session;
485 ssl->s3->established_session->not_resumable = 0;
486 hs->new_session = NULL;
487 }
488
489 if (hs->v2_clienthello) {
490 CRYPTO_STATIC_MUTEX_lock_write(&g_v2clienthello_lock);
491 g_v2clienthello_count++;
492 CRYPTO_STATIC_MUTEX_unlock_write(&g_v2clienthello_lock);
493 }
494
495 ssl->s3->initial_handshake_complete = 1;
496 ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
497
498 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_DONE, 1);
499 ret = 1;
500 goto end;
501
502 default:
503 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
504 ret = -1;
505 goto end;
506 }
507
508 if (hs->state != state) {
509 ssl_do_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 1);
510 }
511 }
512
513 end:
514 ssl_do_info_callback(ssl, SSL_CB_ACCEPT_EXIT, ret);
515 return ret;
516 }
517
ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO * client_hello,uint16_t id)518 int ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO *client_hello,
519 uint16_t id) {
520 CBS cipher_suites;
521 CBS_init(&cipher_suites, client_hello->cipher_suites,
522 client_hello->cipher_suites_len);
523
524 while (CBS_len(&cipher_suites) > 0) {
525 uint16_t got_id;
526 if (!CBS_get_u16(&cipher_suites, &got_id)) {
527 return 0;
528 }
529
530 if (got_id == id) {
531 return 1;
532 }
533 }
534
535 return 0;
536 }
537
negotiate_version(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)538 static int negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
539 const SSL_CLIENT_HELLO *client_hello) {
540 SSL *const ssl = hs->ssl;
541 assert(!ssl->s3->have_version);
542 uint16_t min_version, max_version;
543 if (!ssl_get_version_range(ssl, &min_version, &max_version)) {
544 *out_alert = SSL_AD_PROTOCOL_VERSION;
545 return 0;
546 }
547
548 uint16_t version = 0;
549 /* Check supported_versions extension if it is present. */
550 CBS supported_versions;
551 if (ssl_client_hello_get_extension(client_hello, &supported_versions,
552 TLSEXT_TYPE_supported_versions)) {
553 CBS versions;
554 if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
555 CBS_len(&supported_versions) != 0 ||
556 CBS_len(&versions) == 0) {
557 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
558 *out_alert = SSL_AD_DECODE_ERROR;
559 return 0;
560 }
561
562 /* Choose the newest commonly-supported version advertised by the client.
563 * The client orders the versions according to its preferences, but we're
564 * not required to honor the client's preferences. */
565 int found_version = 0;
566 while (CBS_len(&versions) != 0) {
567 uint16_t ext_version;
568 if (!CBS_get_u16(&versions, &ext_version)) {
569 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
570 *out_alert = SSL_AD_DECODE_ERROR;
571 return 0;
572 }
573 if (!ssl->method->version_from_wire(&ext_version, ext_version)) {
574 continue;
575 }
576 if (min_version <= ext_version &&
577 ext_version <= max_version &&
578 (!found_version || version < ext_version)) {
579 version = ext_version;
580 found_version = 1;
581 }
582 }
583
584 if (!found_version) {
585 goto unsupported_protocol;
586 }
587 } else {
588 /* Process ClientHello.version instead. Note that versions beyond (D)TLS 1.2
589 * do not use this mechanism. */
590 if (SSL_is_dtls(ssl)) {
591 if (client_hello->version <= DTLS1_2_VERSION) {
592 version = TLS1_2_VERSION;
593 } else if (client_hello->version <= DTLS1_VERSION) {
594 version = TLS1_1_VERSION;
595 } else {
596 goto unsupported_protocol;
597 }
598 } else {
599 if (client_hello->version >= TLS1_2_VERSION) {
600 version = TLS1_2_VERSION;
601 } else if (client_hello->version >= TLS1_1_VERSION) {
602 version = TLS1_1_VERSION;
603 } else if (client_hello->version >= TLS1_VERSION) {
604 version = TLS1_VERSION;
605 } else if (client_hello->version >= SSL3_VERSION) {
606 version = SSL3_VERSION;
607 } else {
608 goto unsupported_protocol;
609 }
610 }
611
612 /* Apply our minimum and maximum version. */
613 if (version > max_version) {
614 version = max_version;
615 }
616
617 if (version < min_version) {
618 goto unsupported_protocol;
619 }
620 }
621
622 /* Handle FALLBACK_SCSV. */
623 if (ssl_client_cipher_list_contains_cipher(client_hello,
624 SSL3_CK_FALLBACK_SCSV & 0xffff) &&
625 version < max_version) {
626 OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
627 *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
628 return 0;
629 }
630
631 hs->client_version = client_hello->version;
632 ssl->version = ssl->method->version_to_wire(version);
633
634 /* At this point, the connection's version is known and |ssl->version| is
635 * fixed. Begin enforcing the record-layer version. */
636 ssl->s3->have_version = 1;
637
638 return 1;
639
640 unsupported_protocol:
641 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
642 *out_alert = SSL_AD_PROTOCOL_VERSION;
643 return 0;
644 }
645
STACK_OF(SSL_CIPHER)646 static STACK_OF(SSL_CIPHER) *
647 ssl_parse_client_cipher_list(const SSL_CLIENT_HELLO *client_hello) {
648 CBS cipher_suites;
649 CBS_init(&cipher_suites, client_hello->cipher_suites,
650 client_hello->cipher_suites_len);
651
652 STACK_OF(SSL_CIPHER) *sk = sk_SSL_CIPHER_new_null();
653 if (sk == NULL) {
654 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
655 goto err;
656 }
657
658 while (CBS_len(&cipher_suites) > 0) {
659 uint16_t cipher_suite;
660
661 if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
662 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
663 goto err;
664 }
665
666 const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
667 if (c != NULL && !sk_SSL_CIPHER_push(sk, c)) {
668 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
669 goto err;
670 }
671 }
672
673 return sk;
674
675 err:
676 sk_SSL_CIPHER_free(sk);
677 return NULL;
678 }
679
680 /* ssl_get_compatible_server_ciphers determines the key exchange and
681 * authentication cipher suite masks compatible with the server configuration
682 * and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
683 * exchange mask and |*out_mask_a| to the authentication mask. */
ssl_get_compatible_server_ciphers(SSL_HANDSHAKE * hs,uint32_t * out_mask_k,uint32_t * out_mask_a)684 static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
685 uint32_t *out_mask_k,
686 uint32_t *out_mask_a) {
687 SSL *const ssl = hs->ssl;
688 if (ssl3_protocol_version(ssl) >= TLS1_3_VERSION) {
689 *out_mask_k = SSL_kGENERIC;
690 *out_mask_a = SSL_aGENERIC;
691 return;
692 }
693
694 uint32_t mask_k = 0;
695 uint32_t mask_a = 0;
696
697 if (ssl_has_certificate(ssl)) {
698 int type = ssl_private_key_type(ssl);
699 if (type == NID_rsaEncryption) {
700 mask_k |= SSL_kRSA;
701 mask_a |= SSL_aRSA;
702 } else if (ssl_is_ecdsa_key_type(type)) {
703 mask_a |= SSL_aECDSA;
704 }
705 }
706
707 if (ssl->cert->dh_tmp != NULL || ssl->cert->dh_tmp_cb != NULL) {
708 mask_k |= SSL_kDHE;
709 }
710
711 /* Check for a shared group to consider ECDHE ciphers. */
712 uint16_t unused;
713 if (tls1_get_shared_group(hs, &unused)) {
714 mask_k |= SSL_kECDHE;
715 }
716
717 /* PSK requires a server callback. */
718 if (ssl->psk_server_callback != NULL) {
719 mask_k |= SSL_kPSK;
720 mask_a |= SSL_aPSK;
721 }
722
723 *out_mask_k = mask_k;
724 *out_mask_a = mask_a;
725 }
726
ssl3_choose_cipher(SSL_HANDSHAKE * hs,const SSL_CLIENT_HELLO * client_hello,const struct ssl_cipher_preference_list_st * server_pref)727 static const SSL_CIPHER *ssl3_choose_cipher(
728 SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
729 const struct ssl_cipher_preference_list_st *server_pref) {
730 SSL *const ssl = hs->ssl;
731 const SSL_CIPHER *c, *ret = NULL;
732 STACK_OF(SSL_CIPHER) *srvr = server_pref->ciphers, *prio, *allow;
733 int ok;
734 size_t cipher_index;
735 uint32_t alg_k, alg_a, mask_k, mask_a;
736 /* in_group_flags will either be NULL, or will point to an array of bytes
737 * which indicate equal-preference groups in the |prio| stack. See the
738 * comment about |in_group_flags| in the |ssl_cipher_preference_list_st|
739 * struct. */
740 const uint8_t *in_group_flags;
741 /* group_min contains the minimal index so far found in a group, or -1 if no
742 * such value exists yet. */
743 int group_min = -1;
744
745 STACK_OF(SSL_CIPHER) *clnt = ssl_parse_client_cipher_list(client_hello);
746 if (clnt == NULL) {
747 return NULL;
748 }
749
750 if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
751 prio = srvr;
752 in_group_flags = server_pref->in_group_flags;
753 allow = clnt;
754 } else {
755 prio = clnt;
756 in_group_flags = NULL;
757 allow = srvr;
758 }
759
760 ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
761
762 for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
763 c = sk_SSL_CIPHER_value(prio, i);
764
765 ok = 1;
766
767 /* Check the TLS version. */
768 if (SSL_CIPHER_get_min_version(c) > ssl3_protocol_version(ssl) ||
769 SSL_CIPHER_get_max_version(c) < ssl3_protocol_version(ssl)) {
770 ok = 0;
771 }
772
773 alg_k = c->algorithm_mkey;
774 alg_a = c->algorithm_auth;
775
776 ok = ok && (alg_k & mask_k) && (alg_a & mask_a);
777
778 if (ok && sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
779 if (in_group_flags != NULL && in_group_flags[i] == 1) {
780 /* This element of |prio| is in a group. Update the minimum index found
781 * so far and continue looking. */
782 if (group_min == -1 || (size_t)group_min > cipher_index) {
783 group_min = cipher_index;
784 }
785 } else {
786 if (group_min != -1 && (size_t)group_min < cipher_index) {
787 cipher_index = group_min;
788 }
789 ret = sk_SSL_CIPHER_value(allow, cipher_index);
790 break;
791 }
792 }
793
794 if (in_group_flags != NULL && in_group_flags[i] == 0 && group_min != -1) {
795 /* We are about to leave a group, but we found a match in it, so that's
796 * our answer. */
797 ret = sk_SSL_CIPHER_value(allow, group_min);
798 break;
799 }
800 }
801
802 sk_SSL_CIPHER_free(clnt);
803 return ret;
804 }
805
ssl3_process_client_hello(SSL_HANDSHAKE * hs)806 static int ssl3_process_client_hello(SSL_HANDSHAKE *hs) {
807 SSL *const ssl = hs->ssl;
808 if (!ssl_check_message_type(ssl, SSL3_MT_CLIENT_HELLO)) {
809 return -1;
810 }
811
812 SSL_CLIENT_HELLO client_hello;
813 if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
814 ssl->init_num)) {
815 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
816 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
817 return -1;
818 }
819
820 /* Run the early callback. */
821 if (ssl->ctx->select_certificate_cb != NULL) {
822 switch (ssl->ctx->select_certificate_cb(&client_hello)) {
823 case ssl_select_cert_retry:
824 ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
825 return -1;
826
827 case ssl_select_cert_error:
828 /* Connection rejected. */
829 OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
830 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
831 return -1;
832
833 default:
834 /* fallthrough */;
835 }
836 }
837
838 uint8_t alert = SSL_AD_DECODE_ERROR;
839 if (!negotiate_version(hs, &alert, &client_hello)) {
840 ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
841 return -1;
842 }
843
844 /* Load the client random. */
845 if (client_hello.random_len != SSL3_RANDOM_SIZE) {
846 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
847 return -1;
848 }
849 OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
850 client_hello.random_len);
851
852 /* Only null compression is supported. TLS 1.3 further requires the peer
853 * advertise no other compression. */
854 if (OPENSSL_memchr(client_hello.compression_methods, 0,
855 client_hello.compression_methods_len) == NULL ||
856 (ssl3_protocol_version(ssl) >= TLS1_3_VERSION &&
857 client_hello.compression_methods_len != 1)) {
858 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
859 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
860 return -1;
861 }
862
863 /* TLS extensions. */
864 if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
865 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
866 return -1;
867 }
868
869 return 1;
870 }
871
ssl3_select_certificate(SSL_HANDSHAKE * hs)872 static int ssl3_select_certificate(SSL_HANDSHAKE *hs) {
873 SSL *const ssl = hs->ssl;
874 /* Call |cert_cb| to update server certificates if required. */
875 if (ssl->cert->cert_cb != NULL) {
876 int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
877 if (rv == 0) {
878 OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
879 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
880 return -1;
881 }
882 if (rv < 0) {
883 ssl->rwstate = SSL_X509_LOOKUP;
884 return -1;
885 }
886 }
887
888 if (!ssl->ctx->x509_method->ssl_auto_chain_if_needed(ssl)) {
889 return -1;
890 }
891
892 if (ssl3_protocol_version(ssl) >= TLS1_3_VERSION) {
893 /* Jump to the TLS 1.3 state machine. */
894 hs->state = SSL_ST_TLS13;
895 hs->do_tls13_handshake = tls13_server_handshake;
896 return 1;
897 }
898
899 SSL_CLIENT_HELLO client_hello;
900 if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
901 ssl->init_num)) {
902 return -1;
903 }
904
905 /* Negotiate the cipher suite. This must be done after |cert_cb| so the
906 * certificate is finalized. */
907 hs->new_cipher =
908 ssl3_choose_cipher(hs, &client_hello, ssl_get_cipher_preferences(ssl));
909 if (hs->new_cipher == NULL) {
910 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
911 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
912 return -1;
913 }
914
915 return 1;
916 }
917
ssl3_select_parameters(SSL_HANDSHAKE * hs)918 static int ssl3_select_parameters(SSL_HANDSHAKE *hs) {
919 SSL *const ssl = hs->ssl;
920 uint8_t al = SSL_AD_INTERNAL_ERROR;
921 int ret = -1;
922 SSL_SESSION *session = NULL;
923
924 SSL_CLIENT_HELLO client_hello;
925 if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
926 ssl->init_num)) {
927 return -1;
928 }
929
930 /* Determine whether we are doing session resumption. */
931 int tickets_supported = 0, renew_ticket = 0;
932 switch (ssl_get_prev_session(ssl, &session, &tickets_supported, &renew_ticket,
933 &client_hello)) {
934 case ssl_session_success:
935 break;
936 case ssl_session_error:
937 goto err;
938 case ssl_session_retry:
939 ssl->rwstate = SSL_PENDING_SESSION;
940 goto err;
941 case ssl_session_ticket_retry:
942 ssl->rwstate = SSL_PENDING_TICKET;
943 goto err;
944 }
945
946 if (session != NULL) {
947 if (session->extended_master_secret && !hs->extended_master_secret) {
948 /* A ClientHello without EMS that attempts to resume a session with EMS
949 * is fatal to the connection. */
950 al = SSL_AD_HANDSHAKE_FAILURE;
951 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
952 goto f_err;
953 }
954
955 if (!ssl_session_is_resumable(hs, session) ||
956 /* If the client offers the EMS extension, but the previous session
957 * didn't use it, then negotiate a new session. */
958 hs->extended_master_secret != session->extended_master_secret) {
959 SSL_SESSION_free(session);
960 session = NULL;
961 }
962 }
963
964 if (session != NULL) {
965 /* Use the old session. */
966 hs->ticket_expected = renew_ticket;
967 ssl->session = session;
968 session = NULL;
969 ssl->s3->session_reused = 1;
970 } else {
971 hs->ticket_expected = tickets_supported;
972 ssl_set_session(ssl, NULL);
973 if (!ssl_get_new_session(hs, 1 /* server */)) {
974 goto err;
975 }
976
977 /* Clear the session ID if we want the session to be single-use. */
978 if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
979 hs->new_session->session_id_length = 0;
980 }
981 }
982
983 if (ssl->ctx->dos_protection_cb != NULL &&
984 ssl->ctx->dos_protection_cb(&client_hello) == 0) {
985 /* Connection rejected for DOS reasons. */
986 al = SSL_AD_INTERNAL_ERROR;
987 OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
988 goto f_err;
989 }
990
991 if (ssl->session == NULL) {
992 hs->new_session->cipher = hs->new_cipher;
993
994 /* On new sessions, stash the SNI value in the session. */
995 if (hs->hostname != NULL) {
996 OPENSSL_free(hs->new_session->tlsext_hostname);
997 hs->new_session->tlsext_hostname = BUF_strdup(hs->hostname);
998 if (hs->new_session->tlsext_hostname == NULL) {
999 al = SSL_AD_INTERNAL_ERROR;
1000 goto f_err;
1001 }
1002 }
1003
1004 /* Determine whether to request a client certificate. */
1005 hs->cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
1006 /* Only request a certificate if Channel ID isn't negotiated. */
1007 if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
1008 ssl->s3->tlsext_channel_id_valid) {
1009 hs->cert_request = 0;
1010 }
1011 /* CertificateRequest may only be sent in certificate-based ciphers. */
1012 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1013 hs->cert_request = 0;
1014 }
1015
1016 if (!hs->cert_request) {
1017 /* OpenSSL returns X509_V_OK when no certificates are requested. This is
1018 * classed by them as a bug, but it's assumed by at least NGINX. */
1019 hs->new_session->verify_result = X509_V_OK;
1020 }
1021 }
1022
1023 /* HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
1024 * deferred. Complete it now. */
1025 if (!ssl_negotiate_alpn(hs, &al, &client_hello)) {
1026 goto f_err;
1027 }
1028
1029 /* Now that all parameters are known, initialize the handshake hash and hash
1030 * the ClientHello. */
1031 if (!SSL_TRANSCRIPT_init_hash(&hs->transcript, ssl3_protocol_version(ssl),
1032 hs->new_cipher->algorithm_prf) ||
1033 !ssl_hash_current_message(hs)) {
1034 goto f_err;
1035 }
1036
1037 /* Release the handshake buffer if client authentication isn't required. */
1038 if (!hs->cert_request) {
1039 SSL_TRANSCRIPT_free_buffer(&hs->transcript);
1040 }
1041
1042 ret = 1;
1043
1044 if (0) {
1045 f_err:
1046 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1047 }
1048
1049 err:
1050 SSL_SESSION_free(session);
1051 return ret;
1052 }
1053
ssl3_send_server_hello(SSL_HANDSHAKE * hs)1054 static int ssl3_send_server_hello(SSL_HANDSHAKE *hs) {
1055 SSL *const ssl = hs->ssl;
1056
1057 /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
1058 * known attack while we fix ChannelID itself. */
1059 if (ssl->s3->tlsext_channel_id_valid &&
1060 (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
1061 ssl->s3->tlsext_channel_id_valid = 0;
1062 }
1063
1064 /* If this is a resumption and the original handshake didn't support
1065 * ChannelID then we didn't record the original handshake hashes in the
1066 * session and so cannot resume with ChannelIDs. */
1067 if (ssl->session != NULL &&
1068 ssl->session->original_handshake_hash_len == 0) {
1069 ssl->s3->tlsext_channel_id_valid = 0;
1070 }
1071
1072 struct OPENSSL_timeval now;
1073 ssl_get_current_time(ssl, &now);
1074 ssl->s3->server_random[0] = now.tv_sec >> 24;
1075 ssl->s3->server_random[1] = now.tv_sec >> 16;
1076 ssl->s3->server_random[2] = now.tv_sec >> 8;
1077 ssl->s3->server_random[3] = now.tv_sec;
1078 if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
1079 return -1;
1080 }
1081
1082 /* TODO(davidben): Implement the TLS 1.1 and 1.2 downgrade sentinels once TLS
1083 * 1.3 is finalized and we are not implementing a draft version. */
1084
1085 const SSL_SESSION *session = hs->new_session;
1086 if (ssl->session != NULL) {
1087 session = ssl->session;
1088 }
1089
1090 CBB cbb, body, session_id;
1091 if (!ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_SERVER_HELLO) ||
1092 !CBB_add_u16(&body, ssl->version) ||
1093 !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
1094 !CBB_add_u8_length_prefixed(&body, &session_id) ||
1095 !CBB_add_bytes(&session_id, session->session_id,
1096 session->session_id_length) ||
1097 !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
1098 !CBB_add_u8(&body, 0 /* no compression */) ||
1099 !ssl_add_serverhello_tlsext(hs, &body) ||
1100 !ssl_add_message_cbb(ssl, &cbb)) {
1101 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1102 CBB_cleanup(&cbb);
1103 return -1;
1104 }
1105
1106 return 1;
1107 }
1108
ssl3_send_server_certificate(SSL_HANDSHAKE * hs)1109 static int ssl3_send_server_certificate(SSL_HANDSHAKE *hs) {
1110 SSL *const ssl = hs->ssl;
1111 if (!ssl_has_certificate(ssl)) {
1112 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
1113 return -1;
1114 }
1115
1116 if (!ssl3_output_cert_chain(ssl)) {
1117 return -1;
1118 }
1119 return 1;
1120 }
1121
ssl3_send_certificate_status(SSL_HANDSHAKE * hs)1122 static int ssl3_send_certificate_status(SSL_HANDSHAKE *hs) {
1123 SSL *const ssl = hs->ssl;
1124 CBB cbb, body, ocsp_response;
1125 if (!ssl->method->init_message(ssl, &cbb, &body,
1126 SSL3_MT_CERTIFICATE_STATUS) ||
1127 !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
1128 !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
1129 !CBB_add_bytes(&ocsp_response,
1130 CRYPTO_BUFFER_data(ssl->cert->ocsp_response),
1131 CRYPTO_BUFFER_len(ssl->cert->ocsp_response)) ||
1132 !ssl_add_message_cbb(ssl, &cbb)) {
1133 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1134 CBB_cleanup(&cbb);
1135 return -1;
1136 }
1137
1138 return 1;
1139 }
1140
ssl3_send_server_key_exchange(SSL_HANDSHAKE * hs)1141 static int ssl3_send_server_key_exchange(SSL_HANDSHAKE *hs) {
1142 SSL *const ssl = hs->ssl;
1143 CBB cbb, child;
1144 CBB_zero(&cbb);
1145
1146 /* Put together the parameters. */
1147 if (hs->state == SSL3_ST_SW_KEY_EXCH_A) {
1148 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1149 uint32_t alg_a = hs->new_cipher->algorithm_auth;
1150
1151 /* Pre-allocate enough room to comfortably fit an ECDHE public key. */
1152 if (!CBB_init(&cbb, 128)) {
1153 goto err;
1154 }
1155
1156 /* PSK ciphers begin with an identity hint. */
1157 if (alg_a & SSL_aPSK) {
1158 size_t len =
1159 (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
1160 if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1161 !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
1162 len)) {
1163 goto err;
1164 }
1165 }
1166
1167 if (alg_k & SSL_kDHE) {
1168 /* Determine the group to use. */
1169 DH *params = ssl->cert->dh_tmp;
1170 if (params == NULL && ssl->cert->dh_tmp_cb != NULL) {
1171 params = ssl->cert->dh_tmp_cb(ssl, 0, 1024);
1172 }
1173 if (params == NULL) {
1174 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_DH_KEY);
1175 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1176 goto err;
1177 }
1178
1179 /* Set up DH, generate a key, and emit the public half. */
1180 DH *dh = DHparams_dup(params);
1181 if (dh == NULL) {
1182 goto err;
1183 }
1184
1185 SSL_ECDH_CTX_init_for_dhe(&hs->ecdh_ctx, dh);
1186 if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1187 !BN_bn2cbb_padded(&child, BN_num_bytes(params->p), params->p) ||
1188 !CBB_add_u16_length_prefixed(&cbb, &child) ||
1189 !BN_bn2cbb_padded(&child, BN_num_bytes(params->g), params->g) ||
1190 !CBB_add_u16_length_prefixed(&cbb, &child) ||
1191 !SSL_ECDH_CTX_offer(&hs->ecdh_ctx, &child)) {
1192 goto err;
1193 }
1194 } else if (alg_k & SSL_kECDHE) {
1195 /* Determine the group to use. */
1196 uint16_t group_id;
1197 if (!tls1_get_shared_group(hs, &group_id)) {
1198 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_ECDH_KEY);
1199 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1200 goto err;
1201 }
1202 hs->new_session->group_id = group_id;
1203
1204 /* Set up ECDH, generate a key, and emit the public half. */
1205 if (!SSL_ECDH_CTX_init(&hs->ecdh_ctx, group_id) ||
1206 !CBB_add_u8(&cbb, NAMED_CURVE_TYPE) ||
1207 !CBB_add_u16(&cbb, group_id) ||
1208 !CBB_add_u8_length_prefixed(&cbb, &child) ||
1209 !SSL_ECDH_CTX_offer(&hs->ecdh_ctx, &child)) {
1210 goto err;
1211 }
1212 } else {
1213 assert(alg_k & SSL_kPSK);
1214 }
1215
1216 if (!CBB_finish(&cbb, &hs->server_params, &hs->server_params_len)) {
1217 goto err;
1218 }
1219 }
1220
1221 /* Assemble the message. */
1222 CBB body;
1223 if (!ssl->method->init_message(ssl, &cbb, &body,
1224 SSL3_MT_SERVER_KEY_EXCHANGE) ||
1225 !CBB_add_bytes(&body, hs->server_params, hs->server_params_len)) {
1226 goto err;
1227 }
1228
1229 /* Add a signature. */
1230 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1231 if (!ssl_has_private_key(ssl)) {
1232 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1233 goto err;
1234 }
1235
1236 /* Determine the signature algorithm. */
1237 uint16_t signature_algorithm;
1238 if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
1239 goto err;
1240 }
1241 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1242 if (!CBB_add_u16(&body, signature_algorithm)) {
1243 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1244 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1245 goto err;
1246 }
1247 }
1248
1249 /* Add space for the signature. */
1250 const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
1251 uint8_t *ptr;
1252 if (!CBB_add_u16_length_prefixed(&body, &child) ||
1253 !CBB_reserve(&child, &ptr, max_sig_len)) {
1254 goto err;
1255 }
1256
1257 size_t sig_len;
1258 enum ssl_private_key_result_t sign_result;
1259 if (hs->state == SSL3_ST_SW_KEY_EXCH_A) {
1260 CBB transcript;
1261 uint8_t *transcript_data;
1262 size_t transcript_len;
1263 if (!CBB_init(&transcript,
1264 2 * SSL3_RANDOM_SIZE + hs->server_params_len) ||
1265 !CBB_add_bytes(&transcript, ssl->s3->client_random,
1266 SSL3_RANDOM_SIZE) ||
1267 !CBB_add_bytes(&transcript, ssl->s3->server_random,
1268 SSL3_RANDOM_SIZE) ||
1269 !CBB_add_bytes(&transcript, hs->server_params,
1270 hs->server_params_len) ||
1271 !CBB_finish(&transcript, &transcript_data, &transcript_len)) {
1272 CBB_cleanup(&transcript);
1273 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1274 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1275 goto err;
1276 }
1277
1278 sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len,
1279 signature_algorithm, transcript_data,
1280 transcript_len);
1281 OPENSSL_free(transcript_data);
1282 } else {
1283 assert(hs->state == SSL3_ST_SW_KEY_EXCH_B);
1284 sign_result = ssl_private_key_complete(ssl, ptr, &sig_len, max_sig_len);
1285 }
1286
1287 switch (sign_result) {
1288 case ssl_private_key_success:
1289 if (!CBB_did_write(&child, sig_len)) {
1290 goto err;
1291 }
1292 break;
1293 case ssl_private_key_failure:
1294 goto err;
1295 case ssl_private_key_retry:
1296 ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
1297 hs->state = SSL3_ST_SW_KEY_EXCH_B;
1298 goto err;
1299 }
1300 }
1301
1302 if (!ssl_add_message_cbb(ssl, &cbb)) {
1303 goto err;
1304 }
1305
1306 OPENSSL_free(hs->server_params);
1307 hs->server_params = NULL;
1308 hs->server_params_len = 0;
1309
1310 return 1;
1311
1312 err:
1313 CBB_cleanup(&cbb);
1314 return -1;
1315 }
1316
add_cert_types(SSL * ssl,CBB * cbb)1317 static int add_cert_types(SSL *ssl, CBB *cbb) {
1318 /* Get configured signature algorithms. */
1319 int have_rsa_sign = 0;
1320 int have_ecdsa_sign = 0;
1321 const uint16_t *sig_algs;
1322 size_t num_sig_algs = tls12_get_verify_sigalgs(ssl, &sig_algs);
1323 for (size_t i = 0; i < num_sig_algs; i++) {
1324 switch (sig_algs[i]) {
1325 case SSL_SIGN_RSA_PKCS1_SHA512:
1326 case SSL_SIGN_RSA_PKCS1_SHA384:
1327 case SSL_SIGN_RSA_PKCS1_SHA256:
1328 case SSL_SIGN_RSA_PKCS1_SHA1:
1329 have_rsa_sign = 1;
1330 break;
1331
1332 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
1333 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
1334 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
1335 case SSL_SIGN_ECDSA_SHA1:
1336 have_ecdsa_sign = 1;
1337 break;
1338 }
1339 }
1340
1341 if (have_rsa_sign && !CBB_add_u8(cbb, SSL3_CT_RSA_SIGN)) {
1342 return 0;
1343 }
1344
1345 /* ECDSA certs can be used with RSA cipher suites as well so we don't need to
1346 * check for SSL_kECDH or SSL_kECDHE. */
1347 if (ssl->version >= TLS1_VERSION && have_ecdsa_sign &&
1348 !CBB_add_u8(cbb, TLS_CT_ECDSA_SIGN)) {
1349 return 0;
1350 }
1351
1352 return 1;
1353 }
1354
ssl3_send_certificate_request(SSL_HANDSHAKE * hs)1355 static int ssl3_send_certificate_request(SSL_HANDSHAKE *hs) {
1356 SSL *const ssl = hs->ssl;
1357 CBB cbb, body, cert_types, sigalgs_cbb;
1358 if (!ssl->method->init_message(ssl, &cbb, &body,
1359 SSL3_MT_CERTIFICATE_REQUEST) ||
1360 !CBB_add_u8_length_prefixed(&body, &cert_types) ||
1361 !add_cert_types(ssl, &cert_types)) {
1362 goto err;
1363 }
1364
1365 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1366 const uint16_t *sigalgs;
1367 size_t num_sigalgs = tls12_get_verify_sigalgs(ssl, &sigalgs);
1368 if (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb)) {
1369 goto err;
1370 }
1371
1372 for (size_t i = 0; i < num_sigalgs; i++) {
1373 if (!CBB_add_u16(&sigalgs_cbb, sigalgs[i])) {
1374 goto err;
1375 }
1376 }
1377 }
1378
1379 if (!ssl_add_client_CA_list(ssl, &body) ||
1380 !ssl_add_message_cbb(ssl, &cbb)) {
1381 goto err;
1382 }
1383
1384 return 1;
1385
1386 err:
1387 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1388 CBB_cleanup(&cbb);
1389 return -1;
1390 }
1391
ssl3_send_server_hello_done(SSL_HANDSHAKE * hs)1392 static int ssl3_send_server_hello_done(SSL_HANDSHAKE *hs) {
1393 SSL *const ssl = hs->ssl;
1394 CBB cbb, body;
1395 if (!ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_SERVER_HELLO_DONE) ||
1396 !ssl_add_message_cbb(ssl, &cbb)) {
1397 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1398 CBB_cleanup(&cbb);
1399 return -1;
1400 }
1401
1402 return 1;
1403 }
1404
ssl3_get_client_certificate(SSL_HANDSHAKE * hs)1405 static int ssl3_get_client_certificate(SSL_HANDSHAKE *hs) {
1406 SSL *const ssl = hs->ssl;
1407 assert(hs->cert_request);
1408
1409 int msg_ret = ssl->method->ssl_get_message(ssl);
1410 if (msg_ret <= 0) {
1411 return msg_ret;
1412 }
1413
1414 if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
1415 if (ssl->version == SSL3_VERSION &&
1416 ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
1417 /* In SSL 3.0, the Certificate message is omitted to signal no
1418 * certificate. */
1419 if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1420 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1421 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1422 return -1;
1423 }
1424
1425 /* OpenSSL returns X509_V_OK when no certificates are received. This is
1426 * classed by them as a bug, but it's assumed by at least NGINX. */
1427 hs->new_session->verify_result = X509_V_OK;
1428 ssl->s3->tmp.reuse_message = 1;
1429 return 1;
1430 }
1431
1432 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1433 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1434 return -1;
1435 }
1436
1437 if (!ssl_hash_current_message(hs)) {
1438 return -1;
1439 }
1440
1441 CBS certificate_msg;
1442 CBS_init(&certificate_msg, ssl->init_msg, ssl->init_num);
1443
1444 sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
1445 EVP_PKEY_free(hs->peer_pubkey);
1446 hs->peer_pubkey = NULL;
1447 uint8_t alert = SSL_AD_DECODE_ERROR;
1448 hs->new_session->certs = ssl_parse_cert_chain(
1449 &alert, &hs->peer_pubkey,
1450 ssl->retain_only_sha256_of_client_certs ? hs->new_session->peer_sha256
1451 : NULL,
1452 &certificate_msg, ssl->ctx->pool);
1453 if (hs->new_session->certs == NULL) {
1454 ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
1455 return -1;
1456 }
1457
1458 if (CBS_len(&certificate_msg) != 0 ||
1459 !ssl->ctx->x509_method->session_cache_objects(hs->new_session)) {
1460 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1461 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1462 return -1;
1463 }
1464
1465 if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) == 0) {
1466 /* No client certificate so the handshake buffer may be discarded. */
1467 SSL_TRANSCRIPT_free_buffer(&hs->transcript);
1468
1469 /* In SSL 3.0, sending no certificate is signaled by omitting the
1470 * Certificate message. */
1471 if (ssl->version == SSL3_VERSION) {
1472 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
1473 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1474 return -1;
1475 }
1476
1477 if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1478 /* Fail for TLS only if we required a certificate */
1479 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1480 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1481 return -1;
1482 }
1483
1484 /* OpenSSL returns X509_V_OK when no certificates are received. This is
1485 * classed by them as a bug, but it's assumed by at least NGINX. */
1486 hs->new_session->verify_result = X509_V_OK;
1487 return 1;
1488 }
1489
1490 /* The hash will have been filled in. */
1491 if (ssl->retain_only_sha256_of_client_certs) {
1492 hs->new_session->peer_sha256_valid = 1;
1493 }
1494
1495 if (!ssl->ctx->x509_method->session_verify_cert_chain(hs->new_session, ssl)) {
1496 return -1;
1497 }
1498
1499 return 1;
1500 }
1501
ssl3_get_client_key_exchange(SSL_HANDSHAKE * hs)1502 static int ssl3_get_client_key_exchange(SSL_HANDSHAKE *hs) {
1503 SSL *const ssl = hs->ssl;
1504 int al;
1505 CBS client_key_exchange;
1506 uint32_t alg_k;
1507 uint32_t alg_a;
1508 uint8_t *premaster_secret = NULL;
1509 size_t premaster_secret_len = 0;
1510 uint8_t *decrypt_buf = NULL;
1511
1512 unsigned psk_len = 0;
1513 uint8_t psk[PSK_MAX_PSK_LEN];
1514
1515 if (hs->state == SSL3_ST_SR_KEY_EXCH_A) {
1516 int ret = ssl->method->ssl_get_message(ssl);
1517 if (ret <= 0) {
1518 return ret;
1519 }
1520
1521 if (!ssl_check_message_type(ssl, SSL3_MT_CLIENT_KEY_EXCHANGE) ||
1522 !ssl_hash_current_message(hs)) {
1523 return -1;
1524 }
1525 }
1526
1527 CBS_init(&client_key_exchange, ssl->init_msg, ssl->init_num);
1528 alg_k = hs->new_cipher->algorithm_mkey;
1529 alg_a = hs->new_cipher->algorithm_auth;
1530
1531 /* If using a PSK key exchange, prepare the pre-shared key. */
1532 if (alg_a & SSL_aPSK) {
1533 CBS psk_identity;
1534
1535 /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1536 * then this is the only field in the message. */
1537 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1538 ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1539 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1540 al = SSL_AD_DECODE_ERROR;
1541 goto f_err;
1542 }
1543
1544 if (ssl->psk_server_callback == NULL) {
1545 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_SERVER_CB);
1546 al = SSL_AD_INTERNAL_ERROR;
1547 goto f_err;
1548 }
1549
1550 if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1551 CBS_contains_zero_byte(&psk_identity)) {
1552 OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1553 al = SSL_AD_ILLEGAL_PARAMETER;
1554 goto f_err;
1555 }
1556
1557 if (!CBS_strdup(&psk_identity, &hs->new_session->psk_identity)) {
1558 al = SSL_AD_INTERNAL_ERROR;
1559 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1560 goto f_err;
1561 }
1562
1563 /* Look up the key for the identity. */
1564 psk_len = ssl->psk_server_callback(ssl, hs->new_session->psk_identity, psk,
1565 sizeof(psk));
1566 if (psk_len > PSK_MAX_PSK_LEN) {
1567 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1568 al = SSL_AD_INTERNAL_ERROR;
1569 goto f_err;
1570 } else if (psk_len == 0) {
1571 /* PSK related to the given identity not found */
1572 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1573 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1574 goto f_err;
1575 }
1576 }
1577
1578 /* Depending on the key exchange method, compute |premaster_secret| and
1579 * |premaster_secret_len|. */
1580 if (alg_k & SSL_kRSA) {
1581 /* Allocate a buffer large enough for an RSA decryption. */
1582 const size_t rsa_size = ssl_private_key_max_signature_len(ssl);
1583 decrypt_buf = OPENSSL_malloc(rsa_size);
1584 if (decrypt_buf == NULL) {
1585 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1586 goto err;
1587 }
1588
1589 enum ssl_private_key_result_t decrypt_result;
1590 size_t decrypt_len;
1591 if (hs->state == SSL3_ST_SR_KEY_EXCH_A) {
1592 if (!ssl_has_private_key(ssl) ||
1593 ssl_private_key_type(ssl) != NID_rsaEncryption) {
1594 al = SSL_AD_HANDSHAKE_FAILURE;
1595 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_RSA_CERTIFICATE);
1596 goto f_err;
1597 }
1598 CBS encrypted_premaster_secret;
1599 if (ssl->version > SSL3_VERSION) {
1600 if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1601 &encrypted_premaster_secret) ||
1602 CBS_len(&client_key_exchange) != 0) {
1603 al = SSL_AD_DECODE_ERROR;
1604 OPENSSL_PUT_ERROR(SSL,
1605 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1606 goto f_err;
1607 }
1608 } else {
1609 encrypted_premaster_secret = client_key_exchange;
1610 }
1611
1612 /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
1613 * timing-sensitive code below. */
1614 decrypt_result = ssl_private_key_decrypt(
1615 ssl, decrypt_buf, &decrypt_len, rsa_size,
1616 CBS_data(&encrypted_premaster_secret),
1617 CBS_len(&encrypted_premaster_secret));
1618 } else {
1619 assert(hs->state == SSL3_ST_SR_KEY_EXCH_B);
1620 /* Complete async decrypt. */
1621 decrypt_result =
1622 ssl_private_key_complete(ssl, decrypt_buf, &decrypt_len, rsa_size);
1623 }
1624
1625 switch (decrypt_result) {
1626 case ssl_private_key_success:
1627 break;
1628 case ssl_private_key_failure:
1629 goto err;
1630 case ssl_private_key_retry:
1631 ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
1632 hs->state = SSL3_ST_SR_KEY_EXCH_B;
1633 goto err;
1634 }
1635
1636 if (decrypt_len != rsa_size) {
1637 al = SSL_AD_DECRYPT_ERROR;
1638 OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1639 goto f_err;
1640 }
1641
1642 /* Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1643 * section 7.4.7.1. */
1644 premaster_secret_len = SSL_MAX_MASTER_KEY_LENGTH;
1645 premaster_secret = OPENSSL_malloc(premaster_secret_len);
1646 if (premaster_secret == NULL) {
1647 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1648 goto err;
1649 }
1650 if (!RAND_bytes(premaster_secret, premaster_secret_len)) {
1651 goto err;
1652 }
1653
1654 /* The smallest padded premaster is 11 bytes of overhead. Small keys are
1655 * publicly invalid. */
1656 if (decrypt_len < 11 + premaster_secret_len) {
1657 al = SSL_AD_DECRYPT_ERROR;
1658 OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1659 goto f_err;
1660 }
1661
1662 /* Check the padding. See RFC 3447, section 7.2.2. */
1663 size_t padding_len = decrypt_len - premaster_secret_len;
1664 uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1665 constant_time_eq_int_8(decrypt_buf[1], 2);
1666 for (size_t i = 2; i < padding_len - 1; i++) {
1667 good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1668 }
1669 good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1670
1671 /* The premaster secret must begin with |client_version|. This too must be
1672 * checked in constant time (http://eprint.iacr.org/2003/052/). */
1673 good &= constant_time_eq_8(decrypt_buf[padding_len],
1674 (unsigned)(hs->client_version >> 8));
1675 good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1676 (unsigned)(hs->client_version & 0xff));
1677
1678 /* Select, in constant time, either the decrypted premaster or the random
1679 * premaster based on |good|. */
1680 for (size_t i = 0; i < premaster_secret_len; i++) {
1681 premaster_secret[i] = constant_time_select_8(
1682 good, decrypt_buf[padding_len + i], premaster_secret[i]);
1683 }
1684
1685 OPENSSL_free(decrypt_buf);
1686 decrypt_buf = NULL;
1687 } else if (alg_k & (SSL_kECDHE|SSL_kDHE)) {
1688 /* Parse the ClientKeyExchange. */
1689 CBS peer_key;
1690 if (!SSL_ECDH_CTX_get_key(&hs->ecdh_ctx, &client_key_exchange, &peer_key) ||
1691 CBS_len(&client_key_exchange) != 0) {
1692 al = SSL_AD_DECODE_ERROR;
1693 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1694 goto f_err;
1695 }
1696
1697 /* Compute the premaster. */
1698 uint8_t alert = SSL_AD_DECODE_ERROR;
1699 if (!SSL_ECDH_CTX_finish(&hs->ecdh_ctx, &premaster_secret,
1700 &premaster_secret_len, &alert, CBS_data(&peer_key),
1701 CBS_len(&peer_key))) {
1702 al = alert;
1703 goto f_err;
1704 }
1705
1706 /* The key exchange state may now be discarded. */
1707 SSL_ECDH_CTX_cleanup(&hs->ecdh_ctx);
1708 } else if (alg_k & SSL_kPSK) {
1709 /* For plain PSK, other_secret is a block of 0s with the same length as the
1710 * pre-shared key. */
1711 premaster_secret_len = psk_len;
1712 premaster_secret = OPENSSL_malloc(premaster_secret_len);
1713 if (premaster_secret == NULL) {
1714 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1715 goto err;
1716 }
1717 OPENSSL_memset(premaster_secret, 0, premaster_secret_len);
1718 } else {
1719 al = SSL_AD_HANDSHAKE_FAILURE;
1720 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_TYPE);
1721 goto f_err;
1722 }
1723
1724 /* For a PSK cipher suite, the actual pre-master secret is combined with the
1725 * pre-shared key. */
1726 if (alg_a & SSL_aPSK) {
1727 CBB new_premaster, child;
1728 uint8_t *new_data;
1729 size_t new_len;
1730
1731 CBB_zero(&new_premaster);
1732 if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len) ||
1733 !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1734 !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
1735 !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
1736 !CBB_add_bytes(&child, psk, psk_len) ||
1737 !CBB_finish(&new_premaster, &new_data, &new_len)) {
1738 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1739 CBB_cleanup(&new_premaster);
1740 goto err;
1741 }
1742
1743 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1744 OPENSSL_free(premaster_secret);
1745 premaster_secret = new_data;
1746 premaster_secret_len = new_len;
1747 }
1748
1749 /* Compute the master secret */
1750 hs->new_session->master_key_length = tls1_generate_master_secret(
1751 hs, hs->new_session->master_key, premaster_secret, premaster_secret_len);
1752 if (hs->new_session->master_key_length == 0) {
1753 goto err;
1754 }
1755 hs->new_session->extended_master_secret = hs->extended_master_secret;
1756
1757 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1758 OPENSSL_free(premaster_secret);
1759 return 1;
1760
1761 f_err:
1762 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1763 err:
1764 if (premaster_secret != NULL) {
1765 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
1766 OPENSSL_free(premaster_secret);
1767 }
1768 OPENSSL_free(decrypt_buf);
1769
1770 return -1;
1771 }
1772
ssl3_get_cert_verify(SSL_HANDSHAKE * hs)1773 static int ssl3_get_cert_verify(SSL_HANDSHAKE *hs) {
1774 SSL *const ssl = hs->ssl;
1775 int al;
1776 CBS certificate_verify, signature;
1777
1778 /* Only RSA and ECDSA client certificates are supported, so a
1779 * CertificateVerify is required if and only if there's a client certificate.
1780 * */
1781 if (hs->peer_pubkey == NULL) {
1782 SSL_TRANSCRIPT_free_buffer(&hs->transcript);
1783 return 1;
1784 }
1785
1786 int msg_ret = ssl->method->ssl_get_message(ssl);
1787 if (msg_ret <= 0) {
1788 return msg_ret;
1789 }
1790
1791 if (!ssl_check_message_type(ssl, SSL3_MT_CERTIFICATE_VERIFY)) {
1792 return -1;
1793 }
1794
1795 CBS_init(&certificate_verify, ssl->init_msg, ssl->init_num);
1796
1797 /* Determine the digest type if needbe. */
1798 uint16_t signature_algorithm = 0;
1799 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1800 if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
1801 al = SSL_AD_DECODE_ERROR;
1802 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1803 goto f_err;
1804 }
1805 if (!tls12_check_peer_sigalg(ssl, &al, signature_algorithm)) {
1806 goto f_err;
1807 }
1808 hs->new_session->peer_signature_algorithm = signature_algorithm;
1809 } else if (hs->peer_pubkey->type == EVP_PKEY_RSA) {
1810 signature_algorithm = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
1811 } else if (hs->peer_pubkey->type == EVP_PKEY_EC) {
1812 signature_algorithm = SSL_SIGN_ECDSA_SHA1;
1813 } else {
1814 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1815 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1816 goto f_err;
1817 }
1818
1819 /* Parse and verify the signature. */
1820 if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1821 CBS_len(&certificate_verify) != 0) {
1822 al = SSL_AD_DECODE_ERROR;
1823 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1824 goto f_err;
1825 }
1826
1827 int sig_ok;
1828 /* The SSL3 construction for CertificateVerify does not decompose into a
1829 * single final digest and signature, and must be special-cased. */
1830 if (ssl3_protocol_version(ssl) == SSL3_VERSION) {
1831 uint8_t digest[EVP_MAX_MD_SIZE];
1832 size_t digest_len;
1833 if (!SSL_TRANSCRIPT_ssl3_cert_verify_hash(&hs->transcript, digest,
1834 &digest_len, hs->new_session,
1835 signature_algorithm)) {
1836 goto err;
1837 }
1838
1839 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(hs->peer_pubkey, NULL);
1840 sig_ok = pctx != NULL &&
1841 EVP_PKEY_verify_init(pctx) &&
1842 EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
1843 digest, digest_len);
1844 EVP_PKEY_CTX_free(pctx);
1845 } else {
1846 sig_ok = ssl_public_key_verify(
1847 ssl, CBS_data(&signature), CBS_len(&signature), signature_algorithm,
1848 hs->peer_pubkey, (const uint8_t *)hs->transcript.buffer->data,
1849 hs->transcript.buffer->length);
1850 }
1851
1852 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1853 sig_ok = 1;
1854 ERR_clear_error();
1855 #endif
1856 if (!sig_ok) {
1857 al = SSL_AD_DECRYPT_ERROR;
1858 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1859 goto f_err;
1860 }
1861
1862 /* The handshake buffer is no longer necessary, and we may hash the current
1863 * message.*/
1864 SSL_TRANSCRIPT_free_buffer(&hs->transcript);
1865 if (!ssl_hash_current_message(hs)) {
1866 goto err;
1867 }
1868
1869 return 1;
1870
1871 f_err:
1872 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1873 err:
1874 return 0;
1875 }
1876
1877 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
1878 * sets the next_proto member in s if found */
ssl3_get_next_proto(SSL_HANDSHAKE * hs)1879 static int ssl3_get_next_proto(SSL_HANDSHAKE *hs) {
1880 SSL *const ssl = hs->ssl;
1881 int ret = ssl->method->ssl_get_message(ssl);
1882 if (ret <= 0) {
1883 return ret;
1884 }
1885
1886 if (!ssl_check_message_type(ssl, SSL3_MT_NEXT_PROTO) ||
1887 !ssl_hash_current_message(hs)) {
1888 return -1;
1889 }
1890
1891 CBS next_protocol, selected_protocol, padding;
1892 CBS_init(&next_protocol, ssl->init_msg, ssl->init_num);
1893 if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1894 !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1895 CBS_len(&next_protocol) != 0) {
1896 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1897 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1898 return 0;
1899 }
1900
1901 if (!CBS_stow(&selected_protocol, &ssl->s3->next_proto_negotiated,
1902 &ssl->s3->next_proto_negotiated_len)) {
1903 return 0;
1904 }
1905
1906 return 1;
1907 }
1908
1909 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
ssl3_get_channel_id(SSL_HANDSHAKE * hs)1910 static int ssl3_get_channel_id(SSL_HANDSHAKE *hs) {
1911 SSL *const ssl = hs->ssl;
1912 int msg_ret = ssl->method->ssl_get_message(ssl);
1913 if (msg_ret <= 0) {
1914 return msg_ret;
1915 }
1916
1917 if (!ssl_check_message_type(ssl, SSL3_MT_CHANNEL_ID) ||
1918 !tls1_verify_channel_id(hs) ||
1919 !ssl_hash_current_message(hs)) {
1920 return -1;
1921 }
1922 return 1;
1923 }
1924
ssl3_send_new_session_ticket(SSL_HANDSHAKE * hs)1925 static int ssl3_send_new_session_ticket(SSL_HANDSHAKE *hs) {
1926 SSL *const ssl = hs->ssl;
1927 const SSL_SESSION *session;
1928 SSL_SESSION *session_copy = NULL;
1929 if (ssl->session == NULL) {
1930 /* Fix the timeout to measure from the ticket issuance time. */
1931 ssl_session_rebase_time(ssl, hs->new_session);
1932 session = hs->new_session;
1933 } else {
1934 /* We are renewing an existing session. Duplicate the session to adjust the
1935 * timeout. */
1936 session_copy = SSL_SESSION_dup(ssl->session, SSL_SESSION_INCLUDE_NONAUTH);
1937 if (session_copy == NULL) {
1938 return -1;
1939 }
1940
1941 ssl_session_rebase_time(ssl, session_copy);
1942 session = session_copy;
1943 }
1944
1945 CBB cbb, body, ticket;
1946 int ok =
1947 ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_NEW_SESSION_TICKET) &&
1948 CBB_add_u32(&body, session->timeout) &&
1949 CBB_add_u16_length_prefixed(&body, &ticket) &&
1950 ssl_encrypt_ticket(ssl, &ticket, session) &&
1951 ssl_add_message_cbb(ssl, &cbb);
1952
1953 SSL_SESSION_free(session_copy);
1954 CBB_cleanup(&cbb);
1955
1956 if (!ok) {
1957 return -1;
1958 }
1959
1960 return 1;
1961 }
1962