Python scapy.all.TCP Examples

The following are 30 code examples of scapy.all.TCP(). 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: 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 #2
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 #3
Source File: test_pcap.py    From beagle with MIT License 7 votes vote down vote up
def test_single_http_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=12345, dport=80)
        / HTTP()
        / HTTPRequest(Method="GET", Path="/foo", Host="https://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"] == 12345
    assert events[0]["dport"] == 80
    assert events[0]["http_method"] == "GET"
    assert events[0]["uri"] == "/foo"
    assert events[0]["http_dest"] == "https://google.com"

    assert events[0]["event_type"] == "HTTPRequest" 
Example #4
Source File: metric.py    From transperf with Apache License 2.0 6 votes vote down vote up
def visit_packet(self, time, packet):
        if (IP not in packet and IPv6 not in packet) or TCP not in packet:
            return

        iph = packet[IP] if IP in packet else packet[IPv6]
        tcph = packet[TCP]

        if iph.src == self._rcv_ip:
            return

        port = tcph.sport
        if port not in self._packet_size:
            return

        # TODO(arjunroy) IPv4 = total len, IPv6 = payload len. Is it important?
        packet_len = packet.len if IP in packet else packet.plen
        sizes = self._packet_size[port]
        if packet_len in sizes:
            sizes[packet_len] += 1
        else:
            sizes[packet_len] = 1 
Example #5
Source File: packet_processor.py    From iot-inspector-client with MIT License 6 votes vote down vote up
def _process_http_host(self, pkt, device_id, remote_ip):

        try:
            http_host = pkt[http.HTTPRequest].fields['Host'].decode('utf-8')
        except Exception as e:
            return
        
        device_port = pkt[sc.TCP].sport

        with self._host_state.lock:
            self._host_state \
                .pending_dns_dict \
                .setdefault(
                    (device_id, http_host, 'http-host', device_port), set()) \
                .add(remote_ip)

        utils.log('[UPLOAD] HTTP host:', http_host) 
Example #6
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 #7
Source File: cotopaxi_tester.py    From cotopaxi with GNU General Public License v2.0 6 votes vote down vote up
def sr1_file(test_params, test_filename, display_packet=False):
    """Read test message from given file, sends this message to server and parses response."""
    with open(test_filename, "rb") as file_handle:
        test_packet = file_handle.read()
    if display_packet:
        # print("Protocol: {}".format(proto_mapping(test_params.protocol)))
        try:
            if test_params.protocol in PROTOCOL_TESTERS:
                out_packet = PROTOCOL_TESTERS[test_params.protocol].request_parser(
                    test_packet
                )
            out_packet.show()
            print_verbose(test_params, 60 * "-")
        except (TypeError, struct.error, RuntimeError, ValueError, Scapy_Exception):
            pass
    test_result = None
    if test_params.protocol in [Protocol.SSDP]:
        test_result = ssdp_send_query(test_params, test_packet)
    elif test_params.protocol in protocols_using(UDP):
        test_result = udp_sr1(test_params, test_packet)
    elif test_params.protocol in protocols_using(TCP):
        test_result = tcp_sr1(test_params, test_packet)
    return test_result 
Example #8
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 #9
Source File: common_utils.py    From cotopaxi with GNU General Public License v2.0 6 votes vote down vote up
def proto_mapping_request(protocol):
    """Provide mapping of enum values to implementation classes."""
    return {
        Protocol.ALL: IP,
        Protocol.UDP: UDP,
        Protocol.TCP: TCP,
        Protocol.CoAP: CoAP,
        Protocol.mDNS: DNS,
        Protocol.MQTT: MQTT,
        Protocol.DTLS: DTLS,
        Protocol.QUIC: UDP,
        Protocol.RTSP: HTTPRequest,
        Protocol.SSDP: HTTPRequest,
        Protocol.HTCPCP: HTTPRequest,
        Protocol.HTTP: HTTPRequest,
    }[protocol] 
