s3_both.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 <limits.h>
  115. #include <string.h>
  116. #include <tuple>
  117. #include <openssl/buf.h>
  118. #include <openssl/bytestring.h>
  119. #include <openssl/err.h>
  120. #include <openssl/evp.h>
  121. #include <openssl/mem.h>
  122. #include <openssl/md5.h>
  123. #include <openssl/nid.h>
  124. #include <openssl/rand.h>
  125. #include <openssl/sha.h>
  126. #include "../crypto/internal.h"
  127. #include "internal.h"
  128. BSSL_NAMESPACE_BEGIN
  129. static bool add_record_to_flight(SSL *ssl, uint8_t type,
  130. Span<const uint8_t> in) {
  131. // The caller should have flushed |pending_hs_data| first.
  132. assert(!ssl->s3->pending_hs_data);
  133. // We'll never add a flight while in the process of writing it out.
  134. assert(ssl->s3->pending_flight_offset == 0);
  135. if (ssl->s3->pending_flight == nullptr) {
  136. ssl->s3->pending_flight.reset(BUF_MEM_new());
  137. if (ssl->s3->pending_flight == nullptr) {
  138. return false;
  139. }
  140. }
  141. size_t max_out = in.size() + SSL_max_seal_overhead(ssl);
  142. size_t new_cap = ssl->s3->pending_flight->length + max_out;
  143. if (max_out < in.size() || new_cap < max_out) {
  144. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  145. return false;
  146. }
  147. size_t len;
  148. if (!BUF_MEM_reserve(ssl->s3->pending_flight.get(), new_cap) ||
  149. !tls_seal_record(ssl,
  150. (uint8_t *)ssl->s3->pending_flight->data +
  151. ssl->s3->pending_flight->length,
  152. &len, max_out, type, in.data(), in.size())) {
  153. return false;
  154. }
  155. ssl->s3->pending_flight->length += len;
  156. return true;
  157. }
  158. bool ssl3_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  159. // Pick a modest size hint to save most of the |realloc| calls.
  160. if (!CBB_init(cbb, 64) ||
  161. !CBB_add_u8(cbb, type) ||
  162. !CBB_add_u24_length_prefixed(cbb, body)) {
  163. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  164. CBB_cleanup(cbb);
  165. return false;
  166. }
  167. return true;
  168. }
  169. bool ssl3_finish_message(SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg) {
  170. return CBBFinishArray(cbb, out_msg);
  171. }
  172. bool ssl3_add_message(SSL *ssl, Array<uint8_t> msg) {
  173. // Pack handshake data into the minimal number of records. This avoids
  174. // unnecessary encryption overhead, notably in TLS 1.3 where we send several
  175. // encrypted messages in a row. For now, we do not do this for the null
  176. // cipher. The benefit is smaller and there is a risk of breaking buggy
  177. // implementations.
  178. //
  179. // TODO(davidben): See if we can do this uniformly.
  180. Span<const uint8_t> rest = msg;
  181. if (ssl->quic_method == nullptr &&
  182. ssl->s3->aead_write_ctx->is_null_cipher()) {
  183. while (!rest.empty()) {
  184. Span<const uint8_t> chunk = rest.subspan(0, ssl->max_send_fragment);
  185. rest = rest.subspan(chunk.size());
  186. if (!add_record_to_flight(ssl, SSL3_RT_HANDSHAKE, chunk)) {
  187. return false;
  188. }
  189. }
  190. } else {
  191. while (!rest.empty()) {
  192. // Flush if |pending_hs_data| is full.
  193. if (ssl->s3->pending_hs_data &&
  194. ssl->s3->pending_hs_data->length >= ssl->max_send_fragment &&
  195. !tls_flush_pending_hs_data(ssl)) {
  196. return false;
  197. }
  198. size_t pending_len =
  199. ssl->s3->pending_hs_data ? ssl->s3->pending_hs_data->length : 0;
  200. Span<const uint8_t> chunk =
  201. rest.subspan(0, ssl->max_send_fragment - pending_len);
  202. assert(!chunk.empty());
  203. rest = rest.subspan(chunk.size());
  204. if (!ssl->s3->pending_hs_data) {
  205. ssl->s3->pending_hs_data.reset(BUF_MEM_new());
  206. }
  207. if (!ssl->s3->pending_hs_data ||
  208. !BUF_MEM_append(ssl->s3->pending_hs_data.get(), chunk.data(),
  209. chunk.size())) {
  210. return false;
  211. }
  212. }
  213. }
  214. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HANDSHAKE, msg);
  215. // TODO(svaldez): Move this up a layer to fix abstraction for SSLTranscript on
  216. // hs.
  217. if (ssl->s3->hs != NULL &&
  218. !ssl->s3->hs->transcript.Update(msg)) {
  219. return false;
  220. }
  221. return true;
  222. }
  223. bool tls_flush_pending_hs_data(SSL *ssl) {
  224. if (!ssl->s3->pending_hs_data || ssl->s3->pending_hs_data->length == 0) {
  225. return true;
  226. }
  227. UniquePtr<BUF_MEM> pending_hs_data = std::move(ssl->s3->pending_hs_data);
  228. auto data =
  229. MakeConstSpan(reinterpret_cast<const uint8_t *>(pending_hs_data->data),
  230. pending_hs_data->length);
  231. if (ssl->quic_method) {
  232. if (!ssl->quic_method->add_handshake_data(ssl, ssl->s3->write_level,
  233. data.data(), data.size())) {
  234. OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_INTERNAL_ERROR);
  235. return false;
  236. }
  237. return true;
  238. }
  239. return add_record_to_flight(ssl, SSL3_RT_HANDSHAKE, data);
  240. }
  241. bool ssl3_add_change_cipher_spec(SSL *ssl) {
  242. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  243. if (!tls_flush_pending_hs_data(ssl)) {
  244. return false;
  245. }
  246. if (!ssl->quic_method &&
  247. !add_record_to_flight(ssl, SSL3_RT_CHANGE_CIPHER_SPEC,
  248. kChangeCipherSpec)) {
  249. return false;
  250. }
  251. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_CHANGE_CIPHER_SPEC,
  252. kChangeCipherSpec);
  253. return true;
  254. }
  255. int ssl3_flush_flight(SSL *ssl) {
  256. if (!tls_flush_pending_hs_data(ssl)) {
  257. return -1;
  258. }
  259. if (ssl->quic_method) {
  260. if (ssl->s3->write_shutdown != ssl_shutdown_none) {
  261. OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
  262. return -1;
  263. }
  264. if (!ssl->quic_method->flush_flight(ssl)) {
  265. OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_INTERNAL_ERROR);
  266. return -1;
  267. }
  268. }
  269. if (ssl->s3->pending_flight == nullptr) {
  270. return 1;
  271. }
  272. if (ssl->s3->write_shutdown != ssl_shutdown_none) {
  273. OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
  274. return -1;
  275. }
  276. static_assert(INT_MAX <= 0xffffffff, "int is larger than 32 bits");
  277. if (ssl->s3->pending_flight->length > INT_MAX) {
  278. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  279. return -1;
  280. }
  281. // If there is pending data in the write buffer, it must be flushed out before
  282. // any new data in pending_flight.
  283. if (!ssl->s3->write_buffer.empty()) {
  284. int ret = ssl_write_buffer_flush(ssl);
  285. if (ret <= 0) {
  286. ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
  287. return ret;
  288. }
  289. }
  290. // Write the pending flight.
  291. while (ssl->s3->pending_flight_offset < ssl->s3->pending_flight->length) {
  292. int ret = BIO_write(
  293. ssl->wbio.get(),
  294. ssl->s3->pending_flight->data + ssl->s3->pending_flight_offset,
  295. ssl->s3->pending_flight->length - ssl->s3->pending_flight_offset);
  296. if (ret <= 0) {
  297. ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
  298. return ret;
  299. }
  300. ssl->s3->pending_flight_offset += ret;
  301. }
  302. if (BIO_flush(ssl->wbio.get()) <= 0) {
  303. ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
  304. return -1;
  305. }
  306. ssl->s3->pending_flight.reset();
  307. ssl->s3->pending_flight_offset = 0;
  308. return 1;
  309. }
  310. static ssl_open_record_t read_v2_client_hello(SSL *ssl, size_t *out_consumed,
  311. Span<const uint8_t> in) {
  312. *out_consumed = 0;
  313. assert(in.size() >= SSL3_RT_HEADER_LENGTH);
  314. // Determine the length of the V2ClientHello.
  315. size_t msg_length = ((in[0] & 0x7f) << 8) | in[1];
  316. if (msg_length > (1024 * 4)) {
  317. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  318. return ssl_open_record_error;
  319. }
  320. if (msg_length < SSL3_RT_HEADER_LENGTH - 2) {
  321. // Reject lengths that are too short early. We have already read
  322. // |SSL3_RT_HEADER_LENGTH| bytes, so we should not attempt to process an
  323. // (invalid) V2ClientHello which would be shorter than that.
  324. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_LENGTH_MISMATCH);
  325. return ssl_open_record_error;
  326. }
  327. // Ask for the remainder of the V2ClientHello.
  328. if (in.size() < 2 + msg_length) {
  329. *out_consumed = 2 + msg_length;
  330. return ssl_open_record_partial;
  331. }
  332. CBS v2_client_hello = CBS(ssl->s3->read_buffer.span().subspan(2, msg_length));
  333. // The V2ClientHello without the length is incorporated into the handshake
  334. // hash. This is only ever called at the start of the handshake, so hs is
  335. // guaranteed to be non-NULL.
  336. if (!ssl->s3->hs->transcript.Update(v2_client_hello)) {
  337. return ssl_open_record_error;
  338. }
  339. ssl_do_msg_callback(ssl, 0 /* read */, 0 /* V2ClientHello */,
  340. v2_client_hello);
  341. uint8_t msg_type;
  342. uint16_t version, cipher_spec_length, session_id_length, challenge_length;
  343. CBS cipher_specs, session_id, challenge;
  344. if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
  345. !CBS_get_u16(&v2_client_hello, &version) ||
  346. !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
  347. !CBS_get_u16(&v2_client_hello, &session_id_length) ||
  348. !CBS_get_u16(&v2_client_hello, &challenge_length) ||
  349. !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
  350. !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
  351. !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
  352. CBS_len(&v2_client_hello) != 0) {
  353. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  354. return ssl_open_record_error;
  355. }
  356. // msg_type has already been checked.
  357. assert(msg_type == SSL2_MT_CLIENT_HELLO);
  358. // The client_random is the V2ClientHello challenge. Truncate or left-pad with
  359. // zeros as needed.
  360. size_t rand_len = CBS_len(&challenge);
  361. if (rand_len > SSL3_RANDOM_SIZE) {
  362. rand_len = SSL3_RANDOM_SIZE;
  363. }
  364. uint8_t random[SSL3_RANDOM_SIZE];
  365. OPENSSL_memset(random, 0, SSL3_RANDOM_SIZE);
  366. OPENSSL_memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
  367. rand_len);
  368. // Write out an equivalent TLS ClientHello directly to the handshake buffer.
  369. size_t max_v3_client_hello = SSL3_HM_HEADER_LENGTH + 2 /* version */ +
  370. SSL3_RANDOM_SIZE + 1 /* session ID length */ +
  371. 2 /* cipher list length */ +
  372. CBS_len(&cipher_specs) / 3 * 2 +
  373. 1 /* compression length */ + 1 /* compression */;
  374. ScopedCBB client_hello;
  375. CBB hello_body, cipher_suites;
  376. if (!ssl->s3->hs_buf) {
  377. ssl->s3->hs_buf.reset(BUF_MEM_new());
  378. }
  379. if (!ssl->s3->hs_buf ||
  380. !BUF_MEM_reserve(ssl->s3->hs_buf.get(), max_v3_client_hello) ||
  381. !CBB_init_fixed(client_hello.get(), (uint8_t *)ssl->s3->hs_buf->data,
  382. ssl->s3->hs_buf->max) ||
  383. !CBB_add_u8(client_hello.get(), SSL3_MT_CLIENT_HELLO) ||
  384. !CBB_add_u24_length_prefixed(client_hello.get(), &hello_body) ||
  385. !CBB_add_u16(&hello_body, version) ||
  386. !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
  387. // No session id.
  388. !CBB_add_u8(&hello_body, 0) ||
  389. !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
  390. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  391. return ssl_open_record_error;
  392. }
  393. // Copy the cipher suites.
  394. while (CBS_len(&cipher_specs) > 0) {
  395. uint32_t cipher_spec;
  396. if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
  397. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  398. return ssl_open_record_error;
  399. }
  400. // Skip SSLv2 ciphers.
  401. if ((cipher_spec & 0xff0000) != 0) {
  402. continue;
  403. }
  404. if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
  405. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  406. return ssl_open_record_error;
  407. }
  408. }
  409. // Add the null compression scheme and finish.
  410. if (!CBB_add_u8(&hello_body, 1) ||
  411. !CBB_add_u8(&hello_body, 0) ||
  412. !CBB_finish(client_hello.get(), NULL, &ssl->s3->hs_buf->length)) {
  413. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  414. return ssl_open_record_error;
  415. }
  416. *out_consumed = 2 + msg_length;
  417. ssl->s3->is_v2_hello = true;
  418. return ssl_open_record_success;
  419. }
  420. static bool parse_message(const SSL *ssl, SSLMessage *out,
  421. size_t *out_bytes_needed) {
  422. if (!ssl->s3->hs_buf) {
  423. *out_bytes_needed = 4;
  424. return false;
  425. }
  426. CBS cbs;
  427. uint32_t len;
  428. CBS_init(&cbs, reinterpret_cast<const uint8_t *>(ssl->s3->hs_buf->data),
  429. ssl->s3->hs_buf->length);
  430. if (!CBS_get_u8(&cbs, &out->type) ||
  431. !CBS_get_u24(&cbs, &len)) {
  432. *out_bytes_needed = 4;
  433. return false;
  434. }
  435. if (!CBS_get_bytes(&cbs, &out->body, len)) {
  436. *out_bytes_needed = 4 + len;
  437. return false;
  438. }
  439. CBS_init(&out->raw, reinterpret_cast<const uint8_t *>(ssl->s3->hs_buf->data),
  440. 4 + len);
  441. out->is_v2_hello = ssl->s3->is_v2_hello;
  442. return true;
  443. }
  444. bool ssl3_get_message(const SSL *ssl, SSLMessage *out) {
  445. size_t unused;
  446. if (!parse_message(ssl, out, &unused)) {
  447. return false;
  448. }
  449. if (!ssl->s3->has_message) {
  450. if (!out->is_v2_hello) {
  451. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, out->raw);
  452. }
  453. ssl->s3->has_message = true;
  454. }
  455. return true;
  456. }
  457. bool tls_can_accept_handshake_data(const SSL *ssl, uint8_t *out_alert) {
  458. // If there is a complete message, the caller must have consumed it first.
  459. SSLMessage msg;
  460. size_t bytes_needed;
  461. if (parse_message(ssl, &msg, &bytes_needed)) {
  462. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  463. *out_alert = SSL_AD_INTERNAL_ERROR;
  464. return false;
  465. }
  466. // Enforce the limit so the peer cannot force us to buffer 16MB.
  467. if (bytes_needed > 4 + ssl_max_handshake_message_len(ssl)) {
  468. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  469. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  470. return false;
  471. }
  472. return true;
  473. }
  474. bool tls_has_unprocessed_handshake_data(const SSL *ssl) {
  475. size_t msg_len = 0;
  476. if (ssl->s3->has_message) {
  477. SSLMessage msg;
  478. size_t unused;
  479. if (parse_message(ssl, &msg, &unused)) {
  480. msg_len = CBS_len(&msg.raw);
  481. }
  482. }
  483. return ssl->s3->hs_buf && ssl->s3->hs_buf->length > msg_len;
  484. }
  485. bool tls_append_handshake_data(SSL *ssl, Span<const uint8_t> data) {
  486. // Re-create the handshake buffer if needed.
  487. if (!ssl->s3->hs_buf) {
  488. ssl->s3->hs_buf.reset(BUF_MEM_new());
  489. }
  490. return ssl->s3->hs_buf &&
  491. BUF_MEM_append(ssl->s3->hs_buf.get(), data.data(), data.size());
  492. }
  493. ssl_open_record_t ssl3_open_handshake(SSL *ssl, size_t *out_consumed,
  494. uint8_t *out_alert, Span<uint8_t> in) {
  495. *out_consumed = 0;
  496. // Bypass the record layer for the first message to handle V2ClientHello.
  497. if (ssl->server && !ssl->s3->v2_hello_done) {
  498. // Ask for the first 5 bytes, the size of the TLS record header. This is
  499. // sufficient to detect a V2ClientHello and ensures that we never read
  500. // beyond the first record.
  501. if (in.size() < SSL3_RT_HEADER_LENGTH) {
  502. *out_consumed = SSL3_RT_HEADER_LENGTH;
  503. return ssl_open_record_partial;
  504. }
  505. // Some dedicated error codes for protocol mixups should the application
  506. // wish to interpret them differently. (These do not overlap with
  507. // ClientHello or V2ClientHello.)
  508. const char *str = reinterpret_cast<const char*>(in.data());
  509. if (strncmp("GET ", str, 4) == 0 ||
  510. strncmp("POST ", str, 5) == 0 ||
  511. strncmp("HEAD ", str, 5) == 0 ||
  512. strncmp("PUT ", str, 4) == 0) {
  513. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTP_REQUEST);
  514. *out_alert = 0;
  515. return ssl_open_record_error;
  516. }
  517. if (strncmp("CONNE", str, 5) == 0) {
  518. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTPS_PROXY_REQUEST);
  519. *out_alert = 0;
  520. return ssl_open_record_error;
  521. }
  522. // Check for a V2ClientHello.
  523. if ((in[0] & 0x80) != 0 && in[2] == SSL2_MT_CLIENT_HELLO &&
  524. in[3] == SSL3_VERSION_MAJOR) {
  525. auto ret = read_v2_client_hello(ssl, out_consumed, in);
  526. if (ret == ssl_open_record_error) {
  527. *out_alert = 0;
  528. } else if (ret == ssl_open_record_success) {
  529. ssl->s3->v2_hello_done = true;
  530. }
  531. return ret;
  532. }
  533. ssl->s3->v2_hello_done = true;
  534. }
  535. uint8_t type;
  536. Span<uint8_t> body;
  537. auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
  538. if (ret != ssl_open_record_success) {
  539. return ret;
  540. }
  541. // WatchGuard's TLS 1.3 interference bug is very distinctive: they drop the
  542. // ServerHello and send the remaining encrypted application data records
  543. // as-is. This manifests as an application data record when we expect
  544. // handshake. Report a dedicated error code for this case.
  545. if (!ssl->server && type == SSL3_RT_APPLICATION_DATA &&
  546. ssl->s3->aead_read_ctx->is_null_cipher()) {
  547. OPENSSL_PUT_ERROR(SSL, SSL_R_APPLICATION_DATA_INSTEAD_OF_HANDSHAKE);
  548. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  549. return ssl_open_record_error;
  550. }
  551. if (type != SSL3_RT_HANDSHAKE) {
  552. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  553. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  554. return ssl_open_record_error;
  555. }
  556. // Append the entire handshake record to the buffer.
  557. if (!tls_append_handshake_data(ssl, body)) {
  558. *out_alert = SSL_AD_INTERNAL_ERROR;
  559. return ssl_open_record_error;
  560. }
  561. return ssl_open_record_success;
  562. }
  563. void ssl3_next_message(SSL *ssl) {
  564. SSLMessage msg;
  565. if (!ssl3_get_message(ssl, &msg) ||
  566. !ssl->s3->hs_buf ||
  567. ssl->s3->hs_buf->length < CBS_len(&msg.raw)) {
  568. assert(0);
  569. return;
  570. }
  571. OPENSSL_memmove(ssl->s3->hs_buf->data,
  572. ssl->s3->hs_buf->data + CBS_len(&msg.raw),
  573. ssl->s3->hs_buf->length - CBS_len(&msg.raw));
  574. ssl->s3->hs_buf->length -= CBS_len(&msg.raw);
  575. ssl->s3->is_v2_hello = false;
  576. ssl->s3->has_message = false;
  577. // Post-handshake messages are rare, so release the buffer after every
  578. // message. During the handshake, |on_handshake_complete| will release it.
  579. if (!SSL_in_init(ssl) && ssl->s3->hs_buf->length == 0) {
  580. ssl->s3->hs_buf.reset();
  581. }
  582. }
  583. // CipherScorer produces a "score" for each possible cipher suite offered by
  584. // the client.
  585. class CipherScorer {
  586. public:
  587. CipherScorer(uint16_t group_id)
  588. : aes_is_fine_(EVP_has_aes_hardware()),
  589. security_128_is_fine_(group_id != SSL_CURVE_CECPQ2 &&
  590. group_id != SSL_CURVE_CECPQ2b) {}
  591. typedef std::tuple<bool, bool, bool> Score;
  592. // MinScore returns a |Score| that will compare less than the score of all
  593. // cipher suites.
  594. Score MinScore() const {
  595. return Score(false, false, false);
  596. }
  597. Score Evaluate(const SSL_CIPHER *a) const {
  598. return Score(
  599. // Something is always preferable to nothing.
  600. true,
  601. // Either 128-bit is fine, or 256-bit is preferred.
  602. security_128_is_fine_ || a->algorithm_enc != SSL_AES128GCM,
  603. // Either AES is fine, or else ChaCha20 is preferred.
  604. aes_is_fine_ || a->algorithm_enc == SSL_CHACHA20POLY1305);
  605. }
  606. private:
  607. const bool aes_is_fine_;
  608. const bool security_128_is_fine_;
  609. };
  610. const SSL_CIPHER *ssl_choose_tls13_cipher(CBS cipher_suites, uint16_t version,
  611. uint16_t group_id) {
  612. if (CBS_len(&cipher_suites) % 2 != 0) {
  613. return nullptr;
  614. }
  615. const SSL_CIPHER *best = nullptr;
  616. CipherScorer scorer(group_id);
  617. CipherScorer::Score best_score = scorer.MinScore();
  618. while (CBS_len(&cipher_suites) > 0) {
  619. uint16_t cipher_suite;
  620. if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
  621. return nullptr;
  622. }
  623. // Limit to TLS 1.3 ciphers we know about.
  624. const SSL_CIPHER *candidate = SSL_get_cipher_by_value(cipher_suite);
  625. if (candidate == nullptr ||
  626. SSL_CIPHER_get_min_version(candidate) > version ||
  627. SSL_CIPHER_get_max_version(candidate) < version) {
  628. continue;
  629. }
  630. const CipherScorer::Score candidate_score = scorer.Evaluate(candidate);
  631. // |candidate_score| must be larger to displace the current choice. That way
  632. // the client's order controls between ciphers with an equal score.
  633. if (candidate_score > best_score) {
  634. best = candidate;
  635. best_score = candidate_score;
  636. }
  637. }
  638. return best;
  639. }
  640. BSSL_NAMESPACE_END