Skip to content

Commit 72d7f9d

Browse files
committed
fix _packet_subnet calculation logic
1 parent dbaaf69 commit 72d7f9d

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

scapy/layers/dns.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -558,34 +558,31 @@ def m2i(self, pkt, x):
558558
x = x[: operator.floordiv(self.af_length, 8)]
559559
return inet_ntop(self.af_familly, x)
560560

561-
def _pack_subnet(self, subnet):
562-
# type: (bytes) -> bytes
561+
def _pack_subnet(self, subnet, pkt):
562+
# type: (bytes, Packet) -> bytes
563563
packed_subnet = inet_pton(self.af_familly, plain_str(subnet))
564-
for i in list(range(operator.floordiv(self.af_length, 8)))[::-1]:
565-
if packed_subnet[i] != 0:
566-
i += 1
567-
break
568-
return packed_subnet[:i]
564+
sz = operator.floordiv(self.length_from(pkt) + 7, 8)
565+
return packed_subnet[:sz]
569566

570567
def i2m(self, pkt, x):
571568
# type: (Optional[Packet], Optional[Union[str, Net]]) -> bytes
572569
if x is None:
573570
return self.af_default
574571
try:
575-
return self._pack_subnet(x)
572+
return self._pack_subnet(x, pkt)
576573
except (OSError, socket.error):
577574
pkt.family = 2
578-
return ClientSubnetv6("", "")._pack_subnet(x)
575+
return ClientSubnetv6("", "")._pack_subnet(x, pkt)
579576

580577
def i2len(self, pkt, x):
581578
# type: (Packet, Any) -> int
582579
if x is None:
583580
return 1
584581
try:
585-
return len(self._pack_subnet(x))
582+
return len(self._pack_subnet(x, pkt))
586583
except (OSError, socket.error):
587584
pkt.family = 2
588-
return len(ClientSubnetv6("", "")._pack_subnet(x))
585+
return len(ClientSubnetv6("", "")._pack_subnet(x, pkt))
589586

590587

591588
class ClientSubnetv6(ClientSubnetv4):

test/scapy/layers/dns.uts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,3 +520,6 @@ for i in pkt:
520520
b = b'\x00\x08\x00\x0c\x00\x02=\x00+\xaf\xa3\xc4\xed\xeeW\xb8'
521521
p = EDNS0ClientSubnet(b)
522522
assert p.source_plen == 61 and p.address == '2baf:a3c4:edee:57b8::'
523+
524+
b = EDNS0ClientSubnet(source_plen=23, address='101.132.0.0')
525+
assert bytes(b) == b'\x00\x08\x00\x07\x00\x01\x17\x00e\x84\x00'

0 commit comments

Comments
 (0)