Skip to content

ahmad12583719/NetForensics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚡ NetForensics

Forensic Packet Intelligence & Evidence Platform

A professional-grade, open-source packet sniffer built with a forensic focus — designed to capture, analyse, and produce court-ready evidence reports.

Python License: MIT Scapy Streamlit


📋 Table of Contents


✨ Features

🔬 Forensic Capture Engine

  • Real-time packet capture via Scapy
  • BPF (Berkeley Packet Filter) support for targeted capture
  • Full Layer 2–7 parsing: Ethernet · IPv4 · IPv6 · TCP · UDP · ICMP · ARP · DNS · HTTP
  • SHA-256 payload hashing for evidence integrity
  • Automatic MAC address extraction
  • DNS query/response tracking
  • Crude HTTP method, URI, and Host header extraction

⚠️ Forensic Heuristics & Anomaly Detection

Heuristic Description
TCP Scan Detection NULL, Xmas, FIN-only, All-flags scans
Cleartext Protocols HTTP, FTP, Telnet, POP3, IMAP flagged
DNS Tunnelling Unusually long DNS queries (>80 chars)
Gratuitous ARP Possible ARP spoofing / MITM indicator
Large Payloads Anomalous payload sizes (>8 KB)
Risk Scoring 0–100 composite score per packet

📄 Court-Ready Reports

  • JSON — machine-readable, chain-of-custody metadata, full packet log
  • CSV — spreadsheet-compatible flat packet log
  • HTML — self-contained, print-ready forensic report with colour-coded risk
  • TXT — plain-text archival format with full evidence attestation block

Every report includes:

  • Capture host, interface, BPF filter, operator name, case ID
  • Session start/end timestamps (UTC, ISO-8601)
  • SHA-256 digest of the entire packet log (chain-of-custody)
  • Anomaly index with per-packet risk scores
  • Legal disclaimer and evidence attestation

📡 Streamlit Dashboard

  • Dark terminal-inspired UI with electric-cyan accents
  • Live packet stream table with risk progress bars
  • Protocol distribution donut chart
  • Risk distribution donut chart
  • Packet volume timeline
  • Top source IPs and destination ports bar charts
  • Risk × payload size scatter plot
  • Full anomaly drill-down with packet-level JSON detail
  • One-click multi-format report export with download buttons
  • SHA-256 chain-of-custody hash displayed in-app

💻 Command-Line Interface

  • Coloured real-time packet output
  • Graceful Ctrl-C stop
  • Automatic multi-format report export on exit
  • Full operator / case ID metadata

📐 Architecture

netforensics/
├── core/
│   ├── sniffer.py          # PacketSniffer, PacketRecord, risk heuristics
│   └── __init__.py
├── reports/
│   ├── generator.py        # JSON, CSV, TXT, HTML export functions
│   └── __init__.py
├── ui/
│   └── app.py              # Streamlit dashboard
├── utils/
│   └── interfaces.py       # Network interface enumeration
├── tests/
│   └── test_sniffer.py     # pytest unit tests (no root required)
├── cli.py                  # Command-line entry point
├── requirements.txt
└── README.md

Data flow:

Network Interface
      │
      ▼
Scapy sniff()  ──────────────────────────────────────────────────────┐
      │                                                               │
      ▼                                                               │
PacketSniffer._handle_packet()                                        │
      │                                                               │
      ├─► Layer 2–7 parsing ──► PacketRecord (dataclass)             │
      │                                │                              │
      ├─► compute_risk() ─────► anomalies + risk_score               │
      │                                │                              │
      └─► callback (UI/CLI live feed)  │                              │
                                       ▼                              │
                                 _records[]  ◄─────────────────────┘
                                       │
                          ┌────────────┴─────────────┐
                          ▼                           ▼
                     CLI report             Streamlit dashboard
                   export_*.py              ui/app.py

📦 Requirements

Requirement Notes
Python 3.9+ 3.10+ recommended
Root / Administrator Required at runtime for raw socket access
libpcap / WinPcap Usually pre-installed on Linux/macOS; Npcap for Windows
pip packages See requirements.txt

🚀 Installation

1. Clone the repository

git clone https://github.com/your-org/NetForensics.git
cd NetForensics

2. Create a virtual environment (recommended)

python -m venv .venv
source .venv/bin/activate          # Linux / macOS
.venv\Scripts\activate             # Windows

3. Install dependencies

pip install -r requirements.txt

4. Verify Scapy (optional smoke test)

python -c "from scapy.all import sniff; print('Scapy OK')"

Platform notes

Linux

# Install libpcap if needed
sudo apt install libpcap-dev          # Debian / Ubuntu
sudo dnf install libpcap-devel        # Fedora / RHEL

macOS

# libpcap is bundled with Xcode Command Line Tools
xcode-select --install

