Debian Codegraph @

external/boringssl/ssl/handshake_client.c

raw
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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 * [email protected].
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 * ([email protected]). This product includes software written by Tim
107 * Hudson ([email protected]).
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
150 #include <openssl/ssl.h>
151
152 #include <assert.h>
153 #include <string.h>
154
155 #include <openssl/bn.h>
156 #include <openssl/buf.h>
157 #include <openssl/bytestring.h>
158 #include <openssl/dh.h>
159 #include <openssl/ec_key.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/err.h>
162 #include <openssl/evp.h>
163 #include <openssl/md5.h>
164 #include <openssl/mem.h>
165 #include <openssl/rand.h>
166 #include <openssl/x509.h>
167 #include <openssl/x509v3.h>
168
169 #include "internal.h"
170 #include "../crypto/dh/internal.h"
171
172
173 static int ssl3_send_client_hello(SSL *ssl);
174 static int dtls1_get_hello_verify(SSL *ssl);
175 static int ssl3_get_server_hello(SSL *ssl);
176 static int ssl3_get_server_certificate(SSL *ssl);
177 static int ssl3_get_cert_status(SSL *ssl);
178 static int ssl3_verify_server_cert(SSL *ssl);
179 static int ssl3_get_server_key_exchange(SSL *ssl);
180 static int ssl3_get_certificate_request(SSL *ssl);
181 static int ssl3_get_server_hello_done(SSL *ssl);
182 static int ssl3_send_client_certificate(SSL *ssl);
183 static int ssl3_send_client_key_exchange(SSL *ssl);
184 static int ssl3_send_cert_verify(SSL *ssl);
185 static int ssl3_send_next_proto(SSL *ssl);
186 static int ssl3_send_channel_id(SSL *ssl);
187 static int ssl3_get_new_session_ticket(SSL *ssl);
188
189 int ssl3_connect(SSL *ssl) {
190 BUF_MEM *buf = NULL;
191 int ret = -1;
192 int state, skip = 0;
193
194 assert(ssl->handshake_func == ssl3_connect);
195 assert(!ssl->server);
196
197 for (;;) {
198 state = ssl->state;
199
200 switch (ssl->state) {
201 case SSL_ST_CONNECT:
202 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
203
204 if (ssl->init_buf == NULL) {
205 buf = BUF_MEM_new();
206 if (buf == NULL ||
207 !BUF_MEM_reserve(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
208 ret = -1;
209 goto end;
210 }
211
212 ssl->init_buf = buf;
213 buf = NULL;
214 }
215 ssl->init_num = 0;
216
217 if (!ssl_init_wbio_buffer(ssl)) {
218 ret = -1;
219 goto end;
220 }
221
222 ssl->state = SSL3_ST_CW_CLNT_HELLO_A;
223 break;
224
225 case SSL3_ST_CW_CLNT_HELLO_A:
226 case SSL3_ST_CW_CLNT_HELLO_B:
227 ret = ssl3_send_client_hello(ssl);
228 if (ret <= 0) {
229 goto end;
230 }
231
232 if (!SSL_IS_DTLS(ssl) || ssl->d1->send_cookie) {
233 ssl->s3->tmp.next_state = SSL3_ST_CR_SRVR_HELLO_A;
234 } else {
235 ssl->s3->tmp.next_state = DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
236 }
237 ssl->state = SSL3_ST_CW_FLUSH;
238 break;
239
240 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
241 assert(SSL_IS_DTLS(ssl));
242 ret = dtls1_get_hello_verify(ssl);
243 if (ret <= 0) {
244 goto end;
245 }
246 if (ssl->d1->send_cookie) {
247 ssl->method->received_flight(ssl);
248 ssl->state = SSL3_ST_CW_CLNT_HELLO_A;
249 } else {
250 ssl->state = SSL3_ST_CR_SRVR_HELLO_A;
251 }
252 break;
253
254 case SSL3_ST_CR_SRVR_HELLO_A:
255 ret = ssl3_get_server_hello(ssl);
256 if (ret <= 0) {
257 goto end;
258 }
259
260 if (ssl->hit) {
261 ssl->state = SSL3_ST_CR_CHANGE;
262 if (ssl->tlsext_ticket_expected) {
263 /* receive renewed session ticket */
264 ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
265 }
266 } else {
267 ssl->state = SSL3_ST_CR_CERT_A;
268 }
269 break;
270
271 case SSL3_ST_CR_CERT_A:
272 if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
273 ret = ssl3_get_server_certificate(ssl);
274 if (ret <= 0) {
275 goto end;
276 }
277 if (ssl->s3->tmp.certificate_status_expected) {
278 ssl->state = SSL3_ST_CR_CERT_STATUS_A;
279 } else {
280 ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
281 }
282 } else {
283 skip = 1;
284 ssl->state = SSL3_ST_CR_KEY_EXCH_A;
285 }
286 break;
287
288 case SSL3_ST_CR_CERT_STATUS_A:
289 ret = ssl3_get_cert_status(ssl);
290 if (ret <= 0) {
291 goto end;
292 }
293 ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
294 break;
295
296 case SSL3_ST_VERIFY_SERVER_CERT:
297 ret = ssl3_verify_server_cert(ssl);
298 if (ret <= 0) {
299 goto end;
300 }
301
302 ssl->state = SSL3_ST_CR_KEY_EXCH_A;
303 break;
304
305 case SSL3_ST_CR_KEY_EXCH_A:
306 ret = ssl3_get_server_key_exchange(ssl);
307 if (ret <= 0) {
308 goto end;
309 }
310 if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
311 ssl->state = SSL3_ST_CR_CERT_REQ_A;
312 } else {
313 ssl->state = SSL3_ST_CR_SRVR_DONE_A;
314 }
315 break;
316
317 case SSL3_ST_CR_CERT_REQ_A:
318 ret = ssl3_get_certificate_request(ssl);
319 if (ret <= 0) {
320 goto end;
321 }
322 ssl->state = SSL3_ST_CR_SRVR_DONE_A;
323 break;
324
325 case SSL3_ST_CR_SRVR_DONE_A:
326 ret = ssl3_get_server_hello_done(ssl);
327 if (ret <= 0) {
328 goto end;
329 }
330 ssl->method->received_flight(ssl);
331 if (ssl->s3->tmp.cert_req) {
332 ssl->state = SSL3_ST_CW_CERT_A;
333 } else {
334 ssl->state = SSL3_ST_CW_KEY_EXCH_A;
335 }
336 break;
337
338 case SSL3_ST_CW_CERT_A:
339 case SSL3_ST_CW_CERT_B:
340 case SSL3_ST_CW_CERT_C:
341 case SSL3_ST_CW_CERT_D:
342 ret = ssl3_send_client_certificate(ssl);
343 if (ret <= 0) {
344 goto end;
345 }
346 ssl->state = SSL3_ST_CW_KEY_EXCH_A;
347 break;
348
349 case SSL3_ST_CW_KEY_EXCH_A:
350 case SSL3_ST_CW_KEY_EXCH_B:
351 ret = ssl3_send_client_key_exchange(ssl);
352 if (ret <= 0) {
353 goto end;
354 }
355 /* For TLS, cert_req is set to 2, so a cert chain
356 * of nothing is sent, but no verify packet is sent */
357 if (ssl->s3->tmp.cert_req == 1) {
358 ssl->state = SSL3_ST_CW_CERT_VRFY_A;
359 } else {
360 ssl->state = SSL3_ST_CW_CHANGE_A;
361 }
362 break;
363
364 case SSL3_ST_CW_CERT_VRFY_A:
365 case SSL3_ST_CW_CERT_VRFY_B:
366 case SSL3_ST_CW_CERT_VRFY_C:
367 ret = ssl3_send_cert_verify(ssl);
368 if (ret <= 0) {
369 goto end;
370 }
371 ssl->state = SSL3_ST_CW_CHANGE_A;
372 break;
373
374 case SSL3_ST_CW_CHANGE_A:
375 case SSL3_ST_CW_CHANGE_B:
376 ret = ssl->method->send_change_cipher_spec(ssl, SSL3_ST_CW_CHANGE_A,
377 SSL3_ST_CW_CHANGE_B);
378 if (ret <= 0) {
379 goto end;
380 }
381
382 ssl->state = SSL3_ST_CW_FINISHED_A;
383 if (ssl->s3->tlsext_channel_id_valid) {
384 ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
385 }
386 if (ssl->s3->next_proto_neg_seen) {
387 ssl->state = SSL3_ST_CW_NEXT_PROTO_A;
388 }
389
390 if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
391 ret = -1;
392 goto end;
393 }
394
395 break;
396
397 case SSL3_ST_CW_NEXT_PROTO_A:
398 case SSL3_ST_CW_NEXT_PROTO_B:
399 ret = ssl3_send_next_proto(ssl);
400 if (ret <= 0) {
401 goto end;
402 }
403
404 if (ssl->s3->tlsext_channel_id_valid) {
405 ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
406 } else {
407 ssl->state = SSL3_ST_CW_FINISHED_A;
408 }
409 break;
410
411 case SSL3_ST_CW_CHANNEL_ID_A:
412 case SSL3_ST_CW_CHANNEL_ID_B:
413 ret = ssl3_send_channel_id(ssl);
414 if (ret <= 0) {
415 goto end;
416 }
417 ssl->state = SSL3_ST_CW_FINISHED_A;
418 break;
419
420 case SSL3_ST_CW_FINISHED_A:
421 case SSL3_ST_CW_FINISHED_B:
422 ret = ssl3_send_finished(ssl, SSL3_ST_CW_FINISHED_A,
423 SSL3_ST_CW_FINISHED_B);
424 if (ret <= 0) {
425 goto end;
426 }
427 ssl->state = SSL3_ST_CW_FLUSH;
428
429 if (ssl->hit) {
430 ssl->s3->tmp.next_state = SSL_ST_OK;
431 } else {
432 /* This is a non-resumption handshake. If it involves ChannelID, then
433 * record the handshake hashes at this point in the session so that
434 * any resumption of this session with ChannelID can sign those
435 * hashes. */
436 ret = tls1_record_handshake_hashes_for_channel_id(ssl);
437 if (ret <= 0) {
438 goto end;
439 }
440 if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
441 ssl3_can_false_start(ssl) &&
442 /* No False Start on renegotiation (would complicate the state
443 * machine). */
444 !ssl->s3->initial_handshake_complete) {
445 ssl->s3->tmp.next_state = SSL3_ST_FALSE_START;
446 } else {
447 /* Allow NewSessionTicket if ticket expected */
448 if (ssl->tlsext_ticket_expected) {
449 ssl->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
450 } else {
451 ssl->s3->tmp.next_state = SSL3_ST_CR_CHANGE;
452 }
453 }
454 }
455 break;
456
457 case SSL3_ST_FALSE_START:
458 /* Allow NewSessionTicket if ticket expected */
459 if (ssl->tlsext_ticket_expected) {
460 ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
461 } else {
462 ssl->state = SSL3_ST_CR_CHANGE;
463 }
464 ssl->s3->tmp.in_false_start = 1;
465
466 ssl_free_wbio_buffer(ssl);
467 ret = 1;
468 goto end;
469
470 case SSL3_ST_CR_SESSION_TICKET_A:
471 ret = ssl3_get_new_session_ticket(ssl);
472 if (ret <= 0) {
473 goto end;
474 }
475 ssl->state = SSL3_ST_CR_CHANGE;
476 break;
477
478 case SSL3_ST_CR_CHANGE:
479 ret = ssl->method->ssl_read_change_cipher_spec(ssl);
480 if (ret <= 0) {
481 goto end;
482 }
483
484 if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_CLIENT_READ)) {
485 ret = -1;
486 goto end;
487 }
488 ssl->state = SSL3_ST_CR_FINISHED_A;
489 break;
490
491 case SSL3_ST_CR_FINISHED_A:
492 ret = ssl3_get_finished(ssl);
493 if (ret <= 0) {
494 goto end;
495 }
496 ssl->method->received_flight(ssl);
497
498 if (ssl->hit) {
499 ssl->state = SSL3_ST_CW_CHANGE_A;
500 } else {
501 ssl->state = SSL_ST_OK;
502 }
503 break;
504
505 case SSL3_ST_CW_FLUSH:
506 if (BIO_flush(ssl->wbio) <= 0) {
507 ssl->rwstate = SSL_WRITING;
508 ret = -1;
509 goto end;
510 }
511 ssl->state = ssl->s3->tmp.next_state;
512 if (ssl->state != SSL_ST_OK) {
513 ssl->method->expect_flight(ssl);
514 }
515 break;
516
517 case SSL_ST_OK:
518 /* clean a few things up */
519 ssl3_cleanup_key_block(ssl);
520
521 /* |init_buf| cannot be released in DTLS because post-handshake
522 * retransmit relies on that buffer being available as scratch space.
523 *
524 * TODO(davidben): Fix this. */
525 if (!SSL_IS_DTLS(ssl)) {
526 BUF_MEM_free(ssl->init_buf);
527 ssl->init_buf = NULL;
528 ssl->init_num = 0;
529 }
530
531 /* Remove write buffering now. */
532 ssl_free_wbio_buffer(ssl);
533
534 const int is_initial_handshake = !ssl->s3->initial_handshake_complete;
535
536 ssl->s3->tmp.in_false_start = 0;
537 ssl->s3->initial_handshake_complete = 1;
538
539 if (is_initial_handshake) {
540 /* Renegotiations do not participate in session resumption. */
541 ssl_update_cache(ssl, SSL_SESS_CACHE_CLIENT);
542 }
543
544 if (SSL_IS_DTLS(ssl)) {
545 ssl->d1->handshake_read_seq = 0;
546 ssl->d1->next_handshake_write_seq = 0;
547 }
548
549 ret = 1;
550 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_DONE, 1);
551 goto end;
552
553 default:
554 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
555 ret = -1;
556 goto end;
557 }
558
559 if (!ssl->s3->tmp.reuse_message && !skip && ssl->state != state) {
560 int new_state = ssl->state;
561 ssl->state = state;
562 ssl_do_info_callback(ssl, SSL_CB_CONNECT_LOOP, 1);
563 ssl->state = new_state;
564 }
565 skip = 0;
566 }
567
568 end:
569 BUF_MEM_free(buf);
570 ssl_do_info_callback(ssl, SSL_CB_CONNECT_EXIT, ret);
571 return ret;
572 }
573
574 static int ssl3_write_client_cipher_list(SSL *ssl, CBB *out) {
575 /* Prepare disabled cipher masks. */
576 ssl_set_client_disabled(ssl);
577
578 CBB child;
579 if (!CBB_add_u16_length_prefixed(out, &child)) {
580 return 0;
581 }
582
583 STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
584
585 int any_enabled = 0;
586 size_t i;
587 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
588 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
589 /* Skip disabled ciphers */
590 if ((cipher->algorithm_mkey & ssl->cert->mask_k) ||
591 (cipher->algorithm_auth & ssl->cert->mask_a)) {
592 continue;
593 }
594 if (SSL_CIPHER_get_min_version(cipher) >
595 ssl3_version_from_wire(ssl, ssl->client_version)) {
596 continue;
597 }
598 any_enabled = 1;
599 if (!CBB_add_u16(&child, ssl_cipher_get_value(cipher))) {
600 return 0;
601 }
602 }
603
604 /* If all ciphers were disabled, return the error to the caller. */
605 if (!any_enabled) {
606 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
607 return 0;
608 }
609
610 /* For SSLv3, the SCSV is added. Otherwise the renegotiation extension is
611 * added. */
612 if (ssl->client_version == SSL3_VERSION &&
613 !ssl->s3->initial_handshake_complete) {
614 if (!CBB_add_u16(&child, SSL3_CK_SCSV & 0xffff)) {
615 return 0;
616 }
617 /* The renegotiation extension is required to be at index zero. */
618 ssl->s3->tmp.extensions.sent |= (1u << 0);
619 }
620
621 if ((ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) &&
622 !CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
623 return 0;
624 }
625
626 return CBB_flush(out);
627 }
628
629 static int ssl3_send_client_hello(SSL *ssl) {
630 if (ssl->state == SSL3_ST_CW_CLNT_HELLO_B) {
631 return ssl_do_write(ssl);
632 }
633
634 /* The handshake buffer is reset on every ClientHello. Notably, in DTLS, we
635 * may send multiple ClientHellos if we receive HelloVerifyRequest. */
636 if (!ssl3_init_handshake_buffer(ssl)) {
637 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
638 return -1;
639 }
640
641 CBB cbb;
642 CBB_zero(&cbb);
643
644 assert(ssl->state == SSL3_ST_CW_CLNT_HELLO_A);
645 if (!ssl->s3->have_version) {
646 uint16_t max_version = ssl3_get_max_client_version(ssl);
647 /* Disabling all versions is silly: return an error. */
648 if (max_version == 0) {
649 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
650 goto err;
651 }
652
653 ssl->version = max_version;
654 /* Only set |ssl->client_version| on the initial handshake. Renegotiations,
655 * although locked to a version, reuse the value. When using the plain RSA
656 * key exchange, the ClientHello version is checked in the premaster secret.
657 * Some servers fail when this value changes. */
658 ssl->client_version = max_version;
659 }
660
661 /* If the configured session has expired or was created at a disabled
662 * version, drop it. */
663 if (ssl->session != NULL &&
664 (ssl->session->session_id_length == 0 || ssl->session->not_resumable ||
665 ssl->session->timeout < (long)(time(NULL) - ssl->session->time) ||
666 !ssl3_is_version_enabled(ssl, ssl->session->ssl_version))) {
667 SSL_set_session(ssl, NULL);
668 }
669
670 /* If resending the ClientHello in DTLS after a HelloVerifyRequest, don't
671 * renegerate the client_random. The random must be reused. */
672 if ((!SSL_IS_DTLS(ssl) || !ssl->d1->send_cookie) &&
673 !ssl_fill_hello_random(ssl->s3->client_random,
674 sizeof(ssl->s3->client_random), 0 /* client */)) {
675 goto err;
676 }
677
678 /* Renegotiations do not participate in session resumption. */
679 int has_session = ssl->session != NULL &&
680 !ssl->s3->initial_handshake_complete;
681
682 CBB child;
683 if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
684 ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
685 !CBB_add_u16(&cbb, ssl->client_version) ||
686 !CBB_add_bytes(&cbb, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
687 !CBB_add_u8_length_prefixed(&cbb, &child) ||
688 (has_session &&
689 !CBB_add_bytes(&child, ssl->session->session_id,
690 ssl->session->session_id_length))) {
691 goto err;
692 }
693
694 if (SSL_IS_DTLS(ssl)) {
695 if (!CBB_add_u8_length_prefixed(&cbb, &child) ||
696 !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
697 goto err;
698 }
699 }
700
701 size_t length;
702 if (!ssl3_write_client_cipher_list(ssl, &cbb) ||
703 !CBB_add_u8(&cbb, 1 /* one compression method */) ||
704 !CBB_add_u8(&cbb, 0 /* null compression */) ||
705 !ssl_add_clienthello_tlsext(ssl, &cbb,
706 CBB_len(&cbb) + SSL_HM_HEADER_LENGTH(ssl)) ||
707 !CBB_finish(&cbb, NULL, &length) ||
708 !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_HELLO, length)) {
709 goto err;
710 }
711
712 ssl->state = SSL3_ST_CW_CLNT_HELLO_B;
713 return ssl_do_write(ssl);
714
715 err:
716 CBB_cleanup(&cbb);
717 return -1;
718 }
719
720 static int dtls1_get_hello_verify(SSL *ssl) {
721 long n;
722 int al, ok = 0;
723 CBS hello_verify_request, cookie;
724 uint16_t server_version;
725
726 n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
727
728 if (!ok) {
729 return n;
730 }
731
732 if (ssl->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
733 ssl->d1->send_cookie = 0;
734 ssl->s3->tmp.reuse_message = 1;
735 return 1;
736 }
737
738 CBS_init(&hello_verify_request, ssl->init_msg, n);
739
740 if (!CBS_get_u16(&hello_verify_request, &server_version) ||
741 !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
742 CBS_len(&hello_verify_request) != 0) {
743 al = SSL_AD_DECODE_ERROR;
744 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
745 goto f_err;
746 }
747
748 if (CBS_len(&cookie) > sizeof(ssl->d1->cookie)) {
749 al = SSL_AD_ILLEGAL_PARAMETER;
750 goto f_err;
751 }
752
753 memcpy(ssl->d1->cookie, CBS_data(&cookie), CBS_len(&cookie));
754 ssl->d1->cookie_len = CBS_len(&cookie);
755
756 ssl->d1->send_cookie = 1;
757 return 1;
758
759 f_err:
760 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
761 return -1;
762 }
763
764 static int ssl3_get_server_hello(SSL *ssl) {
765 STACK_OF(SSL_CIPHER) *sk;
766 const SSL_CIPHER *c;
767 CERT *ct = ssl->cert;
768 int al = SSL_AD_INTERNAL_ERROR, ok;
769 long n;
770 CBS server_hello, server_random, session_id;
771 uint16_t server_version, cipher_suite;
772 uint8_t compression_method;
773
774 n = ssl->method->ssl_get_message(ssl, SSL3_MT_SERVER_HELLO, ssl_hash_message,
775 &ok);
776
777 if (!ok) {
778 uint32_t err = ERR_peek_error();
779 if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
780 ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
781 /* Add a dedicated error code to the queue for a handshake_failure alert
782 * in response to ClientHello. This matches NSS's client behavior and
783 * gives a better error on a (probable) failure to negotiate initial
784 * parameters. Note: this error code comes after the original one.
785 *
786 * See https://crbug.com/446505. */
787 OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
788 }
789 return n;
790 }
791
792 CBS_init(&server_hello, ssl->init_msg, n);
793
794 if (!CBS_get_u16(&server_hello, &server_version) ||
795 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
796 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
797 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
798 !CBS_get_u16(&server_hello, &cipher_suite) ||
799 !CBS_get_u8(&server_hello, &compression_method)) {
800 al = SSL_AD_DECODE_ERROR;
801 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
802 goto f_err;
803 }
804
805 assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
806 if (!ssl->s3->have_version) {
807 if (!ssl3_is_version_enabled(ssl, server_version)) {
808 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
809 ssl->version = server_version;
810 /* Mark the version as fixed so the record-layer version is not clamped
811 * to TLS 1.0. */
812 ssl->s3->have_version = 1;
813 al = SSL_AD_PROTOCOL_VERSION;
814 goto f_err;
815 }
816 ssl->version = server_version;
817 ssl->s3->enc_method = ssl3_get_enc_method(server_version);
818 assert(ssl->s3->enc_method != NULL);
819 /* At this point, the connection's version is known and ssl->version is
820 * fixed. Begin enforcing the record-layer version. */
821 ssl->s3->have_version = 1;
822 } else if (server_version != ssl->version) {
823 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
824 al = SSL_AD_PROTOCOL_VERSION;
825 goto f_err;
826 }
827
828 /* Copy over the server random. */
829 memcpy(ssl->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
830
831 assert(ssl->session == NULL || ssl->session->session_id_length > 0);
832 if (!ssl->s3->initial_handshake_complete && ssl->session != NULL &&
833 CBS_mem_equal(&session_id, ssl->session->session_id,
834 ssl->session->session_id_length)) {
835 if (ssl->sid_ctx_length != ssl->session->sid_ctx_length ||
836 memcmp(ssl->session->sid_ctx, ssl->sid_ctx, ssl->sid_ctx_length)) {
837 /* actually a client application bug */
838 al = SSL_AD_ILLEGAL_PARAMETER;
839 OPENSSL_PUT_ERROR(SSL,
840 SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
841 goto f_err;
842 }
843 ssl->hit = 1;
844 } else {
845 /* The session wasn't resumed. Create a fresh SSL_SESSION to
846 * fill out. */
847 ssl->hit = 0;
848 if (!ssl_get_new_session(ssl, 0 /* client */)) {
849 goto f_err;
850 }
851 /* Note: session_id could be empty. */
852 ssl->session->session_id_length = CBS_len(&session_id);
853 memcpy(ssl->session->session_id, CBS_data(&session_id),
854 CBS_len(&session_id));
855 }
856
857 c = SSL_get_cipher_by_value(cipher_suite);
858 if (c == NULL) {
859 /* unknown cipher */
860 al = SSL_AD_ILLEGAL_PARAMETER;
861 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
862 goto f_err;
863 }
864 /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
865 * the server selected it, it's an error. */
866 if ((c->algorithm_mkey & ct->mask_k) || (c->algorithm_auth & ct->mask_a) ||
867 SSL_CIPHER_get_min_version(c) > ssl3_protocol_version(ssl)) {
868 al = SSL_AD_ILLEGAL_PARAMETER;
869 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
870 goto f_err;
871 }
872
873 sk = ssl_get_ciphers_by_id(ssl);
874 if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
875 /* we did not say we would use this cipher */
876 al = SSL_AD_ILLEGAL_PARAMETER;
877 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
878 goto f_err;
879 }
880
881 if (ssl->hit) {
882 if (ssl->session->cipher != c) {
883 al = SSL_AD_ILLEGAL_PARAMETER;
884 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
885 goto f_err;
886 }
887 if (ssl->session->ssl_version != ssl->version) {
888 al = SSL_AD_ILLEGAL_PARAMETER;
889 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
890 goto f_err;
891 }
892 } else {
893 ssl->session->cipher = c;
894 }
895 ssl->s3->tmp.new_cipher = c;
896
897 /* Now that the cipher is known, initialize the handshake hash. */
898 if (!ssl3_init_handshake_hash(ssl)) {
899 goto f_err;
900 }
901
902 /* If doing a full handshake with TLS 1.2, the server may request a client
903 * certificate which requires hashing the handshake transcript under a
904 * different hash. Otherwise, the handshake buffer may be released. */
905 if (ssl->hit || ssl3_protocol_version(ssl) < TLS1_2_VERSION ||
906 !ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
907 ssl3_free_handshake_buffer(ssl);
908 }
909
910 /* Only the NULL compression algorithm is supported. */
911 if (compression_method != 0) {
912 al = SSL_AD_ILLEGAL_PARAMETER;
913 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
914 goto f_err;
915 }
916
917 /* TLS extensions */
918 if (!ssl_parse_serverhello_tlsext(ssl, &server_hello)) {
919 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
920 goto err;
921 }
922
923 /* There should be nothing left over in the record. */
924 if (CBS_len(&server_hello) != 0) {
925 /* wrong packet length */
926 al = SSL_AD_DECODE_ERROR;
927 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
928 goto f_err;
929 }
930
931 if (ssl->hit &&
932 ssl->s3->tmp.extended_master_secret !=
933 ssl->session->extended_master_secret) {
934 al = SSL_AD_HANDSHAKE_FAILURE;
935 if (ssl->session->extended_master_secret) {
936 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
937 } else {
938 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
939 }
940 goto f_err;
941 }
942
943 return 1;
944
945 f_err:
946 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
947 err:
948 return -1;
949 }
950
951 /* ssl3_check_leaf_certificate returns one if |leaf| is a suitable leaf server
952 * certificate for |ssl|. Otherwise, it returns zero and pushes an error on the
953 * error queue. */
954 static int ssl3_check_leaf_certificate(SSL *ssl, X509 *leaf) {
955 int ret = 0;
956 EVP_PKEY *pkey = X509_get_pubkey(leaf);
957 if (pkey == NULL) {
958 goto err;
959 }
960
961 /* Check the certificate's type matches the cipher. */
962 const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
963 int expected_type = ssl_cipher_get_key_type(cipher);
964 assert(expected_type != EVP_PKEY_NONE);
965 if (pkey->type != expected_type) {
966 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
967 goto err;
968 }
969
970 if (cipher->algorithm_auth & SSL_aECDSA) {
971 /* TODO(davidben): This behavior is preserved from upstream. Should key
972 * usages be checked in other cases as well? */
973 /* This call populates the ex_flags field correctly */
974 X509_check_purpose(leaf, -1, 0);
975 if ((leaf->ex_flags & EXFLAG_KUSAGE) &&
976 !(leaf->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)) {
977 OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
978 goto err;
979 }
980
981 if (!tls1_check_ec_cert(ssl, leaf)) {
982 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
983 goto err;
984 }
985 }
986
987 ret = 1;
988
989 err:
990 EVP_PKEY_free(pkey);
991 return ret;
992 }
993
994 static int ssl3_get_server_certificate(SSL *ssl) {
995 int al, ok, ret = -1;
996 unsigned long n;
997 X509 *x = NULL;
998 STACK_OF(X509) *sk = NULL;
999 EVP_PKEY *pkey = NULL;
1000 CBS cbs, certificate_list;
1001 const uint8_t *data;
1002
1003 n = ssl->method->ssl_get_message(ssl, SSL3_MT_CERTIFICATE, ssl_hash_message,
1004 &ok);
1005
1006 if (!ok) {
1007 return n;
1008 }
1009
1010 CBS_init(&cbs, ssl->init_msg, n);
1011
1012 sk = sk_X509_new_null();
1013 if (sk == NULL) {
1014 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1015 goto err;
1016 }
1017
1018 if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
1019 CBS_len(&certificate_list) == 0 ||
1020 CBS_len(&cbs) != 0) {
1021 al = SSL_AD_DECODE_ERROR;
1022 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1023 goto f_err;
1024 }
1025
1026 while (CBS_len(&certificate_list) > 0) {
1027 CBS certificate;
1028 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
1029 al = SSL_AD_DECODE_ERROR;
1030 OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
1031 goto f_err;
1032 }
1033 /* A u24 length cannot overflow a long. */
1034 data = CBS_data(&certificate);
1035 x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
1036 if (x == NULL) {
1037 al = SSL_AD_BAD_CERTIFICATE;
1038 OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
1039 goto f_err;
1040 }
1041 if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
1042 al = SSL_AD_DECODE_ERROR;
1043 OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
1044 goto f_err;
1045 }
1046 if (!sk_X509_push(sk, x)) {
1047 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1048 goto err;
1049 }
1050 x = NULL;
1051 }
1052
1053 X509 *leaf = sk_X509_value(sk, 0);
1054 if (!ssl3_check_leaf_certificate(ssl, leaf)) {
1055 al = SSL_AD_ILLEGAL_PARAMETER;
1056 goto f_err;
1057 }
1058
1059 /* NOTE: Unlike the server half, the client's copy of |cert_chain| includes
1060 * the leaf. */
1061 sk_X509_pop_free(ssl->session->cert_chain, X509_free);
1062 ssl->session->cert_chain = sk;
1063 sk = NULL;
1064
1065 X509_free(ssl->session->peer);
1066 ssl->session->peer = X509_up_ref(leaf);
1067
1068 ssl->session->verify_result = ssl->verify_result;
1069
1070 ret = 1;
1071
1072 if (0) {
1073 f_err:
1074 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1075 }
1076
1077 err:
1078 EVP_PKEY_free(pkey);
1079 X509_free(x);
1080 sk_X509_pop_free(sk, X509_free);
1081 return ret;
1082 }
1083
1084 static int ssl3_get_cert_status(SSL *ssl) {
1085 int ok, al;
1086 long n;
1087 CBS certificate_status, ocsp_response;
1088 uint8_t status_type;
1089
1090 n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
1091
1092 if (!ok) {
1093 return n;
1094 }
1095
1096 if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1097 /* A server may send status_request in ServerHello and then change
1098 * its mind about sending CertificateStatus. */
1099 ssl->s3->tmp.reuse_message = 1;
1100 return 1;
1101 }
1102
1103 CBS_init(&certificate_status, ssl->init_msg, n);
1104 if (!CBS_get_u8(&certificate_status, &status_type) ||
1105 status_type != TLSEXT_STATUSTYPE_ocsp ||
1106 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
1107 CBS_len(&ocsp_response) == 0 ||
1108 CBS_len(&certificate_status) != 0) {
1109 al = SSL_AD_DECODE_ERROR;
1110 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1111 goto f_err;
1112 }
1113
1114 if (!CBS_stow(&ocsp_response, &ssl->session->ocsp_response,
1115 &ssl->session->ocsp_response_length)) {
1116 al = SSL_AD_INTERNAL_ERROR;
1117 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1118 goto f_err;
1119 }
1120 return 1;
1121
1122 f_err:
1123 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1124 return -1;
1125 }
1126
1127 static int ssl3_verify_server_cert(SSL *ssl) {
1128 int ret = ssl_verify_cert_chain(ssl, ssl->session->cert_chain);
1129 if (ssl->verify_mode != SSL_VERIFY_NONE && ret <= 0) {
1130 int al = ssl_verify_alarm_type(ssl->verify_result);
1131 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1132 OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
1133 } else {
1134 ret = 1;
1135 ERR_clear_error(); /* but we keep ssl->verify_result */
1136 }
1137
1138 return ret;
1139 }
1140
1141 static int ssl3_get_server_key_exchange(SSL *ssl) {
1142 EVP_MD_CTX md_ctx;
1143 int al, ok;
1144 EVP_PKEY *pkey = NULL;
1145 DH *dh = NULL;
1146 EC_KEY *ecdh = NULL;
1147 EC_POINT *srvr_ecpoint = NULL;
1148
1149 long n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
1150 if (!ok) {
1151 return n;
1152 }
1153
1154 if (ssl->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1155 if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher)) {
1156 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1157 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1158 return -1;
1159 }
1160
1161 /* In plain PSK ciphersuite, ServerKeyExchange may be omitted to send no
1162 * identity hint. */
1163 if (ssl->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
1164 /* TODO(davidben): This should be reset in one place with the rest of the
1165 * handshake state. */
1166 OPENSSL_free(ssl->s3->tmp.peer_psk_identity_hint);
1167 ssl->s3->tmp.peer_psk_identity_hint = NULL;
1168 }
1169 ssl->s3->tmp.reuse_message = 1;
1170 return 1;
1171 }
1172
1173 /* Retain a copy of the original CBS to compute the signature over. */
1174 CBS server_key_exchange;
1175 CBS_init(&server_key_exchange, ssl->init_msg, n);
1176 CBS server_key_exchange_orig = server_key_exchange;
1177
1178 uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
1179 uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
1180 EVP_MD_CTX_init(&md_ctx);
1181
1182 if (alg_a & SSL_aPSK) {
1183 CBS psk_identity_hint;
1184
1185 /* Each of the PSK key exchanges begins with a psk_identity_hint. */
1186 if (!CBS_get_u16_length_prefixed(&server_key_exchange,
1187 &psk_identity_hint)) {
1188 al = SSL_AD_DECODE_ERROR;
1189 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1190 goto f_err;
1191 }
1192
1193 /* Store PSK identity hint for later use, hint is used in
1194 * ssl3_send_client_key_exchange. Assume that the maximum length of a PSK
1195 * identity hint can be as long as the maximum length of a PSK identity.
1196 * Also do not allow NULL characters; identities are saved as C strings.
1197 *
1198 * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
1199 * a specific identity. */
1200 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
1201 CBS_contains_zero_byte(&psk_identity_hint)) {
1202 al = SSL_AD_HANDSHAKE_FAILURE;
1203 OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1204 goto f_err;
1205 }
1206
1207 /* Save the identity hint as a C string. */
1208 if (!CBS_strdup(&psk_identity_hint, &ssl->s3->tmp.peer_psk_identity_hint)) {
1209 al = SSL_AD_INTERNAL_ERROR;
1210 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1211 goto f_err;
1212 }
1213 }
1214
1215 if (alg_k & SSL_kDHE) {
1216 CBS dh_p, dh_g, dh_Ys;
1217 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
1218 CBS_len(&dh_p) == 0 ||
1219 !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
1220 CBS_len(&dh_g) == 0 ||
1221 !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
1222 CBS_len(&dh_Ys) == 0) {
1223 al = SSL_AD_DECODE_ERROR;
1224 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1225 goto f_err;
1226 }
1227
1228 dh = DH_new();
1229 if (dh == NULL) {
1230 goto err;
1231 }
1232
1233 dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL);
1234 dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL);
1235 if (dh->p == NULL || dh->g == NULL) {
1236 goto err;
1237 }
1238
1239 ssl->session->key_exchange_info = DH_num_bits(dh);
1240 if (ssl->session->key_exchange_info < 1024) {
1241 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DH_P_LENGTH);
1242 goto err;
1243 } else if (ssl->session->key_exchange_info > 4096) {
1244 /* Overly large DHE groups are prohibitively expensive, so enforce a limit
1245 * to prevent a server from causing us to perform too expensive of a
1246 * computation. */
1247 OPENSSL_PUT_ERROR(SSL, SSL_R_DH_P_TOO_LONG);
1248 goto err;
1249 }
1250
1251 SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
1252 dh = NULL;
1253
1254 /* Save the peer public key for later. */
1255 size_t peer_key_len;
1256 if (!CBS_stow(&dh_Ys, &ssl->s3->tmp.peer_key, &peer_key_len)) {
1257 goto err;
1258 }
1259 /* |dh_Ys| was initialized with CBS_get_u16_length_prefixed, so peer_key_len
1260 * fits in a uint16_t. */
1261 assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
1262 ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
1263 } else if (alg_k & SSL_kECDHE) {
1264 /* Parse the server parameters. */
1265 uint8_t group_type;
1266 uint16_t group_id;
1267 CBS point;
1268 if (!CBS_get_u8(&server_key_exchange, &group_type) ||
1269 group_type != NAMED_CURVE_TYPE ||
1270 !CBS_get_u16(&server_key_exchange, &group_id) ||
1271 !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
1272 al = SSL_AD_DECODE_ERROR;
1273 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1274 goto f_err;
1275 }
1276 ssl->session->key_exchange_info = group_id;
1277
1278 /* Ensure the group is consistent with preferences. */
1279 if (!tls1_check_group_id(ssl, group_id)) {
1280 al = SSL_AD_ILLEGAL_PARAMETER;
1281 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
1282 goto f_err;
1283 }
1284
1285 /* Initialize ECDH and save the peer public key for later. */
1286 size_t peer_key_len;
1287 if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, group_id) ||
1288 !CBS_stow(&point, &ssl->s3->tmp.peer_key, &peer_key_len)) {
1289 goto err;
1290 }
1291 /* |point| was initialized with CBS_get_u8_length_prefixed, so peer_key_len
1292 * fits in a uint16_t. */
1293 assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
1294 ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
1295 } else if (alg_k & SSL_kCECPQ1) {
1296 if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, SSL_GROUP_CECPQ1)) {
1297 goto err;
1298 }
1299 CBS key;
1300 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &key)) {
1301 al = SSL_AD_DECODE_ERROR;
1302 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1303 goto f_err;
1304 }
1305
1306 size_t peer_key_len;
1307 if (!CBS_stow(&key, &ssl->s3->tmp.peer_key, &peer_key_len)) {
1308 goto err;
1309 }
1310 /* |key| was initialized with CBS_get_u16_length_prefixed, so peer_key_len
1311 * fits in a uint16_t. */
1312 assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
1313 ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
1314 } else if (!(alg_k & SSL_kPSK)) {
1315 al = SSL_AD_UNEXPECTED_MESSAGE;
1316 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1317 goto f_err;
1318 }
1319
1320 /* At this point, |server_key_exchange| contains the signature, if any, while
1321 * |server_key_exchange_orig| contains the entire message. From that, derive
1322 * a CBS containing just the parameter. */
1323 CBS parameter;
1324 CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
1325 CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
1326
1327 /* ServerKeyExchange should be signed by the server's public key. */
1328 if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
1329 pkey = X509_get_pubkey(ssl->session->peer);
1330 if (pkey == NULL) {
1331 goto err;
1332 }
1333
1334 const EVP_MD *md = NULL;
1335 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1336 uint8_t hash, signature;
1337 if (!CBS_get_u8(&server_key_exchange, &hash) ||
1338 !CBS_get_u8(&server_key_exchange, &signature)) {
1339 al = SSL_AD_DECODE_ERROR;
1340 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1341 goto f_err;
1342 }
1343 if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature, pkey)) {
1344 goto f_err;
1345 }
1346 ssl->s3->tmp.server_key_exchange_hash = hash;
1347 } else if (pkey->type == EVP_PKEY_RSA) {
1348 md = EVP_md5_sha1();
1349 } else {
1350 md = EVP_sha1();
1351 }
1352
1353 /* The last field in |server_key_exchange| is the signature. */
1354 CBS signature;
1355 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1356 CBS_len(&server_key_exchange) != 0) {
1357 al = SSL_AD_DECODE_ERROR;
1358 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1359 goto f_err;
1360 }
1361
1362 int sig_ok = EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) &&
1363 EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->client_random,
1364 SSL3_RANDOM_SIZE) &&
1365 EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->server_random,
1366 SSL3_RANDOM_SIZE) &&
1367 EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
1368 CBS_len(&parameter)) &&
1369 EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
1370 CBS_len(&signature));
1371 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1372 sig_ok = 1;
1373 ERR_clear_error();
1374 #endif
1375 if (!sig_ok) {
1376 /* bad signature */
1377 al = SSL_AD_DECRYPT_ERROR;
1378 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1379 goto f_err;
1380 }
1381 } else {
1382 /* PSK ciphers are the only supported certificate-less ciphers. */
1383 assert(alg_a == SSL_aPSK);
1384
1385 if (CBS_len(&server_key_exchange) > 0) {
1386 al = SSL_AD_DECODE_ERROR;
1387 OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1388 goto f_err;
1389 }
1390 }
1391 EVP_PKEY_free(pkey);
1392 EVP_MD_CTX_cleanup(&md_ctx);
1393 return 1;
1394
1395 f_err:
1396 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
1397 err:
1398 EVP_PKEY_free(pkey);
1399 DH_free(dh);
1400 EC_POINT_free(srvr_ecpoint);
1401 EC_KEY_free(ecdh);
1402 EVP_MD_CTX_cleanup(&md_ctx);
1403 return -1;
1404 }
1405
1406 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
1407 return X509_NAME_cmp(*a, *b);
1408 }
1409
1410 static int ssl3_get_certificate_request(SSL *ssl) {
1411 int ok, ret = 0;
1412 X509_NAME *xn = NULL;
1413 STACK_OF(X509_NAME) *ca_sk = NULL;
1414
1415 long n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
1416
1417 if (!ok) {
1418 return n;
1419 }
1420
1421 ssl->s3->tmp.cert_req = 0;
1422
1423 if (ssl->s3->tmp.message_type == SSL3_MT_SERVER_HELLO_DONE) {
1424 ssl->s3->tmp.reuse_message = 1;
1425 /* If we get here we don't need the handshake buffer as we won't be doing
1426 * client auth. */
1427 ssl3_free_handshake_buffer(ssl);
1428 return 1;
1429 }
1430
1431 if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1432 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1433 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1434 goto err;
1435 }
1436
1437 CBS cbs;
1438 CBS_init(&cbs, ssl->init_msg, n);
1439
1440 ca_sk = sk_X509_NAME_new(ca_dn_cmp);
1441 if (ca_sk == NULL) {
1442 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1443 goto err;
1444 }
1445
1446 /* get the certificate types */
1447 CBS certificate_types;
1448 if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
1449 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1450 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1451 goto err;
1452 }
1453
1454 if (!CBS_stow(&certificate_types, &ssl->s3->tmp.certificate_types,
1455 &ssl->s3->tmp.num_certificate_types)) {
1456 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1457 goto err;
1458 }
1459
1460 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1461 CBS supported_signature_algorithms;
1462 if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms) ||
1463 !tls1_parse_peer_sigalgs(ssl, &supported_signature_algorithms)) {
1464 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1465 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1466 goto err;
1467 }
1468 }
1469
1470 /* get the CA RDNs */
1471 CBS certificate_authorities;
1472 if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
1473 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1474 OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
1475 goto err;
1476 }
1477
1478 while (CBS_len(&certificate_authorities) > 0) {
1479 CBS distinguished_name;
1480 if (!CBS_get_u16_length_prefixed(&certificate_authorities,
1481 &distinguished_name)) {
1482 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1483 OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
1484 goto err;
1485 }
1486
1487 const uint8_t *data = CBS_data(&distinguished_name);
1488 /* A u16 length cannot overflow a long. */
1489 xn = d2i_X509_NAME(NULL, &data, (long)CBS_len(&distinguished_name));
1490 if (xn == NULL ||
1491 data != CBS_data(&distinguished_name) + CBS_len(&distinguished_name)) {
1492 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1493 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1494 goto err;
1495 }
1496
1497 if (!sk_X509_NAME_push(ca_sk, xn)) {
1498 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1499 goto err;
1500 }
1501 xn = NULL;
1502 }
1503
1504 /* we should setup a certificate to return.... */
1505 ssl->s3->tmp.cert_req = 1;
1506 sk_X509_NAME_pop_free(ssl->s3->tmp.ca_names, X509_NAME_free);
1507 ssl->s3->tmp.ca_names = ca_sk;
1508 ca_sk = NULL;
1509
1510 ret = 1;
1511
1512 err:
1513 X509_NAME_free(xn);
1514 sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1515 return ret;
1516 }
1517
1518 static int ssl3_get_server_hello_done(SSL *ssl) {
1519 int ok;
1520 long n;
1521
1522 n = ssl->method->ssl_get_message(ssl, SSL3_MT_SERVER_HELLO_DONE,
1523 ssl_hash_message, &ok);
1524
1525 if (!ok) {
1526 return n;
1527 }
1528
1529 if (n > 0) {
1530 /* should contain no data */
1531 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1532 OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
1533 return -1;
1534 }
1535
1536 return 1;
1537 }
1538
1539 /* ssl3_has_client_certificate returns true if a client certificate is
1540 * configured. */
1541 static int ssl3_has_client_certificate(SSL *ssl) {
1542 return ssl->cert && ssl->cert->x509 && ssl_has_private_key(ssl);
1543 }
1544
1545 static int ssl_do_client_cert_cb(SSL *ssl, X509 **out_x509,
1546 EVP_PKEY **out_pkey) {
1547 if (ssl->ctx->client_cert_cb == NULL) {
1548 return 0;
1549 }
1550
1551 int ret = ssl->ctx->client_cert_cb(ssl, out_x509, out_pkey);
1552 if (ret <= 0) {
1553 return ret;
1554 }
1555
1556 assert(*out_x509 != NULL);
1557 assert(*out_pkey != NULL);
1558 return 1;
1559 }
1560
1561 static int ssl3_send_client_certificate(SSL *ssl) {
1562 if (ssl->state == SSL3_ST_CW_CERT_A) {
1563 /* Call cert_cb to update the certificate. */
1564 if (ssl->cert->cert_cb) {
1565 int ret = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
1566 if (ret < 0) {
1567 ssl->rwstate = SSL_X509_LOOKUP;
1568 return -1;
1569 }
1570 if (ret == 0) {
1571 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1572 return -1;
1573 }
1574 }
1575
1576 if (ssl3_has_client_certificate(ssl)) {
1577 ssl->state = SSL3_ST_CW_CERT_C;
1578 } else {
1579 ssl->state = SSL3_ST_CW_CERT_B;
1580 }
1581 }
1582
1583 if (ssl->state == SSL3_ST_CW_CERT_B) {
1584 /* Call client_cert_cb to update the certificate. */
1585 X509 *x509 = NULL;
1586 EVP_PKEY *pkey = NULL;
1587 int ret = ssl_do_client_cert_cb(ssl, &x509, &pkey);
1588 if (ret < 0) {
1589 ssl->rwstate = SSL_X509_LOOKUP;
1590 return -1;
1591 }
1592
1593 int setup_error = ret == 1 && (!SSL_use_certificate(ssl, x509) ||
1594 !SSL_use_PrivateKey(ssl, pkey));
1595 X509_free(x509);
1596 EVP_PKEY_free(pkey);
1597 if (setup_error) {
1598 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1599 return -1;
1600 }
1601
1602 ssl->state = SSL3_ST_CW_CERT_C;
1603 }
1604
1605 if (ssl->state == SSL3_ST_CW_CERT_C) {
1606 if (!ssl3_has_client_certificate(ssl)) {
1607 /* Without a client certificate, the handshake buffer may be released. */
1608 ssl3_free_handshake_buffer(ssl);
1609
1610 if (ssl->version == SSL3_VERSION) {
1611 /* In SSL 3.0, send no certificate by skipping both messages. */
1612 ssl->s3->tmp.cert_req = 0;
1613 ssl3_send_alert(ssl, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
1614 return 1;
1615 }
1616
1617 /* In TLS, send an empty Certificate message. */
1618 ssl->s3->tmp.cert_req = 2;
1619 uint8_t *p = ssl_handshake_start(ssl);
1620 l2n3(0, p);
1621 if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE, 3)) {
1622 return -1;
1623 }
1624 } else if (!ssl3_output_cert_chain(ssl)) {
1625 return -1;
1626 }
1627 ssl->state = SSL3_ST_CW_CERT_D;
1628 }
1629
1630 assert(ssl->state == SSL3_ST_CW_CERT_D);
1631 return ssl_do_write(ssl);
1632 }
1633
1634 OPENSSL_COMPILE_ASSERT(sizeof(size_t) >= sizeof(unsigned),
1635 SIZE_T_IS_SMALLER_THAN_UNSIGNED);
1636
1637 static int ssl3_send_client_key_exchange(SSL *ssl) {
1638 if (ssl->state == SSL3_ST_CW_KEY_EXCH_B) {
1639 return ssl_do_write(ssl);
1640 }
1641 assert(ssl->state == SSL3_ST_CW_KEY_EXCH_A);
1642
1643 uint8_t *pms = NULL;
1644 size_t pms_len = 0;
1645 CBB cbb;
1646 if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
1647 ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
1648 goto err;
1649 }
1650
1651 uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
1652 uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
1653
1654 /* If using a PSK key exchange, prepare the pre-shared key. */
1655 unsigned psk_len = 0;
1656 uint8_t psk[PSK_MAX_PSK_LEN];
1657 if (alg_a & SSL_aPSK) {
1658 if (ssl->psk_client_callback == NULL) {
1659 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1660 goto err;
1661 }
1662
1663 char identity[PSK_MAX_IDENTITY_LEN + 1];
1664 memset(identity, 0, sizeof(identity));
1665 psk_len = ssl->psk_client_callback(
1666 ssl, ssl->s3->tmp.peer_psk_identity_hint, identity, sizeof(identity),
1667 psk, sizeof(psk));
1668 if (psk_len == 0) {
1669 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1670 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1671 goto err;
1672 }
1673 assert(psk_len <= PSK_MAX_PSK_LEN);
1674
1675 OPENSSL_free(ssl->session->psk_identity);
1676 ssl->session->psk_identity = BUF_strdup(identity);
1677 if (ssl->session->psk_identity == NULL) {
1678 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1679 goto err;
1680 }
1681
1682 /* Write out psk_identity. */
1683 CBB child;
1684 if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1685 !CBB_add_bytes(&child, (const uint8_t *)identity,
1686 OPENSSL_strnlen(identity, sizeof(identity))) ||
1687 !CBB_flush(&cbb)) {
1688 goto err;
1689 }
1690 }
1691
1692 /* Depending on the key exchange method, compute |pms| and |pms_len|. */
1693 if (alg_k & SSL_kRSA) {
1694 pms_len = SSL_MAX_MASTER_KEY_LENGTH;
1695 pms = OPENSSL_malloc(pms_len);
1696 if (pms == NULL) {
1697 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1698 goto err;
1699 }
1700
1701 EVP_PKEY *pkey = X509_get_pubkey(ssl->session->peer);
1702 if (pkey == NULL) {
1703 goto err;
1704 }
1705
1706 RSA *rsa = EVP_PKEY_get0_RSA(pkey);
1707 if (rsa == NULL) {
1708 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1709 EVP_PKEY_free(pkey);
1710 goto err;
1711 }
1712
1713 ssl->session->key_exchange_info = EVP_PKEY_bits(pkey);
1714 EVP_PKEY_free(pkey);
1715
1716 pms[0] = ssl->client_version >> 8;
1717 pms[1] = ssl->client_version & 0xff;
1718 if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1719 goto err;
1720 }
1721
1722 CBB child, *enc_pms = &cbb;
1723 size_t enc_pms_len;
1724 /* In TLS, there is a length prefix. */
1725 if (ssl->version > SSL3_VERSION) {
1726 if (!CBB_add_u16_length_prefixed(&cbb, &child)) {
1727 goto err;
1728 }
1729 enc_pms = &child;
1730 }
1731
1732 uint8_t *ptr;
1733 if (!CBB_reserve(enc_pms, &ptr, RSA_size(rsa)) ||
1734 !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms, pms_len,
1735 RSA_PKCS1_PADDING) ||
1736 /* Log the premaster secret, if logging is enabled. */
1737 !ssl_log_rsa_client_key_exchange(ssl, ptr, enc_pms_len, pms, pms_len) ||
1738 !CBB_did_write(enc_pms, enc_pms_len) ||
1739 !CBB_flush(&cbb)) {
1740 goto err;
1741 }
1742 } else if (alg_k & (SSL_kECDHE|SSL_kDHE|SSL_kCECPQ1)) {
1743 /* Generate a keypair and serialize the public half. */
1744 CBB child;
1745 if (!SSL_ECDH_CTX_add_key(&ssl->s3->tmp.ecdh_ctx, &cbb, &child)) {
1746 goto err;
1747 }
1748
1749 /* Compute the premaster. */
1750 uint8_t alert;
1751 if (!SSL_ECDH_CTX_accept(&ssl->s3->tmp.ecdh_ctx, &child, &pms, &pms_len,
1752 &alert, ssl->s3->tmp.peer_key,
1753 ssl->s3->tmp.peer_key_len)) {
1754 ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
1755 goto err;
1756 }
1757 if (!CBB_flush(&cbb)) {
1758 goto err;
1759 }
1760
1761 /* The key exchange state may now be discarded. */
1762 SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
1763 OPENSSL_free(ssl->s3->tmp.peer_key);
1764 ssl->s3->tmp.peer_key = NULL;
1765 } else if (alg_k & SSL_kPSK) {
1766 /* For plain PSK, other_secret is a block of 0s with the same length as
1767 * the pre-shared key. */
1768 pms_len = psk_len;
1769 pms = OPENSSL_malloc(pms_len);
1770 if (pms == NULL) {
1771 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1772 goto err;
1773 }
1774 memset(pms, 0, pms_len);
1775 } else {
1776 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1777 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1778 goto err;
1779 }
1780
1781 /* For a PSK cipher suite, other_secret is combined with the pre-shared
1782 * key. */
1783 if (alg_a & SSL_aPSK) {
1784 CBB pms_cbb, child;
1785 uint8_t *new_pms;
1786 size_t new_pms_len;
1787
1788 CBB_zero(&pms_cbb);
1789 if (!CBB_init(&pms_cbb, 2 + psk_len + 2 + pms_len) ||
1790 !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
1791 !CBB_add_bytes(&child, pms, pms_len) ||
1792 !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
1793 !CBB_add_bytes(&child, psk, psk_len) ||
1794 !CBB_finish(&pms_cbb, &new_pms, &new_pms_len)) {
1795 CBB_cleanup(&pms_cbb);
1796 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1797 goto err;
1798 }
1799 OPENSSL_cleanse(pms, pms_len);
1800 OPENSSL_free(pms);
1801 pms = new_pms;
1802 pms_len = new_pms_len;
1803 }
1804
1805 /* The message must be added to the finished hash before calculating the
1806 * master secret. */
1807 size_t length;
1808 if (!CBB_finish(&cbb, NULL, &length) ||
1809 !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_KEY_EXCHANGE, length)) {
1810 goto err;
1811 }
1812 ssl->state = SSL3_ST_CW_KEY_EXCH_B;
1813
1814 ssl->session->master_key_length =
1815 tls1_generate_master_secret(ssl, ssl->session->master_key, pms, pms_len);
1816 if (ssl->session->master_key_length == 0) {
1817 goto err;
1818 }
1819 ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
1820 OPENSSL_cleanse(pms, pms_len);
1821 OPENSSL_free(pms);
1822
1823 /* SSL3_ST_CW_KEY_EXCH_B */
1824 return ssl_do_write(ssl);
1825
1826 err:
1827 CBB_cleanup(&cbb);
1828 if (pms != NULL) {
1829 OPENSSL_cleanse(pms, pms_len);
1830 OPENSSL_free(pms);
1831 }
1832 return -1;
1833 }
1834
1835 static int ssl3_send_cert_verify(SSL *ssl) {
1836 if (ssl->state == SSL3_ST_CW_CERT_VRFY_C) {
1837 return ssl_do_write(ssl);
1838 }
1839
1840 CBB cbb, child;
1841 if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
1842 ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
1843 goto err;
1844 }
1845
1846 assert(ssl_has_private_key(ssl));
1847
1848 const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
1849 size_t sig_len;
1850 enum ssl_private_key_result_t sign_result;
1851 if (ssl->state == SSL3_ST_CW_CERT_VRFY_A) {
1852 /* Select and write out the digest type in TLS 1.2. */
1853 const EVP_MD *md = NULL;
1854 if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
1855 md = tls1_choose_signing_digest(ssl);
1856 if (!tls12_add_sigandhash(ssl, &cbb, md)) {
1857 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1858 goto err;
1859 }
1860 }
1861
1862 /* Compute the digest. In TLS 1.1 and below, the digest type is also
1863 * selected here. */
1864 uint8_t digest[EVP_MAX_MD_SIZE];
1865 size_t digest_len;
1866 if (!ssl3_cert_verify_hash(ssl, digest, &digest_len, &md,
1867 ssl_private_key_type(ssl))) {
1868 goto err;
1869 }
1870
1871 /* The handshake buffer is no longer necessary. */
1872 ssl3_free_handshake_buffer(ssl);
1873
1874 /* Sign the digest. */
1875 uint8_t *ptr;
1876 if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
1877 !CBB_reserve(&child, &ptr, max_sig_len)) {
1878 goto err;
1879 }
1880 sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
1881 digest, digest_len);
1882 } else {
1883 assert(ssl->state == SSL3_ST_CW_CERT_VRFY_B);
1884
1885 /* Skip over the already written signature algorithm and retry the
1886 * signature. */
1887 uint8_t *ptr;
1888 if ((ssl3_protocol_version(ssl) >= TLS1_2_VERSION &&
1889 !CBB_did_write(&cbb, 2)) ||
1890 !CBB_add_u16_length_prefixed(&cbb, &child) ||
1891 !CBB_reserve(&child, &ptr, max_sig_len)) {
1892 goto err;
1893 }
1894 sign_result =
1895 ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
1896 }
1897
1898 switch (sign_result) {
1899 case ssl_private_key_success:
1900 break;
1901 case ssl_private_key_failure:
1902 goto err;
1903 case ssl_private_key_retry:
1904 ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
1905 ssl->state = SSL3_ST_CW_CERT_VRFY_B;
1906 goto err;
1907 }
1908
1909 size_t length;
1910 if (!CBB_did_write(&child, sig_len) ||
1911 !CBB_finish(&cbb, NULL, &length) ||
1912 !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_VERIFY, length)) {
1913 goto err;
1914 }
1915
1916 ssl->state = SSL3_ST_CW_CERT_VRFY_C;
1917 return ssl_do_write(ssl);
1918
1919 err:
1920 CBB_cleanup(&cbb);
1921 return -1;
1922 }
1923
1924 static int ssl3_send_next_proto(SSL *ssl) {
1925 if (ssl->state == SSL3_ST_CW_NEXT_PROTO_B) {
1926 return ssl_do_write(ssl);
1927 }
1928
1929 assert(ssl->state == SSL3_ST_CW_NEXT_PROTO_A);
1930
1931 static const uint8_t kZero[32] = {0};
1932 size_t padding_len = 32 - ((ssl->s3->next_proto_negotiated_len + 2) % 32);
1933
1934 CBB cbb, child;
1935 size_t length;
1936 CBB_zero(&cbb);
1937 if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
1938 ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
1939 !CBB_add_u8_length_prefixed(&cbb, &child) ||
1940 !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated,
1941 ssl->s3->next_proto_negotiated_len) ||
1942 !CBB_add_u8_length_prefixed(&cbb, &child) ||
1943 !CBB_add_bytes(&child, kZero, padding_len) ||
1944 !CBB_finish(&cbb, NULL, &length) ||
1945 !ssl_set_handshake_header(ssl, SSL3_MT_NEXT_PROTO, length)) {
1946 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1947 CBB_cleanup(&cbb);
1948 return -1;
1949 }
1950
1951 ssl->state = SSL3_ST_CW_NEXT_PROTO_B;
1952 return ssl_do_write(ssl);
1953 }
1954
1955 static int ssl3_send_channel_id(SSL *ssl) {
1956 if (ssl->state == SSL3_ST_CW_CHANNEL_ID_B) {
1957 return ssl_do_write(ssl);
1958 }
1959
1960 assert(ssl->state == SSL3_ST_CW_CHANNEL_ID_A);
1961
1962 if (ssl->tlsext_channel_id_private == NULL &&
1963 ssl->ctx->channel_id_cb != NULL) {
1964 EVP_PKEY *key = NULL;
1965 ssl->ctx->channel_id_cb(ssl, &key);
1966 if (key != NULL &&
1967 !SSL_set1_tls_channel_id(ssl, key)) {
1968 EVP_PKEY_free(key);
1969 return -1;
1970 }
1971 EVP_PKEY_free(key);
1972 }
1973
1974 if (ssl->tlsext_channel_id_private == NULL) {
1975 ssl->rwstate = SSL_CHANNEL_ID_LOOKUP;
1976 return -1;
1977 }
1978
1979 EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(ssl->tlsext_channel_id_private);
1980 if (ec_key == NULL) {
1981 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1982 return -1;
1983 }
1984
1985 int ret = -1;
1986 BIGNUM *x = BN_new();
1987 BIGNUM *y = BN_new();
1988 ECDSA_SIG *sig = NULL;
1989 if (x == NULL || y == NULL ||
1990 !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
1991 EC_KEY_get0_public_key(ec_key),
1992 x, y, NULL)) {
1993 goto err;
1994 }
1995
1996 uint8_t digest[EVP_MAX_MD_SIZE];
1997 size_t digest_len;
1998 if (!tls1_channel_id_hash(ssl, digest, &digest_len)) {
1999 goto err;
2000 }
2001
2002 sig = ECDSA_do_sign(digest, digest_len, ec_key);
2003 if (sig == NULL) {
2004 goto err;
2005 }
2006
2007 CBB cbb, child;
2008 size_t length;
2009 CBB_zero(&cbb);
2010 if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
2011 ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
2012 !CBB_add_u16(&cbb, TLSEXT_TYPE_channel_id) ||
2013 !CBB_add_u16_length_prefixed(&cbb, &child) ||
2014 !BN_bn2cbb_padded(&child, 32, x) ||
2015 !BN_bn2cbb_padded(&child, 32, y) ||
2016 !BN_bn2cbb_padded(&child, 32, sig->r) ||
2017 !BN_bn2cbb_padded(&child, 32, sig->s) ||
2018 !CBB_finish(&cbb, NULL, &length) ||
2019 !ssl_set_handshake_header(ssl, SSL3_MT_CHANNEL_ID_ENCRYPTED_EXTENSIONS,
2020 length)) {
2021 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2022 CBB_cleanup(&cbb);
2023 goto err;
2024 }
2025
2026 ssl->state = SSL3_ST_CW_CHANNEL_ID_B;
2027 ret = ssl_do_write(ssl);
2028
2029 err:
2030 BN_free(x);
2031 BN_free(y);
2032 ECDSA_SIG_free(sig);
2033 return ret;
2034 }
2035
2036 static int ssl3_get_new_session_ticket(SSL *ssl) {
2037 int ok, al;
2038 long n = ssl->method->ssl_get_message(ssl, SSL3_MT_NEW_SESSION_TICKET,
2039 ssl_hash_message, &ok);
2040
2041 if (!ok) {
2042 return n;
2043 }
2044
2045 CBS new_session_ticket, ticket;
2046 uint32_t ticket_lifetime_hint;
2047 CBS_init(&new_session_ticket, ssl->init_msg, n);
2048 if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
2049 !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
2050 CBS_len(&new_session_ticket) != 0) {
2051 al = SSL_AD_DECODE_ERROR;
2052 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2053 goto f_err;
2054 }
2055
2056 if (CBS_len(&ticket) == 0) {
2057 /* RFC 5077 allows a server to change its mind and send no ticket after
2058 * negotiating the extension. The value of |tlsext_ticket_expected| is
2059 * checked in |ssl_update_cache| so is cleared here to avoid an unnecessary
2060 * update. */
2061 ssl->tlsext_ticket_expected = 0;
2062 return 1;
2063 }
2064
2065 if (ssl->hit) {
2066 /* The server is sending a new ticket for an existing session. Sessions are
2067 * immutable once established, so duplicate all but the ticket of the
2068 * existing session. */
2069 uint8_t *bytes;
2070 size_t bytes_len;
2071 if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &bytes, &bytes_len)) {
2072 goto err;
2073 }
2074 SSL_SESSION *new_session = SSL_SESSION_from_bytes(bytes, bytes_len);
2075 OPENSSL_free(bytes);
2076 if (new_session == NULL) {
2077 /* This should never happen. */
2078 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2079 goto err;
2080 }
2081
2082 SSL_SESSION_free(ssl->session);
2083 ssl->session = new_session;
2084 }
2085
2086 if (!CBS_stow(&ticket, &ssl->session->tlsext_tick,
2087 &ssl->session->tlsext_ticklen)) {
2088 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
2089 goto err;
2090 }
2091 ssl->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2092
2093 /* Generate a session ID for this session based on the session ticket. We use
2094 * the session ID mechanism for detecting ticket resumption. This also fits in
2095 * with assumptions elsewhere in OpenSSL.*/
2096 if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), ssl->session->session_id,
2097 &ssl->session->session_id_length, EVP_sha256(), NULL)) {
2098 goto err;
2099 }
2100
2101 return 1;
2102
2103 f_err:
2104 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
2105 err:
2106 return -1;
2107 }