From 084f512d345bb3649d18676da2200ec8297d7ad0 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Tue, 5 Jan 2021 22:01:49 +0100 Subject: [PATCH] Check that packet length is good --- squinnondation/messages.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/squinnondation/messages.py b/squinnondation/messages.py index fad4f57..bf00e23 100644 --- a/squinnondation/messages.py +++ b/squinnondation/messages.py @@ -492,14 +492,21 @@ class Packet: pkt.magic = data[0] pkt.version = data[1] pkt.body_length = socket.ntohs(int.from_bytes(data[2:4], sys.byteorder)) + if len(data) != 4 + pkt.body_length: + raise ValueError(f"Invalid packet length: " + f"declared body length is {pkt.body_length} while {len(data) - 4} bytes are avalaible") pkt.body = [] read_bytes = 0 while read_bytes < min(len(data) - 4, pkt.body_length): tlv_type = data[4 + read_bytes] if not (0 <= tlv_type < len(TLV.tlv_classes())): raise ValueError(f"TLV type is not supported: {tlv_type}") + tlv_length = data[4 + read_bytes + 1] if tlv_type > 0 else -1 + if 2 + tlv_length > pkt.body_length - read_bytes: + raise ValueError(f"TLV length is too long: requesting {tlv_length} bytes, " + f"remaining {pkt.body_length - read_bytes}") tlv = TLV.tlv_classes()[tlv_type]() - tlv.unmarshal(data[4 + read_bytes:4 + read_bytes + pkt.body_length]) + tlv.unmarshal(data[4 + read_bytes:4 + read_bytes + 2 + tlv_length]) pkt.body.append(tlv) read_bytes += len(tlv)