Skip to content

Instantly share code, notes, and snippets.

@dustyfresh
Last active June 1, 2022 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dustyfresh/66dd02c6514d960345fcdab3da786020 to your computer and use it in GitHub Desktop.
Save dustyfresh/66dd02c6514d960345fcdab3da786020 to your computer and use it in GitHub Desktop.
Systemd service to capture all traffic on ports 53/80/443. tshark will store up to 10MB of data per pcap file, and keep store up to 2GB of captures on disk. Once 2GB disk limit is reached, tshark will rotate older pcaps. Change the filecount in the capture script if you want to store more traffic on disk.

Continuous capture

Tested on Ubuntu 18.04.

Install tshark

You will want to allow non-root users to capture packets. These users must be part of the wireshark group.

$ sudo apt update
$ sudo apt install -y tshark

Add user to group

in this example we are using the ubuntu user

$ sudo usermod -aG wireshark ubuntu

Create capture output directory

$ sudo mkdir -p /opt/data/network
$ sudo chown -R ubuntu. /opt/data

Create capture script

Capture all traffic on ports 53/80/443 and rotate each pcap when it reaches a buffer of 10MB, but will keep up to 2GB on disk.

$ sudo vim /opt/data/network/tshark.sh

Add the capture script

#!/bin/bash
tshark -a filesize:10000 -b files:200 -i eth0 -w /opt/data/network/sniff.pcap -f "port 80 or port 53 or port 443"

Executable permissions

$ sudo chmod +x /opt/data/network/tshark.sh
$ sudo chown ubuntu. /opt/data/network/tshark.sh

Systemd configuration

$ sudo vim /lib/systemd/system/tshark.service

Add the config below to this file /lib/systemd/system/tshark.service

[Unit]
Description=Tshark Capture Service
After=multi-user.target

[Service]
Type=idle
User=ubuntu
group=ubuntu
ExecStart=/opt/data/network/tshark.sh

[Install]
WantedBy=multi-user.target

Change permissions of the systemd config and enable the service

$ sudo chmod 644 /lib/systemd/system/tshark.service
$ sudo systemctl daemon-reload
$ sudo systemctl enable tshark.service
$ sudo systemctl start tshark.service

PCAP Output

Up to 2GB of pcaps will be stored here. Once we hit 2GB of pcap data on disk tshark will begin rotating older capture files.

$ ll /opt/data/network/
total 20
drwxr-xr-x 2 ubuntu ubuntu  4096 Apr  7 20:55 ./
drwxr-xr-x 3 ubuntu ubuntu  4096 Apr  7 20:44 ../
-rw------- 1 ubuntu ubuntu 10016 Apr  7 21:02 sniff_00001_20200407205537.pcap

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