Example #10
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 #11
Source File: ebcLib.py    From SMBetray with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, client_ip = "", server_ip = "", client_port = 0, server_port = 0, protocol = "TCP", interface = ""):
		self.client_ip 		= client_ip
		self.server_ip 		= server_ip
		self.client_port 	= client_port
		self.server_port 	= server_port
		self.protocol 		= protocol.lower()
		self.interface 		= interface

	# This returns just the source address & port in a string format
	# so that it can be hashed and tied back to the connectionManager.
	# The protocol, source address, and port are the only shared pieces of information
	# that both the MiTMModule socket and nfqueue intercept have access to, so
	# nfqueue hashes this info together and uses that hash as the key in the 
	# connectionMnaager. Once the MiTMModule recieves the intercepted connection,
	# it will hash the proto/source ip/port to pull back the whole Connection
	# object from the connectionManager - and thus - have the destination ip and port
	# to then behave like a fully transparent TCP/UDP MiTM server. 
Example #12
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 #13
Source File: send_tcp_packets.py    From raw-packet with MIT License 6 votes vote down vote up
def get_syn_and_ack_numbers(request):
    global src_ip_address
    global response_sequence_number
    global response_acknowledgement_number
    global response_timestamp
    global response_payload_len

    if request.haslayer(TCP):
        response_sequence_number = request[TCP].seq
        response_acknowledgement_number = request[TCP].ack
        response_timestamp = request[TCP].time
        response_payload_len += len(request[TCP].payload)

        print(Base.c_success + "Response seq: " + str(response_sequence_number) + " ack: " + \)
              str(response_acknowledgement_number) + " timestamp: " + str(response_timestamp) + " len: " + \
              str(len(request[TCP].payload)) 
Example #14
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 #15
Source File: test_cotopaxi_tester.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def test_protocols_using_pos(self):
        udp_protos = protocols_using(UDP)
        self.assertGreaterEqual(len(udp_protos), 4)
        self.assertTrue(Protocol.CoAP in udp_protos)
        self.assertTrue(Protocol.RTSP not in udp_protos)
        for proto in udp_protos:
            self.assertIsInstance(proto, Protocol)
        tcp_protos = protocols_using(TCP)
        self.assertGreaterEqual(len(tcp_protos), 4)
        for proto in tcp_protos:
            self.assertIsInstance(proto, Protocol)
        self.assertTrue(Protocol.RTSP in tcp_protos)
        self.assertTrue(Protocol.CoAP not in tcp_protos) 
Example #16
Source File: carpa.py    From circo with MIT License 5 votes vote down vote up
def pkt_callback(self, pkt):
        """
        Proccess HTTP packets (direct)
        """
        if pkt[IP].id >= 200 and pkt[IP].id < 300:
            self.pktlen = pkt[IP].id - 200
        elif pkt[IP].id >= 300 and pkt[IP].id < 400:
            self.pkttotal = pkt[IP].id - 300
        elif pkt[IP].id >= 500 and pkt[IP].id < 600:
            self.dic[pkt[IP].id - 500] = '{:04x}'.format(pkt[TCP].window)
        elif pkt[IP].id == 666:
            print(time.strftime("%Y-%m-%d %H:%M:%S ", time.gmtime())
                  + 'HTTP:' + pkt[IP].src + ':ALARM Case Open!')

        if len(self.dic) == self.pkttotal:
            odic = collections.OrderedDict(sorted(self.dic.items()))
            final = ''
            for value in odic.iteritems():
                final = final + value[1]
            text = decrypt(final[:self.pktlen])
            text = text.strip()
            hexip = text.split(',')[-1]
            text = text.replace(hexip, hextoip(hexip))
            text = 'HTTP:' + pkt[IP].src + ':' + text
            printer(self.filed, text)
            self.dic = {}
            self.pkttotal = 200 
Example #17
Source File: cotopaxi_tester.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def protocol_enabled(protocol, proto_mask):
    """Check whether protocol is enabled for test using given protocol mask."""
    if proto_mask == Protocol.ALL:
        return True
    if proto_mask == protocol:
        return True
    if proto_mask == Protocol.TCP and protocol in protocols_using(Protocol.TCP):
        return True
    if proto_mask == Protocol.UDP and protocol in protocols_using(Protocol.UDP):
        return True
    return False


