'How do i create a tcp packet in a pcap
I want to create (not send or sniff) tcp packets and put them in a created pcap.
i'm trying scapy but a lot of documentation is for sending packets or sniffing existing networking traffic. I want to create tcp packets and sessions with custom headers and put/create them in pcap
Solution 1:[1]
You have the wrpcap function that writes a packet to a pcap file if that's what you're looking for. In this small script, I craft three SYN TCP
packets that target destination port 80 and that I write to a pcap file:
from scapy.all import IP, TCP, wrpcap
for ip in [
'8.8.8.8',
'151.101.65.69',
'104.244.42.129'
]:
p = IP(dst=ip)/TCP(dport=80, flags='S')
wrpcap('packets.pcap', p, append=True)
The output packets.pcap file can then be opened using, e.g., wireshark.
[EDIT] You can then craft packets and simulate TCP sessions. You just need to be careful with IP adresses, TCP ports, flags and seq numbers.
For instance in that script I simulate a TCP connection between
1.1.1.1:10000 (client) and 2.2.2.2:80 (server). After the handshake,
the client sends the word GET and the server answers with DATA.
Then the disconnection takes place.
Wireshark seems to be happy with the generated pcap file.
#!/usr/bin/env python3
from scapy.all import IP, TCP, wrpcap
src = '1.1.1.1' # source IP
dst = '2.2.2.2' # destination IP
sport = 10_000 # source port
dport = 80 # destination port
packets = [
##### TCP 3-way handshake
# 1.1.1.1:10000 --SYN--> 2.2.2.2:80
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='S'),
# 2.2.2.2:80 --SYN,ACK--> 1.1.1.1:10000
IP(src=dst, dst=src)/TCP(sport=dport, dport=sport, flags='SA'),
# 1.1.1.1:10000 --ACK--> 2.2.2.2:80
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='A'),
#####
##### data exchange
# 1.1.1.1:10000 --GET--> 2.2.2.2:80
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='', seq=1)/'GET',
# 2.2.2.2:80 --ACK=4--> 1.1.1.1:10000 (4 = 1 + len('GET'))
IP(src=dst, dst=src)/TCP(sport=dport, dport=sport, flags='A', seq=1, ack=4),
# 2.2.2.2:80 --DATA--> 1.1.1.1:10000
IP(src=dst, dst=src)/TCP(sport=dport, dport=sport, flags='', seq=1)/'DATA',
# 1.1.1.1:10000 --ACK=5--> 2.2.2.2:80 (5 = 1 + len('DATA'))
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='A', ack=5),
#####
##### TCP disconnection
# 1.1.1.1:10000 --FIN--> 2.2.2.2:80
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='F', seq=4),
# 2.2.2.2:80 --FIN,ACK--> 1.1.1.1:10000
IP(src=dst, dst=src)/TCP(sport=dport, dport=sport, flags='FA', seq=5),
# 1.1.1.1:10000 --ACK--> 2.2.2.2:80
IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='A')
#####
]
wrpcap('packets.pcap', packets)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
