Python scapy.layers.inet.TCP Examples

The following are 30 code examples of scapy.layers.inet.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.layers.inet , or try the search function .
Example #1
Source File: queso.py    From CyberScan with GNU General Public License v3.0 7 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #2
Source File: mptcp_scanner.py    From mptcp-abuse with GNU General Public License v2.0 6 votes vote down vote up
def makeJoinSyn(sourceAddr,dport,dstAddr, sport=None, initTCPSeq=None, \
                mptcpAddrId=None,isBackupFlow=False, \
                rcvToken=None,sendNonce=None):

    if sport is None: sport = randintb(16)
    if sendNonce is None: sendNonce = randintb(32)
    if initTCPSeq is None: initTCPSeq = randintb(32)
    if rcvToken is None: rcvToken = randintb(32)
    if sendNonce is None: sendNonce = randintb(32)
    if mptcpAddrId is None: mptcpAddrId = randintb(8)
    #TODO: make more elegant type handling for IPADDR
    dstAddr = str(dstAddr)

    pkt = (IP(version=4L,src=sourceAddr,dst=dstAddr)/        \
        TCP(sport=sport,dport=dport,flags="S",seq=initTCPSeq, \
        options=[TCPOption_MP(mptcp=MPTCP_JoinSYN(
                            addr_id=mptcpAddrId,
                            backup_flow=isBackupFlow,
                            rcv_token=rcvToken,
                            snd_nonce=sendNonce,))]))

    return pkt 
Example #3
Source File: queso.py    From dash-hack with MIT License 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #4
Source File: socks.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def guess_payload_class(self, pkt):
        d_port = s_port = True
        if self.underlayer and isinstance(self.underlayer, TCP):
            ports = conf.contribs['socks']['serverports']
            d_port = self.underlayer.dport in ports
            s_port = self.underlayer.sport in ports
        if self.vn == 0x5:
            if d_port:
                return SOCKS5Request
            elif s_port:
                return SOCKS5Reply
        elif self.vn == 0x4:
            if d_port:
                return SOCKS4Request
        elif self.vn == 0x0:
            if s_port:
                return SOCKS4Reply
        warning("No TCP underlayer, or dport/sport not in "
                "conf.contribs['socks']['serverports']. "
                "Assuming a SOCKS v5 request layer")
        return SOCKS5Request 
Example #5
Source File: queso.py    From dash-hack with MIT License 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #6
Source File: dns.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def pre_dissect(self, s):
        """
        Check that a valid DNS over TCP message can be decoded
        """
        if isinstance(self.underlayer, TCP):

            # Compute the length of the DNS packet
            if len(s) >= 2:
                dns_len = struct.unpack("!H", s[:2])[0]
            else:
                message = "Malformed DNS message: too small!"
                warning(message)
                raise Scapy_Exception(message)

            # Check if the length is valid
            if dns_len < 14 or len(s) < dns_len:
                message = "Malformed DNS message: invalid length!"
                warning(message)
                raise Scapy_Exception(message)

        return s


# https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4 
Example #7
Source File: queso.py    From dash-hack with MIT License 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #8
Source File: queso.py    From isip with MIT License 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #9
Source File: queso.py    From POC-EXP with GNU General Public License v3.0 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #10
Source File: queso.py    From mptcp-abuse with GNU General Public License v2.0 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #11
Source File: packets.py    From aggr-inject with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def tcp_syn(src_ip, dst_ip, port):
    tcp_syn_p = TCP(dport=port, flags="S", window=29200, seq=random.randint(0, 100000), sport=random.randint(40000, 60000), options=[('MSS', 1460), ('SAckOK', ''), ('Timestamp', (147229543, 0)), ('NOP', None), ('WScale', 7)])

    syn = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \
               / SNAP(OUI=0x000000, code=ETH_P_IP) \
               / IP(src=src_ip, dst=dst_ip, flags=0x02, tos=0x10, len=(20 + len(tcp_syn_p))) \
               / tcp_syn_p
    syn = LLC(str(syn))

    #syn.show()

    return syn


