diff --git a/csnode/include/csnode/compressor.hpp b/csnode/include/csnode/compressor.hpp index 9490dc7b8..5e2f17863 100644 --- a/csnode/include/csnode/compressor.hpp +++ b/csnode/include/csnode/compressor.hpp @@ -1,6 +1,7 @@ #ifndef COMPRESSOR_HPP #define COMPRESSOR_HPP +#include #include #include @@ -65,6 +66,12 @@ class Compressor { // try to decompress data, returns object if serializable template T decompress(const CompressedRegion& region) { + // region and its binary size may come from the network: reject what no compress() could produce + if (region.size() < static_cast(byteSizeof_)) { + cserror() << "Decompress error of " << cstype(T) << ": empty region"; + return T{}; + } + const auto compression = checkCompression(region.data(), region.size()); cs::Bytes bytes; @@ -72,6 +79,14 @@ class Compressor { size_t size = 0; if (compression == Compression::Compressed) { + const size_t compressedSize = region.size() - static_cast(byteSizeof_); + + if (region.binarySize() > static_cast(std::numeric_limits::max()) || + region.binarySize() > compressedSize * kLz4MaxExpansion) { + cserror() << "Decompress error of " << cstype(T) << ": invalid binary size " << region.binarySize(); + return T{}; + } + bytes.resize(region.binarySize()); const int uncompressedSize = LZ4_decompress_safe(reinterpret_cast(region.data()) + byteSizeof_, reinterpret_cast(bytes.data()), @@ -99,6 +114,9 @@ class Compressor { private: static inline int byteSizeof_ = sizeof(cs::Byte); + + // LZ4 can not expand compressed data more than 255 times + static constexpr size_t kLz4MaxExpansion = 256; }; // multi-threaded compressor diff --git a/tests/csnode/compressor_tests.cpp b/tests/csnode/compressor_tests.cpp index 236386202..d2126bf73 100644 --- a/tests/csnode/compressor_tests.cpp +++ b/tests/csnode/compressor_tests.cpp @@ -56,6 +56,27 @@ TEST(Compressor, TestCompressByte) { ASSERT_EQ(byte, entity); } +// a region and its binary size are read from the network (Node::getBlockReply) +TEST(Compressor, RejectsBinarySizeLz4CannotProduce) { + cs::Compressor compressor; + std::vector data(100, 7); + + auto region = compressor.compress(data); + ASSERT_EQ(cs::Compressor::checkCompression(region), cs::Compressor::Compression::Compressed); + + cs::CompressedRegion forged{ cs::Bytes(region.bytes()), std::numeric_limits::max() / 2 }; + auto entity = compressor.decompress>(forged); + + ASSERT_TRUE(entity.empty()); +} + +TEST(Compressor, RejectsEmptyRegion) { + cs::Compressor compressor; + auto entity = compressor.decompress>(cs::CompressedRegion{}); + + ASSERT_TRUE(entity.empty()); +} + TEST(SynchronizedCompressor, BaseSynchronizedCompressorUsage) { cs::SynchronizedCompressor compressor;