diff --git a/scapy/pton_ntop.py b/scapy/pton_ntop.py index 30512923eb41eca16d04eab1d30ac74b4df8f98a..bd3a3a41ce569a7da33867a4153ffb10a0c8598a 100644 --- a/scapy/pton_ntop.py +++ b/scapy/pton_ntop.py @@ -13,6 +13,7 @@ without IPv6 support, on Windows for instance. import socket import re +_IP4_FORMAT = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") _IP6_ZEROS = re.compile('(?::|^)(0(?::0)+)(?::|$)') def inet_pton(af, addr): @@ -34,9 +35,16 @@ def inet_pton(af, addr): joker_pos = None # The last part of an IPv6 address can be an IPv4 address + ipv4_bin = None ipv4_addr = None if "." in addr: ipv4_addr = addr.split(":")[-1] + if _IP4_FORMAT.match(ipv4_addr) is None: + raise Exception("Illegal syntax for IP address") + try: + ipv4_bin = socket.inet_aton(ipv4_addr) + except socket.error: + raise Exception("Illegal syntax for IP address") result = "" parts = addr.split(":") @@ -47,9 +55,8 @@ def inet_pton(af, addr): joker_pos = len(result) else: raise Exception("Illegal syntax for IP address") - elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part - # FIXME: inet_aton allows IPv4 addresses with less than 4 octets - result += socket.inet_aton(ipv4_addr) + elif part == ipv4_addr: + result += ipv4_bin else: # Each part must be 16bit. Add missing zeroes before decoding. try: diff --git a/test/regression.uts b/test/regression.uts index fe8c8c5706dc50da2cb7cc9fb10096c161be88f4..36d2fef2af0b996c88269c90e646e6f57f1cedf9 100644 --- a/test/regression.uts +++ b/test/regression.uts @@ -7464,6 +7464,32 @@ in6_getscope("ff05::2807") == IPV6_ADDR_SITELOCAL in6_getscope("ff01::2807") == IPV6_ADDR_LOOPBACK in6_getscope("::1") == IPV6_ADDR_LOOPBACK += inet_pton() + +import socket + +ip6_bad_addrs = ["fe80::2e67:ef2d:7eca::ed8a", + "fe80:1234:abcd::192.168.40.12:abcd", + "fe80:1234:abcd::192.168.40", + "fe80:1234:abcd::192.168.400.12"] +for ip6 in ip6_bad_addrs: + rc = False + try: + inet_pton(socket.AF_INET6, ip6) + except Exception, e: + rc = True + assert rc + +ip6_good_addrs = ["fe80:1234:abcd::192.168.40.12", + "fe80:1234:abcd::fe06", + "fe80::2e67:ef2d:7ece:ed8a"] +for ip6 in ip6_good_addrs: + rc = True + try: + inet_pton(socket.AF_INET6, ip6) + except Exception, e: + rc = False + assert rc ############ ############