# 802.11 Beacon frame
# TODO: Fix me; duplicate code 
Example #12
Source File: mptcp_scanner.py    From mptcp-abuse with GNU General Public License v2.0 6 votes vote down vote up
def checkMPTCPSupportViaRST(port,target,timeout,localIP,MpCapAlreadyPassed=False):
    MpCapPassed = MpCapAlreadyPassed
    #TODO: Abstract this out more elegantly so i dont repeat code from elsewhere
    if not MpCapPassed:
        pkt = makeMPCapableSyn(localIP, port, target)
        response=sr1(pkt,timeout=timeout)
        if response and getMpOption(pkt.getlayer("TCP")) is not None:
            MpCapPassed = True

    if MpCapPassed:
        pkt = makeJoinSyn(localIP, port, target)
        response=sr1(pkt,timeout=timeout)
        #TODO: Add checks for other types of response (such as ICMP)
        #TODO: Make this clearer

        #Check for the flag with a mask
        print response.getlayer("TCP").flags
        if (0x04 & response.getlayer("TCP").flags) == 0x04:
            print "RST Test indicates MPTCP support"
            return True
        else:
            print "RST Test indicates host doesn't understand MPTCP"
            return False 
Example #13
Source File: mptcp_scanner.py    From mptcp-abuse with GNU General Public License v2.0 6 votes vote down vote up
def makeMPCapableSyn(sourceAddr,dport,dstAddr, sport=None, initTCPSeq=None, \
                     sendKey=None):

    if sport is None: sport = randintb(16)
    if initTCPSeq is None: initTCPSeq = randintb(32)
    if sendKey is None: sendKey = randintb(32)
    #TODO: make more elegant type handling for IPADDR
    dstAddr = str(dstAddr)


    pkt = (IP(version=4L,src=sourceAddr,dst=dstAddr)/        \
        TCP(sport=sport,dport=dport,flags="S",seq=initTCPSeq, \
        options=[TCPOption_MP(mptcp=MPTCP_CapableSYN(
                            checksum_req=1,
                            snd_key=sendKey))]))
    return pkt 
Example #14
Source File: queso.py    From arissploit with GNU General Public License v3.0 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #15
Source File: queso.py    From CVE-2016-6366 with MIT License 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #16
Source File: queso.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def queso_sig(target, dport=80, timeout=3):
    p = queso_kdb.get_base()
    ret = []
    for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]:
        ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()),
                        timeout=timeout, verbose=0)
        if len(ans) == 0:
            rs = "- - - -"
        else:
            s,r = ans[0]
            rs = "%i" % (r.seq != 0)
            if not r.ack:
                r += " 0"
            elif r.ack-s.seq > 666:
                rs += " R" % 0
            else:
                rs += " +%i" % (r.ack-s.seq)
            rs += " %X" % r.window
            rs += " %x" % r.payload.flags
        ret.append(rs)
    return ret 
Example #17
Source File: nat64.py    From ai-smarthome with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, src, dst, sport, dport):
        super(TCP64State, self).__init__(src, dst, sport, dport, PROTO_TCP)
        ip4dst = ipaddress.ip_address(ipaddress.ip_address(dst).packed[-4:])
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("0.0.0.0", TCP64State.tcp_port))
        sock.settimeout(1.0)
        sock.connect((str(ip4dst), dport))
        self.sock = sock
        self.state = TCP_INIT
        self.ack = 0
        self.seq = 4711
        self.window = 1200
        self.mss = 1200
        log.debug("TCP opening ", ip4dst, dport, sock)
        TCP64State.tcp_port = TCP64State.tcp_port + 1

    # Handle TCP state - forward data from socket to tun. 
