handshake.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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-2002 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. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  110. * ECC cipher suite support in OpenSSL originally developed by
  111. * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */
  112. #include <openssl/ssl.h>
  113. #include <assert.h>
  114. #include <utility>
  115. #include <openssl/rand.h>
  116. #include "../crypto/internal.h"
  117. #include "internal.h"
  118. BSSL_NAMESPACE_BEGIN
  119. SSL_HANDSHAKE::SSL_HANDSHAKE(SSL *ssl_arg)
  120. : ssl(ssl_arg),
  121. scts_requested(false),
  122. needs_psk_binder(false),
  123. received_hello_retry_request(false),
  124. sent_hello_retry_request(false),
  125. handshake_finalized(false),
  126. accept_psk_mode(false),
  127. cert_request(false),
  128. certificate_status_expected(false),
  129. ocsp_stapling_requested(false),
  130. delegated_credential_requested(false),
  131. should_ack_sni(false),
  132. in_false_start(false),
  133. in_early_data(false),
  134. early_data_offered(false),
  135. can_early_read(false),
  136. can_early_write(false),
  137. next_proto_neg_seen(false),
  138. ticket_expected(false),
  139. extended_master_secret(false),
  140. pending_private_key_op(false),
  141. grease_seeded(false),
  142. handback(false),
  143. cert_compression_negotiated(false),
  144. apply_jdk11_workaround(false) {
  145. assert(ssl);
  146. }
  147. SSL_HANDSHAKE::~SSL_HANDSHAKE() {
  148. ssl->ctx->x509_method->hs_flush_cached_ca_names(this);
  149. }
  150. void SSL_HANDSHAKE::ResizeSecrets(size_t hash_len) {
  151. if (hash_len > SSL_MAX_MD_SIZE) {
  152. abort();
  153. }
  154. hash_len_ = hash_len;
  155. }
  156. UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl) {
  157. UniquePtr<SSL_HANDSHAKE> hs = MakeUnique<SSL_HANDSHAKE>(ssl);
  158. if (!hs || !hs->transcript.Init()) {
  159. return nullptr;
  160. }
  161. hs->config = ssl->config.get();
  162. if (!hs->config) {
  163. assert(hs->config);
  164. return nullptr;
  165. }
  166. return hs;
  167. }
  168. bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type) {
  169. if (msg.type != type) {
  170. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  171. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  172. ERR_add_error_dataf("got type %d, wanted type %d", msg.type, type);
  173. return false;
  174. }
  175. return true;
  176. }
  177. bool ssl_add_message_cbb(SSL *ssl, CBB *cbb) {
  178. Array<uint8_t> msg;
  179. if (!ssl->method->finish_message(ssl, cbb, &msg) ||
  180. !ssl->method->add_message(ssl, std::move(msg))) {
  181. return false;
  182. }
  183. return true;
  184. }
  185. size_t ssl_max_handshake_message_len(const SSL *ssl) {
  186. // kMaxMessageLen is the default maximum message size for handshakes which do
  187. // not accept peer certificate chains.
  188. static const size_t kMaxMessageLen = 16384;
  189. if (SSL_in_init(ssl)) {
  190. SSL_CONFIG *config = ssl->config.get(); // SSL_in_init() implies not NULL.
  191. if ((!ssl->server || (config->verify_mode & SSL_VERIFY_PEER)) &&
  192. kMaxMessageLen < ssl->max_cert_list) {
  193. return ssl->max_cert_list;
  194. }
  195. return kMaxMessageLen;
  196. }
  197. if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
  198. // In TLS 1.2 and below, the largest acceptable post-handshake message is
  199. // a HelloRequest.
  200. return 0;
  201. }
  202. if (ssl->server) {
  203. // The largest acceptable post-handshake message for a server is a
  204. // KeyUpdate. We will never initiate post-handshake auth.
  205. return 1;
  206. }
  207. // Clients must accept NewSessionTicket, so allow the default size.
  208. return kMaxMessageLen;
  209. }
  210. bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
  211. // V2ClientHello messages are pre-hashed.
  212. if (msg.is_v2_hello) {
  213. return true;
  214. }
  215. return hs->transcript.Update(msg.raw);
  216. }
  217. int ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
  218. const SSL_EXTENSION_TYPE *ext_types,
  219. size_t num_ext_types, int ignore_unknown) {
  220. // Reset everything.
  221. for (size_t i = 0; i < num_ext_types; i++) {
  222. *ext_types[i].out_present = 0;
  223. CBS_init(ext_types[i].out_data, NULL, 0);
  224. }
  225. CBS copy = *cbs;
  226. while (CBS_len(&copy) != 0) {
  227. uint16_t type;
  228. CBS data;
  229. if (!CBS_get_u16(&copy, &type) ||
  230. !CBS_get_u16_length_prefixed(&copy, &data)) {
  231. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  232. *out_alert = SSL_AD_DECODE_ERROR;
  233. return 0;
  234. }
  235. const SSL_EXTENSION_TYPE *ext_type = NULL;
  236. for (size_t i = 0; i < num_ext_types; i++) {
  237. if (type == ext_types[i].type) {
  238. ext_type = &ext_types[i];
  239. break;
  240. }
  241. }
  242. if (ext_type == NULL) {
  243. if (ignore_unknown) {
  244. continue;
  245. }
  246. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
  247. *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
  248. return 0;
  249. }
  250. // Duplicate ext_types are forbidden.
  251. if (*ext_type->out_present) {
  252. OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_EXTENSION);
  253. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  254. return 0;
  255. }
  256. *ext_type->out_present = 1;
  257. *ext_type->out_data = data;
  258. }
  259. return 1;
  260. }
  261. enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs) {
  262. SSL *const ssl = hs->ssl;
  263. const SSL_SESSION *prev_session = ssl->s3->established_session.get();
  264. if (prev_session != NULL) {
  265. // If renegotiating, the server must not change the server certificate. See
  266. // https://mitls.org/pages/attacks/3SHAKE. We never resume on renegotiation,
  267. // so this check is sufficient to ensure the reported peer certificate never
  268. // changes on renegotiation.
  269. assert(!ssl->server);
  270. if (sk_CRYPTO_BUFFER_num(prev_session->certs.get()) !=
  271. sk_CRYPTO_BUFFER_num(hs->new_session->certs.get())) {
  272. OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
  273. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  274. return ssl_verify_invalid;
  275. }
  276. for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(hs->new_session->certs.get());
  277. i++) {
  278. const CRYPTO_BUFFER *old_cert =
  279. sk_CRYPTO_BUFFER_value(prev_session->certs.get(), i);
  280. const CRYPTO_BUFFER *new_cert =
  281. sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), i);
  282. if (CRYPTO_BUFFER_len(old_cert) != CRYPTO_BUFFER_len(new_cert) ||
  283. OPENSSL_memcmp(CRYPTO_BUFFER_data(old_cert),
  284. CRYPTO_BUFFER_data(new_cert),
  285. CRYPTO_BUFFER_len(old_cert)) != 0) {
  286. OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
  287. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  288. return ssl_verify_invalid;
  289. }
  290. }
  291. // The certificate is identical, so we may skip re-verifying the
  292. // certificate. Since we only authenticated the previous one, copy other
  293. // authentication from the established session and ignore what was newly
  294. // received.
  295. hs->new_session->ocsp_response = UpRef(prev_session->ocsp_response);
  296. hs->new_session->signed_cert_timestamp_list =
  297. UpRef(prev_session->signed_cert_timestamp_list);
  298. hs->new_session->verify_result = prev_session->verify_result;
  299. return ssl_verify_ok;
  300. }
  301. uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
  302. enum ssl_verify_result_t ret;
  303. if (hs->config->custom_verify_callback != nullptr) {
  304. ret = hs->config->custom_verify_callback(ssl, &alert);
  305. switch (ret) {
  306. case ssl_verify_ok:
  307. hs->new_session->verify_result = X509_V_OK;
  308. break;
  309. case ssl_verify_invalid:
  310. // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result.
  311. if (hs->config->verify_mode == SSL_VERIFY_NONE) {
  312. ERR_clear_error();
  313. ret = ssl_verify_ok;
  314. }
  315. hs->new_session->verify_result = X509_V_ERR_APPLICATION_VERIFICATION;
  316. break;
  317. case ssl_verify_retry:
  318. break;
  319. }
  320. } else {
  321. ret = ssl->ctx->x509_method->session_verify_cert_chain(
  322. hs->new_session.get(), hs, &alert)
  323. ? ssl_verify_ok
  324. : ssl_verify_invalid;
  325. }
  326. if (ret == ssl_verify_invalid) {
  327. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  328. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  329. }
  330. // Emulate OpenSSL's client OCSP callback. OpenSSL verifies certificates
  331. // before it receives the OCSP, so it needs a second callback for OCSP.
  332. if (ret == ssl_verify_ok && !ssl->server &&
  333. hs->config->ocsp_stapling_enabled &&
  334. ssl->ctx->legacy_ocsp_callback != nullptr) {
  335. int cb_ret =
  336. ssl->ctx->legacy_ocsp_callback(ssl, ssl->ctx->legacy_ocsp_callback_arg);
  337. if (cb_ret <= 0) {
  338. OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
  339. ssl_send_alert(ssl, SSL3_AL_FATAL,
  340. cb_ret == 0 ? SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
  341. : SSL_AD_INTERNAL_ERROR);
  342. ret = ssl_verify_invalid;
  343. }
  344. }
  345. return ret;
  346. }
  347. // Verifies a stored certificate when resuming a session. A few things are
  348. // different from verify_peer_cert:
  349. // 1. We can't be renegotiating if we're resuming a session.
  350. // 2. The session is immutable, so we don't support verify_mode ==
  351. // SSL_VERIFY_NONE
  352. // 3. We don't call the OCSP callback.
  353. // 4. We only support custom verify callbacks.
  354. enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs) {
  355. SSL *const ssl = hs->ssl;
  356. assert(ssl->s3->established_session == nullptr);
  357. assert(hs->config->verify_mode != SSL_VERIFY_NONE);
  358. uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
  359. enum ssl_verify_result_t ret = ssl_verify_invalid;
  360. if (hs->config->custom_verify_callback != nullptr) {
  361. ret = hs->config->custom_verify_callback(ssl, &alert);
  362. }
  363. if (ret == ssl_verify_invalid) {
  364. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  365. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  366. }
  367. return ret;
  368. }
  369. uint16_t ssl_get_grease_value(SSL_HANDSHAKE *hs,
  370. enum ssl_grease_index_t index) {
  371. // Draw entropy for all GREASE values at once. This avoids calling
  372. // |RAND_bytes| repeatedly and makes the values consistent within a
  373. // connection. The latter is so the second ClientHello matches after
  374. // HelloRetryRequest and so supported_groups and key_shares are consistent.
  375. if (!hs->grease_seeded) {
  376. RAND_bytes(hs->grease_seed, sizeof(hs->grease_seed));
  377. hs->grease_seeded = true;
  378. }
  379. // This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16.
  380. uint16_t ret = hs->grease_seed[index];
  381. ret = (ret & 0xf0) | 0x0a;
  382. ret |= ret << 8;
  383. return ret;
  384. }
  385. enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs) {
  386. SSL *const ssl = hs->ssl;
  387. SSLMessage msg;
  388. if (!ssl->method->get_message(ssl, &msg)) {
  389. return ssl_hs_read_message;
  390. }
  391. if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED)) {
  392. return ssl_hs_error;
  393. }
  394. // Snapshot the finished hash before incorporating the new message.
  395. uint8_t finished[EVP_MAX_MD_SIZE];
  396. size_t finished_len;
  397. if (!hs->transcript.GetFinishedMAC(finished, &finished_len,
  398. SSL_get_session(ssl), !ssl->server) ||
  399. !ssl_hash_message(hs, msg)) {
  400. return ssl_hs_error;
  401. }
  402. int finished_ok = CBS_mem_equal(&msg.body, finished, finished_len);
  403. #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  404. finished_ok = 1;
  405. #endif
  406. if (!finished_ok) {
  407. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
  408. OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
  409. return ssl_hs_error;
  410. }
  411. // Copy the Finished so we can use it for renegotiation checks.
  412. if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
  413. finished_len > sizeof(ssl->s3->previous_server_finished)) {
  414. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  415. return ssl_hs_error;
  416. }
  417. if (ssl->server) {
  418. OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
  419. ssl->s3->previous_client_finished_len = finished_len;
  420. } else {
  421. OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
  422. ssl->s3->previous_server_finished_len = finished_len;
  423. }
  424. ssl->method->next_message(ssl);
  425. return ssl_hs_ok;
  426. }
  427. bool ssl_send_finished(SSL_HANDSHAKE *hs) {
  428. SSL *const ssl = hs->ssl;
  429. const SSL_SESSION *session = SSL_get_session(ssl);
  430. uint8_t finished[EVP_MAX_MD_SIZE];
  431. size_t finished_len;
  432. if (!hs->transcript.GetFinishedMAC(finished, &finished_len, session,
  433. ssl->server)) {
  434. return 0;
  435. }
  436. // Log the master secret, if logging is enabled.
  437. if (!ssl_log_secret(
  438. ssl, "CLIENT_RANDOM",
  439. MakeConstSpan(session->master_key, session->master_key_length))) {
  440. return 0;
  441. }
  442. // Copy the Finished so we can use it for renegotiation checks.
  443. if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
  444. finished_len > sizeof(ssl->s3->previous_server_finished)) {
  445. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  446. return 0;
  447. }
  448. if (ssl->server) {
  449. OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
  450. ssl->s3->previous_server_finished_len = finished_len;
  451. } else {
  452. OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
  453. ssl->s3->previous_client_finished_len = finished_len;
  454. }
  455. ScopedCBB cbb;
  456. CBB body;
  457. if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
  458. !CBB_add_bytes(&body, finished, finished_len) ||
  459. !ssl_add_message_cbb(ssl, cbb.get())) {
  460. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  461. return 0;
  462. }
  463. return 1;
  464. }
  465. bool ssl_output_cert_chain(SSL_HANDSHAKE *hs) {
  466. ScopedCBB cbb;
  467. CBB body;
  468. if (!hs->ssl->method->init_message(hs->ssl, cbb.get(), &body,
  469. SSL3_MT_CERTIFICATE) ||
  470. !ssl_add_cert_chain(hs, &body) ||
  471. !ssl_add_message_cbb(hs->ssl, cbb.get())) {
  472. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  473. return false;
  474. }
  475. return true;
  476. }
  477. int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) {
  478. SSL *const ssl = hs->ssl;
  479. for (;;) {
  480. // Resolve the operation the handshake was waiting on.
  481. switch (hs->wait) {
  482. case ssl_hs_error:
  483. ERR_restore_state(hs->error.get());
  484. return -1;
  485. case ssl_hs_flush: {
  486. int ret = ssl->method->flush_flight(ssl);
  487. if (ret <= 0) {
  488. return ret;
  489. }
  490. break;
  491. }
  492. case ssl_hs_read_server_hello:
  493. case ssl_hs_read_message:
  494. case ssl_hs_read_change_cipher_spec: {
  495. if (ssl->quic_method) {
  496. hs->wait = ssl_hs_ok;
  497. // The change cipher spec is omitted in QUIC.
  498. if (hs->wait != ssl_hs_read_change_cipher_spec) {
  499. ssl->s3->rwstate = SSL_ERROR_WANT_READ;
  500. return -1;
  501. }
  502. break;
  503. }
  504. uint8_t alert = SSL_AD_DECODE_ERROR;
  505. size_t consumed = 0;
  506. ssl_open_record_t ret;
  507. if (hs->wait == ssl_hs_read_change_cipher_spec) {
  508. ret = ssl_open_change_cipher_spec(ssl, &consumed, &alert,
  509. ssl->s3->read_buffer.span());
  510. } else {
  511. ret = ssl_open_handshake(ssl, &consumed, &alert,
  512. ssl->s3->read_buffer.span());
  513. }
  514. if (ret == ssl_open_record_error &&
  515. hs->wait == ssl_hs_read_server_hello) {
  516. uint32_t err = ERR_peek_error();
  517. if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
  518. ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
  519. // Add a dedicated error code to the queue for a handshake_failure
  520. // alert in response to ClientHello. This matches NSS's client
  521. // behavior and gives a better error on a (probable) failure to
  522. // negotiate initial parameters. Note: this error code comes after
  523. // the original one.
  524. //
  525. // See https://crbug.com/446505.
  526. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
  527. }
  528. }
  529. bool retry;
  530. int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
  531. if (bio_ret <= 0) {
  532. return bio_ret;
  533. }
  534. if (retry) {
  535. continue;
  536. }
  537. ssl->s3->read_buffer.DiscardConsumed();
  538. break;
  539. }
  540. case ssl_hs_read_end_of_early_data: {
  541. if (ssl->s3->hs->can_early_read) {
  542. // While we are processing early data, the handshake returns early.
  543. *out_early_return = true;
  544. return 1;
  545. }
  546. hs->wait = ssl_hs_ok;
  547. break;
  548. }
  549. case ssl_hs_certificate_selection_pending:
  550. ssl->s3->rwstate = SSL_ERROR_PENDING_CERTIFICATE;
  551. hs->wait = ssl_hs_ok;
  552. return -1;
  553. case ssl_hs_handoff:
  554. ssl->s3->rwstate = SSL_ERROR_HANDOFF;
  555. hs->wait = ssl_hs_ok;
  556. return -1;
  557. case ssl_hs_handback:
  558. ssl->s3->rwstate = SSL_ERROR_HANDBACK;
  559. hs->wait = ssl_hs_handback;
  560. return -1;
  561. case ssl_hs_x509_lookup:
  562. ssl->s3->rwstate = SSL_ERROR_WANT_X509_LOOKUP;
  563. hs->wait = ssl_hs_ok;
  564. return -1;
  565. case ssl_hs_channel_id_lookup:
  566. ssl->s3->rwstate = SSL_ERROR_WANT_CHANNEL_ID_LOOKUP;
  567. hs->wait = ssl_hs_ok;
  568. return -1;
  569. case ssl_hs_private_key_operation:
  570. ssl->s3->rwstate = SSL_ERROR_WANT_PRIVATE_KEY_OPERATION;
  571. hs->wait = ssl_hs_ok;
  572. return -1;
  573. case ssl_hs_pending_session:
  574. ssl->s3->rwstate = SSL_ERROR_PENDING_SESSION;
  575. hs->wait = ssl_hs_ok;
  576. return -1;
  577. case ssl_hs_pending_ticket:
  578. ssl->s3->rwstate = SSL_ERROR_PENDING_TICKET;
  579. hs->wait = ssl_hs_ok;
  580. return -1;
  581. case ssl_hs_certificate_verify:
  582. ssl->s3->rwstate = SSL_ERROR_WANT_CERTIFICATE_VERIFY;
  583. hs->wait = ssl_hs_ok;
  584. return -1;
  585. case ssl_hs_early_data_rejected:
  586. assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
  587. ssl->s3->rwstate = SSL_ERROR_EARLY_DATA_REJECTED;
  588. // Cause |SSL_write| to start failing immediately.
  589. hs->can_early_write = false;
  590. return -1;
  591. case ssl_hs_early_return:
  592. *out_early_return = true;
  593. hs->wait = ssl_hs_ok;
  594. return 1;
  595. case ssl_hs_ok:
  596. break;
  597. }
  598. // Run the state machine again.
  599. hs->wait = ssl->do_handshake(hs);
  600. if (hs->wait == ssl_hs_error) {
  601. hs->error.reset(ERR_save_state());
  602. return -1;
  603. }
  604. if (hs->wait == ssl_hs_ok) {
  605. // The handshake has completed.
  606. *out_early_return = false;
  607. return 1;
  608. }
  609. // Otherwise, loop to the beginning and resolve what was blocking the
  610. // handshake.
  611. }
  612. }
  613. BSSL_NAMESPACE_END