compress.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. log_fn(protocol_warn_level, LD_PROTOCOL,
  137. "Unexpected extra input while decompressing");
  138. log_debug(LD_GENERAL, "method: %d level: %d at len: %lu",
  139. method, compression_level, (unsigned long)in_len);
  140. goto err;
  141. } else {
  142. goto done;
  143. }
  144. }
  145. break;
  146. case TOR_COMPRESS_BUFFER_FULL: {
  147. if (!compress && outptr < *out+out_alloc) {
  148. // A buffer error in this case means that we have a problem
  149. // with our input.
  150. log_fn(protocol_warn_level, LD_PROTOCOL,
  151. "Possible truncated or corrupt compressed data");
  152. goto err;
  153. }
  154. if (out_alloc >= SIZE_T_CEILING / 2) {
  155. log_warn(LD_GENERAL, "While %scompresing data: ran out of space.",
  156. compress?"":"un");
  157. goto err;
  158. }
  159. if (!compress &&
  160. tor_compress_is_compression_bomb(in_len_orig, out_alloc)) {
  161. // This should already have been caught down in the backend logic.
  162. // LCOV_EXCL_START
  163. tor_assert_nonfatal_unreached();
  164. goto err;
  165. // LCOV_EXCL_STOP
  166. }
  167. const size_t offset = outptr - *out;
  168. out_alloc *= 2;
  169. *out = tor_realloc(*out, out_alloc);
  170. outptr = *out + offset;
  171. out_remaining = out_alloc - offset;
  172. break;
  173. }
  174. case TOR_COMPRESS_ERROR:
  175. log_fn(protocol_warn_level, LD_GENERAL,
  176. "Error while %scompresing data: bad input?",
  177. compress?"":"un");
  178. goto err; // bad data.
  179. default:
  180. // LCOV_EXCL_START
  181. tor_assert_nonfatal_unreached();
  182. goto err;
  183. // LCOV_EXCL_STOP
  184. }
  185. }
  186. done:
  187. *out_len = outptr - *out;
  188. if (compress && tor_compress_is_compression_bomb(*out_len, in_len_orig)) {
  189. log_warn(LD_BUG, "We compressed something and got an insanely high "
  190. "compression factor; other Tors would think this was a "
  191. "compression bomb.");
  192. goto err;
  193. }
  194. if (!compress) {
  195. // NUL-terminate our output.
  196. if (out_alloc == *out_len)
  197. *out = tor_realloc(*out, out_alloc + 1);
  198. (*out)[*out_len] = '\0';
  199. }
  200. rv = 0;
  201. goto out;
  202. err:
  203. tor_free(*out);
  204. *out_len = 0;
  205. rv = -1;
  206. goto out;
  207. out:
  208. tor_compress_free(stream);
  209. return rv;
  210. }
  211. /** Given <b>in_len</b> bytes at <b>in</b>, compress them into a newly
  212. * allocated buffer, using the method described in <b>method</b>. Store the
  213. * compressed string in *<b>out</b>, and its length in *<b>out_len</b>.
  214. * Return 0 on success, -1 on failure.
  215. */
  216. int
  217. tor_compress(char **out, size_t *out_len,
  218. const char *in, size_t in_len,
  219. compress_method_t method)
  220. {
  221. return tor_compress_impl(1, out, out_len, in, in_len, method,
  222. BEST_COMPRESSION,
  223. 1, LOG_WARN);
  224. }
  225. /** Given zero or more compressed strings of total length <b>in_len</b> bytes
  226. * at <b>in</b>, uncompress them into a newly allocated buffer, using the
  227. * method described in <b>method</b>. Store the uncompressed string in
  228. * *<b>out</b>, and its length in *<b>out_len</b>. Return 0 on success, -1 on
  229. * failure.
  230. *
  231. * If any bytes are written to <b>out</b>, an extra byte NUL is always
  232. * written at the end, but not counted in <b>out_len</b>. This is a
  233. * safety feature to ensure that the output can be treated as a
  234. * NUL-terminated string -- though of course, callers should check
  235. * out_len anyway.
  236. *
  237. * If <b>complete_only</b> is true, we consider a truncated input as a
  238. * failure; otherwise we decompress as much as we can. Warn about truncated
  239. * or corrupt inputs at <b>protocol_warn_level</b>.
  240. */
  241. int
  242. tor_uncompress(char **out, size_t *out_len,
  243. const char *in, size_t in_len,
  244. compress_method_t method,
  245. int complete_only,
  246. int protocol_warn_level)
  247. {
  248. return tor_compress_impl(0, out, out_len, in, in_len, method,
  249. BEST_COMPRESSION,
  250. complete_only, protocol_warn_level);
  251. }
  252. /** Try to tell whether the <b>in_len</b>-byte string in <b>in</b> is likely
  253. * to be compressed or not. If it is, return the likeliest compression method.
  254. * Otherwise, return UNKNOWN_METHOD.
  255. */
  256. compress_method_t
  257. detect_compression_method(const char *in, size_t in_len)
  258. {
  259. if (in_len > 2 && fast_memeq(in, "\x1f\x8b", 2)) {
  260. return GZIP_METHOD;
  261. } else if (in_len > 2 && (in[0] & 0x0f) == 8 &&
  262. (ntohs(get_uint16(in)) % 31) == 0) {
  263. return ZLIB_METHOD;
  264. } else if (in_len > 2 &&
  265. fast_memeq(in, "\x5d\x00\x00", 3)) {
  266. return LZMA_METHOD;
  267. } else if (in_len > 3 &&
  268. fast_memeq(in, "\x28\xb5\x2f\xfd", 4)) {
  269. return ZSTD_METHOD;
  270. } else {
  271. return UNKNOWN_METHOD;
  272. }
  273. }
  274. /** Return 1 if a given <b>method</b> is supported; otherwise 0. */
  275. int
  276. tor_compress_supports_method(compress_method_t method)
  277. {
  278. switch (method) {
  279. case GZIP_METHOD:
  280. case ZLIB_METHOD:
  281. return tor_zlib_method_supported();
  282. case LZMA_METHOD:
  283. return tor_lzma_method_supported();
  284. case ZSTD_METHOD:
  285. return tor_zstd_method_supported();
  286. case NO_METHOD:
  287. return 1;
  288. case UNKNOWN_METHOD:
  289. default:
  290. return 0;
  291. }
  292. }
  293. /**
  294. * Return a bitmask of the supported compression types, where 1&lt;&lt;m is
  295. * set in the bitmask if and only if compression with method <b>m</b> is
  296. * supported.
  297. */
  298. unsigned
  299. tor_compress_get_supported_method_bitmask(void)
  300. {
  301. static unsigned supported = 0;
  302. if (supported == 0) {
  303. compress_method_t m;
  304. for (m = NO_METHOD; m <= UNKNOWN_METHOD; ++m) {
  305. if (tor_compress_supports_method(m)) {
  306. supported |= (1u << m);
  307. }
  308. }
  309. }
  310. return supported;
  311. }
  312. /** Table of compression method names. These should have an "x-" prefix,
  313. * if they are not listed in the IANA content coding registry. */
  314. static const struct {
  315. const char *name;
  316. compress_method_t method;
  317. } compression_method_names[] = {
  318. { "gzip", GZIP_METHOD },
  319. { "deflate", ZLIB_METHOD },
  320. // We call this "x-tor-lzma" rather than "x-lzma", because we impose a
  321. // lower maximum memory usage on the decoding side.
  322. { "x-tor-lzma", LZMA_METHOD },
  323. { "x-zstd" , ZSTD_METHOD },
  324. { "identity", NO_METHOD },
  325. /* Later entries in this table are not canonical; these are recognized but
  326. * not emitted. */
  327. { "x-gzip", GZIP_METHOD },
  328. };
  329. /** Return the canonical string representation of the compression method
  330. * <b>method</b>, or NULL if the method isn't recognized. */
  331. const char *
  332. compression_method_get_name(compress_method_t method)
  333. {
  334. unsigned i;
  335. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  336. if (method == compression_method_names[i].method)
  337. return compression_method_names[i].name;
  338. }
  339. return NULL;
  340. }
  341. /** Table of compression human readable method names. */
  342. static const struct {
  343. compress_method_t method;
  344. const char *name;
  345. } compression_method_human_names[] = {
  346. { NO_METHOD, "uncompressed" },
  347. { GZIP_METHOD, "gzipped" },
  348. { ZLIB_METHOD, "deflated" },
  349. { LZMA_METHOD, "LZMA compressed" },
  350. { ZSTD_METHOD, "Zstandard compressed" },
  351. { UNKNOWN_METHOD, "unknown encoding" },
  352. };
  353. /** Return a human readable string representation of the compression method
  354. * <b>method</b>, or NULL if the method isn't recognized. */
  355. const char *
  356. compression_method_get_human_name(compress_method_t method)
  357. {
  358. unsigned i;
  359. for (i = 0; i < ARRAY_LENGTH(compression_method_human_names); ++i) {
  360. if (method == compression_method_human_names[i].method)
  361. return compression_method_human_names[i].name;
  362. }
  363. return NULL;
  364. }
  365. /** Return the compression method represented by the string <b>name</b>, or
  366. * UNKNOWN_METHOD if the string isn't recognized. */
  367. compress_method_t
  368. compression_method_get_by_name(const char *name)
  369. {
  370. unsigned i;
  371. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  372. if (!strcmp(compression_method_names[i].name, name))
  373. return compression_method_names[i].method;
  374. }
  375. return UNKNOWN_METHOD;
  376. }
  377. /** Return a string representation of the version of the library providing the
  378. * compression method given in <b>method</b>. Returns NULL if <b>method</b> is
  379. * unknown or unsupported. */
  380. const char *
  381. tor_compress_version_str(compress_method_t method)
  382. {
  383. switch (method) {
  384. case GZIP_METHOD:
  385. case ZLIB_METHOD:
  386. return tor_zlib_get_version_str();
  387. case LZMA_METHOD:
  388. return tor_lzma_get_version_str();
  389. case ZSTD_METHOD:
  390. return tor_zstd_get_version_str();
  391. case NO_METHOD:
  392. case UNKNOWN_METHOD:
  393. default:
  394. return NULL;
  395. }
  396. }
  397. /** Return a string representation of the version of the library, found at
  398. * compile time, providing the compression method given in <b>method</b>.
  399. * Returns NULL if <b>method</b> is unknown or unsupported. */
  400. const char *
  401. tor_compress_header_version_str(compress_method_t method)
  402. {
  403. switch (method) {
  404. case GZIP_METHOD:
  405. case ZLIB_METHOD:
  406. return tor_zlib_get_header_version_str();
  407. case LZMA_METHOD:
  408. return tor_lzma_get_header_version_str();
  409. case ZSTD_METHOD:
  410. return tor_zstd_get_header_version_str();
  411. case NO_METHOD:
  412. case UNKNOWN_METHOD:
  413. default:
  414. return NULL;
  415. }
  416. }
  417. /** Return the approximate number of bytes allocated for all
  418. * supported compression schemas. */
  419. size_t
  420. tor_compress_get_total_allocation(void)
  421. {
  422. return atomic_counter_get(&total_compress_allocation) +
  423. tor_zlib_get_total_allocation() +
  424. tor_lzma_get_total_allocation() +
  425. tor_zstd_get_total_allocation();
  426. }
  427. /** Internal state for an incremental compression/decompression. The body of
  428. * this struct is not exposed. */
  429. struct tor_compress_state_t {
  430. compress_method_t method; /**< The compression method. */
  431. union {
  432. tor_zlib_compress_state_t *zlib_state;
  433. tor_lzma_compress_state_t *lzma_state;
  434. tor_zstd_compress_state_t *zstd_state;
  435. } u; /**< Compression backend state. */
  436. };
  437. /** Construct and return a tor_compress_state_t object using <b>method</b>. If
  438. * <b>compress</b>, it's for compression; otherwise it's for decompression. */
  439. tor_compress_state_t *
  440. tor_compress_new(int compress, compress_method_t method,
  441. compression_level_t compression_level)
  442. {
  443. tor_compress_state_t *state;
  444. state = tor_malloc_zero(sizeof(tor_compress_state_t));
  445. state->method = method;
  446. switch (method) {
  447. case GZIP_METHOD:
  448. case ZLIB_METHOD: {
  449. tor_zlib_compress_state_t *zlib_state =
  450. tor_zlib_compress_new(compress, method, compression_level);
  451. if (zlib_state == NULL)
  452. goto err;
  453. state->u.zlib_state = zlib_state;
  454. break;
  455. }
  456. case LZMA_METHOD: {
  457. tor_lzma_compress_state_t *lzma_state =
  458. tor_lzma_compress_new(compress, method, compression_level);
  459. if (lzma_state == NULL)
  460. goto err;
  461. state->u.lzma_state = lzma_state;
  462. break;
  463. }
  464. case ZSTD_METHOD: {
  465. tor_zstd_compress_state_t *zstd_state =
  466. tor_zstd_compress_new(compress, method, compression_level);
  467. if (zstd_state == NULL)
  468. goto err;
  469. state->u.zstd_state = zstd_state;
  470. break;
  471. }
  472. case NO_METHOD: {
  473. break;
  474. }
  475. case UNKNOWN_METHOD:
  476. goto err;
  477. }
  478. atomic_counter_add(&total_compress_allocation,
  479. sizeof(tor_compress_state_t));
  480. return state;
  481. err:
  482. tor_free(state);
  483. return NULL;
  484. }
  485. /** Compress/decompress some bytes using <b>state</b>. Read up to
  486. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  487. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  488. * we've reached the end of the input.
  489. *
  490. * Return TOR_COMPRESS_DONE if we've finished the entire
  491. * compression/decompression.
  492. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  493. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  494. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  495. */
  496. tor_compress_output_t
  497. tor_compress_process(tor_compress_state_t *state,
  498. char **out, size_t *out_len,
  499. const char **in, size_t *in_len,
  500. int finish)
  501. {
  502. tor_assert(state != NULL);
  503. const size_t in_len_orig = *in_len;
  504. const size_t out_len_orig = *out_len;
  505. tor_compress_output_t rv;
  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. }