Scapy: fields to recompute when forging packets - python

I'm forging with Scapy the TTL value in the IP header in some data packet that I captured. Besides the checksum in both IP and transport layer headers, is there anything else I should recompute?
Right now I'm doing:
for p in myPackets:
p[IP].ttl = targetTTL
del(p[IP].chksum)
del(p[IP].payload.chksum)
for i in range(len(myPackets)):
myPackets[i] = myPackets[i].__class__(str(myPackets[i]))
I'm asking this because Scapy's sr function, which matches packets with their responses (ICMP in my case) has been returning data with a few RTTs > 1 second, which is absurd since I'm using ttl=1.

Have you tried just sending the packet? Scapy should recompute the checksums for you automatically.You could also try setting them to None, but I don't believe that's necessary.

I believe scapy will automatically recalculate the checksums if you call the show2() command on the packet. So if you have a packet at index 0 in the object pckt, you should call pckt.show2() and the checksum should be correct. At least that's my understanding.
pkt.show2() same as show but on the assembled packet (checksum is calculated, for instance) Source

Related

Scapy: get/set frequency or channel of a packet

I have been trying to capture WIFI packets with Linux and see the frequency/channel at which packet was captured. I tried Wireshark and there was no luck and no help. Though using a sample packets from Wireshark, I can see the frequency/channel.
So now I'm experimenting with Scapy. I wanted to figure out the frequency/channel of a sniffed packet, but still no luck. Is there a way to do this with Scapy.
P.S.
If there is a better tool than Scapy, or Python, I appreciate comments
I found out that RadioTab headers are not part of any Dot11 protocol but are merely added by the network interface. And the reason I got the RadioTab headers on sample packets from Wireshark.org and not from my live wireshark capture is because some network adapters do not add RadioTap while others do and the network adapter of my laptop does not add RadioTab headers. I checked this with a new external WiFi adapter and it did add the RadioTap headers.
If the adapter does not inject the additional information as it captures frames, then no radiotap headers will be added.
So to my main question, how to get/set frequency of a packet.
I expected Scapy to have this option but it doesn't, and it shouldn't. The reason is that the frequency depends on what is set on the network adapter. So what I did was to set the frequency/channel of my WiFi adapter to a different one. My external WiFi adapter can work in various channels so I changed each and confirmed with the RadioTap header. There are a simple linux commands/tools that helped me check the supported channels of my WiFi interface, and switch to a particular channel.
To capture/send packets at a certain frequency or channel, you need to change the working channel of your interface and set the sniffer/sender interface in scapy to that interface.
EDIT - Other problems I faced and solutions:
If you are on linux, and you want to change the working channel of your interface you need to disable network-manager for that interface and to do this
First
Add the following snippet to /etc/network/interfaces
auto $iface
iface $iface inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
replace $iface with your interface name. This will let you control the interface by yourself. And then add the following lines to /etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=/var/run/wpa_supplicant
network={
ssid="Your_AP_SSID"
psk="Your_Passphrase"
freq_list=2412 2437 2462
}
Note that 2412 2437 2462 are the frequencies (channel 1, 6, 11 in this case) for your interface to choose from. You can edit them to desired frequency. Source. But first you have to check that your interface supports these frequencies. To check that
iwlist channel
Finally after everything is done.
sendp(Ether()/IP(dst="1.2.3.4",ttl=(1,4)), iface="wlp3s0")
This will send you packets at the frequency that wlp3s0 is set.
This answer is scoped to the question's title and content: Providing getters and setters for frequency and channel of a packet.
For this solution, use the wpa-Induction.pcap file in Wireshark's Sample Captures.
Poking around
It's useful to poke around one packet to see what fields Scapy has access to in the Scapy interpreter.
>>> pkts = rdpcap('wpa-Induction.pcap')
>>> pkts[0].summary()
"RadioTap / Dot11FCS / Dot11Beacon / Dot11Elt / Dot11EltRates / Dot11Elt / Dot11Elt / Dot11Elt / Dot11Elt / Dot11EltRSN / Dot11Elt / Dot11EltVendorSpecific / Dot11EltMicrosoftWPA / SSID=''"
>>> pkts[0].show()
###[ RadioTap dummy ]###
version= 0
pad= 0
len= 24
present= Flags+Rate+Channel+Lock_Quality+Antenna+dB_AntSignal+RXFlags
Flags= FCS
Rate= 2
Channel= 2412
ChannelFlags= CCK+2GHz
Antenna= 84
notdecoded= '\x00\x00+\x00\x00\x9fa\xc9\\'
... <output truncated> ...
While 2412 is a frequency and NOT a channel, this is the data we want. RadioTap is the layer per pkts[0].summary(). Putting it together,
>>> frequency = pkts[0][RadioTap].Channel
>>> print(frequency)
2412
Scapy does not provide access to the channel, but it's trivial to convert frequency to channel.
Putting it Together
Getting the Frequency
Given a file and packet number, we can now get the channel and frequency for a packet.
from scapy.all import RadioTap, rdpcap
def getChannel(frequency):
base = 2407 # 2.4Ghz
if frequency//1000 == 5:
base = 5000 # 5Ghz
# 2.4 and 5Ghz channels increment by 5
return (frequency-base)//5
def getFrequency(file, packet_number):
pkts = rdpcap(file)
# Scapy mixes up Channel/Frequency here
frequency = pkts[packet_number][RadioTap].Channel
return frequency
freq = getFrequency('wpa-Induction.pcap', 0)
chan = getChannel(freq)
print("Channel: {0} \nFrequency: {1}".format(freq, chan))
Setting the Frequency
Let's say we wanted to change the frequency to 5300 and save it. This would only require iterating over the packet list, change the frequency for every packet, and saving the result. In the scapy interpreter:
>>> for i in range(len(pkts)):
... pkts[i][RadioTap].Channel = 5300
>>> wrpcap('temp.pcap', pkts)
>>> pkts2 = rdpcap('temp.pcap')
>>> pkts[0].Channel
5300

Python: wrong ip is shown in packet header

I'm forwarding a machine's packets through mine. I tested with tcpdump host <machine_ip> to see if everything is alright, and it is. Now I need to capture these packets. I chose to do this with Python. Right now I'm trying to filter the packets, but the ip that is printed is different from the right one. It should've been 192.168.0.8:
import socket
from struct import *
print("Started")
with socket.socket(socket.AF_PACKET,socket.SOCK_RAW, socket.ntohs(0x0003)) as s:
while True:
packet=s.recvfrom(65565)
content=packet[0]
ip_header=unpack('!BBHHHBBH4s4s', content[:20])
source_ip=socket.inet_ntoa(ip_header[8])
print(source_ip)
The printed ones are 8.0.69.0 and 8.0.69.16, which none of these matches the expected form.
This is because in front of the raw data is the MAC header.
If You change the line:
ip_header=unpack('!BBHHHBBH4s4s', content[:20])
to
ip_header=unpack('!BBHHHBBH4s4s', content[14:34])
You will probably get your ip address. I said probably becase it really depends on the link layer, as there might be a vlan tag present, thus shifting the ip header even further.

Is there an efficienct way to get field offset in pyshark

Is there an efficient way to get the offset of some field in a packet captured with pyshark?
For example, I need to get the offset of the source IP within the whole packet or within some layer header in the packet. Is it possible?
I was able to solve my issue. Here is a sample code:
import pyshark
packets = pyshark.FileCapture(input_file=pcap_file_dir)
print(int(packets[0].ip.src.pos)) # Prints the offset of source IP

Scapy - persistent RandIP

I am trying to simulate a TCP communication between two hosts with scapy.
My problem is, that I can't save the random IP addresses scapy generates for me.
This code
src_IP = RandIP()
print(src_IP)
print(src_IP)
print(src_IP)
gives me an output like this
234.200.98.20
147.3.56.17
135.102.142.49
So every time I access src_IP it has a new value.
Is there a way to save a random IP from scapy? So I could generated 2 IPs at the beginning of my function and use them as source and destination for my TCP communication.
I could generate the IPs myself, but I thought there had to be a more elegant solution to it.
BTW. non of the packets are going to be sent, they will be written into a PCAP file. Therefor I have to create both sides of the communication.
The accepted answer is a hack; it is correct (as in "it works and do what was asked"), but it is not the correct way to do that in Scapy.
The method you are looking for is ._fix(). It will work with any volatile value type.
src_IP = RandIP()._fix()
If you also need for example a random source port, you could do:
src_port = RandShort()._fix()
I found an answer.
RandIP() creates an instance of an object, and every time this object gets accessed, to print or do send a packet or something else, it generates a new IP.
So my solution is to cast it to a string
src_IP = str(RandIP())
print(src_IP)
print(src_IP)
print(src_IP)
And the output is just as intended
232.119.133.38
232.119.133.38
232.119.133.38

Specifying packet length with scapy

I'm trying to send a specific packet size (100 bytes) with scapy but cant seem to get it.
I'm using this to start.
sr(IP(dst="192.168.1.1")/TCP(dport=443))
Looking at the docs / help I cant tell if I can use PacketLenField to specify the length of the packet. I can do it with NMAP & NSE but would like to do it outside of NMAP.
Any ideas on this one?
Thanks!
You can just add on the required number of bytes as a String when crafting the packet e.g.:
payload = 'ZZZZZZZZZZZZZZZZZZZZZ'
pkt = Ether() / IP() / TCP() / payload
will work. You just need to adjust the length of the payload as you require.
Scapy's Raw() function populates the payload of the packet. If you know your header size, you only need to fill in the remaining bytes with random data.
You can use RandString() to generate random padding. The following command sends a packet of length 100 (and listens for a response):
sr(IP(dst="192.168.1.1")/TCP(dport=443)/Raw(RandString(size=72))
You may use inet.Padding() from scapy library:
packet = IP(dst="192.168.1.1")/TCP(dport=443)
if len(packet)<100:
#"\x00" is a single zero byte
myString = "\x00"*(100 - len(packet))
packet = packet/inet.Padding(myString)

Categories