From 4dab1f30919e619cdbbffdbe9bdd90cc26fa08cd Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Wed, 25 Nov 2026 19:57:14 +0800 Subject: [PATCH 1/2] fix: bound metadata parsing before allocation The 1.1.0 reader accepted an uncompressed metadata size up to 4 GiB and allocated it before decompression; block metadata was then pre-sized from a declared count at about 216 B per entry, so a small compressed archive could drive 14 GiB+ of allocations. The legacy layout had no fixed cap at all. Add a per-archive metadata budget (--max-metadata-size, default 1 GiB, 0 disables), enforced in ReadPackHeaderOnly before any metadata buffer is allocated, for every archive reader. Reject compressed metadata above the LZ4 int limit, decompress into uninitialized buffers so a failed stream does not commit the declared size to RSS, grow the block vector while parsing instead of resize(count), and reject empty blocks so the minimum serialized block size bounds the count. No format change; archive bytes are unchanged. Closes #74 --- README.md | 5 ++ README_CN.md | 4 ++ doc/file_format.md | 1 + doc/file_format_CN.md | 1 + src/cli/arg_parser.cpp | 86 ++++++++++++++++++++++++++++++++ src/cli/arg_parser.h | 2 + src/core/block_store.cpp | 87 ++++++++++++++++++++++----------- src/core/block_store.h | 5 ++ src/core/file_format.cpp | 6 +++ src/core/options.h | 5 ++ test/cases/test_block_store.cpp | 47 ++++++++++++++++++ test/cases/test_cli.cpp | 42 ++++++++++++++++ test/cases/test_file_format.cpp | 11 +++++ 13 files changed, 274 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index aa71e34..82e1005 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,11 @@ ctar dump pack_file.ctar `--max-decompressed-size SIZE` to change it (`0` disables the limit). Larger files are rejected until chunked unpacking (#38) lands. +Archive readers (`unpack`, `tree`, `ls`, `dump`, `stat`) also limit the +uncompressed metadata region to 1 GiB by default; use `--max-metadata-size SIZE` +to change it (`0` disables the limit). This keeps a small crafted archive from +expanding into a multi-gigabyte metadata buffer. + In most cases the `pack` and `unpack` commands are all you need, and the more files there are, the more noticeable the benefit. If you have other requirements — for example, storing the packed file in the cloud but wanting to retrieve only part of the data inside it — refer to the short tutorial below. diff --git a/README_CN.md b/README_CN.md index ab19ac3..085cf7d 100644 --- a/README_CN.md +++ b/README_CN.md @@ -98,6 +98,10 @@ ctar dump pack_file.ctar `--max-decompressed-size SIZE` 调整(`0` 表示不限制)。超过预算的文件会被拒绝, 在分块支持(#38)落地前需要显式调大预算。 +归档读取命令(`unpack`、`tree`、`ls`、`dump`、`stat`)还会把未压缩 metadata 限制为 +1 GiB;可用 `--max-metadata-size SIZE` 调整(`0` 表示不限制)。这样小的恶意归档 +无法膨胀成数 GiB 的 metadata 缓冲区。 + 一般情况下,使用 `pack` 和 `unpack` 命令即可满足大部分的需求,文件越多收益越明显。如果有其他需求,如将打包后的文件放在云端,但只想获取打包文件中的部分数据时,可参考下面的简短教程。 ## 简短教程 diff --git a/doc/file_format.md b/doc/file_format.md index c06dbae..1696bc8 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -167,6 +167,7 @@ The reader rejects archives that violate these cross-field invariants; a writer - Every `file_ids[i]` exists in `file_entry_records`; the entry's `block_id`, `file_orig_size`, `file_compressed_size` and absolute `file_offset` agree with the block, and every indexed file is referenced exactly once. - Directory paths are unique, and a directory contains no duplicate file names, so every extracted file has a distinct output path. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). +- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) before allocating the uncompressed metadata. Compressed metadata above the LZ4 `int` limit is always rejected, and empty data blocks are invalid. ### version encoding and compatibility diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index 1956bab..0f81f6e 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -165,6 +165,7 @@ data_block_meta[data_block_count] - 每个 `file_ids[i]` 都必须存在于 `file_entry_records`,其 `block_id`、`file_orig_size`、`file_compressed_size` 和绝对 `file_offset` 与块元数据一致;所有索引文件都必须被且仅被引用一次。 - 目录路径唯一,同一目录内文件名唯一,保证每个解压文件有唯一的输出路径。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 +- 所有归档读取命令都在分配未压缩 metadata 之前施加每归档 metadata 预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制)。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,空 data block 也是非法的。 ### 版本编码与兼容性 diff --git a/src/cli/arg_parser.cpp b/src/cli/arg_parser.cpp index c8df505..97de179 100644 --- a/src/cli/arg_parser.cpp +++ b/src/cli/arg_parser.cpp @@ -84,6 +84,11 @@ COMMAND OPTIONS Per-file decompressed-size limit (default 1G, 0 = unlimited). Files above it are rejected during unpack. + --max-metadata-size SIZE + Per-archive metadata limit for unpack/tree/ls/dump/stat + (default 1G, 0 = unlimited). Larger metadata is rejected before + it is allocated. + ls: -h Print sizes in human-readable form (1024-based: K, M, G). @@ -318,6 +323,21 @@ namespace ctar::cli opt.max_decompressed_file_size = size; ++pos; } + else if (op == "--max-metadata-size" && subcommand_name == "unpack") + { + ++pos; + if (pos >= argc) + { + return error_invalid_arg("missing size after {}", op); + } + uint64_t size = 0; + if (!ParseSize(argv[pos], size)) + { + return error_invalid_arg("invalid size '{}' for {}; use e.g. 512M or 1G", argv[pos], op); + } + opt.max_metadata_size = size; + ++pos; + } else { return error_invalid_arg("unknown option for {}: {}", subcommand_name, op); @@ -390,6 +410,29 @@ namespace ctar::cli { opt.cmd = CommandType::STAT; pos++; + while (pos < argc && argv[pos][0] == '-') + { + std::string_view op{argv[pos]}; + if (op == "--max-metadata-size") + { + ++pos; + if (pos >= argc) + { + return error_invalid_arg("missing size after {}", op); + } + uint64_t size = 0; + if (!ParseSize(argv[pos], size)) + { + return error_invalid_arg("invalid size '{}' for {}; use e.g. 512M or 1G", argv[pos], op); + } + opt.max_metadata_size = size; + } + else + { + return error_invalid_arg("unknown option for stat: {}", op); + } + pos++; + } int remain_argc = argc - pos; if (remain_argc != 1) { @@ -456,6 +499,20 @@ namespace ctar::cli opt.enable_tree_dir_only = true; else if (op == "-s") opt.enable_tree_stats = true; + else if (op == "--max-metadata-size") + { + ++pos; + if (pos >= argc) + { + return error_invalid_arg("missing size after {}", op); + } + uint64_t size = 0; + if (!ParseSize(argv[pos], size)) + { + return error_invalid_arg("invalid size '{}' for {}; use e.g. 512M or 1G", argv[pos], op); + } + opt.max_metadata_size = size; + } else { return error_invalid_arg("unknown option for tree: {}", op); @@ -496,6 +553,20 @@ namespace ctar::cli std::string_view op{argv[pos]}; if (op == "-h") opt.enable_human_readable = true; + else if (op == "--max-metadata-size") + { + ++pos; + if (pos >= argc) + { + return error_invalid_arg("missing size after {}", op); + } + uint64_t size = 0; + if (!ParseSize(argv[pos], size)) + { + return error_invalid_arg("invalid size '{}' for {}; use e.g. 512M or 1G", argv[pos], op); + } + opt.max_metadata_size = size; + } else { return error_invalid_arg("unknown option for ls: {}", op); @@ -550,6 +621,20 @@ namespace ctar::cli { opt.enable_dump_header = true; } + else if (op == "--max-metadata-size") + { + ++pos; + if (pos >= argc) + { + return error_invalid_arg("missing size after {}", op); + } + uint64_t size = 0; + if (!ParseSize(argv[pos], size)) + { + return error_invalid_arg("invalid size '{}' for {}; use e.g. 512M or 1G", argv[pos], op); + } + opt.max_metadata_size = size; + } else { return error_invalid_arg("unknown option for dump: {}", op); @@ -626,6 +711,7 @@ namespace ctar::cli unsigned hw_thread_cnt = (hw == 0) ? 1 : (hw); unsigned worker_thread_cnt = opt.thread_cnt > 0 ? opt.thread_cnt : hw_thread_cnt; BlockStore store(worker_thread_cnt, opt.comp_config); + store.SetMaxMetadataSize(opt.max_metadata_size); switch (opt.cmd) { case CommandType::HELP: diff --git a/src/cli/arg_parser.h b/src/cli/arg_parser.h index ca08e95..3735d41 100644 --- a/src/cli/arg_parser.h +++ b/src/cli/arg_parser.h @@ -64,6 +64,8 @@ namespace ctar::cli bool force = false; // Per-file decompressed-size limit for unpack; 0 disables the limit. uint64_t max_decompressed_file_size = kDefaultMaxDecompressedFileSize; + // Per-archive uncompressed metadata limit for archive readers; 0 disables it. + uint64_t max_metadata_size = kDefaultMaxMetadataSize; std::string input_data; bool enable_hash_file = false; diff --git a/src/core/block_store.cpp b/src/core/block_store.cpp index df34301..d9c6c5f 100644 --- a/src/core/block_store.cpp +++ b/src/core/block_store.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -1121,13 +1122,27 @@ namespace ctar return error_corruption("corrupt archive '{}': metadata size {} exceeds the file size {}", pack_file_path, header.metadata_compressed_size, file_size); } - // Bound the allocation for a maliciously large uncompressed metadata size. - constexpr uint64_t kMaxMetadataSize = 4ULL * 1024 * 1024 * 1024; - if (header.metadata_original_size == 0 || header.metadata_original_size > kMaxMetadataSize || - header.metadata_compressed_size == 0) + if (header.metadata_original_size == 0 || header.metadata_compressed_size == 0) { return error_corruption("corrupt archive '{}': impossible metadata sizes", pack_file_path); } + // The metadata size is untrusted: compression can amplify a small region by + // up to 255x, and parsing allocates the full size plus the block metadata + // vector. Refuse it before allocating anything. + if (max_metadata_size_ > 0 && header.metadata_original_size > max_metadata_size_) + { + return error_corruption( + "archive '{}': metadata size {} exceeds the configured limit {} " + "(use --max-metadata-size to raise it)", + pack_file_path, header.metadata_original_size, max_metadata_size_); + } + // LZ4 takes int sizes, so larger compressed metadata cannot be decoded. + if (header.metadata_compressed_type != static_cast(CompressionType::kNone) && + header.metadata_original_size > static_cast(std::numeric_limits::max())) + { + return error_corruption("corrupt archive '{}': compressed metadata size {} exceeds the LZ4 limit", + pack_file_path, header.metadata_original_size); + } if (header.metadata_compressed_type != static_cast(CompressionType::kNone) && header.metadata_original_size / header.metadata_compressed_size > 255) { @@ -1167,6 +1182,12 @@ namespace ctar return error_corruption("corrupt archive '{}': metadata size {} exceeds the file size {}", pack_file_path, header.file_meta_size, file_size); } + if (max_metadata_size_ > 0 && header.file_meta_size > max_metadata_size_) + { + return error_corruption( + "archive '{}': legacy metadata size {} exceeds the configured limit {}", pack_file_path, + header.file_meta_size, max_metadata_size_); + } legacy_layout_ = true; pack_file_header_ = PackFileHeader{}; legacy_file_meta_size_ = header.file_meta_size; @@ -1195,55 +1216,58 @@ namespace ctar } auto& read_file = read_file_status.value(); - std::string metadata_bytes; + std::unique_ptr metadata_storage; + uint64_t metadata_size = 0; if (legacy_layout_) { - metadata_bytes.assign(static_cast(legacy_file_meta_size_), '\0'); + metadata_storage = std::make_unique_for_overwrite(static_cast(legacy_file_meta_size_)); auto read_status = read_file->RandomRead(static_cast(LegacyPackFileHeader::kSerializedSize), - legacy_file_meta_size_, metadata_bytes.data()); + legacy_file_meta_size_, metadata_storage.get()); if (!read_status || read_status.value() != static_cast(legacy_file_meta_size_)) { return error_io("fail to read metadata from {}", pack_file_path); } + metadata_size = legacy_file_meta_size_; } else { - std::string stored(static_cast(metadata_compressed_size_), '\0'); - if (!stored.empty()) + // Both buffers are uninitialized: zero-filling the metadata would commit + // its full declared size to RSS before decompression has a chance to fail. + auto stored = std::make_unique_for_overwrite(static_cast(metadata_compressed_size_)); + auto read_status = read_file->RandomRead(static_cast(pack_file_header_.metadata_offset), + metadata_compressed_size_, stored.get()); + if (!read_status || read_status.value() != static_cast(metadata_compressed_size_)) { - auto read_status = read_file->RandomRead(static_cast(pack_file_header_.metadata_offset), - metadata_compressed_size_, stored.data()); - if (!read_status || read_status.value() != static_cast(metadata_compressed_size_)) - { - return error_io("fail to read metadata from {}", pack_file_path); - } + return error_io("fail to read metadata from {}", pack_file_path); } const auto metadata_type = static_cast(metadata_compressed_type_); if (metadata_type == CompressionType::kNone) { - metadata_bytes = std::move(stored); + metadata_storage = std::move(stored); + metadata_size = metadata_compressed_size_; } else { - metadata_bytes.assign(static_cast(metadata_original_size_), '\0'); + metadata_storage = std::make_unique_for_overwrite(static_cast(metadata_original_size_)); const uint64_t decompressed_size = - compress::Decompress(metadata_type, stored.data(), metadata_bytes.data(), + compress::Decompress(metadata_type, stored.get(), metadata_storage.get(), metadata_compressed_size_, metadata_original_size_); if (decompressed_size != metadata_original_size_) { return error_corruption("corrupt archive '{}': failed to decompress metadata", pack_file_path); } + metadata_size = metadata_original_size_; } - const uint64_t checksum = XXH64(metadata_bytes.data(), metadata_bytes.size(), kHashSeed); + const uint64_t checksum = XXH64(metadata_storage.get(), metadata_size, kHashSeed); if (checksum != metadata_checksum_) { return error_corruption("corrupt archive '{}': metadata checksum mismatch", pack_file_path); } } - const char* meta_ptr = metadata_bytes.data(); - const char* const meta_end = metadata_bytes.data() + metadata_bytes.size(); + const char* meta_ptr = metadata_storage.get(); + const char* const meta_end = meta_ptr + static_cast(metadata_size); s = pack_file_handle_.DeserializePackFileMeta(meta_ptr, meta_end); if (!s) { @@ -1255,7 +1279,10 @@ namespace ctar } const auto data_block_count = DecodeFixed64(meta_ptr); meta_ptr += sizeof(uint64_t); - constexpr uint64_t kMinDataBlockMetaSize = 12 * sizeof(uint64_t); + // A block must contain at least one file (ValidateDataBlockMeta rejects empty + // blocks), and the smallest one serializes to 137 bytes: six fixed u64, six + // vector counts, one id/size/offset/hash each, and one compression type byte. + constexpr uint64_t kMinDataBlockMetaSize = 17 * sizeof(uint64_t) + sizeof(uint8_t); if (data_block_count > static_cast(meta_end - meta_ptr) / kMinDataBlockMetaSize) { return error_corruption("corrupt archive '{}': data block count {} is impossible", pack_file_path, @@ -1279,24 +1306,28 @@ namespace ctar }; data_block_metas_.clear(); - data_block_metas_.resize(static_cast(data_block_count)); + // Grow with the blocks that actually parse instead of trusting the declared + // count up front; a crafted count must not allocate the whole vector before + // the metadata has been read. + data_block_metas_.reserve(static_cast(std::min(data_block_count, 1024))); // Cross-block and cross-index checks. Together with the per-block range checks // this prevents a hostile archive from reusing the same compressed bytes, or the // same output path, through several block entries. std::vector> block_ranges; - block_ranges.reserve(data_block_metas_.size()); + block_ranges.reserve(data_block_metas_.capacity()); std::unordered_set block_ids; const auto& file_records = pack_file_handle_.GetFileEntryRecords(); std::vector> file_names; file_names.reserve(file_records.size()); - for (size_t i = 0; i < data_block_metas_.size(); ++i) + for (uint64_t i = 0; i < data_block_count; ++i) { - s = data_block_metas_[i].Deserialize(meta_ptr, meta_end); + data_block_metas_.emplace_back(); + auto& block_meta = data_block_metas_.back(); + s = block_meta.Deserialize(meta_ptr, meta_end); if (!s) { return s; } - const auto& block_meta = data_block_metas_[i]; if (block_meta.block_size > block_region_size_ || block_meta.block_file_offset > block_region_size_ - block_meta.block_size) { @@ -1316,7 +1347,7 @@ namespace ctar block_meta.block_file_offset + block_meta.block_size); if (auto dir_path = pack_file_handle_.GetDirPathByDirId(block_meta.dir_id)) { - data_block_metas_[i].dir_stats.dir_path = dir_path.value(); + block_meta.dir_stats.dir_path = dir_path.value(); } else { diff --git a/src/core/block_store.h b/src/core/block_store.h index 5efe0aa..3da476c 100644 --- a/src/core/block_store.h +++ b/src/core/block_store.h @@ -198,6 +198,8 @@ namespace ctar unsigned thread_cnt_ = 1; // Per-file decompression budget for unpack; 0 means unlimited. uint64_t max_decompressed_file_size_ = kDefaultMaxDecompressedFileSize; + // Per-archive uncompressed metadata budget for every reader; 0 means unlimited. + uint64_t max_metadata_size_ = kDefaultMaxMetadataSize; [[nodiscard]] uint64_t GetRawMetaSize() const; @@ -278,6 +280,9 @@ namespace ctar /// @brief Set the per-file decompression budget used by unpack (0 = unlimited). void SetMaxDecompressedFileSize(const uint64_t bytes) { max_decompressed_file_size_ = bytes; } + /// @brief Set the per-archive uncompressed metadata budget (0 = unlimited). + void SetMaxMetadataSize(const uint64_t bytes) { max_metadata_size_ = bytes; } + [[nodiscard]] Status CreateUnpackDir(); diff --git a/src/core/file_format.cpp b/src/core/file_format.cpp index 52642d4..b855124 100644 --- a/src/core/file_format.cpp +++ b/src/core/file_format.cpp @@ -370,6 +370,12 @@ namespace { return error_corruption("block {}: per-file vectors have different lengths", block_meta.block_id); } + // Pack never emits an empty block; rejecting them also keeps the minimum + // serialized block size (and therefore the block-count bound) meaningful. + if (file_count == 0) + { + return error_corruption("block {}: contains no files", block_meta.block_id); + } // The stored path is resolved only when there is an error to report, so valid // blocks pay no lookup cost. When it is unavailable, fall back to the entry's diff --git a/src/core/options.h b/src/core/options.h index 915fcda..3233ac9 100644 --- a/src/core/options.h +++ b/src/core/options.h @@ -46,6 +46,11 @@ namespace ctar // override the limit with --max-decompressed-size. constexpr uint64_t kDefaultMaxDecompressedFileSize = 1ULL * unit::GiB; + // Default per-archive limit for the uncompressed metadata region. Readers + // reject larger metadata before allocating it; the CLI can override it with + // --max-metadata-size (0 disables the limit). + constexpr uint64_t kDefaultMaxMetadataSize = 1ULL * unit::GiB; + // Thread-local read/block buffers larger than this are trimmed back to this // size after a task, instead of being held until the process exits. constexpr size_t kMaxRetainedBufferBytes = 128UL * unit::MiB; diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index 29fc176..6ea5a69 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -833,6 +833,53 @@ namespace ctar fixture.Cleanup(); } + TEST(MetadataBudget, RejectsMetadataAboveLimit) + { + MalformedArchiveFixture fixture; + fixture.Create(); + BlockStore store; + store.SetMaxMetadataSize(1); + const Status status = store.UnPackPipeline(fixture.archive.string(), fixture.out_dir.string(), true); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("metadata size"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + + TEST(MetadataBudget, ZeroDisablesLimit) + { + MalformedArchiveFixture fixture; + fixture.Create(); + BlockStore store; + store.SetMaxMetadataSize(0); + EXPECT_TRUE(store.UnPackPipeline(fixture.archive.string(), fixture.out_dir.string(), true)); + fixture.Cleanup(); + } + + TEST(MetadataBudget, RejectsCompressedMetadataAboveLz4Limit) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + constexpr size_t kMetadataOriginalSizeOffset = 104; + constexpr size_t kMetadataCompressedSizeOffset = 112; + constexpr size_t kMetadataCompressedTypeOffset = 120; + WriteU64At(bytes, kMetadataOriginalSizeOffset, 0x80000000ULL); + WriteU64At(bytes, kMetadataCompressedSizeOffset, 1); + WriteU64At(bytes, kMetadataCompressedTypeOffset, static_cast(CompressionType::kLZ4)); + WriteWholeFile(fixture.archive.string(), bytes); + + BlockStore store; + store.SetMaxMetadataSize(0); + const Status status = store.ReadPackHeaderOnly(fixture.archive.string()); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("LZ4 limit"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + namespace { diff --git a/test/cases/test_cli.cpp b/test/cases/test_cli.cpp index 66f63e8..47f343c 100644 --- a/test/cases/test_cli.cpp +++ b/test/cases/test_cli.cpp @@ -144,6 +144,48 @@ namespace ctar } } + TEST(ArgParserTest, CommandMaxMetadataSize) + { + { + cli::CliOption opt{}; + const std::vector args{"ctar", "unpack", "--max-metadata-size", "512M", "in.ctar", + "out"}; + ASSERT_TRUE(cli::ParseArgs(args, opt)); + EXPECT_EQ(opt.max_metadata_size, 512ULL * 1024 * 1024); + } + { + cli::CliOption opt{}; + const std::vector args{"ctar", "tree", "--max-metadata-size", "2G", "a.ctar"}; + ASSERT_TRUE(cli::ParseArgs(args, opt)); + EXPECT_EQ(opt.max_metadata_size, 2ULL * 1024 * 1024 * 1024); + EXPECT_EQ(opt.pack_file_path, "a.ctar"); + } + { + cli::CliOption opt{}; + const std::vector args{"ctar", "ls", "--max-metadata-size", "0", "a.ctar"}; + ASSERT_TRUE(cli::ParseArgs(args, opt)); + EXPECT_EQ(opt.max_metadata_size, 0U); + } + { + cli::CliOption opt{}; + const std::vector args{"ctar", "dump", "--max-metadata-size", "1M", "a.ctar"}; + ASSERT_TRUE(cli::ParseArgs(args, opt)); + EXPECT_EQ(opt.max_metadata_size, 1ULL * 1024 * 1024); + } + { + cli::CliOption opt{}; + const std::vector args{"ctar", "stat", "--max-metadata-size", "1G", "a.ctar"}; + ASSERT_TRUE(cli::ParseArgs(args, opt)); + EXPECT_EQ(opt.max_metadata_size, 1ULL * 1024 * 1024 * 1024); + } + { + cli::CliOption opt{}; + const std::vector args{"ctar", "unpack", "--max-metadata-size", "2X", "in.ctar", + "out"}; + EXPECT_FALSE(cli::ParseArgs(args, opt)); + } + } + TEST(ArgParserTest, CommandPackCompressNone) { cli::CliOption opt{}; diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index 68c5597..0b3fe23 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -359,6 +359,17 @@ namespace ctar << status.error().message(); } + TEST(DataBlobMeta, RejectsEmptyBlock) + { + DataBlockMeta block; + block.block_id = 7; + const Status status = ValidateDataBlockMeta(block); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("contains no files"), std::string::npos) + << status.error().message(); + } + TEST(DataBlobMeta, SerializeDeserializeEmptyArrays) { DataBlockMeta src; From 7a5e89b821b7b8f4b3515942afbf67582725fb46 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Wed, 25 Nov 2026 20:38:34 +0800 Subject: [PATCH 2/2] fix: bound stored metadata size and LZ4 input ReadPackHeaderOnly only bounded the uncompressed metadata size. A crafted header could set metadata_compressed_size above the budget (and above the LZ4 int limit) while keeping original_size small; the ratio check then became zero and the stored buffer was still allocated up to the archive-size bound. Require compressed metadata to be strictly smaller than its original size (the packer's raw fallback otherwise), apply the metadata budget to the stored size, and check both sizes against the LZ4 int limit. Fix the error text that named the compressed size while checking the original. Refs #74 --- README.md | 8 +++--- README_CN.md | 6 ++--- doc/file_format.md | 2 +- doc/file_format_CN.md | 2 +- src/cli/arg_parser.cpp | 6 ++--- src/core/block_store.cpp | 47 +++++++++++++++++++++++++------- test/cases/test_block_store.cpp | 48 ++++++++++++++++++++++++++++++++- 7 files changed, 96 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 82e1005..d630c84 100644 --- a/README.md +++ b/README.md @@ -106,10 +106,10 @@ ctar dump pack_file.ctar `--max-decompressed-size SIZE` to change it (`0` disables the limit). Larger files are rejected until chunked unpacking (#38) lands. -Archive readers (`unpack`, `tree`, `ls`, `dump`, `stat`) also limit the -uncompressed metadata region to 1 GiB by default; use `--max-metadata-size SIZE` -to change it (`0` disables the limit). This keeps a small crafted archive from -expanding into a multi-gigabyte metadata buffer. +Archive readers (`unpack`, `tree`, `ls`, `dump`, `stat`) also limit the stored +and uncompressed metadata regions to 1 GiB by default; use +`--max-metadata-size SIZE` to change it (`0` disables the limit). This keeps a +small crafted archive from expanding into a multi-gigabyte metadata buffer. In most cases the `pack` and `unpack` commands are all you need, and the more files there are, the more noticeable the benefit. If you have other requirements — for example, storing the packed file in the cloud but wanting to diff --git a/README_CN.md b/README_CN.md index 085cf7d..2a06a49 100644 --- a/README_CN.md +++ b/README_CN.md @@ -98,9 +98,9 @@ ctar dump pack_file.ctar `--max-decompressed-size SIZE` 调整(`0` 表示不限制)。超过预算的文件会被拒绝, 在分块支持(#38)落地前需要显式调大预算。 -归档读取命令(`unpack`、`tree`、`ls`、`dump`、`stat`)还会把未压缩 metadata 限制为 -1 GiB;可用 `--max-metadata-size SIZE` 调整(`0` 表示不限制)。这样小的恶意归档 -无法膨胀成数 GiB 的 metadata 缓冲区。 +归档读取命令(`unpack`、`tree`、`ls`、`dump`、`stat`)还会把存储和未压缩 metadata +都限制为 1 GiB;可用 `--max-metadata-size SIZE` 调整(`0` 表示不限制)。这样小的 +恶意归档无法膨胀成数 GiB 的 metadata 缓冲区。 一般情况下,使用 `pack` 和 `unpack` 命令即可满足大部分的需求,文件越多收益越明显。如果有其他需求,如将打包后的文件放在云端,但只想获取打包文件中的部分数据时,可参考下面的简短教程。 diff --git a/doc/file_format.md b/doc/file_format.md index 1696bc8..db5d9ee 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -167,7 +167,7 @@ The reader rejects archives that violate these cross-field invariants; a writer - Every `file_ids[i]` exists in `file_entry_records`; the entry's `block_id`, `file_orig_size`, `file_compressed_size` and absolute `file_offset` agree with the block, and every indexed file is referenced exactly once. - Directory paths are unique, and a directory contains no duplicate file names, so every extracted file has a distinct output path. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). -- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) before allocating the uncompressed metadata. Compressed metadata above the LZ4 `int` limit is always rejected, and empty data blocks are invalid. +- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, compressed metadata must be strictly smaller than its original size, and empty data blocks are invalid. ### version encoding and compatibility diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index 0f81f6e..fc04041 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -165,7 +165,7 @@ data_block_meta[data_block_count] - 每个 `file_ids[i]` 都必须存在于 `file_entry_records`,其 `block_id`、`file_orig_size`、`file_compressed_size` 和绝对 `file_offset` 与块元数据一致;所有索引文件都必须被且仅被引用一次。 - 目录路径唯一,同一目录内文件名唯一,保证每个解压文件有唯一的输出路径。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 -- 所有归档读取命令都在分配未压缩 metadata 之前施加每归档 metadata 预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制)。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,空 data block 也是非法的。 +- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小,空 data block 也是非法的。 ### 版本编码与兼容性 diff --git a/src/cli/arg_parser.cpp b/src/cli/arg_parser.cpp index 97de179..a4f8ed2 100644 --- a/src/cli/arg_parser.cpp +++ b/src/cli/arg_parser.cpp @@ -85,9 +85,9 @@ COMMAND OPTIONS Files above it are rejected during unpack. --max-metadata-size SIZE - Per-archive metadata limit for unpack/tree/ls/dump/stat - (default 1G, 0 = unlimited). Larger metadata is rejected before - it is allocated. + Per-archive limit on stored and uncompressed metadata for + unpack/tree/ls/dump/stat (default 1G, 0 = unlimited). Larger + metadata is rejected before it is allocated. ls: -h diff --git a/src/core/block_store.cpp b/src/core/block_store.cpp index d9c6c5f..ad9befc 100644 --- a/src/core/block_store.cpp +++ b/src/core/block_store.cpp @@ -1136,17 +1136,44 @@ namespace ctar "(use --max-metadata-size to raise it)", pack_file_path, header.metadata_original_size, max_metadata_size_); } - // LZ4 takes int sizes, so larger compressed metadata cannot be decoded. - if (header.metadata_compressed_type != static_cast(CompressionType::kNone) && - header.metadata_original_size > static_cast(std::numeric_limits::max())) + const bool compressed_metadata = + header.metadata_compressed_type != static_cast(CompressionType::kNone); + if (compressed_metadata) { - return error_corruption("corrupt archive '{}': compressed metadata size {} exceeds the LZ4 limit", - pack_file_path, header.metadata_original_size); - } - if (header.metadata_compressed_type != static_cast(CompressionType::kNone) && - header.metadata_original_size / header.metadata_compressed_size > 255) - { - return error_corruption("corrupt archive '{}': impossible metadata compression ratio", pack_file_path); + // The stored buffer is allocated before decompression too, so it needs + // the same budget and the same LZ4 int bound as the output. + if (max_metadata_size_ > 0 && header.metadata_compressed_size > max_metadata_size_) + { + return error_corruption( + "archive '{}': stored metadata size {} exceeds the configured limit {} " + "(use --max-metadata-size to raise it)", + pack_file_path, header.metadata_compressed_size, max_metadata_size_); + } + if (header.metadata_original_size > static_cast(std::numeric_limits::max())) + { + return error_corruption( + "corrupt archive '{}': uncompressed metadata size {} exceeds the LZ4 limit", pack_file_path, + header.metadata_original_size); + } + if (header.metadata_compressed_size > static_cast(std::numeric_limits::max())) + { + return error_corruption( + "corrupt archive '{}': compressed metadata size {} exceeds the LZ4 limit", pack_file_path, + header.metadata_compressed_size); + } + // Pack stores compressed metadata only when it is strictly smaller; + // equal or larger sizes are the raw/kNone fallback. + if (header.metadata_compressed_size >= header.metadata_original_size) + { + return error_corruption( + "corrupt archive '{}': compressed metadata is not smaller than its original size", + pack_file_path); + } + if (header.metadata_original_size / header.metadata_compressed_size > 255) + { + return error_corruption("corrupt archive '{}': impossible metadata compression ratio", + pack_file_path); + } } if (!IsValidCompressionType(header.file_data_compressed_type) || !IsValidCompressionType(header.metadata_compressed_type)) diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index 6ea5a69..8fdcef2 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -857,7 +857,7 @@ namespace ctar fixture.Cleanup(); } - TEST(MetadataBudget, RejectsCompressedMetadataAboveLz4Limit) + TEST(MetadataBudget, RejectsUncompressedMetadataAboveLz4Limit) { MalformedArchiveFixture fixture; fixture.Create(); @@ -880,6 +880,52 @@ namespace ctar fixture.Cleanup(); } + TEST(MetadataBudget, RejectsStoredMetadataAboveBudget) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + constexpr size_t kMetadataOriginalSizeOffset = 104; + constexpr size_t kMetadataCompressedSizeOffset = 112; + constexpr size_t kMetadataCompressedTypeOffset = 120; + WriteU64At(bytes, kMetadataOriginalSizeOffset, 100); + WriteU64At(bytes, kMetadataCompressedSizeOffset, 150); + WriteU64At(bytes, kMetadataCompressedTypeOffset, static_cast(CompressionType::kLZ4)); + WriteWholeFile(fixture.archive.string(), bytes); + + BlockStore store; + store.SetMaxMetadataSize(120); + const Status status = store.ReadPackHeaderOnly(fixture.archive.string()); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("stored metadata size"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + + TEST(MetadataBudget, RejectsCompressedMetadataNotSmallerThanOriginal) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + constexpr size_t kMetadataOriginalSizeOffset = 104; + constexpr size_t kMetadataCompressedSizeOffset = 112; + constexpr size_t kMetadataCompressedTypeOffset = 120; + WriteU64At(bytes, kMetadataOriginalSizeOffset, 100); + WriteU64At(bytes, kMetadataCompressedSizeOffset, 100); + WriteU64At(bytes, kMetadataCompressedTypeOffset, static_cast(CompressionType::kLZ4)); + WriteWholeFile(fixture.archive.string(), bytes); + + BlockStore store; + store.SetMaxMetadataSize(0); + const Status status = store.ReadPackHeaderOnly(fixture.archive.string()); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("not smaller"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + namespace {