Skip to content

Yash-Patil-1/PacketWatch

Repository files navigation

📡 PacketWatch

Network Traffic Analyzer & Anomaly Detector

Python version License Status Tests

SOC-grade CLI tool for PCAP analysis — detect port scans, DNS tunnels, C2 beacons, brute force attacks, and data exfiltration.


📋 Overview

PacketWatch reads PCAP files, reconstructs network flows, and applies five detection modules to identify suspicious network activity. Built for SOC analysts, threat hunters, and security students who need practical network traffic analysis capabilities.

Why this project? Network traffic analysis is a core SOC skill. PacketWatch demonstrates practical ability to parse raw packets (using Scapy, pyshark, or a built-in raw parser), reconstruct bidirectional flows, and apply detection logic at the network layer.


✨ Features

Feature Description
Multi-backend PCAP Reader Scapy (primary), pyshark/TShark (fallback), raw binary parser (zero deps)
5 Detection Modules Port scan, DNS tunnel, C2 beacon, brute force, data exfiltration
Flow Reconstruction Bidirectional flow builder with timing, byte counts, and protocol analysis
HTML Reports Dark-themed professional reports with matplotlib charts (pie, bar, timeline)
JSON Export Structured output for SIEM ingestion and programmatic processing
Terminal Output Colorized console reporting with severity badges and ASCII charts
MITRE ATT&CK Each anomaly mapped to MITRE technique IDs
Detector Registry Auto-discovery of detection modules — easy to extend
Sample PCAP Bundled PCAP with 6 attack scenarios for testing

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/Yash-Patil-1/PacketWatch.git
cd PacketWatch

# Create a virtual environment (recommended)
python3 -m venv .venv
source .venv/bin/activate

# Install PacketWatch
pip install -e .

# Verify installation
packetwatch --version

Basic Usage

# Analyze a PCAP file with all detectors
packetwatch analyze sample_traffic.pcap

# Analyze with verbose output and per-detector breakdown
packetwatch analyze sample_traffic.pcap --verbose

# Run specific detectors only
packetwatch analyze sample_traffic.pcap --detectors port_scan,dns_tunnel

# Generate HTML/JSON/terminal reports
packetwatch analyze sample_traffic.pcap --output ./reports

# List all available detection modules
packetwatch list-detectors

# Show PCAP file info (packets, protocols, duration)
packetwatch info sample_traffic.pcap

# Show detailed version and backend info
packetwatch version

Example Output

$ packetwatch analyze sample_traffic.pcap --verbose
[+] Loaded 184 packets from sample_traffic.pcap
[+] Built 126 flows
[+] Running 5 detectors...

────────────────────────────────────────────────────────────
🚨 HIGH     | beacon       | Regular packet intervals to 203.0.113.200:443 — mean: 1.0s, jitter: 0.0%
🚨 HIGH     | dns_tunnel   | 192.168.1.100 made 43 DNS queries (129/min) — possible tunneling
⚠️ MEDIUM   | exfil        | 10.0.0.10 sent 2.0 MB to 203.0.113.200:443 (50 packets)
⚠️ MEDIUM   | exfil        | 10.0.0.10 sent 2.0 MB but received only 0 B (ratio: inf:1)
⚠️ MEDIUM   | port_scan    | 10.0.0.99 performed a FIN scan on 192.168.1.1 (7 ports)
⚠️ MEDIUM   | brute_force  | 192.168.1.200 attempted 20 SSH connections to 1 targets (126/min)
🟢 LOW      | port_scan    | 10.0.0.5 has 16 short connections to 1 targets
🟢 LOW      | port_scan    | 192.168.1.200 has 20 short connections to 1 targets
────────────────────────────────────────────────────────────

Results: 9 anomalies detected

PCAP Stats:
  Duration:    587.00s
  Protocols:   TCP, UDP
  Reader:      scapy

Anomaly Breakdown by Detector:
  port_scan: 3
  exfil: 2
  brute_force: 2
  beacon: 1
  dns_tunnel: 1

🔍 Detection Modules

Detector Anomaly Method MITRE
Port Scan SYN, FIN, Xmas, NULL scan TCP flag analysis, unique dest ports, connection rate T1046
DNS Tunnel Data exfiltration over DNS Shannon entropy on domains, TXT record size, query volume T1572
C2 Beacon Command & control communication Timing interval regularity, coefficient of variation (jitter) analysis T1571
Brute Force SSH/RDP password guessing SYN bursts to auth ports (22/3389/21/23), connection rate T1110
Data Exfil Large outbound transfers Per-flow byte counts, src-to-dst ratio, duration Z-score outliers T1048

