Example #1
0
 def parse_options(
         self,
         pool=Net("192.168.1.128/25"),
         network="192.168.1.0/24",
         gw="192.168.1.1",  # noqa: E501
         domain="localnet",
         renewal_time=60,
         lease_time=1800):
     self.domain = domain
     netw, msk = (network.split("/") + ["32"])[:2]
     msk = itom(int(msk))
     self.netmask = ltoa(msk)
     self.network = ltoa(atol(netw) & msk)
     self.broadcast = ltoa(atol(self.network) | (0xffffffff & ~msk))
     self.gw = gw
     if isinstance(pool, six.string_types):
         pool = Net(pool)
     if isinstance(pool, Iterable):
         pool = [
             k for k in pool if k not in [gw, self.network, self.broadcast]
         ]  # noqa: E501
         pool.reverse()
     if len(pool) == 1:
         pool, = pool
     self.pool = pool
     self.lease_time = lease_time
     self.renewal_time = renewal_time
     self.leases = {}
Example #2
0
def _read_routes_xp():
    # The InterfaceIndex in Win32_IP4RouteTable does not match the
    # InterfaceIndex in Win32_NetworkAdapter under some platforms
    # (namely Windows XP): let's try an IP association
    routes = []
    partial_routes = []
    # map local IP addresses to interfaces
    local_addresses = {iface.ip: iface for iface in six.itervalues(IFACES)}
    iface_indexes = {}
    for line in exec_query(['Get-WmiObject', 'Win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex']):
        if line[2] in local_addresses:
            iface = local_addresses[line[2]]
            # This gives us an association InterfaceIndex <-> interface
            iface_indexes[line[3]] = iface
            routes.append(
                (atol(line[0]), atol(line[1]), "0.0.0.0", iface, iface.ip))
        else:
            partial_routes.append(
                (atol(line[0]), atol(line[1]), line[2], line[3]))
    for dst, mask, gw, ifidx in partial_routes:
        if ifidx in iface_indexes:
            iface = iface_indexes[ifidx]
            routes.append((dst, mask, gw, iface, iface.ip))
    return routes
Example #3
0
    def route(self, dest, verbose=None):
        if type(dest) is list and dest:
            dest = dest[0]
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose = conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*", "0")
        while 1:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:] + ".").find(".")
            dst = dst[:l] + dst[l + m:]

        dst = atol(dst)
        pathes = []
        for d, m, gw, i, a in self.routes:
            aa = atol(a)
            if aa == dst:
                pathes.append((0xffffffffL, (LOOPBACK_NAME, a, "0.0.0.0")))
            if (dst & m) == (d & m):
                pathes.append((m, (i, a, gw)))
        if not pathes:
            if verbose:
                warning("No route found (no default route?)")
            return LOOPBACK_NAME, "0.0.0.0", "0.0.0.0"  #XXX linux specific!
        # Choose the more specific route (greatest netmask).
        # XXX: we don't care about metrics
        pathes.sort()
        ret = pathes[-1][1]
        self.cache[dest] = ret
        return ret
Example #4
0
def _read_routes_xp():
    # The InterfaceIndex in Win32_IP4RouteTable does not match the
    # InterfaceIndex in Win32_NetworkAdapter under some platforms
    # (namely Windows XP): let's try an IP association
    routes = []
    partial_routes = []
    # map local IP addresses to interfaces
    local_addresses = {iface.ip: iface for iface in six.itervalues(IFACES)}
    iface_indexes = {}
    for line in exec_query(['Get-WmiObject', 'Win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex', 'Metric1']):
        if line[2] in local_addresses:
            iface = local_addresses[line[2]]
            # This gives us an association InterfaceIndex <-> interface
            iface_indexes[line[3]] = iface
            routes.append((atol(line[0]), atol(line[1]), "0.0.0.0", iface,
                           iface.ip, int(line[4])))
        else:
            partial_routes.append((atol(line[0]), atol(line[1]), line[2],
                                   line[3], int(line[4])))
    for dst, mask, gw, ifidx, metric in partial_routes:
        if ifidx in iface_indexes:
            iface = iface_indexes[ifidx]
            routes.append((dst, mask, gw, iface, iface.ip, metric))
    return routes
Example #5
0
def read_routes_7():
    routes = []
    for line in exec_query(["Get-WmiObject", "win32_IP4RouteTable"], ["Name", "Mask", "NextHop", "InterfaceIndex"]):
        try:
            iface = dev_from_index(line[3])
        except ValueError:
            continue
        routes.append((atol(line[0]), atol(line[1]), line[2], iface, iface.ip))
    return routes
Example #6
0
def read_routes_7():
    routes=[]
    for line in exec_query(['Get-WmiObject', 'win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex']):
        try:
            iface = dev_from_index(line[3])
        except ValueError:
            continue
        routes.append((atol(line[0]), atol(line[1]), line[2], iface, iface.ip))
    return routes
Example #7
0
def read_routes_7():
    routes = []
    for line in exec_query(['Get-WmiObject', 'win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex']):
        try:
            iface = dev_from_index(line[3])
        except ValueError:
            continue
        routes.append((atol(line[0]), atol(line[1]), line[2], iface, iface.ip))
    return routes
Example #8
0
def _read_routes_7():
    routes=[]
    for line in exec_query(['Get-WmiObject', 'Win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex', 'Metric1']):
        try:
            iface = dev_from_index(line[3])
            ip = "127.0.0.1" if line[3] == "1" else iface.ip # Force loopback on iface 1
            routes.append((atol(line[0]), atol(line[1]), line[2], iface, ip, int(line[4])))
        except ValueError:
            continue
    return routes
Example #9
0
def _read_routes_7():
    routes=[]
    for line in exec_query(['Get-WmiObject', 'Win32_IP4RouteTable'],
                           ['Name', 'Mask', 'NextHop', 'InterfaceIndex', 'Metric1']):
        try:
            iface = dev_from_index(line[3])
            ip = "127.0.0.1" if line[3] == "1" else iface.ip # Force loopback on iface 1
            routes.append((atol(line[0]), atol(line[1]), line[2], iface, ip, int(line[4])))
        except ValueError:
            continue
    return routes
    def route(self, dst=None, verbose=conf.verb):
        # type: (Optional[str], int) -> Tuple[str, str, str]
        """Returns the IPv4 routes to a host.
        parameters:
         - dst: the IPv4 of the destination host

        returns: (iface, output_ip, gateway_ip)
         - iface: the interface used to connect to the host
         - output_ip: the outgoing IP that will be used
         - gateway_ip: the gateway IP that will be used
        """
        dst = dst or "0.0.0.0"  # Enable route(None) to return default route
        if isinstance(dst, bytes):
            try:
                dst = plain_str(dst)
            except UnicodeDecodeError:
                raise TypeError("Unknown IP address input (bytes)")
        if dst in self.cache:
            return self.cache[dst]
        # Transform "192.168.*.1-5" to one IP of the set
        _dst = dst.split("/")[0].replace("*", "0")
        while True:
            idx = _dst.find("-")
            if idx < 0:
                break
            m = (_dst[idx:] + ".").find(".")
            _dst = _dst[:idx] + _dst[idx + m:]

        atol_dst = atol(_dst)
        paths = []
        for d, m, gw, i, a, me in self.routes:
            if not a:  # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == atol_dst:
                paths.append(
                    (0xffffffff, 1, (conf.loopback_name, a, "0.0.0.0"))  # noqa: E501
                )
            if (atol_dst & m) == (d & m):
                paths.append((m, me, (i, a, gw)))

        if not paths:
            if verbose:
                warning("No route found (no default route?)")
            return conf.loopback_name, "0.0.0.0", "0.0.0.0"
        # Choose the more specific route
        # Sort by greatest netmask and use metrics as a tie-breaker
        paths.sort(key=lambda x: (-x[0], x[1]))
        # Return interface
        ret = paths[0][2]
        self.cache[dst] = ret
        return ret
