From 0be9180977bdc2a8977a18c700c166ddaac8c052 Mon Sep 17 00:00:00 2001 From: Etan Kissling Date: Mon, 13 Dec 2021 19:31:05 +0100 Subject: [PATCH] harden `ProtoBuffer.finish()` assert (#672) This hardens the length check in `ProtoBuffer.finish` to account for passed `options`. --- libp2p/protobuf/minprotobuf.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libp2p/protobuf/minprotobuf.nim b/libp2p/protobuf/minprotobuf.nim index 2d72c97..6977064 100644 --- a/libp2p/protobuf/minprotobuf.nim +++ b/libp2p/protobuf/minprotobuf.nim @@ -265,8 +265,8 @@ proc write*(pb: var ProtoBuffer, field: int, value: ProtoBuffer) {.inline.} = proc finish*(pb: var ProtoBuffer) = ## Prepare protobuf's buffer ``pb`` for writing to stream. - doAssert(len(pb.buffer) > 0) if WithVarintLength in pb.options: + doAssert(len(pb.buffer) >= 10) let size = uint(len(pb.buffer) - 10) let pos = 10 - vsizeof(size) var usedBytes = 0 @@ -274,14 +274,17 @@ proc finish*(pb: var ProtoBuffer) = doAssert(res.isOk()) pb.offset = pos elif WithUint32BeLength in pb.options: + doAssert(len(pb.buffer) >= 4) let size = uint(len(pb.buffer) - 4) pb.buffer[0 ..< 4] = toBytesBE(uint32(size)) pb.offset = 4 elif WithUint32LeLength in pb.options: + doAssert(len(pb.buffer) >= 4) let size = uint(len(pb.buffer) - 4) pb.buffer[0 ..< 4] = toBytesLE(uint32(size)) pb.offset = 4 else: + doAssert(len(pb.buffer) > 0) pb.offset = 0 proc getHeader(data: var ProtoBuffer,