compress.c 17 KB

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