Example #11
0
    def route(self, dst=None, verbose=conf.verb):
        """Returns the IPv4 routes to a host.
        parameters:
         - dst: the IPv4 of the destination host

        returns: (iface, output_ip, gateway_ip)
         - iface: the interface used to connect to the host
         - output_ip: the outgoing IP that will be used
         - gateway_ip: the gateway IP that will be used
        """
        dst = dst or "0.0.0.0"  # Enable route(None) to return default route
        if isinstance(dst, bytes):
            try:
                dst = plain_str(dst)
            except UnicodeDecodeError:
                raise TypeError("Unknown IP address input (bytes)")
        if dst in self.cache:
            return self.cache[dst]
        # Transform "192.168.*.1-5" to one IP of the set
        _dst = dst.split("/")[0].replace("*", "0")
        while True:
            idx = _dst.find("-")
            if idx < 0:
                break
            m = (_dst[idx:] + ".").find(".")
            _dst = _dst[:idx] + _dst[idx + m:]

        atol_dst = atol(_dst)
        paths = []
        for d, m, gw, i, a, me in self.routes:
            if not a:  # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == atol_dst:
                paths.append(
                    (0xffffffff, 1, (scapy.consts.LOOPBACK_INTERFACE, a, "0.0.0.0"))  # noqa: E501
                )
            if (atol_dst & m) == (d & m):
                paths.append((m, me, (i, a, gw)))

        if not paths:
            if verbose:
                warning("No route found (no default route?)")
            return scapy.consts.LOOPBACK_INTERFACE, "0.0.0.0", "0.0.0.0"
        # Choose the more specific route
        # Sort by greatest netmask and use metrics as a tie-breaker
        paths.sort(key=lambda x: (-x[0], x[1]))
        # Return interface
        ret = paths[0][2]
        self.cache[dst] = ret
        return ret
Example #12
0
    def route(self, dest, verbose=None):
        if dest is None:
            dest = "0.0.0.0"
        elif isinstance(dest, bytes):
            try:
                dest = plain_str(dest)
            except UnicodeDecodeError:
                dest = "0.0.0.0"
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose = conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*", "0")
        while True:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:] + ".").find(".")
            dst = dst[:l] + dst[l + m:]

        dst = atol(dst)
        pathes = []
        for d, m, gw, i, a, me in self.routes:
            if not a:  # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == dst:
                pathes.append(
                    (0xffffffff, 1, (scapy.consts.LOOPBACK_INTERFACE, a, "0.0.0.0"))  # noqa: E501
                )
            if (dst & m) == (d & m):
                pathes.append((m, me, (i, a, gw)))
        if not pathes:
            if verbose:
                warning("No route found (no default route?)")
            return scapy.consts.LOOPBACK_INTERFACE, "0.0.0.0", "0.0.0.0"
        # Choose the more specific route
        # Sort by greatest netmask
        pathes.sort(key=lambda x: x[0], reverse=True)
        # Get all pathes having the (same) greatest mask
        pathes = [i for i in pathes if i[0] == pathes[0][0]]
        # Tie-breaker: Metrics
        pathes.sort(key=lambda x: x[1])
        # Return interface
        ret = pathes[0][2]
        self.cache[dest] = ret
        return ret
Example #13
0
    def route(self, dest, verbose=None):
        if dest is None:
            dest = "0.0.0.0"
        elif isinstance(dest, bytes):
            try:
                dest = plain_str(dest)
            except UnicodeDecodeError:
                dest = "0.0.0.0"
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose = conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*", "0")
        while True:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:] + ".").find(".")
            dst = dst[:l] + dst[l + m:]

        dst = atol(dst)
        paths = []
        for d, m, gw, i, a, me in self.routes:
            if not a:  # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == dst:
                paths.append((0xffffffff, 1, (scapy.consts.LOOPBACK_INTERFACE,
                                              a, "0.0.0.0"))  # noqa: E501
                             )
            if (dst & m) == (d & m):
                paths.append((m, me, (i, a, gw)))
        if not paths:
            if verbose:
                warning("No route found (no default route?)")
            return scapy.consts.LOOPBACK_INTERFACE, "0.0.0.0", "0.0.0.0"
        # Choose the more specific route
        # Sort by greatest netmask
        paths.sort(key=lambda x: x[0], reverse=True)
        # Get all paths having the (same) greatest mask
        paths = [i for i in paths if i[0] == paths[0][0]]
        # Tie-breaker: Metrics
        paths.sort(key=lambda x: x[1])
        # Return interface
        ret = paths[0][2]
        self.cache[dest] = ret
        return ret
 def make_route(self,
                host=None,  # type: Optional[str]
                net=None,  # type: Optional[str]
                gw=None,  # type: Optional[str]
                dev=None,  # type: Optional[str]
                metric=1,  # type: int
                ):
     # type: (...) -> Tuple[int, int, str, str, str, int]
     from scapy.arch import get_if_addr
     if host is not None:
         thenet, msk = host, 32
     elif net is not None:
         thenet, msk_b = net.split("/")
         msk = int(msk_b)
     else:
         raise Scapy_Exception("make_route: Incorrect parameters. You should specify a host or a net")  # noqa: E501
     if gw is None:
         gw = "0.0.0.0"
     if dev is None:
         if gw:
             nhop = gw
         else:
             nhop = thenet
         dev, ifaddr, _ = self.route(nhop)
     else:
         ifaddr = get_if_addr(dev)
     return (atol(thenet), itom(msk), gw, dev, ifaddr, metric)
Example #15
0
    def setUpClass(cls):
        super(TestVxlan, cls).setUpClass()

        try:
            cls.dport = 4789
            cls.flags = 0x8

            # Create 2 pg interfaces.
            cls.create_pg_interfaces(range(4))
            for pg in cls.pg_interfaces:
                pg.admin_up()

            # Configure IPv4 addresses on VPP pg0.
            cls.pg0.config_ip4()

            # Resolve MAC address for VPP's IP address on pg0.
            cls.pg0.resolve_arp()

            # Our Multicast address
            cls.mcast_ip4 = '239.1.1.1'
            cls.mcast_ip4n = socket.inet_pton(socket.AF_INET, cls.mcast_ip4)
            iplong = atol(cls.mcast_ip4)
            cls.mcast_mac = "01:00:5e:%02x:%02x:%02x" % (
                (iplong >> 16) & 0x7F, (iplong >> 8) & 0xFF, iplong & 0xFF)

        except Exception:
            super(TestVxlan, cls).tearDownClass()
            raise
Example #16
0
    def setUpClass(cls):
        super(TestVxlan, cls).setUpClass()

        try:
            cls.dport = 4789
            cls.flags = 0x8

            # Create 2 pg interfaces.
            cls.create_pg_interfaces(range(4))
            for pg in cls.pg_interfaces:
                pg.admin_up()

            # Configure IPv4 addresses on VPP pg0.
            cls.pg0.config_ip4()

            # Resolve MAC address for VPP's IP address on pg0.
            cls.pg0.resolve_arp()

            # Our Multicast address
            cls.mcast_ip4 = '239.1.1.1'
            cls.mcast_ip4n = socket.inet_pton(socket.AF_INET, cls.mcast_ip4)
            iplong = atol(cls.mcast_ip4)
            cls.mcast_mac4 = "01:00:5e:%02x:%02x:%02x" % (
                (iplong >> 16) & 0x7F, (iplong >> 8) & 0xFF, iplong & 0xFF)

            # Create VXLAN VTEP on VPP pg0, and put vxlan_tunnel0 and pg1
            #  into BD.
            cls.single_tunnel_bd = 1
            r = cls.vapi.vxlan_add_del_tunnel(src_addr=cls.pg0.local_ip4n,
                                              dst_addr=cls.pg0.remote_ip4n,
                                              vni=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index,
                                                bd_id=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(cls.pg1.sw_if_index,
                                                bd_id=cls.single_tunnel_bd)

            # Setup vni 2 to test multicast flooding
            cls.mcast_flood_bd = 2
            cls.create_vxlan_flood_test_bd(cls.mcast_flood_bd)
            r = cls.vapi.vxlan_add_del_tunnel(src_addr=cls.pg0.local_ip4n,
                                              dst_addr=cls.mcast_ip4n,
                                              mcast_sw_if_index=1,
                                              vni=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index,
                                                bd_id=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(cls.pg2.sw_if_index,
                                                bd_id=cls.mcast_flood_bd)

            # Add and delete mcast tunnels to check stability
            cls.add_mcast_load()
            cls.del_mcast_load()

            # Setup vni 3 to test unicast flooding
            cls.ucast_flood_bd = 3
            cls.create_vxlan_flood_test_bd(cls.ucast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(cls.pg3.sw_if_index,
                                                bd_id=cls.ucast_flood_bd)
        except Exception:
            super(TestVxlan, cls).tearDownClass()
            raise
Example #17
0
def _read_routes_post2008():
    routes = []
    if_index = '(\d+)'
    dest = '(\d+\.\d+\.\d+\.\d+)/(\d+)'
    next_hop = '(\d+\.\d+\.\d+\.\d+)'
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([if_index, dest, next_hop, metric_pattern])
    pattern = re.compile(netstat_line)
    # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed
    ps = sp.Popen([
        conf.prog.powershell, 'Get-NetRoute', '-AddressFamily IPV4', '|',
        'select ifIndex, DestinationPrefix, NextHop, RouteMetric'
    ],
                  stdout=sp.PIPE,
                  universal_newlines=True)
    stdout, stdin = ps.communicate()
    for l in stdout.split('\n'):
        match = re.search(pattern, l)
        if match:
            try:
                iface = dev_from_index(match.group(1))
                if iface.ip == "0.0.0.0":
                    continue
            except:
                continue
            # try:
            #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            # except OSError:
            #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
            #     continue
            routes.append((atol(match.group(2)), itom(int(match.group(3))),
                           match.group(4), iface, iface.ip))
    return routes
Example #18
0
 def ifadd(self, iff, addr):
     self.invalidate_cache()
     the_addr,the_msk = (addr.split("/")+["32"])[:2]
     the_msk = itom(int(the_msk))
     the_rawaddr = atol(the_addr)
     the_net = the_rawaddr & the_msk
     self.routes.append((the_net,the_msk,'0.0.0.0',iff,the_addr))
Example #19
0
 def ifadd(self, iff, addr):
     self.invalidate_cache()
     the_addr,the_msk = (addr.split("/")+["32"])[:2]
     the_msk = itom(int(the_msk))
     the_rawaddr = atol(the_addr)
     the_net = the_rawaddr & the_msk
     self.routes.append((the_net,the_msk,'0.0.0.0',iff,the_addr))
Example #20
0
def _read_routes_post2008():
    routes = []
    if4_metrics = None
    # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed
    # Get-NetRoute -AddressFamily IPV4 | select ifIndex, DestinationPrefix, NextHop, RouteMetric, InterfaceMetric | fl
    for line in exec_query(['Get-NetRoute', '-AddressFamily IPV4'], ['ifIndex', 'DestinationPrefix', 'NextHop', 'RouteMetric', 'InterfaceMetric']):
        try:
            iface = dev_from_index(line[0])
            if iface.ip == "0.0.0.0":
                continue
        except:
            continue
        # try:
        #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
        # except OSError:
        #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s", dest)
        #     continue
        dest, mask = line[1].split('/')
        ip = "127.0.0.1" if line[0] == "1" else iface.ip # Force loopback on iface 1
        if not line[4].strip():  # InterfaceMetric is not available. Load it from netsh
            if not if4_metrics:
                 if4_metrics = _get_metrics()
            metric = int(line[3]) + if4_metrics.get(iface.win_index, 0)  # RouteMetric + InterfaceMetric
        else:
            metric = int(line[3]) + int(line[4])  # RouteMetric + InterfaceMetric
        routes.append((atol(dest), itom(int(mask)),
                       line[2], iface, ip, metric))
    return routes
Example #21
0
def read_routes():
    routes = []
    if_index = '(\d+)'
    dest = '(\d+\.\d+\.\d+\.\d+)/(\d+)'
    next_hop = '(\d+\.\d+\.\d+\.\d+)'
    metric_pattern = "(\d+)"
    delim = "\s+"        # The columns are separated by whitespace
    netstat_line = delim.join([if_index, dest, next_hop, metric_pattern])
    pattern = re.compile(netstat_line)
    ps = sp.Popen(['powershell', 'Get-NetRoute', '-AddressFamily IPV4', '|', 'select ifIndex, DestinationPrefix, NextHop, RouteMetric'], stdout = sp.PIPE, universal_newlines = True)
    stdout, stdin = ps.communicate(timeout = 10)
    for l in stdout.split('\n'):
        match = re.search(pattern,l)
        if match:
            try:
                iface = devname_from_index(int(match.group(1)))
                addr = ifaces[iface].ip
            except:
                continue
            dest = atol(match.group(2))
            mask = itom(int(match.group(3)))
            gw = match.group(4)
            # try:
            #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            # except OSError:
            #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
            #     continue               
            routes.append((dest, mask, gw, iface, addr))
    return routes
Example #22
0
def read_routes_post2008():
    # XXX TODO: FIX THIS XXX
    routes = []
    if_index = '(\d+)'
    dest = '(\d+\.\d+\.\d+\.\d+)/(\d+)'
    next_hop = '(\d+\.\d+\.\d+\.\d+)'
    metric_pattern = "(\d+)"
    delim = "\s+"        # The columns are separated by whitespace
    netstat_line = delim.join([if_index, dest, next_hop, metric_pattern])
    pattern = re.compile(netstat_line)
    # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed
    ps = sp.Popen([conf.prog.powershell, 'Get-NetRoute', '-AddressFamily IPV4', '|', 'select ifIndex, DestinationPrefix, NextHop, RouteMetric'], stdout = sp.PIPE, universal_newlines = True)
    stdout, stdin = ps.communicate()
    for l in stdout.split('\n'):
        match = re.search(pattern,l)
        if match:
            try:
                iface = dev_from_index(match.group(1))
            except:
                continue
            # try:
            #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            # except OSError:
            #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
            #     continue               
            routes.append((atol(match.group(2)), itom(int(match.group(3))),
                           match.group(4), iface, iface.ip))
    return routes
    async def send(self, pkt):
        tx_frame = ArpHdrTransaction()
        tx_frame.eth_dest_mac = int.from_bytes(mac2str(pkt[Ether].dst), 'big')
        tx_frame.eth_src_mac = int.from_bytes(mac2str(pkt[Ether].src), 'big')
        tx_frame.eth_type = pkt[Ether].type
        tx_frame.arp_htype = pkt[ARP].hwtype
        tx_frame.arp_ptype = pkt[ARP].ptype
        tx_frame.arp_hlen = pkt[ARP].hwlen
        tx_frame.arp_plen = pkt[ARP].plen
        tx_frame.arp_oper = pkt[ARP].op
        tx_frame.arp_sha = int.from_bytes(mac2str(pkt[ARP].hwsrc), 'big')
        tx_frame.arp_spa = atol(pkt[ARP].psrc)
        tx_frame.arp_tha = int.from_bytes(mac2str(pkt[ARP].hwdst), 'big')
        tx_frame.arp_tpa = atol(pkt[ARP].pdst)

        await self.source.send(tx_frame)
 def get_if_bcast(self, iff):
     for net, msk, gw, iface, addr in self.routes:
         if (iff == iface and net != 0):
             bcast = atol(addr) | (~msk & 0xffffffff)
             # FIXME: check error in atol()
             return ltoa(bcast)
     warning("No broadcast address found for iface %s\n" % iff)
Example #25
0
 def get_if_bcast(self, iff):
     for net, msk, gw, iface, addr in self.routes:
         if (iff == iface and net != 0L):
             bcast = atol(addr) | (~msk & 0xffffffffL)
             # FIXME: check error in atol()
             return ltoa(bcast)
     warning("No broadcast address found for iface %s\n" % iff)
Example #26
0
def _read_routes_post2008():
    routes = []
    if4_metrics = None
    # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed
    # Get-NetRoute -AddressFamily IPV4 | select ifIndex, DestinationPrefix, NextHop, RouteMetric, InterfaceMetric | fl
    for line in exec_query(['Get-NetRoute', '-AddressFamily IPV4'], ['ifIndex', 'DestinationPrefix', 'NextHop', 'RouteMetric', 'InterfaceMetric']):
        try:
            iface = dev_from_index(line[0])
            if iface.ip == "0.0.0.0":
                continue
        except:
            continue
        # try:
        #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
        # except OSError:
        #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s", dest)
        #     continue
        dest, mask = line[1].split('/')
        ip = "127.0.0.1" if line[0] == "1" else iface.ip # Force loopback on iface 1
        if not line[4].strip():  # InterfaceMetric is not available. Load it from netsh
            if not if4_metrics:
                 if4_metrics = _get_metrics()
            metric = int(line[3]) + if4_metrics.get(iface.win_index, 0)  # RouteMetric + InterfaceMetric
        else:
            metric = int(line[3]) + int(line[4])  # RouteMetric + InterfaceMetric
        routes.append((atol(dest), itom(int(mask)),
                       line[2], iface, ip, metric))
    return routes
 def ifadd(self, iff, addr):
     # type: (str, str) -> None
     self.invalidate_cache()
     the_addr, the_msk_b = (addr.split("/") + ["32"])[:2]
     the_msk = itom(int(the_msk_b))
     the_rawaddr = atol(the_addr)
     the_net = the_rawaddr & the_msk
     self.routes.append((the_net, the_msk, '0.0.0.0', iff, the_addr, 1))
def read_routes():
    ok = 0
    routes = []
    ip = '(\d+\.\d+\.\d+\.\d+)'
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = '(.+)'
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f = os.popen("netstat -rn")
    for l in f.readlines():
        match = re.search(pattern, l)
        if match:
            dest = match.group(1)
            mask = match.group(2)
            gw = match.group(3)
            netif = match.group(4)
            metric = match.group(5)
            try:
                intf = pcapdnet.dnet.intf().get_dst(
                    pcapdnet.dnet.addr(type=2, addrtxt=dest))
            except OSError:
                log_loading.warning(
                    "Building Scapy's routing table: Couldn't get outgoing interface for destination %s"
                    % dest)
                continue
            if not intf.has_key("addr"):
                break
            addr = str(intf["addr"])
            addr = addr.split("/")[0]

            dest = atol(dest)
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search('\d+\.\d+\.\d+\.\d+', gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
            routes.append((dest, mask, gw, str(intf["name"]), addr))
    f.close()
    return routes
Example #29
0
def read_routes():
    ok = 0
    routes = []
    ip = "(\d+\.\d+\.\d+\.\d+)"
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = "(.+)"
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f = os.popen("netstat -rn")
    for l in f.readlines():
        match = re.search(pattern, l)
        if match:
            dest = match.group(1)
            mask = match.group(2)
            gw = match.group(3)
            netif = match.group(4)
            metric = match.group(5)
            try:
                intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            except OSError:
                log_loading.warning(
                    "Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest
                )
                continue
            if not intf.has_key("addr"):
                break
            addr = str(intf["addr"])
            addr = addr.split("/")[0]

            dest = atol(dest)
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search("\d+\.\d+\.\d+\.\d+", gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
            routes.append((dest, mask, gw, str(intf["name"]), addr))
    f.close()
    return routes
Example #30
0
 def parse_options(self, pool=Net("192.168.1.128/25"), network="192.168.1.0/24", gw="192.168.1.1",  # noqa: E501
                   domain="localnet", renewal_time=60, lease_time=1800):
     self.domain = domain
     netw, msk = (network.split("/") + ["32"])[:2]
     msk = itom(int(msk))
     self.netmask = ltoa(msk)
     self.network = ltoa(atol(netw) & msk)
     self.broadcast = ltoa(atol(self.network) | (0xffffffff & ~msk))
     self.gw = gw
     if isinstance(pool, six.string_types):
         pool = Net(pool)
     if isinstance(pool, Iterable):
         pool = [k for k in pool if k not in [gw, self.network, self.broadcast]]  # noqa: E501
         pool.reverse()
     if len(pool) == 1:
         pool, = pool
     self.pool = pool
     self.lease_time = lease_time
     self.renewal_time = renewal_time
     self.leases = {}
Example #31
0
 def get_if_bcast(self, iff):
     for net, msk, gw, iface, addr, metric in self.routes:
         if net == 0:
             continue
         if scapy.consts.WINDOWS:
             if iff.guid != iface.guid:
                 continue
         elif iff != iface:
             continue
         bcast = atol(addr) | (~msk & 0xffffffff)  # FIXME: check error in atol()  # noqa: E501
         return ltoa(bcast)
     warning("No broadcast address found for iface %s\n", iff)
Example #32
0
 def get_if_bcast(self, iff):
     for net, msk, gw, iface, addr in self.routes:
         if net == 0:
             continue
         if WINDOWS:
             if iff.guid != iface.guid:
                 continue
         elif iff != iface:
             continue
         bcast = atol(addr)|(~msk&0xffffffffL); # FIXME: check error in atol()
         return ltoa(bcast)
     warning("No broadcast address found for iface %s\n" % iff);
Example #33
0
File: route.py Project: mcpat/scapy
 def get_if_bcast(self, iff):
     for net, msk, gw, iface, addr in self.routes:
         if net == 0:
             continue
         if WINDOWS:
             if iff.guid != iface.guid:
                 continue
         elif iff != iface:
             continue
         bcast = atol(addr)|(~msk&0xffffffff); # FIXME: check error in atol()
         return ltoa(bcast)
     warning("No broadcast address found for iface %s\n" % iff);
Example #34
0
def read_routes_xp():
    # The InterfaceIndex in Win32_IP4RouteTable does not match the
    # InterfaceIndex in Win32_NetworkAdapter under some platforms
    # (namely Windows XP): let's try an IP association
    routes = []
    partial_routes = []
    # map local IP addresses to interfaces
    local_addresses = dict((iface.ip, iface) for iface in IFACES.itervalues())
    iface_indexes = {}
    for line in exec_query(["Get-WmiObject", "Win32_IP4RouteTable"], ["Name", "Mask", "NextHop", "InterfaceIndex"]):
        if line[2] in local_addresses:
            iface = local_addresses[line[2]]
            # This gives us an association InterfaceIndex <-> interface
            iface_indexes[line[3]] = iface
            routes.append((atol(line[0]), atol(line[1]), "0.0.0.0", iface, iface.ip))
        else:
            partial_routes.append((atol(line[0]), atol(line[1]), line[2], line[3]))
    for dst, mask, gw, ifidx in partial_routes:
        if ifidx in iface_indexes:
            iface = iface_indexes[ifidx]
            routes.append((dst, mask, gw, iface, iface.ip))
    return routes
Example #35
0
    def route(self, dest, verbose=None):
        if isinstance(dest, list) and dest:
            dest = dest[0]
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose = conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*", "0")
        while True:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:] + ".").find(".")
            dst = dst[:l] + dst[l + m:]

        dst = atol(dst)
        pathes = []
        for d, m, gw, i, a in self.routes:
            if not a:  # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == dst:
                pathes.append((0xffffffff, (scapy.consts.LOOPBACK_INTERFACE, a,
                                            "0.0.0.0")))
            if (dst & m) == (d & m):
                pathes.append((m, (i, a, gw)))
        if not pathes:
            if verbose:
                warning("No route found (no default route?)")
            return scapy.consts.LOOPBACK_INTERFACE, "0.0.0.0", "0.0.0.0"
        # Choose the more specific route (greatest netmask).
        # XXX: we don't care about metrics
        pathes.sort(key=lambda x: x[0])
        ret = pathes[-1][1]
        self.cache[dest] = ret
        return ret
Example #36
0
File: route.py Project: mcpat/scapy
    def route(self,dest,verbose=None):
        if isinstance(dest, list) and dest:
            dest = dest[0]
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose=conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*","0") 
        while True:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:]+".").find(".")
            dst = dst[:l]+dst[l+m:]

            
        dst = atol(dst)
        pathes=[]
        for d,m,gw,i,a in self.routes:
            if not a: # some interfaces may not currently be connected
                continue
            aa = atol(a)
            if aa == dst:
                pathes.append((0xffffffff,(LOOPBACK_INTERFACE,a,"0.0.0.0")))
            if (dst & m) == (d & m):
                pathes.append((m,(i,a,gw)))
        if not pathes:
            if verbose:
                warning("No route found (no default route?)")
            return LOOPBACK_INTERFACE,"0.0.0.0","0.0.0.0"
        # Choose the more specific route (greatest netmask).
        # XXX: we don't care about metrics
        pathes.sort()
        ret = pathes[-1][1]
        self.cache[dest] = ret
        return ret
Example #37
0
    def route(self,dest,verbose=None):
        if type(dest) is list and dest:
            dest = dest[0]
        if dest in self.cache:
            return self.cache[dest]
        if verbose is None:
            verbose=conf.verb
        # Transform "192.168.*.1-5" to one IP of the set
        dst = dest.split("/")[0]
        dst = dst.replace("*","0") 
        while True:
            l = dst.find("-")
            if l < 0:
                break
            m = (dst[l:]+".").find(".")
            dst = dst[:l]+dst[l+m:]

            
        dst = atol(dst)
        pathes=[]
        for d,m,gw,i,a in self.routes:
            aa = atol(a)
            #Commented out after issue with virtual network with local address 0.0.0.0
            #if aa == dst:
            #    pathes.append((0xffffffff,(LOOPBACK_NAME,a,"0.0.0.0")))
            if (dst & m) == (d & m):
                pathes.append((m,(i,a,gw)))
        if not pathes:
            if verbose:
                warning("No route found (no default route?)")
            return LOOPBACK_NAME,"0.0.0.0","0.0.0.0" #XXX linux specific!
        # Choose the more specific route (greatest netmask).
        # XXX: we don't care about metrics
        pathes.sort()
        ret = pathes[-1][1]
        self.cache[dest] = ret
        return ret
    def ifchange(self, iff, addr):
        self.invalidate_cache()
        the_addr, the_msk = (addr.split("/") + ["32"])[:2]
        the_msk = itom(int(the_msk))
        the_rawaddr = atol(the_addr)
        the_net = the_rawaddr & the_msk

        for i in range(len(self.routes)):
            net, msk, gw, iface, addr = self.routes[i]
            if iface != iff:
                continue
            if gw == '0.0.0.0':
                self.routes[i] = (the_net, the_msk, gw, iface, the_addr)
            else:
                self.routes[i] = (net, msk, gw, iface, the_addr)
        conf.netcache.flush()
Example #39
0
    def ifchange(self, iff, addr):
        self.invalidate_cache()
        the_addr, the_msk = (addr.split("/") + ["32"])[:2]
        the_msk = itom(int(the_msk))
        the_rawaddr = atol(the_addr)
        the_net = the_rawaddr & the_msk

        for i, route in enumerate(self.routes):
            net, msk, gw, iface, addr = route
            if iface != iff:
                continue
            if gw == '0.0.0.0':
                self.routes[i] = (the_net, the_msk, gw, iface, the_addr)
            else:
                self.routes[i] = (net, msk, gw, iface, the_addr)
        conf.netcache.flush()
    def ifchange(self, iff, addr):
        # type: (str, str) -> None
        self.invalidate_cache()
        the_addr, the_msk_b = (addr.split("/") + ["32"])[:2]
        the_msk = itom(int(the_msk_b))
        the_rawaddr = atol(the_addr)
        the_net = the_rawaddr & the_msk

        for i, route in enumerate(self.routes):
            net, msk, gw, iface, addr, metric = route
            if iff != iface:
                continue
            if gw == '0.0.0.0':
                self.routes[i] = (the_net, the_msk, gw, iface, the_addr, metric)  # noqa: E501
            else:
                self.routes[i] = (net, msk, gw, iface, the_addr, metric)
        conf.netcache.flush()
Example #41
0
def _read_routes_c(ipv6=False):
    """Retrieve Windows routes through a GetIpForwardTable2 call.

    This is not available on Windows XP !"""
    af = socket.AF_INET6 if ipv6 else socket.AF_INET
    sock_addr_name = 'Ipv6' if ipv6 else 'Ipv4'
    sin_addr_name = 'sin6_addr' if ipv6 else 'sin_addr'
    metric_name = 'ipv6_metric' if ipv6 else 'ipv4_metric'
    ip_len = 16 if ipv6 else 4
    if ipv6:
        lifaddr = in6_getifaddr()
    routes = []

    def _extract_ip_netmask(obj):
        ip = obj[sock_addr_name][sin_addr_name]
        ip = bytes(bytearray(ip['byte']))
        # Extract netmask
        netmask = (ip_len - (len(ip) - len(ip.rstrip(b"\x00")))) * 8
        # Build IP
        ip = inet_ntop(af, ip)
        return ip, netmask

    for route in GetIpForwardTable2(af):
        # Extract data
        ifIndex = route['InterfaceIndex']
        _dest = route['DestinationPrefix']
        dest, netmask = _extract_ip_netmask(_dest['Prefix'])
        nexthop, _ = _extract_ip_netmask(route['NextHop'])
        metric = route['Metric']
        # Build route
        try:
            iface = dev_from_index(ifIndex)
            if iface.ip == "0.0.0.0":
                continue
        except ValueError:
            continue
        ip = iface.ip
        # RouteMetric + InterfaceMetric
        metric = metric + getattr(iface, metric_name)
        if ipv6:
            _append_route6(routes, dest, netmask, nexthop, iface, lifaddr,
                           metric)
        else:
            routes.append(
                (atol(dest), itom(int(netmask)), nexthop, iface, ip, metric))
    return routes
Example #42
0
    def ifchange(self, iff, addr):
        self.invalidate_cache()
        the_addr, the_msk = (addr.split("/") + ["32"])[:2]
        the_msk = itom(int(the_msk))
        the_rawaddr = atol(the_addr)
        the_net = the_rawaddr & the_msk

        for i, route in enumerate(self.routes):
            net, msk, gw, iface, addr, metric = route
            if scapy.consts.WINDOWS:
                if iff.guid != iface.guid:
                    continue
            elif iff != iface:
                continue
            if gw == '0.0.0.0':
                self.routes[i] = (the_net, the_msk, gw, iface, the_addr, metric)  # noqa: E501
            else:
                self.routes[i] = (net, msk, gw, iface, the_addr, metric)
        conf.netcache.flush()
 def make_route(self, host=None, net=None, gw=None, dev=None):
     if host is not None:
         thenet,msk = host,32
     elif net is not None:
         thenet,msk = net.split("/")
         msk = int(msk)
     else:
         raise Scapy_Exception("make_route: Incorrect parameters. You should specify a host or a net")
     if gw is None:
         gw="0.0.0.0"
     if dev is None:
         if gw:
             nhop = gw
         else:
             nhop = thenet
         dev,ifaddr,x = self.route(nhop)
     else:
         ifaddr = get_if_addr(dev)
     return (atol(thenet), itom(msk), gw, dev, ifaddr)
Example #44
0
def read_routes():
    routes = []
    if_index = '(\d+)'
    dest = '(\d+\.\d+\.\d+\.\d+)'
    mask = '(\d+\.\d+\.\d+\.\d+)'
    next_hop = '(\d+\.\d+\.\d+\.\d+)'
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([if_index, dest, mask, next_hop, metric_pattern])
    pattern = re.compile(netstat_line)
    # This way works on Windows 7+ (probably as well on older Windows systems). Note the | ft in the end to keep table
    # format, as powershell will change from table to line based format when it has to print more than 4 columns
    ps = sp.Popen([
        'powershell', 'Get-WMIObject', 'Win32_IP4RouteTable', '|',
        'select InterfaceIndex, Destination, Mask, NextHop, Metric1', '|', 'ft'
    ],
                  stdout=sp.PIPE,
                  universal_newlines=True)
    stdout, stdin = ps.communicate(timeout=10)
    for l in stdout.split('\n'):
        match = re.search(pattern, l)
        if match:
            try:
                iface = devname_from_index(int(match.group(1)))
                addr = ifaces[iface].ip
            except:
                continue
            dest = atol(match.group(2))
            mask = itom(
                sum([
                    len(bin(int(a)).replace("0", "")) - 1
                    for a in match.group(3).split(".")
                ]))
            gw = match.group(4)
            # try:
            #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            # except OSError:
            #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
            #     continue
            routes.append((dest, mask, gw, iface, addr))
    return routes
Example #45
0
def _read_routes_post2008():
    routes = []
    # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed
    # Get-NetRoute -AddressFamily IPV4 | select ifIndex, DestinationPrefix, NextHop, RouteMetric, InterfaceMetric | fl
    for line in exec_query(['Get-NetRoute', '-AddressFamily IPV4'], [
            'ifIndex', 'DestinationPrefix', 'NextHop', 'RouteMetric',
            'InterfaceMetric'
    ]):
        try:
            iface = dev_from_index(line[0])
            if iface.ip == "0.0.0.0":
                continue
        except:
            continue
        # try:
        #     intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
        # except OSError:
        #     log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s", dest)
        #     continue
        dest, mask = line[1].split('/')
        routes.append((atol(dest), itom(int(mask)), line[2], iface, iface.ip,
                       int(line[3]) + int(line[4])))
    return routes
Example #46
0
def isValidMCAddr(ip):
    """convert dotted quad string to long and check the first octet"""
    FirstOct = atol(ip) >> 24 & 0xFF
    return (FirstOct >= 224) and (FirstOct <= 239)
Example #47
0
async def run_test(dut, idle_inserter=None, backpressure_inserter=None):

    tb = TB(dut)

    await tb.reset()

    tb.set_idle_generator(idle_inserter)
    tb.set_backpressure_generator(backpressure_inserter)

    local_mac = 'DA:D1:D2:D3:D4:D5'
    local_ip = '192.168.1.101'
    gateway_ip = '192.168.1.1'
    subnet_mask = '255.255.255.0'

    dut.local_mac <= int.from_bytes(mac2str(local_mac), 'big')
    dut.local_ip <= atol(local_ip)
    dut.gateway_ip <= atol(gateway_ip)
    dut.subnet_mask <= atol(subnet_mask)

    for k in range(10):
        await RisingEdge(dut.clk)

    tb.log.info("test ARP request")

    eth = Ether(src='5A:51:52:53:54:55', dst='FF:FF:FF:FF:FF:FF')
    arp = ARP(hwtype=1,
              ptype=0x0800,
              hwlen=6,
              plen=4,
              op=1,
              hwsrc='5A:51:52:53:54:55',
              psrc='192.168.1.100',
              hwdst='00:00:00:00:00:00',
              pdst='192.168.1.101')
    test_pkt = eth / arp

    await tb.send(test_pkt)

    rx_pkt = await tb.recv()

    tb.log.info("RX packet: %s", repr(rx_pkt))

    assert rx_pkt[Ether].dst.casefold() == test_pkt[Ether].src.casefold()
    assert rx_pkt[Ether].src.casefold() == local_mac.casefold()
    assert rx_pkt[Ether].type == test_pkt[Ether].type
    assert rx_pkt[ARP].hwtype == test_pkt[Ether].hwtype
    assert rx_pkt[ARP].ptype == test_pkt[Ether].ptype
    assert rx_pkt[ARP].hwlen == test_pkt[Ether].hwlen
    assert rx_pkt[ARP].plen == test_pkt[Ether].plen
    assert rx_pkt[ARP].op == 2
    assert rx_pkt[ARP].hwsrc.casefold() == local_mac.casefold()
    assert rx_pkt[ARP].psrc == local_ip
    assert rx_pkt[ARP].hwdst.casefold() == test_pkt[ARP].hwsrc.casefold()
    assert rx_pkt[ARP].pdst == test_pkt[ARP].psrc

    tb.log.info("Cached read")

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('192.168.1.100')))

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert not resp.error
    assert resp.mac == int.from_bytes(mac2str(test_pkt[Ether].src), 'big')

    tb.log.info("Uncached read, inside subnet")

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('192.168.1.102')))

    # wait for ARP request
    rx_pkt = await tb.recv()

    tb.log.info("RX packet: %s", repr(rx_pkt))

    assert rx_pkt[Ether].dst.casefold() == "ff:ff:ff:ff:ff:ff".casefold()
    assert rx_pkt[Ether].src.casefold() == local_mac.casefold()
    assert rx_pkt[Ether].type == 0x0806
    assert rx_pkt[ARP].hwtype == 0x0001
    assert rx_pkt[ARP].ptype == 0x0800
    assert rx_pkt[ARP].hwlen == 6
    assert rx_pkt[ARP].plen == 4
    assert rx_pkt[ARP].op == 1
    assert rx_pkt[ARP].hwsrc.casefold() == local_mac.casefold()
    assert rx_pkt[ARP].psrc == local_ip
    assert rx_pkt[ARP].hwdst.casefold() == "00:00:00:00:00:00".casefold()
    assert rx_pkt[ARP].pdst == '192.168.1.102'

    # generate response
    eth = Ether(src='6A:61:62:63:64:65', dst=local_mac)
    arp = ARP(hwtype=1,
              ptype=0x0800,
              hwlen=6,
              plen=4,
              op=2,
              hwsrc='6A:61:62:63:64:65',
              psrc='192.168.1.102',
              hwdst=local_mac,
              pdst=local_ip)
    test_pkt = eth / arp

    await tb.send(test_pkt)

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert not resp.error
    assert resp.mac == int.from_bytes(mac2str(test_pkt[Ether].src), 'big')

    tb.log.info("Uncached read, outside of subnet")

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('8.8.8.8')))

    # wait for ARP request
    rx_pkt = await tb.recv()

    tb.log.info("RX packet: %s", repr(rx_pkt))

    assert rx_pkt[Ether].dst.casefold() == "ff:ff:ff:ff:ff:ff".casefold()
    assert rx_pkt[Ether].src.casefold() == local_mac.casefold()
    assert rx_pkt[Ether].type == 0x0806
    assert rx_pkt[ARP].hwtype == 0x0001
    assert rx_pkt[ARP].ptype == 0x0800
    assert rx_pkt[ARP].hwlen == 6
    assert rx_pkt[ARP].plen == 4
    assert rx_pkt[ARP].op == 1
    assert rx_pkt[ARP].hwsrc.casefold() == local_mac.casefold()
    assert rx_pkt[ARP].psrc == local_ip
    assert rx_pkt[ARP].hwdst.casefold() == "00:00:00:00:00:00".casefold()
    assert rx_pkt[ARP].pdst == gateway_ip

    # generate response
    eth = Ether(src='AA:BB:CC:DD:EE:FF', dst=local_mac)
    arp = ARP(hwtype=1,
              ptype=0x0800,
              hwlen=6,
              plen=4,
              op=2,
              hwsrc='AA:BB:CC:DD:EE:FF',
              psrc='192.168.1.1',
              hwdst=local_mac,
              pdst=local_ip)
    test_pkt = eth / arp

    await tb.send(test_pkt)

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert not resp.error
    assert resp.mac == int.from_bytes(mac2str(test_pkt[Ether].src), 'big')

    tb.log.info("Uncached read, timeout")

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('192.168.1.103')))

    # wait for ARP request
    for k in range(4):
        rx_pkt = await tb.recv()

        tb.log.info("RX packet: %s", repr(rx_pkt))

        assert rx_pkt[Ether].dst.casefold() == "ff:ff:ff:ff:ff:ff".casefold()
        assert rx_pkt[Ether].src.casefold() == local_mac.casefold()
        assert rx_pkt[Ether].type == 0x0806
        assert rx_pkt[ARP].hwtype == 0x0001
        assert rx_pkt[ARP].ptype == 0x0800
        assert rx_pkt[ARP].hwlen == 6
        assert rx_pkt[ARP].plen == 4
        assert rx_pkt[ARP].op == 1
        assert rx_pkt[ARP].hwsrc.casefold() == local_mac.casefold()
        assert rx_pkt[ARP].psrc == local_ip
        assert rx_pkt[ARP].hwdst.casefold() == "00:00:00:00:00:00".casefold()
        assert rx_pkt[ARP].pdst == '192.168.1.103'

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert resp.error

    tb.log.info("Broadcast")

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('192.168.1.255')))

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert not resp.error
    assert resp.mac == int.from_bytes(mac2str('FF:FF:FF:FF:FF:FF'), 'big')

    await tb.arp_req_source.send(ArpReqTransaction(ip=atol('255.255.255.255')))

    resp = await tb.arp_resp_sink.recv()

    tb.log.info("Read value: %s", resp)

    assert not resp.error
    assert resp.mac == int.from_bytes(mac2str('FF:FF:FF:FF:FF:FF'), 'big')

    assert tb.header_sink.empty()
    assert tb.payload_sink.empty()

    await RisingEdge(dut.clk)
    await RisingEdge(dut.clk)