Windows

  1. Install Npcap with "WinPcap API-compatible Mode" checked.
  2. Run PowerShell / cmd as Administrator.

💻 Usage — CLI

⚠️ All capture commands require root / Administrator privileges.

Basic capture (30 seconds, auto-select interface)

sudo python cli.py --duration 30

Capture on a specific interface with a BPF filter

sudo python cli.py \
  --interface eth0 \
  --filter "tcp port 80 or tcp port 443" \
  --duration 60 \
  --case CASE-2024-001 \
  --operator "Jane Smith" \
  --format json,html,csv

Capture a fixed number of packets

sudo python cli.py --interface eth0 --count 500

Quiet mode (no per-packet output)

sudo python cli.py -i eth0 -d 120 -q --format json,txt

All options

usage: netforensics [-h] [-i INTERFACE] [-f BPF] [-c COUNT] [-d DURATION]
                    [--format FORMAT] [--output-dir DIR] [--case ID]
                    [--operator OPERATOR] [--notes NOTES] [-q] [--no-banner]

Capture:
  -i, --interface   Network interface (default: Scapy auto-select)
  -f, --filter      BPF capture filter, e.g. 'tcp port 80'
  -c, --count       Stop after N packets (0 = unlimited)
  -d, --duration    Stop after N seconds  (0 = until Ctrl-C)

Report:
  --format          Comma-separated: json,csv,txt,html  (default: json,txt)
  --output-dir      Report output directory  (default: ./netforensics_output)
  --case            Case / evidence identifier
  --operator        Analyst name
  --notes           Free-text notes appended to the report

Display:
  -q, --quiet       Suppress per-packet output
  --no-banner       Suppress ASCII banner

Example output

  ███╗   ██╗███████╗████████╗███████╗ ██████╗ ██████╗ ███████╗
  ...
       Forensic Packet Intelligence Platform  v1.0.0

  SESSION CONFIGURATION
    Interface  : eth0
    BPF Filter : tcp port 443
    Duration   : 30 s
    Formats    : html, json, txt
    Case ID    : CASE-2024-001

  ▶  Capture started. Press Ctrl-C to stop.

  #1       12:00:01.123456  TCP    192.168.1.10:54321 → 93.184.216.34:443  [LOW   0]
  #2       12:00:01.234567  TCP    192.168.1.10:23    → 10.0.0.1:54322    [HIGH 40] ⚠  Telnet – credentials in plaintext

  CAPTURE SUMMARY
    Packets captured : 142
    Duration         : 30.0 s
    Throughput       : 4.73 pkts/s
    Risk → Critical: 0  High: 1  Medium: 3  Low: 138

  EXPORTING REPORTS
    ✓ JSON : ./netforensics_output/netforensics_20240115_120031.json
    ✓ TXT  : ./netforensics_output/netforensics_20240115_120031.txt
    ✓ HTML : ./netforensics_output/netforensics_20240115_120031.html

  ✓  Done. Reports written to ./netforensics_output

🖥️ Usage — Streamlit UI

# Must be run with root privileges for capture to work
sudo streamlit run ui/app.py

Then open your browser at http://localhost:8501

On macOS you may need:

sudo $(which streamlit) run ui/app.py

Dashboard walkthrough

Tab Contents
📡 LIVE FEED Scrolling real-time packet table (last 200), risk progress bars
📊 ANALYTICS Protocol pie · Risk donut · Volume timeline · Top IPs · Risk scatter
⚠ ANOMALIES Anomaly frequency chart · Detail table · Packet drill-down JSON viewer
📄 EXPORT REPORT Case metadata form · Format checkboxes · Download buttons · SHA-256 digest

Sidebar controls

  1. Interface — Leave blank for Scapy auto-select, or enter eth0 / en0 etc.
  2. BPF Filter — Standard tcpdump-style filter e.g. tcp port 80
  3. Packet Limit / Duration0 means unlimited
  4. Case Metadata — Case ID, analyst name, and notes are embedded in every report
  5. ▶ START / ⏹ STOP — Control capture
  6. Auto-refresh — Toggle 2-second live polling

📄 Report Formats

JSON

Full structured output with forensic metadata at the top:

{
  "forensic_metadata": {
    "case_id": "CASE-001",
    "operator": "Jane Smith",
    "report_generated_utc": "2024-01-15T12:00:31+00:00",
    "packet_log_sha256": "a3f2...",
    "disclaimer": "..."
  },
  "session_statistics": { ... },
  "anomaly_index": [ ... ],
  "packet_log": [ ... ]
}

HTML

Self-contained, print-ready report with:

  • Dark terminal theme
  • Colour-coded risk rows (critical/high/medium/low)
  • Evidence metadata table
  • Statistical summary cards
  • Full packet log table (first 500)

CSV

Flat, spreadsheet-compatible packet log with all fields.

Plain Text

Printable, archival-friendly text report with full evidence block, anomaly index, and packet listing.


