compress.c 14 KB

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