Capture the traffic of a process (and nothing more)

We’ve all been there. We want to know what traffic some python script or something creates. But, well, its the cloud era, and our device is chirping all the time at DNS, at gmail, etc. We try capturing too much and then filtering out. We try idling down the other culprits. If only there was a better way!

Well, put on your peril-sensitive sunglasses my friends. From the house of hack comes this lovely little script. Run it and you will end up in a shell with wireshark open. All the traffic derived from that shell will show up in that wireshark, and nothing else. When you exit the shell, wireshark is gone.

Its pretty self-explanatory to anyone with an advanced degree in bash and namespaces and veths.

#!/bin/sh

[ $(id -u) != 0 ] && exec sudo "$0" "$@"

DEFAULT_IF=$(ip route get 1.1.1.1 | awk '{ print $5}')
DEFAULT_SRC=$(ip route get 1.1.1.1 | awk '{ print $7}')

purge() {
  ip netns del capme 2>/dev/null
  ip link del veth-in 2>/dev/null
  ip link del veth-out 2>/dev/null
  iptables -t nat -D POSTROUTING -s 172.16.250.0/24 -o $DEFAULT_IF -j SNAT --to-source $DEFAULT_SRC 2>/dev/null
}

purge
set -e
ip netns add capme
ip link add veth-in type veth peer name veth-out
ip link set veth-in netns capme
ip netns exec capme ip addr add 172.16.250.1/24 dev veth-in
ip netns exec capme ip link set dev veth-in up
ip addr add 172.16.250.2/24 dev veth-out
ip link set dev veth-out up
ip netns exec capme ip route add default via 172.16.250.2 dev veth-in
mkdir -p /etc/netns/capme
echo nameserver 1.1.1.1 > /etc/netns/capme/resolv.conf
ip netns exec capme ip link set dev lo up
ip netns exec capme ip route add 127.0.0.0/8 dev lo
ip link set dev veth-out multicast off
ip netns exec capme ip link set dev veth-in multicast off
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s 172.16.250.0/24 -o $DEFAULT_IF -j SNAT --to-source $DEFAULT_SRC

sudo ip netns exec capme wireshark -i veth-in &
pid=$!
echo "pid is... $pid"
echo "Until exit, all commands run in sub-namespace and are captured in wireshark"
sudo ip netns exec capme bash
sudo ip netns pids capme | xargs sudo ip netns exec capme xargs -r kill -9
sleep 1
purge

 


Posted

in

by

Tags:

Comments

One response to “Capture the traffic of a process (and nothing more)”

  1. Bobola Oke

    Nice to discover your blog Don. Learned alot from this post!

Leave a Reply

Your email address will not be published. Required fields are marked *