Example #18
Source File: fabric_test.py    From fabric-p4test with Apache License 2.0 6 votes vote down vote up
def get_int_pkt(self, pkt, instructions, max_hop, transit_hops=0, hop_metadata=None):
        proto = UDP if UDP in pkt else TCP
        int_pkt = pkt.copy()
        int_pkt[IP].tos = 0x04
        shim_len = 4 + len(instructions) * transit_hops
        int_shim = INT_L45_HEAD(int_type=1, length=shim_len)
        int_header = INT_META_HDR(
            ins_cnt=len(instructions),
            max_hop_cnt=max_hop,
            total_hop_cnt=transit_hops,
            inst_mask=self.get_ins_mask(instructions))
        int_tail = INT_L45_TAIL(next_proto=pkt[IP].proto, proto_param=pkt[proto].dport)
        metadata = "".join([hop_metadata] * transit_hops)
        int_payload = int_shim / int_header / metadata / int_tail
        int_pkt[proto].payload = int_payload / int_pkt[proto].payload
        return int_pkt 
Example #19
Source File: PortscanAttack.py    From ID2T with MIT License 6 votes vote down vote up
def __init__(self):
        """
        Creates a new instance of the PortscanAttack.
        This attack injects TCP Syn-requests and respective responses into the output pcap file.
        """
        # Initialize attack
        super(PortscanAttack, self).__init__("Portscan Attack", "Injects a nmap 'regular scan'",
                                             "Scanning/Probing")

        # Define allowed parameters and their type
        self.update_params([
            Parameter(self.IP_SOURCE, IPAddress()),
            Parameter(self.IP_DESTINATION, IPAddress()),
            Parameter(self.PORT_SOURCE, Port()),
            Parameter(self.PORT_DESTINATION, Port()),
            Parameter(self.PORT_OPEN, Port()),
            Parameter(self.MAC_SOURCE, MACAddress()),
            Parameter(self.MAC_DESTINATION, MACAddress()),
            Parameter(self.PORT_DEST_SHUFFLE, Boolean()),
            Parameter(self.PORT_DEST_ORDER_DESC, Boolean()),
            Parameter(self.IP_SOURCE_RANDOMIZE, Boolean()),
            Parameter(self.PACKETS_PER_SECOND, Float()),
            Parameter(self.PORT_SOURCE_RANDOMIZE, Boolean())
        ]) 
Example #20
Source File: ponsim.py    From voltha with Apache License 2.0 5 votes vote down vote up
def _clear_alarm(alarm_event, olt, egress):
        try:
            alarm_event['state'] = AlarmEventState.CLEARED
            frame = Ether() / Dot1Q(vlan=4000) / IP() / TCP() / Raw(load=json.dumps(alarm_event))
            egress(0, frame)

        except Exception as e:
            log.exception('failed-to-clear-alarm', e=e) 
Example #21
Source File: dns.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def post_build(self, pkt, pay):
        if isinstance(self.underlayer, TCP) and self.length is None:
            l = len(pkt) - 2
            pkt = struct.pack("!H", l) + pkt[2:]
            return pkt + pay
        else:
            return pkt + pay 
Example #22
Source File: packets.py    From aggr-inject with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def arp_packet(hwsrc, psrc, hwdst, pdst):
    arp_packet = ARP(hwsrc=hwsrc, psrc=psrc, hwdst=hwdst, pdst=pdst, op=1)
    arp = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \
               / SNAP(OUI=0x000000, code=0x0806) \
               / arp_packet

    return arp


# TCP syn packet 
Example #23
Source File: ssl_tls.py    From public_drown_scanner with GNU General Public License v2.0 5 votes vote down vote up
def pre_dissect(self, s):
        # figure out if we're UDP or TCP
        
        if self.underlayer and self.underlayer.haslayer(UDP):
            self.guessed_next_layer = DTLSRecord
        elif ord(s[0]) & 0x80:
            # SSLv2 Header
            self.guessed_next_layer = SSLv2Record
        else:
            self.guessed_next_layer = TLSRecord
        self.fields_desc = [PacketListField("records", None, self.guessed_next_layer)]
        return s 
Example #24
Source File: nat64.py    From ai-smarthome with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update_tcp_state_totun(self, data):
        ipv6 = IPv6(src = self.dst, dst = self.src)/TCP(sport=self.dport, dport=self.sport, flags="PA") / raw(data)
        # Update with the current seq and ack.
        ipv6.seq = self.seq
        ipv6.ack = self.ack
        return ipv6

    # receive packet and send to tun. 
