compress.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. /* Copyright (c) 2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compress.c
  7. * \brief Common compression API.
  8. **/
  9. #include "orconfig.h"
  10. #include <stdlib.h>
  11. #include <stdio.h>
  12. #include <assert.h>
  13. #include <string.h>
  14. #include "torint.h"
  15. #ifdef HAVE_NETINET_IN_H
  16. #include <netinet/in.h>
  17. #endif
  18. #include "util.h"
  19. #include "torlog.h"
  20. #include "compress.h"
  21. #include "compress_lzma.h"
  22. #include "compress_none.h"
  23. #include "compress_zlib.h"
  24. #include "compress_zstd.h"
  25. /** Total number of bytes allocated for compression state overhead. */
  26. static atomic_counter_t total_compress_allocation;
  27. /** @{ */
  28. /* These macros define the maximum allowable compression factor. Anything of
  29. * size greater than CHECK_FOR_COMPRESSION_BOMB_AFTER is not allowed to
  30. * have an uncompression factor (uncompressed size:compressed size ratio) of
  31. * any greater than MAX_UNCOMPRESSION_FACTOR.
  32. *
  33. * Picking a value for MAX_UNCOMPRESSION_FACTOR is a trade-off: we want it to
  34. * be small to limit the attack multiplier, but we also want it to be large
  35. * enough so that no legitimate document --even ones we might invent in the
  36. * future -- ever compresses by a factor of greater than
  37. * MAX_UNCOMPRESSION_FACTOR. Within those parameters, there's a reasonably
  38. * large range of possible values. IMO, anything over 8 is probably safe; IMO
  39. * anything under 50 is probably sufficient.
  40. */
  41. #define MAX_UNCOMPRESSION_FACTOR 25
  42. #define CHECK_FOR_COMPRESSION_BOMB_AFTER (1024*64)
  43. /** @} */
  44. /** Return true if uncompressing an input of size <b>in_size</b> to an input of
  45. * size at least <b>size_out</b> looks like a compression bomb. */
  46. int
  47. tor_compress_is_compression_bomb(size_t size_in, size_t size_out)
  48. {
  49. if (size_in == 0 || size_out < CHECK_FOR_COMPRESSION_BOMB_AFTER)
  50. return 0;
  51. return (size_out / size_in > MAX_UNCOMPRESSION_FACTOR);
  52. }
  53. /** Guess the size that <b>in_len</b> will be after compression or
  54. * decompression. */
  55. static size_t
  56. guess_compress_size(int compress, compress_method_t method,
  57. compression_level_t compression_level,
  58. size_t in_len)
  59. {
  60. // ignore these for now.
  61. (void)compression_level;
  62. if (method == NO_METHOD) {
  63. /* Guess that we'll need an extra byte, to avoid a needless realloc
  64. * for nul-termination */
  65. return (in_len < SIZE_MAX) ? in_len + 1 : in_len;
  66. }
  67. /* Always guess a factor of 2. */
  68. if (compress) {
  69. in_len /= 2;
  70. } else {
  71. if (in_len < SIZE_T_CEILING/2)
  72. in_len *= 2;
  73. }
  74. return MAX(in_len, 1024);
  75. }
  76. /** Internal function to implement tor_compress/tor_uncompress, depending on
  77. * whether <b>compress</b> is set. All arguments are as for tor_compress or
  78. * tor_uncompress. */
  79. static int
  80. tor_compress_impl(int compress,
  81. char **out, size_t *out_len,
  82. const char *in, size_t in_len,
  83. compress_method_t method,
  84. compression_level_t compression_level,
  85. int complete_only,
  86. int protocol_warn_level)
  87. {
  88. tor_compress_state_t *stream;
  89. int rv;
  90. stream = tor_compress_new(compress, method, compression_level);
  91. if (stream == NULL) {
  92. log_warn(LD_GENERAL, "NULL stream while %scompressing",
  93. compress?"":"de");
  94. log_debug(LD_GENERAL, "method: %d level: %d at len: %lu",
  95. method, compression_level, (unsigned long)in_len);
  96. return -1;
  97. }
  98. size_t in_len_orig = in_len;
  99. size_t out_remaining, out_alloc;
  100. char *outptr;
  101. out_remaining = out_alloc =
  102. guess_compress_size(compress, method, compression_level, in_len);
  103. *out = outptr = tor_malloc(out_remaining);
  104. const int finish = complete_only || compress;
  105. while (1) {
  106. switch (tor_compress_process(stream,
  107. &outptr, &out_remaining,
  108. &in, &in_len, finish)) {
  109. case TOR_COMPRESS_DONE:
  110. if (in_len == 0 || compress) {
  111. goto done;
  112. } else {
  113. // More data is present, and we're decompressing. So we may need to
  114. // reinitialize the stream if we are handling multiple concatenated
  115. // inputs.
  116. tor_compress_free(stream);
  117. stream = tor_compress_new(compress, method, compression_level);
  118. if (stream == NULL) {
  119. log_warn(LD_GENERAL, "NULL stream while %scompressing",
  120. compress?"":"de");
  121. goto err;
  122. }
  123. }
  124. break;
  125. case TOR_COMPRESS_OK:
  126. if (compress || complete_only) {
  127. log_fn(protocol_warn_level, LD_PROTOCOL,
  128. "Unexpected %s while %scompressing",
  129. complete_only?"end of input":"result",
  130. compress?"":"de");
  131. log_debug(LD_GENERAL, "method: %d level: %d at len: %lu",
  132. method, compression_level, (unsigned long)in_len);
  133. goto err;
  134. } else {
  135. if (in_len == 0) {
  136. goto done;
  137. }
  138. }
  139. break;
  140. case TOR_COMPRESS_BUFFER_FULL: {
  141. if (!compress && outptr < *out+out_alloc) {
  142. // A buffer error in this case means that we have a problem
  143. // with our input.
  144. log_fn(protocol_warn_level, LD_PROTOCOL,
  145. "Possible truncated or corrupt compressed data");
  146. goto err;
  147. }
  148. if (out_alloc >= SIZE_T_CEILING / 2) {
  149. log_warn(LD_GENERAL, "While %scompresing data: ran out of space.",
  150. compress?"":"un");
  151. goto err;
  152. }
  153. if (!compress &&
  154. tor_compress_is_compression_bomb(in_len_orig, out_alloc)) {
  155. // This should already have been caught down in the backend logic.
  156. // LCOV_EXCL_START
  157. tor_assert_nonfatal_unreached();
  158. goto err;
  159. // LCOV_EXCL_STOP
  160. }
  161. const size_t offset = outptr - *out;
  162. out_alloc *= 2;
  163. *out = tor_realloc(*out, out_alloc);
  164. outptr = *out + offset;
  165. out_remaining = out_alloc - offset;
  166. break;
  167. }
  168. case TOR_COMPRESS_ERROR:
  169. log_fn(protocol_warn_level, LD_GENERAL,
  170. "Error while %scompresing data: bad input?",
  171. compress?"":"un");
  172. goto err; // bad data.
  173. default:
  174. // LCOV_EXCL_START
  175. tor_assert_nonfatal_unreached();
  176. goto err;
  177. // LCOV_EXCL_STOP
  178. }
  179. }
  180. done:
  181. *out_len = outptr - *out;
  182. if (compress && tor_compress_is_compression_bomb(*out_len, in_len_orig)) {
  183. log_warn(LD_BUG, "We compressed something and got an insanely high "
  184. "compression factor; other Tors would think this was a "
  185. "compression bomb.");
  186. goto err;
  187. }
  188. if (!compress) {
  189. // NUL-terminate our output.
  190. if (out_alloc == *out_len)
  191. *out = tor_realloc(*out, out_alloc + 1);
  192. (*out)[*out_len] = '\0';
  193. }
  194. rv = 0;
  195. goto out;
  196. err:
  197. tor_free(*out);
  198. *out_len = 0;
  199. rv = -1;
  200. goto out;
  201. out:
  202. tor_compress_free(stream);
  203. return rv;
  204. }
  205. /** Given <b>in_len</b> bytes at <b>in</b>, compress them into a newly
  206. * allocated buffer, using the method described in <b>method</b>. Store the
  207. * compressed string in *<b>out</b>, and its length in *<b>out_len</b>.
  208. * Return 0 on success, -1 on failure.
  209. */
  210. int
  211. tor_compress(char **out, size_t *out_len,
  212. const char *in, size_t in_len,
  213. compress_method_t method)
  214. {
  215. return tor_compress_impl(1, out, out_len, in, in_len, method,
  216. BEST_COMPRESSION,
  217. 1, LOG_WARN);
  218. }
  219. /** Given zero or more compressed strings of total length <b>in_len</b> bytes
  220. * at <b>in</b>, uncompress them into a newly allocated buffer, using the
  221. * method described in <b>method</b>. Store the uncompressed string in
  222. * *<b>out</b>, and its length in *<b>out_len</b>. Return 0 on success, -1 on
  223. * failure.
  224. *
  225. * If any bytes are written to <b>out</b>, an extra byte NUL is always
  226. * written at the end, but not counted in <b>out_len</b>. This is a
  227. * safety feature to ensure that the output can be treated as a
  228. * NUL-terminated string -- though of course, callers should check
  229. * out_len anyway.
  230. *
  231. * If <b>complete_only</b> is true, we consider a truncated input as a
  232. * failure; otherwise we decompress as much as we can. Warn about truncated
  233. * or corrupt inputs at <b>protocol_warn_level</b>.
  234. */
  235. int
  236. tor_uncompress(char **out, size_t *out_len,
  237. const char *in, size_t in_len,
  238. compress_method_t method,
  239. int complete_only,
  240. int protocol_warn_level)
  241. {
  242. return tor_compress_impl(0, out, out_len, in, in_len, method,
  243. BEST_COMPRESSION,
  244. complete_only, protocol_warn_level);
  245. }
  246. /** Try to tell whether the <b>in_len</b>-byte string in <b>in</b> is likely
  247. * to be compressed or not. If it is, return the likeliest compression method.
  248. * Otherwise, return UNKNOWN_METHOD.
  249. */
  250. compress_method_t
  251. detect_compression_method(const char *in, size_t in_len)
  252. {
  253. if (in_len > 2 && fast_memeq(in, "\x1f\x8b", 2)) {
  254. return GZIP_METHOD;
  255. } else if (in_len > 2 && (in[0] & 0x0f) == 8 &&
  256. (ntohs(get_uint16(in)) % 31) == 0) {
  257. return ZLIB_METHOD;
  258. } else if (in_len > 2 &&
  259. fast_memeq(in, "\x5d\x00\x00", 3)) {
  260. return LZMA_METHOD;
  261. } else if (in_len > 3 &&
  262. fast_memeq(in, "\x28\xb5\x2f\xfd", 4)) {
  263. return ZSTD_METHOD;
  264. } else {
  265. return UNKNOWN_METHOD;
  266. }
  267. }
  268. /** Return 1 if a given <b>method</b> is supported; otherwise 0. */
  269. int
  270. tor_compress_supports_method(compress_method_t method)
  271. {
  272. switch (method) {
  273. case GZIP_METHOD:
  274. case ZLIB_METHOD:
  275. return tor_zlib_method_supported();
  276. case LZMA_METHOD:
  277. return tor_lzma_method_supported();
  278. case ZSTD_METHOD:
  279. return tor_zstd_method_supported();
  280. case NO_METHOD:
  281. return 1;
  282. case UNKNOWN_METHOD:
  283. default:
  284. return 0;
  285. }
  286. }
  287. /**
  288. * Return a bitmask of the supported compression types, where 1&lt;&lt;m is
  289. * set in the bitmask if and only if compression with method <b>m</b> is
  290. * supported.
  291. */
  292. unsigned
  293. tor_compress_get_supported_method_bitmask(void)
  294. {
  295. static unsigned supported = 0;
  296. if (supported == 0) {
  297. compress_method_t m;
  298. for (m = NO_METHOD; m <= UNKNOWN_METHOD; ++m) {
  299. if (tor_compress_supports_method(m)) {
  300. supported |= (1u << m);
  301. }
  302. }
  303. }
  304. return supported;
  305. }
  306. /** Table of compression method names. These should have an "x-" prefix,
  307. * if they are not listed in the IANA content coding registry. */
  308. static const struct {
  309. const char *name;
  310. compress_method_t method;
  311. } compression_method_names[] = {
  312. { "gzip", GZIP_METHOD },
  313. { "deflate", ZLIB_METHOD },
  314. // We call this "x-tor-lzma" rather than "x-lzma", because we impose a
  315. // lower maximum memory usage on the decoding side.
  316. { "x-tor-lzma", LZMA_METHOD },
  317. { "x-zstd" , ZSTD_METHOD },
  318. { "identity", NO_METHOD },
  319. /* Later entries in this table are not canonical; these are recognized but
  320. * not emitted. */
  321. { "x-gzip", GZIP_METHOD },
  322. };
  323. /** Return the canonical string representation of the compression method
  324. * <b>method</b>, or NULL if the method isn't recognized. */
  325. const char *
  326. compression_method_get_name(compress_method_t method)
  327. {
  328. unsigned i;
  329. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  330. if (method == compression_method_names[i].method)
  331. return compression_method_names[i].name;
  332. }
  333. return NULL;
  334. }
  335. /** Table of compression human readable method names. */
  336. static const struct {
  337. compress_method_t method;
  338. const char *name;
  339. } compression_method_human_names[] = {
  340. { NO_METHOD, "uncompressed" },
  341. { GZIP_METHOD, "gzipped" },
  342. { ZLIB_METHOD, "deflated" },
  343. { LZMA_METHOD, "LZMA compressed" },
  344. { ZSTD_METHOD, "Zstandard compressed" },
  345. { UNKNOWN_METHOD, "unknown encoding" },
  346. };
  347. /** Return a human readable string representation of the compression method
  348. * <b>method</b>, or NULL if the method isn't recognized. */
  349. const char *
  350. compression_method_get_human_name(compress_method_t method)
  351. {
  352. unsigned i;
  353. for (i = 0; i < ARRAY_LENGTH(compression_method_human_names); ++i) {
  354. if (method == compression_method_human_names[i].method)
  355. return compression_method_human_names[i].name;
  356. }
  357. return NULL;
  358. }
  359. /** Return the compression method represented by the string <b>name</b>, or
  360. * UNKNOWN_METHOD if the string isn't recognized. */
  361. compress_method_t
  362. compression_method_get_by_name(const char *name)
  363. {
  364. unsigned i;
  365. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  366. if (!strcmp(compression_method_names[i].name, name))
  367. return compression_method_names[i].method;
  368. }
  369. return UNKNOWN_METHOD;
  370. }
  371. /** Return a string representation of the version of the library providing the
  372. * compression method given in <b>method</b>. Returns NULL if <b>method</b> is
  373. * unknown or unsupported. */
  374. const char *
  375. tor_compress_version_str(compress_method_t method)
  376. {
  377. switch (method) {
  378. case GZIP_METHOD:
  379. case ZLIB_METHOD:
  380. return tor_zlib_get_version_str();
  381. case LZMA_METHOD:
  382. return tor_lzma_get_version_str();
  383. case ZSTD_METHOD:
  384. return tor_zstd_get_version_str();
  385. case NO_METHOD:
  386. case UNKNOWN_METHOD:
  387. default:
  388. return NULL;
  389. }
  390. }
  391. /** Return a string representation of the version of the library, found at
  392. * compile time, providing the compression method given in <b>method</b>.
  393. * Returns NULL if <b>method</b> is unknown or unsupported. */
  394. const char *
  395. tor_compress_header_version_str(compress_method_t method)
  396. {
  397. switch (method) {
  398. case GZIP_METHOD:
  399. case ZLIB_METHOD:
  400. return tor_zlib_get_header_version_str();
  401. case LZMA_METHOD:
  402. return tor_lzma_get_header_version_str();
  403. case ZSTD_METHOD:
  404. return tor_zstd_get_header_version_str();
  405. case NO_METHOD:
  406. case UNKNOWN_METHOD:
  407. default:
  408. return NULL;
  409. }
  410. }
  411. /** Return the approximate number of bytes allocated for all
  412. * supported compression schemas. */
  413. size_t
  414. tor_compress_get_total_allocation(void)
  415. {
  416. return atomic_counter_get(&total_compress_allocation) +
  417. tor_zlib_get_total_allocation() +
  418. tor_lzma_get_total_allocation() +
  419. tor_zstd_get_total_allocation();
  420. }
  421. /** Internal state for an incremental compression/decompression. The body of
  422. * this struct is not exposed. */
  423. struct tor_compress_state_t {
  424. compress_method_t method; /**< The compression method. */
  425. union {
  426. tor_zlib_compress_state_t *zlib_state;
  427. tor_lzma_compress_state_t *lzma_state;
  428. tor_zstd_compress_state_t *zstd_state;
  429. } u; /**< Compression backend state. */
  430. };
  431. /** Construct and return a tor_compress_state_t object using <b>method</b>. If
  432. * <b>compress</b>, it's for compression; otherwise it's for decompression. */
  433. tor_compress_state_t *
  434. tor_compress_new(int compress, compress_method_t method,
  435. compression_level_t compression_level)
  436. {
  437. tor_compress_state_t *state;
  438. state = tor_malloc_zero(sizeof(tor_compress_state_t));
  439. state->method = method;
  440. switch (method) {
  441. case GZIP_METHOD:
  442. case ZLIB_METHOD: {
  443. tor_zlib_compress_state_t *zlib_state =
  444. tor_zlib_compress_new(compress, method, compression_level);
  445. if (zlib_state == NULL)
  446. goto err;
  447. state->u.zlib_state = zlib_state;
  448. break;
  449. }
  450. case LZMA_METHOD: {
  451. tor_lzma_compress_state_t *lzma_state =
  452. tor_lzma_compress_new(compress, method, compression_level);
  453. if (lzma_state == NULL)
  454. goto err;
  455. state->u.lzma_state = lzma_state;
  456. break;
  457. }
  458. case ZSTD_METHOD: {
  459. tor_zstd_compress_state_t *zstd_state =
  460. tor_zstd_compress_new(compress, method, compression_level);
  461. if (zstd_state == NULL)
  462. goto err;
  463. state->u.zstd_state = zstd_state;
  464. break;
  465. }
  466. case NO_METHOD: {
  467. break;
  468. }
  469. case UNKNOWN_METHOD:
  470. goto err;
  471. }
  472. atomic_counter_add(&total_compress_allocation,
  473. sizeof(tor_compress_state_t));
  474. return state;
  475. err:
  476. tor_free(state);
  477. return NULL;
  478. }
  479. /** Compress/decompress some bytes using <b>state</b>. Read up to
  480. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  481. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  482. * we've reached the end of the input.
  483. *
  484. * Return TOR_COMPRESS_DONE if we've finished the entire
  485. * compression/decompression.
  486. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  487. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  488. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  489. */
  490. tor_compress_output_t
  491. tor_compress_process(tor_compress_state_t *state,
  492. char **out, size_t *out_len,
  493. const char **in, size_t *in_len,
  494. int finish)
  495. {
  496. tor_assert(state != NULL);
  497. const size_t in_len_orig = *in_len;
  498. const size_t out_len_orig = *out_len;
  499. tor_compress_output_t rv;
  500. if (*out_len == 0 && (*in_len > 0 || finish)) {
  501. // If we still have input data, but no space for output data, we might as
  502. // well return early and let the caller do the reallocation of the out
  503. // variable.
  504. return TOR_COMPRESS_BUFFER_FULL;
  505. }
  506. switch (state->method) {
  507. case GZIP_METHOD:
  508. case ZLIB_METHOD:
  509. rv = tor_zlib_compress_process(state->u.zlib_state,
  510. out, out_len, in, in_len,
  511. finish);
  512. break;
  513. case LZMA_METHOD:
  514. rv =tor_lzma_compress_process(state->u.lzma_state,
  515. out, out_len, in, in_len,
  516. finish);
  517. break;
  518. case ZSTD_METHOD:
  519. rv = tor_zstd_compress_process(state->u.zstd_state,
  520. out, out_len, in, in_len,
  521. finish);
  522. break;
  523. case NO_METHOD:
  524. rv = tor_cnone_compress_process(out, out_len, in, in_len,
  525. finish);
  526. break;
  527. default:
  528. case UNKNOWN_METHOD:
  529. goto err;
  530. }
  531. if (BUG((rv == TOR_COMPRESS_OK) &&
  532. *in_len == in_len_orig &&
  533. *out_len == out_len_orig)) {
  534. return TOR_COMPRESS_ERROR;
  535. }
  536. return rv;
  537. err:
  538. return TOR_COMPRESS_ERROR;
  539. }
  540. /** Deallocate <b>state</b>. */
  541. void
  542. tor_compress_free(tor_compress_state_t *state)
  543. {
  544. if (state == NULL)
  545. return;
  546. switch (state->method) {
  547. case GZIP_METHOD:
  548. case ZLIB_METHOD:
  549. tor_zlib_compress_free(state->u.zlib_state);
  550. break;
  551. case LZMA_METHOD:
  552. tor_lzma_compress_free(state->u.lzma_state);
  553. break;
  554. case ZSTD_METHOD:
  555. tor_zstd_compress_free(state->u.zstd_state);
  556. break;
  557. case NO_METHOD:
  558. break;
  559. case UNKNOWN_METHOD:
  560. break;
  561. }
  562. atomic_counter_sub(&total_compress_allocation,
  563. sizeof(tor_compress_state_t));
  564. tor_free(state);
  565. }
  566. /** Return the approximate number of bytes allocated for <b>state</b>. */
  567. size_t
  568. tor_compress_state_size(const tor_compress_state_t *state)
  569. {
  570. tor_assert(state != NULL);
  571. size_t size = sizeof(tor_compress_state_t);
  572. switch (state->method) {
  573. case GZIP_METHOD:
  574. case ZLIB_METHOD:
  575. size += tor_zlib_compress_state_size(state->u.zlib_state);
  576. break;
  577. case LZMA_METHOD:
  578. size += tor_lzma_compress_state_size(state->u.lzma_state);
  579. break;
  580. case ZSTD_METHOD:
  581. size += tor_zstd_compress_state_size(state->u.zstd_state);
  582. break;
  583. case NO_METHOD:
  584. case UNKNOWN_METHOD:
  585. break;
  586. }
  587. return size;
  588. }
  589. /** Initialize all compression modules. */
  590. void
  591. tor_compress_init(void)
  592. {
  593. atomic_counter_init(&total_compress_allocation);
  594. tor_zlib_init();
  595. tor_lzma_init();
  596. tor_zstd_init();
  597. }