tls_record.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. #include <openssl/ssl.h>
  109. #include <assert.h>
  110. #include <string.h>
  111. #include <openssl/bytestring.h>
  112. #include <openssl/err.h>
  113. #include <openssl/mem.h>
  114. #include "internal.h"
  115. #include "../crypto/internal.h"
  116. namespace bssl {
  117. // kMaxEmptyRecords is the number of consecutive, empty records that will be
  118. // processed. Without this limit an attacker could send empty records at a
  119. // faster rate than we can process and cause record processing to loop
  120. // forever.
  121. static const uint8_t kMaxEmptyRecords = 32;
  122. // kMaxEarlyDataSkipped is the maximum number of rejected early data bytes that
  123. // will be skipped. Without this limit an attacker could send records at a
  124. // faster rate than we can process and cause trial decryption to loop forever.
  125. // This value should be slightly above kMaxEarlyDataAccepted, which is measured
  126. // in plaintext.
  127. static const size_t kMaxEarlyDataSkipped = 16384;
  128. // kMaxWarningAlerts is the number of consecutive warning alerts that will be
  129. // processed.
  130. static const uint8_t kMaxWarningAlerts = 4;
  131. // ssl_needs_record_splitting returns one if |ssl|'s current outgoing cipher
  132. // state needs record-splitting and zero otherwise.
  133. static int ssl_needs_record_splitting(const SSL *ssl) {
  134. #if !defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  135. return !ssl->s3->aead_write_ctx->is_null_cipher() &&
  136. ssl->s3->aead_write_ctx->ProtocolVersion() < TLS1_1_VERSION &&
  137. (ssl->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0 &&
  138. SSL_CIPHER_is_block_cipher(ssl->s3->aead_write_ctx->cipher());
  139. #else
  140. return 0;
  141. #endif
  142. }
  143. int ssl_record_sequence_update(uint8_t *seq, size_t seq_len) {
  144. for (size_t i = seq_len - 1; i < seq_len; i--) {
  145. ++seq[i];
  146. if (seq[i] != 0) {
  147. return 1;
  148. }
  149. }
  150. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  151. return 0;
  152. }
  153. size_t ssl_record_prefix_len(const SSL *ssl) {
  154. size_t header_len;
  155. if (SSL_is_dtls(ssl)) {
  156. header_len = DTLS1_RT_HEADER_LENGTH;
  157. } else {
  158. header_len = SSL3_RT_HEADER_LENGTH;
  159. }
  160. return header_len + ssl->s3->aead_read_ctx->ExplicitNonceLen();
  161. }
  162. size_t ssl_seal_align_prefix_len(const SSL *ssl) {
  163. if (SSL_is_dtls(ssl)) {
  164. return DTLS1_RT_HEADER_LENGTH + ssl->s3->aead_write_ctx->ExplicitNonceLen();
  165. }
  166. size_t ret =
  167. SSL3_RT_HEADER_LENGTH + ssl->s3->aead_write_ctx->ExplicitNonceLen();
  168. if (ssl_needs_record_splitting(ssl)) {
  169. ret += SSL3_RT_HEADER_LENGTH;
  170. ret += ssl_cipher_get_record_split_len(ssl->s3->aead_write_ctx->cipher());
  171. }
  172. return ret;
  173. }
  174. static ssl_open_record_t skip_early_data(SSL *ssl, uint8_t *out_alert,
  175. size_t consumed) {
  176. ssl->s3->early_data_skipped += consumed;
  177. if (ssl->s3->early_data_skipped < consumed) {
  178. ssl->s3->early_data_skipped = kMaxEarlyDataSkipped + 1;
  179. }
  180. if (ssl->s3->early_data_skipped > kMaxEarlyDataSkipped) {
  181. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MUCH_SKIPPED_EARLY_DATA);
  182. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  183. return ssl_open_record_error;
  184. }
  185. return ssl_open_record_discard;
  186. }
  187. ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type,
  188. Span<uint8_t> *out, size_t *out_consumed,
  189. uint8_t *out_alert, Span<uint8_t> in) {
  190. *out_consumed = 0;
  191. if (ssl->s3->read_shutdown == ssl_shutdown_close_notify) {
  192. return ssl_open_record_close_notify;
  193. }
  194. // If there is an unprocessed handshake message or we are already buffering
  195. // too much, stop before decrypting another handshake record.
  196. if (!tls_can_accept_handshake_data(ssl, out_alert)) {
  197. return ssl_open_record_error;
  198. }
  199. CBS cbs = CBS(in);
  200. // Decode the record header.
  201. uint8_t type;
  202. uint16_t version, ciphertext_len;
  203. if (!CBS_get_u8(&cbs, &type) ||
  204. !CBS_get_u16(&cbs, &version) ||
  205. !CBS_get_u16(&cbs, &ciphertext_len)) {
  206. *out_consumed = SSL3_RT_HEADER_LENGTH;
  207. return ssl_open_record_partial;
  208. }
  209. bool version_ok;
  210. if (ssl->s3->aead_read_ctx->is_null_cipher()) {
  211. // Only check the first byte. Enforcing beyond that can prevent decoding
  212. // version negotiation failure alerts.
  213. version_ok = (version >> 8) == SSL3_VERSION_MAJOR;
  214. } else {
  215. version_ok = version == ssl->s3->aead_read_ctx->RecordVersion();
  216. }
  217. if (!version_ok) {
  218. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
  219. *out_alert = SSL_AD_PROTOCOL_VERSION;
  220. return ssl_open_record_error;
  221. }
  222. // Check the ciphertext length.
  223. if (ciphertext_len > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  224. OPENSSL_PUT_ERROR(SSL, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  225. *out_alert = SSL_AD_RECORD_OVERFLOW;
  226. return ssl_open_record_error;
  227. }
  228. // Extract the body.
  229. CBS body;
  230. if (!CBS_get_bytes(&cbs, &body, ciphertext_len)) {
  231. *out_consumed = SSL3_RT_HEADER_LENGTH + (size_t)ciphertext_len;
  232. return ssl_open_record_partial;
  233. }
  234. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HEADER,
  235. in.subspan(0, SSL3_RT_HEADER_LENGTH));
  236. *out_consumed = in.size() - CBS_len(&cbs);
  237. if (ssl->s3->have_version &&
  238. ssl_is_resumption_experiment(ssl->version) &&
  239. SSL_in_init(ssl) &&
  240. type == SSL3_RT_CHANGE_CIPHER_SPEC &&
  241. ciphertext_len == 1 &&
  242. CBS_data(&body)[0] == 1) {
  243. ssl->s3->empty_record_count++;
  244. if (ssl->s3->empty_record_count > kMaxEmptyRecords) {
  245. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
  246. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  247. return ssl_open_record_error;
  248. }
  249. return ssl_open_record_discard;
  250. }
  251. // Skip early data received when expecting a second ClientHello if we rejected
  252. // 0RTT.
  253. if (ssl->s3->skip_early_data &&
  254. ssl->s3->aead_read_ctx->is_null_cipher() &&
  255. type == SSL3_RT_APPLICATION_DATA) {
  256. return skip_early_data(ssl, out_alert, *out_consumed);
  257. }
  258. // Decrypt the body in-place.
  259. if (!ssl->s3->aead_read_ctx->Open(
  260. out, type, version, ssl->s3->read_sequence,
  261. MakeSpan(const_cast<uint8_t *>(CBS_data(&body)), CBS_len(&body)))) {
  262. if (ssl->s3->skip_early_data && !ssl->s3->aead_read_ctx->is_null_cipher()) {
  263. ERR_clear_error();
  264. return skip_early_data(ssl, out_alert, *out_consumed);
  265. }
  266. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  267. *out_alert = SSL_AD_BAD_RECORD_MAC;
  268. return ssl_open_record_error;
  269. }
  270. ssl->s3->skip_early_data = false;
  271. if (!ssl_record_sequence_update(ssl->s3->read_sequence, 8)) {
  272. *out_alert = SSL_AD_INTERNAL_ERROR;
  273. return ssl_open_record_error;
  274. }
  275. // TLS 1.3 hides the record type inside the encrypted data.
  276. bool has_padding =
  277. !ssl->s3->aead_read_ctx->is_null_cipher() &&
  278. ssl->s3->aead_read_ctx->ProtocolVersion() >= TLS1_3_VERSION;
  279. // If there is padding, the plaintext limit includes the padding, but includes
  280. // extra room for the inner content type.
  281. size_t plaintext_limit =
  282. has_padding ? SSL3_RT_MAX_PLAIN_LENGTH + 1 : SSL3_RT_MAX_PLAIN_LENGTH;
  283. if (out->size() > plaintext_limit) {
  284. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  285. *out_alert = SSL_AD_RECORD_OVERFLOW;
  286. return ssl_open_record_error;
  287. }
  288. if (has_padding) {
  289. // The outer record type is always application_data.
  290. if (type != SSL3_RT_APPLICATION_DATA) {
  291. OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_OUTER_RECORD_TYPE);
  292. *out_alert = SSL_AD_DECODE_ERROR;
  293. return ssl_open_record_error;
  294. }
  295. do {
  296. if (out->empty()) {
  297. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  298. *out_alert = SSL_AD_DECRYPT_ERROR;
  299. return ssl_open_record_error;
  300. }
  301. type = out->back();
  302. *out = out->subspan(0, out->size() - 1);
  303. } while (type == 0);
  304. }
  305. // Limit the number of consecutive empty records.
  306. if (out->empty()) {
  307. ssl->s3->empty_record_count++;
  308. if (ssl->s3->empty_record_count > kMaxEmptyRecords) {
  309. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
  310. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  311. return ssl_open_record_error;
  312. }
  313. // Apart from the limit, empty records are returned up to the caller. This
  314. // allows the caller to reject records of the wrong type.
  315. } else {
  316. ssl->s3->empty_record_count = 0;
  317. }
  318. if (type == SSL3_RT_ALERT) {
  319. // Return end_of_early_data alerts as-is for the caller to process.
  320. if (!ssl_is_draft21(ssl->version) &&
  321. out->size() == 2 &&
  322. (*out)[0] == SSL3_AL_WARNING &&
  323. (*out)[1] == TLS1_AD_END_OF_EARLY_DATA) {
  324. *out_type = type;
  325. return ssl_open_record_success;
  326. }
  327. return ssl_process_alert(ssl, out_alert, *out);
  328. }
  329. // Handshake messages may not interleave with any other record type.
  330. if (type != SSL3_RT_HANDSHAKE &&
  331. tls_has_unprocessed_handshake_data(ssl)) {
  332. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  333. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  334. return ssl_open_record_error;
  335. }
  336. ssl->s3->warning_alert_count = 0;
  337. *out_type = type;
  338. return ssl_open_record_success;
  339. }
  340. static int do_seal_record(SSL *ssl, uint8_t *out_prefix, uint8_t *out,
  341. uint8_t *out_suffix, uint8_t type, const uint8_t *in,
  342. const size_t in_len) {
  343. uint8_t *extra_in = NULL;
  344. size_t extra_in_len = 0;
  345. if (!ssl->s3->aead_write_ctx->is_null_cipher() &&
  346. ssl->s3->aead_write_ctx->ProtocolVersion() >= TLS1_3_VERSION) {
  347. // TLS 1.3 hides the actual record type inside the encrypted data.
  348. extra_in = &type;
  349. extra_in_len = 1;
  350. }
  351. size_t suffix_len;
  352. if (!ssl->s3->aead_write_ctx->SuffixLen(&suffix_len, in_len, extra_in_len)) {
  353. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  354. return 0;
  355. }
  356. size_t ciphertext_len =
  357. ssl->s3->aead_write_ctx->ExplicitNonceLen() + suffix_len;
  358. if (ciphertext_len + in_len < ciphertext_len) {
  359. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  360. return 0;
  361. }
  362. ciphertext_len += in_len;
  363. assert(in == out || !buffers_alias(in, in_len, out, in_len));
  364. assert(!buffers_alias(in, in_len, out_prefix, ssl_record_prefix_len(ssl)));
  365. assert(!buffers_alias(in, in_len, out_suffix, suffix_len));
  366. if (extra_in_len) {
  367. out_prefix[0] = SSL3_RT_APPLICATION_DATA;
  368. } else {
  369. out_prefix[0] = type;
  370. }
  371. uint16_t record_version = ssl->s3->aead_write_ctx->RecordVersion();
  372. out_prefix[1] = record_version >> 8;
  373. out_prefix[2] = record_version & 0xff;
  374. out_prefix[3] = ciphertext_len >> 8;
  375. out_prefix[4] = ciphertext_len & 0xff;
  376. if (!ssl->s3->aead_write_ctx->SealScatter(
  377. out_prefix + SSL3_RT_HEADER_LENGTH, out, out_suffix, type,
  378. record_version, ssl->s3->write_sequence, in, in_len, extra_in,
  379. extra_in_len) ||
  380. !ssl_record_sequence_update(ssl->s3->write_sequence, 8)) {
  381. return 0;
  382. }
  383. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HEADER,
  384. MakeSpan(out_prefix, SSL3_RT_HEADER_LENGTH));
  385. return 1;
  386. }
  387. static size_t tls_seal_scatter_prefix_len(const SSL *ssl, uint8_t type,
  388. size_t in_len) {
  389. size_t ret = SSL3_RT_HEADER_LENGTH;
  390. if (type == SSL3_RT_APPLICATION_DATA && in_len > 1 &&
  391. ssl_needs_record_splitting(ssl)) {
  392. // In the case of record splitting, the 1-byte record (of the 1/n-1 split)
  393. // will be placed in the prefix, as will four of the five bytes of the
  394. // record header for the main record. The final byte will replace the first
  395. // byte of the plaintext that was used in the small record.
  396. ret += ssl_cipher_get_record_split_len(ssl->s3->aead_write_ctx->cipher());
  397. ret += SSL3_RT_HEADER_LENGTH - 1;
  398. } else {
  399. ret += ssl->s3->aead_write_ctx->ExplicitNonceLen();
  400. }
  401. return ret;
  402. }
  403. static bool tls_seal_scatter_suffix_len(const SSL *ssl, size_t *out_suffix_len,
  404. uint8_t type, size_t in_len) {
  405. size_t extra_in_len = 0;
  406. if (!ssl->s3->aead_write_ctx->is_null_cipher() &&
  407. ssl->s3->aead_write_ctx->ProtocolVersion() >= TLS1_3_VERSION) {
  408. // TLS 1.3 adds an extra byte for encrypted record type.
  409. extra_in_len = 1;
  410. }
  411. if (type == SSL3_RT_APPLICATION_DATA && // clang-format off
  412. in_len > 1 &&
  413. ssl_needs_record_splitting(ssl)) {
  414. // With record splitting enabled, the first byte gets sealed into a separate
  415. // record which is written into the prefix.
  416. in_len -= 1;
  417. }
  418. return ssl->s3->aead_write_ctx->SuffixLen(out_suffix_len, in_len, extra_in_len);
  419. }
  420. // tls_seal_scatter_record seals a new record of type |type| and body |in| and
  421. // splits it between |out_prefix|, |out|, and |out_suffix|. Exactly
  422. // |tls_seal_scatter_prefix_len| bytes are written to |out_prefix|, |in_len|
  423. // bytes to |out|, and |tls_seal_scatter_suffix_len| bytes to |out_suffix|. It
  424. // returns one on success and zero on error. If enabled,
  425. // |tls_seal_scatter_record| implements TLS 1.0 CBC 1/n-1 record splitting and
  426. // may write two records concatenated.
  427. static int tls_seal_scatter_record(SSL *ssl, uint8_t *out_prefix, uint8_t *out,
  428. uint8_t *out_suffix, uint8_t type,
  429. const uint8_t *in, size_t in_len) {
  430. if (type == SSL3_RT_APPLICATION_DATA && in_len > 1 &&
  431. ssl_needs_record_splitting(ssl)) {
  432. assert(ssl->s3->aead_write_ctx->ExplicitNonceLen() == 0);
  433. const size_t prefix_len = SSL3_RT_HEADER_LENGTH;
  434. // Write the 1-byte fragment into |out_prefix|.
  435. uint8_t *split_body = out_prefix + prefix_len;
  436. uint8_t *split_suffix = split_body + 1;
  437. if (!do_seal_record(ssl, out_prefix, split_body, split_suffix, type, in,
  438. 1)) {
  439. return 0;
  440. }
  441. size_t split_record_suffix_len;
  442. if (!ssl->s3->aead_write_ctx->SuffixLen(&split_record_suffix_len, 1, 0)) {
  443. assert(false);
  444. return 0;
  445. }
  446. const size_t split_record_len = prefix_len + 1 + split_record_suffix_len;
  447. assert(SSL3_RT_HEADER_LENGTH + ssl_cipher_get_record_split_len(
  448. ssl->s3->aead_write_ctx->cipher()) ==
  449. split_record_len);
  450. // Write the n-1-byte fragment. The header gets split between |out_prefix|
  451. // (header[:-1]) and |out| (header[-1:]).
  452. uint8_t tmp_prefix[SSL3_RT_HEADER_LENGTH];
  453. if (!do_seal_record(ssl, tmp_prefix, out + 1, out_suffix, type, in + 1,
  454. in_len - 1)) {
  455. return 0;
  456. }
  457. assert(tls_seal_scatter_prefix_len(ssl, type, in_len) ==
  458. split_record_len + SSL3_RT_HEADER_LENGTH - 1);
  459. OPENSSL_memcpy(out_prefix + split_record_len, tmp_prefix,
  460. SSL3_RT_HEADER_LENGTH - 1);
  461. OPENSSL_memcpy(out, tmp_prefix + SSL3_RT_HEADER_LENGTH - 1, 1);
  462. return 1;
  463. }
  464. return do_seal_record(ssl, out_prefix, out, out_suffix, type, in, in_len);
  465. }
  466. int tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out_len,
  467. uint8_t type, const uint8_t *in, size_t in_len) {
  468. if (buffers_alias(in, in_len, out, max_out_len)) {
  469. OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
  470. return 0;
  471. }
  472. const size_t prefix_len = tls_seal_scatter_prefix_len(ssl, type, in_len);
  473. size_t suffix_len;
  474. if (!tls_seal_scatter_suffix_len(ssl, &suffix_len, type, in_len)) {
  475. return false;
  476. }
  477. if (in_len + prefix_len < in_len ||
  478. prefix_len + in_len + suffix_len < prefix_len + in_len) {
  479. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  480. return 0;
  481. }
  482. if (max_out_len < in_len + prefix_len + suffix_len) {
  483. OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
  484. return 0;
  485. }
  486. uint8_t *prefix = out;
  487. uint8_t *body = out + prefix_len;
  488. uint8_t *suffix = body + in_len;
  489. if (!tls_seal_scatter_record(ssl, prefix, body, suffix, type, in, in_len)) {
  490. return 0;
  491. }
  492. *out_len = prefix_len + in_len + suffix_len;
  493. return 1;
  494. }
  495. enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert,
  496. Span<const uint8_t> in) {
  497. // Alerts records may not contain fragmented or multiple alerts.
  498. if (in.size() != 2) {
  499. *out_alert = SSL_AD_DECODE_ERROR;
  500. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  501. return ssl_open_record_error;
  502. }
  503. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_ALERT, in);
  504. const uint8_t alert_level = in[0];
  505. const uint8_t alert_descr = in[1];
  506. uint16_t alert = (alert_level << 8) | alert_descr;
  507. ssl_do_info_callback(ssl, SSL_CB_READ_ALERT, alert);
  508. if (alert_level == SSL3_AL_WARNING) {
  509. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  510. ssl->s3->read_shutdown = ssl_shutdown_close_notify;
  511. return ssl_open_record_close_notify;
  512. }
  513. // Warning alerts do not exist in TLS 1.3.
  514. if (ssl->s3->have_version &&
  515. ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
  516. *out_alert = SSL_AD_DECODE_ERROR;
  517. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  518. return ssl_open_record_error;
  519. }
  520. ssl->s3->warning_alert_count++;
  521. if (ssl->s3->warning_alert_count > kMaxWarningAlerts) {
  522. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  523. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_WARNING_ALERTS);
  524. return ssl_open_record_error;
  525. }
  526. return ssl_open_record_discard;
  527. }
  528. if (alert_level == SSL3_AL_FATAL) {
  529. OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
  530. ERR_add_error_dataf("SSL alert number %d", alert_descr);
  531. *out_alert = 0; // No alert to send back to the peer.
  532. return ssl_open_record_error;
  533. }
  534. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  535. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
  536. return ssl_open_record_error;
  537. }
  538. OpenRecordResult OpenRecord(SSL *ssl, Span<uint8_t> *out,
  539. size_t *out_record_len, uint8_t *out_alert,
  540. const Span<uint8_t> in) {
  541. // This API is a work in progress and currently only works for TLS 1.2 servers
  542. // and below.
  543. if (SSL_in_init(ssl) ||
  544. SSL_is_dtls(ssl) ||
  545. ssl_protocol_version(ssl) > TLS1_2_VERSION) {
  546. assert(false);
  547. *out_alert = SSL_AD_INTERNAL_ERROR;
  548. return OpenRecordResult::kError;
  549. }
  550. Span<uint8_t> plaintext;
  551. uint8_t type = 0;
  552. const ssl_open_record_t result = tls_open_record(
  553. ssl, &type, &plaintext, out_record_len, out_alert, in);
  554. switch (result) {
  555. case ssl_open_record_success:
  556. if (type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_ALERT) {
  557. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  558. return OpenRecordResult::kError;
  559. }
  560. *out = plaintext;
  561. return OpenRecordResult::kOK;
  562. case ssl_open_record_discard:
  563. return OpenRecordResult::kDiscard;
  564. case ssl_open_record_partial:
  565. return OpenRecordResult::kIncompleteRecord;
  566. case ssl_open_record_close_notify:
  567. return OpenRecordResult::kAlertCloseNotify;
  568. case ssl_open_record_error:
  569. return OpenRecordResult::kError;
  570. }
  571. assert(false);
  572. return OpenRecordResult::kError;
  573. }
  574. size_t SealRecordPrefixLen(const SSL *ssl, const size_t record_len) {
  575. return tls_seal_scatter_prefix_len(ssl, SSL3_RT_APPLICATION_DATA, record_len);
  576. }
  577. size_t SealRecordSuffixLen(const SSL *ssl, const size_t plaintext_len) {
  578. assert(plaintext_len <= SSL3_RT_MAX_PLAIN_LENGTH);
  579. size_t suffix_len;
  580. if (!tls_seal_scatter_suffix_len(ssl, &suffix_len, SSL3_RT_APPLICATION_DATA,
  581. plaintext_len)) {
  582. assert(false);
  583. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  584. return 0;
  585. }
  586. assert(suffix_len <= SSL3_RT_MAX_ENCRYPTED_OVERHEAD);
  587. return suffix_len;
  588. }
  589. bool SealRecord(SSL *ssl, const Span<uint8_t> out_prefix,
  590. const Span<uint8_t> out, Span<uint8_t> out_suffix,
  591. const Span<const uint8_t> in) {
  592. // This API is a work in progress and currently only works for TLS 1.2 servers
  593. // and below.
  594. if (SSL_in_init(ssl) ||
  595. SSL_is_dtls(ssl) ||
  596. ssl_protocol_version(ssl) > TLS1_2_VERSION) {
  597. assert(false);
  598. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  599. return false;
  600. }
  601. if (out_prefix.size() != SealRecordPrefixLen(ssl, in.size()) ||
  602. out.size() != in.size() ||
  603. out_suffix.size() != SealRecordSuffixLen(ssl, in.size())) {
  604. OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
  605. return false;
  606. }
  607. return tls_seal_scatter_record(ssl, out_prefix.data(), out.data(),
  608. out_suffix.data(), SSL3_RT_APPLICATION_DATA,
  609. in.data(), in.size());
  610. }
  611. } // namespace bssl
  612. using namespace bssl;
  613. size_t SSL_max_seal_overhead(const SSL *ssl) {
  614. if (SSL_is_dtls(ssl)) {
  615. return dtls_max_seal_overhead(ssl, dtls1_use_current_epoch);
  616. }
  617. size_t ret = SSL3_RT_HEADER_LENGTH;
  618. ret += ssl->s3->aead_write_ctx->MaxOverhead();
  619. // TLS 1.3 needs an extra byte for the encrypted record type.
  620. if (!ssl->s3->aead_write_ctx->is_null_cipher() &&
  621. ssl->s3->aead_write_ctx->ProtocolVersion() >= TLS1_3_VERSION) {
  622. ret += 1;
  623. }
  624. if (ssl_needs_record_splitting(ssl)) {
  625. ret *= 2;
  626. }
  627. return ret;
  628. }