Example #25
Source File: nat64.py    From ai-smarthome with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def receive(self):
        global input
        if self.sock is None:
            return None
        log.debug("TCP socket receive: %s" % self)
        maxread = max(self.maxreceive, self.mss)
        data, addr = self.sock.recvfrom(maxread)
        input.remove(self.sock)
        if not data:
            log.debug("Socket closing... TCP state kept to handle TUN close.")
            self.sock.close()
            self.sock = None
            log.debug("TCP: FIN over socket received - sending FIN over tun. %s" % self)
            ipv6 = IPv6(IPv6(src=self.dst, dst=self.src)/TCP(sport=self.dport, dport=self.sport, flags="F", seq=self.seq, ack=self.ack))
            ipv6.show()
            self.last_to_tun = ipv6
            send_to_tun(bytes(ipv6))
            return None
        ipv6 = IPv6(self.update_tcp_state_totun(data))
        log.debug("NAT64 TCP to tun max: %d" % maxread)
        ipv6.show()
        self.last_to_tun = ipv6
        send_to_tun(ipv6)
        return data

    # Handle TCP state - TCP from ipv6 tun toward IPv4 socket 
Example #26
Source File: nat64.py    From ai-smarthome with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __repr__(self):
        return "TCP - src:%s:%d dst:%s:%d state:%d seq:%d ack:%d mss:%d"%(self.src, self.sport, self.dst, self.dport, self.state,
                                                     self.seq, self.ack, self.mss)

# Remove the state for this specific socket 
Example #27
Source File: ponsim.py    From voltha with Apache License 2.0 5 votes vote down vote up
def _raise_alarm(alarm_event, olt, egress):
        try:
            frame = Ether() / Dot1Q(vlan=4000) / IP() / TCP() / Raw(load=json.dumps(alarm_event))
            egress(0, frame)

        except Exception as e:
            log.exception('failed-to-raise-alarm', e=e) 
Example #28
Source File: someip.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def _MAKE_COMMON_IP_SDOPTION_FIELDS_DESC():
    return [
        XByteField("res_tail", 0),
        ByteEnumField("l4_proto", 0x11, {0x06: "TCP", 0x11: "UDP"}),
        ShortField("port", 0)
    ] 
Example #29
Source File: mptcp_scanner.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def getMpSubkind(pkt, kind):
    """Return a generator of mptcp kind suboptions from pkt"""
    l4 = pkt.getlayer("TCP")
    for o in getMpOption(l4):
        if MPTCP_subtypes[o.subtype] == kind:
            yield (l4, o) 
Example #30
Source File: SMBScanAttack.py    From ID2T with MIT License 5 votes vote down vote up
def __init__(self):
        """
        Creates a new instance of the SMBScanAttack.
        This Attack injects TCP Syn Requests to the port 445 of several ips and related response into the output
        pcap file.
        If port 445 is open, it will simulate and inject the SMB Protocol Negotiation too.
        """
        # Initialize attack
        super(SMBScanAttack, self).__init__("SMBScan Attack", "Injects an SMB scan",
                                            "Scanning/Probing")

        self.host_os = Util.get_rnd_os()

        # Define allowed parameters and their type
        self.update_params([
            Parameter(self.IP_SOURCE, IPAddress()),
            Parameter(self.IP_DESTINATION, IPAddress()),
            Parameter(self.MAC_DESTINATION, MACAddress()),
            Parameter(self.TARGET_COUNT, IntegerPositive()),
            Parameter(self.HOSTING_PERCENTAGE, Percentage()),
            Parameter(self.PORT_SOURCE, Port()),
            Parameter(self.MAC_SOURCE, MACAddress()),
            Parameter(self.IP_SOURCE_RANDOMIZE, Boolean()),
            Parameter(self.PACKETS_PER_SECOND, Float()),
            Parameter(self.PORT_SOURCE_RANDOMIZE, Boolean()),
            Parameter(self.HOSTING_IP, IPAddress()),
            Parameter(self.HOSTING_VERSION, String()),
            Parameter(self.SOURCE_PLATFORM, SpecificString(Util.platforms)),
            Parameter(self.PROTOCOL_VERSION, String())
        ])