#include "pistreampacker.h" #include "gtest/gtest.h" #include // A stream (e.g. a malicious network peer) can declare a packet size of // up to INT_MAX in the PIStreamPacker header. The packer must not // accumulate that much and must stay usable for valid packets afterwards. TEST(PIStreamPacker, RejectsOversizedPacket) { static const ushort PACKET_SIGN = 0xAFBE; // PIStreamPacker default sign std::atomic_int count{0}; PIStreamPacker packer(nullptr); CONNECTL(&packer, packetReceiveEvent, [&count](PIByteArray & ba) { count++; }); const int MB = 1024 * 1024; // poison: sign + int32 size = 2147483647 (LE) + 1 MB of junk uchar hdr[6] = { (uchar)(PACKET_SIGN & 0xFF), (uchar)(PACKET_SIGN >> 8), 0xFF, 0xFF, 0xFF, 0x7F // int32 2147483647 LE }; PIByteArray poison; poison.append(hdr, 6); PIByteArray junk(MB, 0x42); poison.append(junk); packer.received(poison); packer.received(junk); EXPECT_LT(packer.receivePacketProgress(), 64 * 1024) << "packer accumulated an unbounded amount of data for a forged size"; // a valid small packet must still be received: sign + int32(5) + "hello" uchar vh[6] = {(uchar)(PACKET_SIGN & 0xFF), (uchar)(PACKET_SIGN >> 8), 0x05, 0x00, 0x00, 0x00}; PIByteArray valid; valid.append(vh, 6); valid.append("hello", 5); packer.received(valid); EXPECT_EQ(1, count.load()) << "packer stopped delivering valid packets"; }