Example #48
0
def read_routes():
    ifaces.load_from_dnet()
    
    zmap = {}
    for i in ifaces:
        for ip in ifaces.get(i).ip_list:
            zmap[ip] = i
    

    ok = 0
    routes = []
    ip = '(\d+\.\d+\.\d+\.\d+)'
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = '(.+)'
    metric_pattern = "(\d+)"
    delim = "\s+"        # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f=os.popen("netstat -rn")
    
    import platform
    is_win7 =  not platform.platform().lower().startswith('windows-xp')
    
    for l in f.readlines():
        #l = l.encode('utf-8')
       
        
        if is_win7:
            str1 = u'永久路由'.encode('gbk')
            if l.find( str1 )!=-1 or l.find('permanant route')!=-1 \
                or l.find('Persistent Routes') !=-1 :
                # Igore the permanant route on Vista and Win7                
                break
        
        match = re.search(pattern,l)
        if match:
            dest2   = match.group(1)
            mask   = match.group(2)
            gw     = match.group(3)
            netif  = match.group(4)
            metric = match.group(5)
           
            dest = atol(dest2)
            if dest >= I_MULTIIP_START and dest <= I_MULTIIP_END:
                # multiple ip address
                
                ifname = zmap.get(netif, 'lo0')
                addr = netif
                
            else:
            
                try:
                    # If addrtxt is multicast IP, it will not function well
                    intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest2))
                except OSError:
                    log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
                    continue               
                if not intf.has_key("addr"):
                    break
                addr = str(intf["addr"])
                addr = addr.split("/")[0]
                
                
                ifname = str(intf["name"])
                
                
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search('\d+\.\d+\.\d+\.\d+', gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
                
                
            #routes.append((dest,mask,gw, str(intf["name"]), addr))
            # when a interface has multi IPs, addr may not be the correct OutIP
            # So I extract the correct IP from ifaces 
            #                                      by  chenzongze 2012.07.24                
            output_ip = netif
            for ifs in ifaces:
                if addr in ifaces[ifs].ip_list:
                
                    for my_ip in ifaces[ifs].ip_list:
                        if ( atol(my_ip) & mask) == ( atol(gw) & mask ) and (mask !=0):
                            output_ip = my_ip
                            break
                    
                    break
            

            
            
            # Add metric        by chenzongze 2012.07.24
            routes.append((dest,mask,gw, ifname, output_ip, metric))
            
            
            
            
            
    f.close()
    return routes
Example #49
0
 def is_valid_mcaddr(ip):
     byte1 = atol(ip) >> 24 & 0xff
     return (byte1 & 0xf0) == 0xe0
Example #50
0
def devname(pcap_name):
    """Return libdnet/Scapy device name for given pypcap device name"""
    return ifaces.devname(pcap_name)
    
def show_interfaces(resolve_mac=True):
    """Print list of available network interfaces"""
    return ifaces.show(resolve_mac)

_orig_open_pcap = pcapdnet.open_pcap
pcapdnet.open_pcap = lambda iface,*args,**kargs: _orig_open_pcap(pcap_name(iface),*args,**kargs)


MULTIIP_START = '224.0.0.0'
MULTIIP_END = '239.255.255.255'
I_MULTIIP_START = atol(MULTIIP_START)
I_MULTIIP_END = atol(MULTIIP_END)
def read_routes():
    ifaces.load_from_dnet()
    
    zmap = {}
    for i in ifaces:
        for ip in ifaces.get(i).ip_list:
            zmap[ip] = i
    

    ok = 0
    routes = []
    ip = '(\d+\.\d+\.\d+\.\d+)'
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
Example #51
0
    def setUpClass(cls):
        super(TestGtpu, cls).setUpClass()

        try:
            cls.dport = 2152
            cls.gtp_type = 0xff

            # Create 2 pg interfaces.
            cls.create_pg_interfaces(range(4))
            for pg in cls.pg_interfaces:
                pg.admin_up()

            # Configure IPv4 addresses on VPP pg0.
            cls.pg0.config_ip4()

            # Resolve MAC address for VPP's IP address on pg0.
            cls.pg0.resolve_arp()

            # Our Multicast address
            cls.mcast_ip4 = '239.1.1.1'
            cls.mcast_ip4n = socket.inet_pton(socket.AF_INET, cls.mcast_ip4)
            iplong = atol(cls.mcast_ip4)
            cls.mcast_mac = "01:00:5e:%02x:%02x:%02x" % (
                (iplong >> 16) & 0x7F, (iplong >> 8) & 0xFF, iplong & 0xFF)

            # Create GTPU VTEP on VPP pg0, and put gtpu_tunnel0 and pg1
            #  into BD.
            cls.single_tunnel_bd = 11
            r = cls.vapi.gtpu_add_del_tunnel(src_addr=cls.pg0.local_ip4n,
                                             dst_addr=cls.pg0.remote_ip4n,
                                             teid=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
                                                bd_id=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd)

            # Setup teid 2 to test multicast flooding
            cls.n_ucast_tunnels = 10
            cls.mcast_flood_bd = 12
            cls.create_gtpu_flood_test_bd(cls.mcast_flood_bd,
                                          cls.n_ucast_tunnels)
            r = cls.vapi.gtpu_add_del_tunnel(src_addr=cls.pg0.local_ip4n,
                                             dst_addr=cls.mcast_ip4n,
                                             mcast_sw_if_index=1,
                                             teid=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
                                                bd_id=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd)

            # Add and delete mcast tunnels to check stability
            cls.add_shared_mcast_dst_load()
            cls.add_mcast_tunnels_load()
            cls.del_shared_mcast_dst_load()
            cls.del_mcast_tunnels_load()

            # Setup teid 3 to test unicast flooding
            cls.ucast_flood_bd = 13
            cls.create_gtpu_flood_test_bd(cls.ucast_flood_bd,
                                          cls.n_ucast_tunnels)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd)
        except Exception:
            super(TestGtpu, cls).tearDownClass()
            raise