🔬 Forensic Heuristics

NetForensics computes a risk score (0–100) for each packet using these heuristics:

Condition Score Added Anomaly Message
Cleartext protocol port (21/23/80/110/143) +10 Cleartext protocol on port N
TCP NULL scan (flags = 0x00) +40 Suspicious TCP flags: NULL scan
TCP Xmas scan (FIN+URG+PSH) +40 Suspicious TCP flags: Xmas scan
All-flags TCP scan (0x3F) +40 Suspicious TCP flags: All-flags scan
Telnet connection (port 23) +30 Telnet – credentials transmitted in plaintext
DNS query > 80 chars +35 Unusually long DNS query (possible DNS tunnelling)
Payload > 8 192 bytes +15 Large payload (N bytes)
Gratuitous ARP reply +50 Possible gratuitous ARP (spoofing indicator)
ICMP Echo (ping) +5 (no anomaly message, low risk)

Scores are capped at 100. Multiple conditions stack.

Risk levels:

  • 🟢 Low (0–24)
  • 🟡 Medium (25–49)
  • 🟠 High (50–74)
  • 🔴 Critical (75–100)

🧪 Running Tests

The test suite uses mock packet data and does not require root or a live network interface.

# Run all tests
pytest tests/

# With coverage report
pytest tests/ --cov=. --cov-report=term-missing

# Verbose output
pytest tests/ -v

Expected output:

tests/test_sniffer.py ....................................  [100%]
36 passed in 0.42s

📁 Project Structure

netforensics/
│
├── core/
│   ├── __init__.py             # Public API: PacketSniffer, PacketRecord
│   └── sniffer.py              # Capture engine, packet parsing, risk scoring
│
├── reports/
│   ├── __init__.py             # Public API: export_*
│   └── generator.py            # JSON / CSV / TXT / HTML report generators
│
├── ui/
│   └── app.py                  # Streamlit dashboard (all tabs, charts, export)
│
├── utils/
│   └── interfaces.py           # Network interface listing utility
│
├── tests/
│   └── test_sniffer.py         # 36 unit tests (pytest, no root required)
│
├── cli.py                      # CLI entry point (argparse)
├── requirements.txt            # Python dependencies
└── README.md                   # This file

🤝 Contributing

We welcome contributions! Please follow these steps:

1. Fork and clone

git clone https://github.com/your-org/NetForensics.git
cd NetForensics
git checkout -b feature/my-feature

2. Set up the development environment

python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

3. Make your changes

  • New heuristic? Add it to core/sniffer.pycompute_risk() and write a test in tests/test_sniffer.py.
  • New report format? Add an export_*() function to reports/generator.py and wire it into cli.py and ui/app.py.
  • UI improvement? Edit ui/app.py. Keep the dark terminal aesthetic consistent.

4. Test your changes

pytest tests/ -v

All existing tests must pass. New features must include tests.

5. Code style

  • Follow PEP 8 and use type hints.
  • Comment every non-trivial function and section.
  • Keep functions short and single-purpose.

6. Submit a pull request

Push your branch and open a PR against main. Describe:

  • What problem your change solves
  • How to test it
  • Any security or forensic implications

Contribution ideas

  • Protocol decoders: TLS/SSL handshake parsing, SSH version extraction
  • PCAP import (load .pcap files for offline analysis)
  • GeoIP integration (flag international traffic)
  • Port-scan detection at session level (same src IP → many ports)
  • Email (SMTP) credential extraction detector
  • Real-time PCAP export (Wireshark-compatible)
  • Elasticsearch / Splunk log forwarder
  • Docker image for rootless deployment
  • Windows installer script

⚖️ Legal & Ethical Notice

This tool is intended for authorised network monitoring, incident response, and digital forensics only.

  • You must have explicit written permission from the network owner before capturing traffic on any network you do not personally own.
  • Packet capture on networks without authorisation may violate the Computer Fraud and Abuse Act (CFAA), GDPR, PECR, and equivalent laws in your jurisdiction.
  • Reports generated by this tool are produced for informational purposes. They should be reviewed by a qualified forensic analyst before submission as legal evidence.
  • The SHA-256 chain-of-custody hash attests to the integrity of the packet log at the time of report generation. It does not constitute a legally certified hash under ISO 27037 or NIST SP 800-86 without additional procedural controls (documented chain of custody, write-blocking, certified tools).
  • The authors and contributors of NetForensics accept no liability for misuse of this software.

📜 License

MIT License — see LICENSE for the full text.

Copyright (c) 2024 NetForensics Contributors
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
...

Built with ⚡ by Ahmad Raza

About

Professional-grade Packet Sniffer & Forensic Intelligence Platform. Features a unique, interactive Streamlit UI + CLI, real-time risk scoring, and court-ready evidence reports with SHA-256 integrity hashing.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages