- Posted on
- • Artificial Intelligence
Using Artificial Intelligence to Analyse tcpdump Output
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Using Artificial Intelligence to Analyse tcpdump Output
Ever stared at a scrolling wall of tcpdump lines at 2 AM and wished for a second pair of eyes? AI can be that tireless teammate. With a little glue, you can funnel tcpdump output into a language model and get quick, human-readable summaries: top talkers, unusual ports, handshake failures, suspected scans, and more.
This post shows why AI can add value to packet triage and how to set it up end to end with practical, reproducible steps.
Why use AI on tcpdump?
tcpdump is terse by design. It’s great for machines and experts, but hard to skim at scale. AI can convert dense lines into patterns, counts, and hypotheses.
Pattern spotting is half the job. Repeated SYNs, flapping handshakes, odd TTL mixes, and abnormal DNS queries often stand out in text. LLMs are good at summarizing such regularities.
Faster triage, better follow-ups. Let AI give you a first pass: “Likely SYN flood from 198.51.100.23,” then you confirm with precise tools and counters.
Local or cloud. You can run an open model locally (privacy-friendly) or a cloud model for convenience and stronger reasoning.
Note: AI doesn’t replace deterministic analysis or forensics. It helps you prioritize where to dig.
Prerequisites and installation
You’ll need tcpdump and either:
a local AI runtime (e.g., Ollama with an open model), or
a cloud AI API (e.g., OpenAI) with Python.
Install the basics with your package manager.
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y tcpdump python3 python3-pip jq tshark
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y tcpdump python3 python3-pip jq wireshark-cli
- openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y tcpdump python3 python3-pip jq wireshark-cli
Notes:
tshark is optional but handy if you want structured fields; it’s provided by wireshark-cli on many distros.
You may need to run tcpdump with sudo depending on capabilities.
Option A: Local AI with Ollama
Install Ollama (single-command installer):
curl -fsSL https://ollama.com/install.sh | sh
Pull a model (example: Llama 3):
ollama pull llama3
Option B: Cloud AI with Python
Install a Python client library (example uses OpenAI):
python3 -m pip install --user openai
Set your API key:
export OPENAI_API_KEY="your_api_key_here"
Workflow: from packets to insight
Here are four actionable steps you can adopt on any Linux box.
1) Capture a focused sample
Keep captures short and filtered. That reduces noise and token usage.
- Live capture to file:
sudo tcpdump -i eth0 -nn -s 0 -w capture.pcap 'port 443 and host 203.0.113.10'
- Or capture a brief burst for quick triage:
sudo timeout 30 tcpdump -i eth0 -nn -s 0 -w capture.pcap
2) Render AI-friendly text
Language models parse text very well. Convert the pcap into readable lines.
- With tcpdump:
tcpdump -nn -tttt -q -r capture.pcap | head -n 2000 > capture.txt
Flags explained:
-nn: no name resolution (faster, clearer)
-tttt: full timestamp
-q: “quick” output (less noise)
-r: read from pcap
Optional: Use tshark to emit fields (cleaner input for AI if you prefer CSV-like):
tshark -r capture.pcap \
-T fields \
-e frame.time_epoch -e ip.src -e ip.dst -e tcp.flags -e udp.length -e tcp.srcport -e tcp.dstport -e dns.qry.name \
| head -n 2000 > capture_fields.txt
3) Send it to the model with a solid prompt
Good prompting is critical. Give the AI a role, clear goals, and ask for concise, actionable findings.
- Local (Ollama):
cat capture.txt | ollama run --system "You are a senior network analyst. The user will paste tcpdump lines. Your job:
- Identify anomalies, likely causes, and top talkers.
- Count by src/dst IP, ports, and flags where useful.
- Call out scans, SYN floods, retransmissions, repeated resets, TLS handshake issues, or DNS anomalies.
- Suggest 1–3 next verification steps with exact commands.
Keep it concise and use bullet points." llama3
- Cloud (Python + OpenAI):
#!/usr/bin/env python3
import os, sys, textwrap
from openai import OpenAI
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} capture.txt", file=sys.stderr)
sys.exit(1)
with open(sys.argv[1], 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
# Chunk to keep within context limits
CHUNK_SIZE = 400
chunks = [lines[i:i+CHUNK_SIZE] for i in range(0, len(lines), CHUNK_SIZE)]
system_prompt = """You are a senior network analyst. The user supplies tcpdump lines.
Output:
- Key patterns (top src/dst, ports, protocols) with counts/estimates
- Notable events (SYN flood, scans, retransmissions, RSTs, TLS failures, DNS anomalies)
- 1–3 next steps with exact Linux commands to verify findings
Be concise and use bullet points. If data is insufficient, say so and suggest a better filter."""
client = OpenAI()
model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
for idx, chunk in enumerate(chunks, 1):
user_prompt = "tcpdump lines:\n" + "".join(chunk)
print(f"\n=== Analysis chunk {idx}/{len(chunks)} ===\n")
resp = client.chat.completions.create(
model=model,
messages=[
{"role":"system","content":system_prompt},
{"role":"user","content":user_prompt},
],
temperature=0.2,
)
print(resp.choices[0].message.content.strip())
Run it:
python3 analyze_tcpdump_ai.py capture.txt
Prompt design tips:
Specify roles, outputs, and constraints (counts, flags, brief bullets).
Encourage commands as follow-ups (tcpdump/tshark/conntrack/ss/ip).
Keep temperatures low (0–0.3) for consistency.
4) Verify with deterministic checks
Treat the AI output as a hypothesis generator. Confirm with direct commands.
Examples:
- Top talkers (quick estimate):
awk '{print $3}' capture.txt | cut -d'.' -f1-4 | sort | uniq -c | sort -nr | head
- Look for SYNs without ACKs (possible SYN flood):
grep 'Flags \[S\]' capture.txt | awk '{print $3}' | cut -d'.' -f1-4 | sort | uniq -c | sort -nr | head
- Repeated resets (connection instability):
grep 'Flags \[R\]' capture.txt | awk '{print $3, $5}' | cut -d'.' -f1-4 | sort | uniq -c | sort -nr | head
- DNS queries with long labels (tunneling suspicion):
grep ' A? \| AAAA? \| TXT?' -E capture.txt | awk '{print $NF}' | awk 'length($0) > 60' | head
Real-world examples you can reproduce
- SYN flood suspicion
12:01:55.100000 IP 198.51.100.23.54321 > 203.0.113.10.80: Flags [S], seq 12345, win 65535, options [mss 1460], length 0
12:01:55.100200 IP 198.51.100.23.54322 > 203.0.113.10.80: Flags [S], seq 22345, win 65535, options [mss 1460], length 0
12:01:55.100250 IP 198.51.100.23.54323 > 203.0.113.10.80: Flags [S], seq 32345, win 65535, options [mss 1460], length 0
...
What AI should notice:
Many SYNs to the same dst, increasing ephemeral src ports, no corresponding SYN-ACK/ACK lines in the sample.
Next steps might include:
sudo tcpdump -i eth0 -nn 'host 198.51.100.23 and tcp[tcpflags] & (tcp-syn|tcp-ack) = tcp-syn' -c 200
sudo ss -ant state syn-recv | head
- TLS handshake failures
12:05:01.001000 IP 203.0.113.10.443 > 192.0.2.15.52344: Flags [R], seq 0, win 0, length 0
12:05:01.300000 IP 192.0.2.15.52345 > 203.0.113.10.443: Flags [S], seq 111, win 64240, options [mss 1460], length 0
12:05:01.301000 IP 203.0.113.10.443 > 192.0.2.15.52345: Flags [S.], seq 555, ack 112, win 65160, length 0
12:05:01.310000 IP 192.0.2.15.52345 > 203.0.113.10.443: Flags [.], ack 556, win 65160, length 0
12:05:01.320000 IP 192.0.2.15.52345 > 203.0.113.10.443: Flags [P.], length 517
12:05:01.321000 IP 203.0.113.10.443 > 192.0.2.15.52345: Flags [R], seq 556, win 0, length 0
What AI should notice:
Repeated RSTs from server after client payload suggests app-layer refusal or mismatch (e.g., TLS alert leading to RST).
Suggested follow-ups:
sudo tcpdump -i eth0 -s0 -w tls_fail.pcap 'host 192.0.2.15 and host 203.0.113.10 and port 443'
tshark -r tls_fail.pcap -Y 'tls.handshake or tcp.flags.reset==1' -V | less
- DNS oddities (potential tunneling)
12:10:33.100000 IP 10.0.0.5.41235 > 8.8.8.8.53: 1000+ A? kj39fks9dk3jf02kfj39dk...sub.example.com. (123)
12:10:33.200000 IP 10.0.0.5.41235 > 8.8.4.4.53: 1001+ TXT? asdf0a9sd8f0a9s8df0a98sdf...sub.example.com. (255)
12:10:34.000000 IP 10.0.0.5.41235 > 8.8.8.8.53: 1002+ A? kj39fks9dk3jf02kfj39dk...sub.example.com. (123)
What AI should notice:
Lengthy, repetitive labels, mix of A and TXT, rapid queries to public resolvers. Might suggest data exfil via DNS.
Suggested follow-ups:
tshark -r capture.pcap -Y 'dns' -T fields -e ip.src -e dns.qry.name | awk '{print $2}' | awk 'length>60' | sort | uniq -c | sort -nr | head
Guardrails and best practices
Minimize sensitive data. Filter on suspected hosts/ports and short time windows before sending to any cloud model.
Prefer local models for regulated environments.
Always validate. Use counters, filters, and deterministic tools to verify AI claims.
Keep prompts and chunk sizes modest. Trim unrelated chatter (e.g.,
-q,-nn) to save tokens.
Conclusion and next steps (CTA)
AI won’t replace your packet-fu, but it will speed up your first 15 minutes: summarizing patterns, highlighting anomalies, and proposing precise follow-ups. Try it on your next incident:
1) Capture a small, focused pcap.
2) Render it with tcpdump -nn -tttt -q -r ... > capture.txt.
3) Run the Ollama or Python flow above.
4) Validate the AI’s findings with the suggested tcpdump/tshark commands.
If this workflow helped, turn it into a quick internal runbook or wrapper script for your team. Your future, sleep-deprived self will thank you.