📁 Project Structure

PacketWatch/
├── pyproject.toml              # Package configuration
├── requirements.txt            # Python dependencies
├── README.md                   # This file
├── PRD.md                      # Product requirements document
├── sample_traffic.pcap         # Bundled sample PCAP (6 attack scenarios)
│
├── src/
│   └── packetwatch/
│       ├── __init__.py         # Package init (version: 1.0.0)
│       ├── models.py           # Packet, Flow, Anomaly, AnalysisResult dataclasses
│       ├── reader.py           # PCAP reader (Scapy/pyshark/raw backends)
│       ├── analyzer.py         # Analysis orchestrator + FlowBuilder
│       ├── reporter.py         # Reporter (HTML, JSON, Terminal)
│       ├── main.py             # CLI entry point (5 subcommands)
│       │
│       ├── detectors/
│       │   ├── __init__.py     # BaseDetector ABC + registry + auto-discovery
│       │   ├── port_scan.py    # SYN, FIN, Xmas, NULL scan detection
│       │   ├── dns_tunnel.py   # High-entropy domains, TXT records, query volume
│       │   ├── beacon.py       # C2 beacon timing jitter analysis
│       │   ├── brute_force.py  # SSH/RDP brute force detection
│       │   └── exfil.py        # Data exfiltration volume/ratio/duration analysis
│       │
│       └── templates/
│           └── report.html     # Jinja2 HTML report template
│
├── scripts/
│   └── generate_sample_pcap.py  # PCAP generator with attack scenarios
│
├── tests/
│   ├── test_reader.py          # 20 tests — PCAP parsing
│   ├── test_detectors.py       # 31 tests — detection logic
│   ├── test_reporter.py        # 34 tests — report generation
│   └── test_main.py            # 23 tests — CLI integration
│
├── docs/                       # Documentation
│   ├── getting_started.md
│   ├── usage.md
│   ├── architecture.md
│   ├── development.md
│   ├── reporting.md
│   └── rules.md
│
└── reports/                    # Generated report output

🧪 Running Tests

# Install with dev dependencies
pip install -e ".[dev]"

# Run all tests
python3 -m pytest tests/ -v

# Run with coverage
python3 -m pytest tests/ --cov=src --cov-report=term

# Run specific test file
python3 -m pytest tests/test_detectors.py -v

Current test results: 104/104 passing


🛠️ CLI Reference

usage: packetwatch [-h] [--version] {info,analyze,list-detectors,version,report} ...

Network Traffic Analyzer & Anomaly Detector

Commands:
  info              Show PCAP file info (packets, protocols, duration)
  analyze           Analyze PCAP for anomalies
  list-detectors    List available detection modules
  version           Show detailed version and system information
  report            Generate reports from cached JSON analysis

analyze

packetwatch analyze <pcap> [--output DIR] [--format {html,json,terminal,all}]
                             [--detectors LIST] [--verbose]
Flag Description Default
pcap Path to PCAP file Required
--output, -o Output directory for reports Disabled
--format, -f Report format: html, json, terminal, all all
--detectors Comma-separated detector names All detectors
--verbose, -v Detailed per-detector breakdown False

report

packetwatch report <json_file> [--output DIR] [--format {html,json,terminal,all}]

Regenerate reports from a previously cached JSON analysis (e.g., from packetwatch analyze --format json).


📊 Sample Report Preview

The HTML report features:

  • Dark GitHub-inspired theme (#0d1117 background)
  • Summary cards — total packets, flows, anomalies, duration
  • Severity mini-cards — critical/high/medium/low counts
  • Severity pie chart — anomaly distribution
  • Detector breakdown bar chart — anomalies by detection module
  • Anomaly timeline scatter plot — chronological attack sequence
  • Top source/destination IPs — ranked by anomaly involvement
  • Anomaly table — severity badges, detector tags, score bars, MITRE IDs
  • Responsive design for desktop and mobile

📝 License

This project is licensed under the MIT License.


👨‍💻 Author

Yash Patil — Cybersecurity Analyst | SOC Operations & Incident Response


🔗 Related Projects


Built with Python, Scapy, matplotlib, Jinja2, and a passion for network security.

About

Network Traffic Analyzer & Anomaly Detector — PCAP analysis with 5 detection modules (port scan, DNS tunnel, C2 beacon, brute force, data exfiltration)

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors