Skip to content

Instantly share code, notes, and snippets.

@lspgn
Last active December 29, 2023 11:56
Show Gist options
  • Save lspgn/ffc8ba8cb70f069913dc9d166f618374 to your computer and use it in GitHub Desktop.
Save lspgn/ffc8ba8cb70f069913dc9d166f618374 to your computer and use it in GitHub Desktop.
tcpreplay and tcprewrite to edit PCAPs

tcpreplay and tcprewrite quick commands

Whether you capture packets either with tcpdump or Wireshark you often get a pcap file containing all the packets.

You can use tools to replay the packets on the interface. When debugging software, it may be necessary to edit the IP and mac addresses inside the pcap. To not rely on the network, it is also possible to use the local interface (lo0 on MacOS).

replay

The following command allows replaying packets

tcpreplay -l [LOOP] -i [INTERFACE] -M [SPEED] capture.pcap

Where loop is the amount of time the packet gets replayed, interface is the interface it's replayed on and finally speed just defines the throughput and ignores the packet timings. Speeds too high could result in packet drops. This is common with UDP.

When a capture was made on a local interface, the packets cannot be sent to a real interface and vice-versa. Rewriting is required and explained later in this document.

rewrite to local

In order to convert a capture on a real interface to a local interface on a Mac, you need to run the following:

For IPv4

tcprewrite -i source.pcap -o destination.pcap \
  --dlt=user \
  -S 0.0.0.0/0:127.0.0.1 \
  -D 0.0.0.0/0:127.0.0.1 \
  --user-dlink 02,00,00,00 \
  --user-dlt 0

For IPv6

tcprewrite -i source.pcap -o destination.pcap \
  --dlt=user \
  -S '[::]/0:[::1]' \
  -D '[::]/0:[::1]' \
  --user-dlink 1e,00,00,00 \
  --user-dlt 0

The DLT is set to zero for loopback. The data link (dlink) information is a pseudo encapsulation composed of 8 bytes with the first byte set to 2 for IPv4 and 30 for IPv6. tcprewrite automatically discards a the Ethernet layer you can find on real interface captures.

rewrite to interface

The opposite process can be done with:

For IPv4

tcprewrite -i source.pcap -o destination.pcap \
  --dlt=user \
  --user-dlt 1 \
  --user-dlink [DSTMAC],[SRCMAC],08,00
  -S 127.0.0.1:192.168.1.0 \
  -D 127.0.0.1:192.168.1.1

For IPv6

tcprewrite -i source.pcap -o destination.pcap \
  --dlt=user \
  --user-dlt 1 \
  --user-dlink [DSTMAC],[SRCMAC],86,dd
  -S '[::1]:[fd01::1]' \
  -D '[::1]:[fd01::2]'

MAC is replaced by the series of bytes corresponding to the source and destination mac addresses. They are followed by two bytes for the EtherTypes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment