diff --git a/csdb/src/pool.cpp b/csdb/src/pool.cpp index 53de8e7c8..58116d6bd 100644 --- a/csdb/src/pool.cpp +++ b/csdb/src/pool.cpp @@ -236,6 +236,16 @@ class Pool::priv : public ::csdb::internal::shared_data { return true; } + // hashingLength_ is read from the data being parsed (possibly from the network) and + // updateHash() hashes that many bytes of them + bool hashingLengthFits(size_t dataSize) const { + if (hashingLength_ > dataSize) { + csmeta(cswarning) << sequence_ << ": hashing length " << hashingLength_ << " exceeds data size " << dataSize; + return false; + } + return true; + } + void updateHash() { const auto begin = binary_representation_.data(); const auto end = begin + hashingLength_; @@ -923,6 +933,9 @@ PoolHash Pool::hash_from_binary(cs::Bytes&& data) { if (!p->get_hashed_data(is)) { return PoolHash(); } + if (!p->hashingLengthFits(data.size())) { + return PoolHash(); + } p->update_binary_representation(std::move(data)); p->updateHash(); return p->hash_; @@ -932,7 +945,7 @@ PoolHash Pool::hash_from_binary(cs::Bytes&& data) { Pool Pool::from_binary(cs::Bytes&& data, bool makeReadOnly) { std::unique_ptr p{new priv()}; ::csdb::priv::ibstream is(data.data(), data.size()); - if (!p->get(is)) { + if (!p->get(is) || !p->hashingLengthFits(data.size())) { return Pool(); } p->update_binary_representation(std::move(data)); @@ -970,7 +983,7 @@ Pool Pool::from_lz4_byte_stream(size_t uncompressedSize) { ::csdb::priv::ibstream is(p->binary_representation_.data(), p->binary_representation_.size()); - if (!p->get(is)) { + if (!p->get(is) || !p->hashingLengthFits(p->binary_representation_.size())) { return Pool(); } diff --git a/tests/csnode/pool_tests.cpp b/tests/csnode/pool_tests.cpp index 8fb435c44..f3127ce8d 100644 --- a/tests/csnode/pool_tests.cpp +++ b/tests/csnode/pool_tests.cpp @@ -1,3 +1,40 @@ #define TESTING #include "gtest/gtest.h" + +#include + +#include + +// serialized pool and its hashing length (written as a raw size_t right after the hashed prefix) +static cs::Bytes poolBinary(size_t& hashingLength) { + csdb::Pool pool; + pool.set_sequence(1); + + cs::Bytes bytes = pool.to_binary_updated(); + hashingLength = pool.hashingLength(); + + return bytes; +} + +TEST(Pool, AcceptsSerializedPool) { + size_t hashingLength = 0; + cs::Bytes bytes = poolBinary(hashingLength); + + ASSERT_TRUE(csdb::Pool::from_binary(std::move(bytes)).is_valid()); +} + +// pool bytes come from the network (blocks requested while syncing) +TEST(Pool, RejectsHashingLengthPastData) { + size_t hashingLength = 0; + cs::Bytes bytes = poolBinary(hashingLength); + + ASSERT_GT(hashingLength, 0u); + ASSERT_LE(hashingLength + sizeof(size_t), bytes.size()); + + const size_t forged = bytes.size() + 1024 * 1024; + std::memcpy(bytes.data() + hashingLength, &forged, sizeof(forged)); + + ASSERT_FALSE(csdb::Pool::from_binary(cs::Bytes(bytes)).is_valid()); + ASSERT_TRUE(csdb::Pool::hash_from_binary(cs::Bytes(bytes)).is_empty()); +}