# Number of characters in line of separator 
Example #18
Source File: common_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def tcp_sr1(test_params, test_packet):
    """Send test message to server using TCP protocol and parses response."""
    in_data = None
    connect_handler = None
    sent_time = test_params.report_sent_packet()

    sock_ip = {4: socket.AF_INET, 6: socket.AF_INET6}
    connect_args = {
        4: (test_params.dst_endpoint.ip_addr, test_params.dst_endpoint.port),
        6: (test_params.dst_endpoint.ip_addr, test_params.dst_endpoint.port, 0, 0),
    }
    try:
        connect_handler = socket.socket(
            sock_ip[test_params.ip_version], socket.SOCK_STREAM
        )
        connect_handler.settimeout(test_params.timeout_sec)
        connect_handler.connect(connect_args[test_params.ip_version])
        try:
            connect_handler.send(test_packet.encode(encoding="ascii"))
        except (AttributeError, UnicodeDecodeError):
            connect_handler.send(bytes(test_packet))

        in_data = connect_handler.recv(INPUT_BUFFER_SIZE)
        if in_data:
            test_params.report_received_packet(sent_time)
    except (socket.timeout, socket.error) as exc:
        if test_params.verbose:
            print ("TCP exception: {}".format(exc))
    finally:
        if connect_handler is not None:
            connect_handler.close()
    return in_data 
Example #19
Source File: amqp_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def transport_protocol():
        """Provide Scapy class of transport protocol used by this tester (usually TCP or UDP)."""
        return TCP 
Example #20
Source File: htcpcp_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def transport_protocol():
        """Provide Scapy class of transport protocol used by this tester (usually TCP or UDP)."""
        return TCP 
Example #21
Source File: http_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def transport_protocol():
        """Provide Scapy class of transport protocol used by this tester (usually TCP or UDP)."""
        return TCP 
Example #22
Source File: metric.py    From transperf with Apache License 2.0 5 votes vote down vote up
def visit_packet(self, time, packet):
        """Generate statistics for each port.

        See the outparser.Visitor interface.
        """
        if (IP not in packet and IPv6 not in packet) or TCP not in packet:
            return

        iph = packet[IP] if IP in packet else packet[IPv6]
        tcph = packet[TCP]

        if iph.src == self._rcv_ip:
            return

        port = tcph.sport
        if port not in self._stats:
            return

        max_seq = self._max_seq[port]
        if IP in packet:
            data_len = iph.len - 4 * iph.ihl - 4 * tcph.dataofs
        else:
            if iph.nh != 6:
                LOG.info('IPv6 pachet has extension headers, skipping.')
                return
            data_len = iph.plen - 4 * tcph.dataofs
        next_seq = tcp.add_seq(tcph.seq, data_len - 1)
        if max_seq == -1 or tcp.after(tcph.seq, max_seq):
            self._max_seq[port] = next_seq
            is_retx = 0
        else:
            is_retx = 1

        tx, retx = self._stats[port]
        self._stats[port] = (tx + data_len, retx + is_retx * data_len) 
Example #23
Source File: mqtt_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def transport_protocol():
        """Provide Scapy class of transport protocol used by this tester (usually TCP or UDP)."""
        return TCP 
Example #24
Source File: rtsp_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def transport_protocol():
        """Provide Scapy class of transport protocol used by this tester (usually TCP or UDP)."""
        return TCP 
Example #25
Source File: port_scan_scapy.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def main():
    for x in xrange(0, 80):
        analyze_port("domain", x)
    print "[*] Ports openned:"
    for x in OPEN_PORTS:
        print " - %s/TCP" % x 
Example #26
Source File: common_utils.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def get_random_high_port():
    """Return random value for private (ephemeral or high) TCP or UDP port."""
    return random.randint(NET_MIN_HIGH_PORT, NET_MAX_PORT) 
Example #27
Source File: metric.py    From transperf with Apache License 2.0 5 votes vote down vote up
def visit_packet(self, time, packet):
        if (IP not in packet and IPv6 not in packet) or TCP not in packet:
            return

        iph = packet[IP] if IP in packet else packet[IPv6]
        tcph = packet[TCP]
        if iph.src == self._rcv_ip:
            self._handle_rcv(time, tcph)
        else:
            self._handle_snd(time, tcph) 
Example #28
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() 
Example #29
Source File: test_protocol_tester.py    From cotopaxi with GNU General Public License v2.0 5 votes vote down vote up
def test_tester_protocol_pos(self):
        protocol = self.tester.transport_protocol()
        self.assertTrue(protocol in [None, TCP, UDP]) 
Example #30
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)