Example #52
0
    def setUpClass(cls):
        super(TestVxlan, cls).setUpClass()

        try:
            cls.dport = 4789
            cls.flags = 0x8

            # Create 2 pg interfaces.
            cls.create_pg_interfaces(range(4))
            for pg in cls.pg_interfaces:
                pg.admin_up()

            # Configure IPv4 addresses on VPP pg0.
            cls.pg0.config_ip4()

            # Resolve MAC address for VPP's IP address on pg0.
            cls.pg0.resolve_arp()

            # Our Multicast address
            cls.mcast_ip4 = '239.1.1.1'
            cls.mcast_ip4n = socket.inet_pton(socket.AF_INET, cls.mcast_ip4)
            iplong = atol(cls.mcast_ip4)
            cls.mcast_mac = "01:00:5e:%02x:%02x:%02x" % (
                (iplong >> 16) & 0x7F, (iplong >> 8) & 0xFF, iplong & 0xFF)

            # Create VXLAN VTEP on VPP pg0, and put vxlan_tunnel0 and pg1
            #  into BD.
            cls.single_tunnel_bd = 1
            r = cls.vapi.vxlan_add_del_tunnel(src_address=cls.pg0.local_ip4n,
                                              dst_address=cls.pg0.remote_ip4n,
                                              vni=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
                                                bd_id=cls.single_tunnel_bd)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd)

            # Setup vni 2 to test multicast flooding
            cls.n_ucast_tunnels = 10
            cls.mcast_flood_bd = 2
            cls.create_vxlan_flood_test_bd(cls.mcast_flood_bd,
                                           cls.n_ucast_tunnels)
            r = cls.vapi.vxlan_add_del_tunnel(src_address=cls.pg0.local_ip4n,
                                              dst_address=cls.mcast_ip4n,
                                              mcast_sw_if_index=1,
                                              vni=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
                                                bd_id=cls.mcast_flood_bd)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd)

            # Add and delete mcast tunnels to check stability
            cls.add_shared_mcast_dst_load()
            cls.add_mcast_tunnels_load()
            cls.del_shared_mcast_dst_load()
            cls.del_mcast_tunnels_load()

            # Setup vni 3 to test unicast flooding
            cls.ucast_flood_bd = 3
            cls.create_vxlan_flood_test_bd(cls.ucast_flood_bd,
                                           cls.n_ucast_tunnels)
            cls.vapi.sw_interface_set_l2_bridge(
                rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd)
        except Exception:
            super(TestVxlan, cls).tearDownClass()
            raise