Skip to content

Deinick/NetGuard

Repository files navigation

NetGuard

A real-time network packet analyzer and intrusion detection system built in Python. Captures live traffic via raw sockets, parses protocols down to the application layer, detects port scans/floods/anomalies, scores IP reputation, and presents everything through a rich terminal dashboard.


Features

  • Raw Packet Capture — Ethernet → IPv4 → TCP/UDP/ICMP parsing with struct unpacking
  • Application-Layer Detection — DNS query/response parser (with compression pointer support), HTTP request/response detection
  • Port Scan Detection — SYN, FIN, XMAS, and TCP Connect scans with windowed unique-port counting
  • SYN Flood Detection — Rate-based with severity scaling (WARNING → HIGH → CRITICAL)
  • Anomaly Detection — Traffic baseline learning (5-min window, std-deviation based), port sweep detection, connection flood detection
  • IP Reputation System — Blacklist/whitelist from files, suspicious scoring with auto-promote to malicious, JSON state persistence
  • Alert System — JSON logging (JSONL, last 1000), severity levels, color-coded terminal output, desktop notifications via notify-send
  • Rich TUI Dashboard — Real-time panels for statistics, alerts, active connections, top talkers, and live packet feed
  • Interactive Controls — Pause/resume, protocol filter cycling, PCAP export, keyboard shortcuts
  • Custom Rules Engine — YAML-based rules with compound conditions, windowed thresholds, toggle/reload at runtime
  • Configuration Management — YAML settings with defaults, deep merge, dot-notation access

Architecture

┌─────────────────────────────────────────────────────────────┐
│                        main.py                              │
│              (argparse, TUI/CLI mode switch)                │
├────────────────────-┬───────────────────────────────────────┤
│   TUI Mode          │              CLI Mode                 │
│   (--tui flag)      │         (interactive menu)            │
│                     │                                       │
│  ┌──────────-┐      │  ┌──────────────┐  ┌───────────────┐  │
│  │interface  │      │  │ capture_     │  │  analyze_     │  │
│  │  .py      │      │  │  packets()   │  │   packets()   │  │
│  │ (Rich TUI)│      │  │ (sniffer.py) │  │ (analyzer.py) │  │
│  └─────┬─────┘      │  └──────┬───────┘  └───────────────┘  │
│        │            │         │                             │
├────────┴────────────┴─────────┴─────────────────────────────┤
│                    Packet Pipeline                          │
│                                                             │
│  ┌──────────┐   ┌──────────────────┐   ┌──────────────────┐ │
│  │ packet.py│──>│ threat_detection │──>│  alert_manager   │ │
│  │ (parser) │   │  .py (scans,     │   │  .py (log, notify│ │
│  │          │   │   SYN flood)     │   │   severity)      │ │
│  └──────────┘   └──────────────────┘   └──────────────────┘ │
│                                                             │
│  ┌──────────────────┐  ┌─────────┐  ┌────────────────────┐  │
│  │anomaly_detection │  │  ip.py  │  │   rule_engine.py   │  │
│  │.py (baseline,    │  │ (reputa-│  │  (custom YAML      │  │
│  │ sweep, flood)    │  │  tion)  │  │   rules)           │  │
│  └──────────────────┘  └─────────┘  └────────────────────┘  │
│                                                             │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │ config_manager   │  │  Supporting modules:             │ │
│  │ .py (YAML        │  │  net_statistics.py, port_utils.py│ │
│  │  settings)       │  │  analyzer.py (ConnectionTracker, │ │
│  └──────────────────┘  │  DNSTracker)                     │ │
│                        └──────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

File Structure

main/
├── main.py               # Entry point — argparse, TUI/CLI mode
├── sniffer.py            # Raw socket packet capture
├── packet.py             # Ethernet/IP/TCP/UDP/DNS/HTTP parser
├── analyzer.py           # ConnectionTracker (TCP state machine), DNSTracker
├── threat_detection.py   # ScanDetector, SYNFloodDetector
├── anomaly_detection.py  # TrafficBaseline, PortSweepDetector, ConnectionFloodDetector
├── ip.py                 # IP reputation (blacklist/whitelist/scoring)
├── alert_manager.py      # Alert logging, notifications, severity
├── rule_engine.py        # Custom YAML rule engine
├── config_manager.py     # YAML settings management
├── net_statistics.py     # ProtocolStatistics (counters, top talkers, ports)
├── port_utils.py         # Port-to-service name mapping
├── interface.py          # Rich TUI dashboard (5 panels)
├── rules.yaml            # Custom detection rules
├── settings.yaml         # Application configuration
├── blacklist.txt         # Blacklisted IPs (one per line)
└── whitelist.txt         # Whitelisted IPs (one per line)

Installation

1. Clone the repository

git clone https://github.com/yourusername/NetGuard.git
cd NetGuard

2. Create a virtual environment

python3 -m venv venv

3. Activate the virtual environment

Linux / macOS:

source venv/bin/activate

Windows (PowerShell):

.\venv\Scripts\Activate.ps1

4. Install dependencies

pip install -r requirements.txt

Quick Start with Dev Container (Recommended for Windows / macOS)

This project uses Linux raw sockets (AF_PACKET), so it requires a Linux environment. The easiest way to run it on any OS is with VS Code Dev Containers — no Linux install needed.

Prerequisites

  1. Install Docker Desktop
  2. Install VS Code
  3. Install the Dev Containers extension in VS Code

Steps

  1. Clone and open the project:
    git clone https://github.com/yourusername/NetGuard.git
    code NetGuard
  2. VS Code will prompt "Reopen in Container" — click it (or press F1Dev Containers: Reopen in Container)
  3. Wait for the container to build (first time only, ~1 min)
  4. Open the terminal in VS Code and run:
    cd main
    python main.py --tui -i eth0

Everything runs inside a Linux container with root access and all dependencies pre-installed. No sudo, no venv setup, no pip install needed.


Requirements

  • Python 3.10+
  • Linux (raw sockets require AF_PACKET) — or use the Dev Container above
  • Root/sudo privileges (for raw socket capture)
  • Python packages: rich, pyyaml (installed automatically via requirements.txt)

Usage

TUI Mode (recommended)

sudo python3 main.py --tui -i eth0

Launches a real-time dashboard with 5 panels. Keyboard shortcuts:

  • p — Pause/resume packet capture display
  • f — Cycle protocol filter (ALL → TCP → UDP → ICMP)
  • e — Export captured packets to capture.pcap
  • q — Quit

CLI Mode

sudo python3 main.py -i eth0 -c 100

Captures 100 packets, runs analysis, then presents a 24-option interactive menu:

# Option # Option
1 Show all packets 13 Show malicious IPs
2 Show connections 14 Check IP reputation
3 Search by IP 15 Add IP to blacklist
4 Search by port 16 Add IP to whitelist
5 Search by protocol 17 Add known malicious IP
6 Show active connections 18 Show recent alerts
7 Show closed connections 19 Show alert summary
8 Connection details 20 Show baseline status
9 Show DNS queries 21 Exit
10 Show top domains 22 Show custom rules
11 Show protocol statistics 23 Toggle a rule
12 Show suspicious IPs 24 Reload rules

Arguments

Flag Default Description
--tui off Launch TUI dashboard
-i, --interface eth0 Network interface to capture on
-c, --count 50 Number of packets to capture (CLI mode)

Configuration

settings.yaml

Controls all runtime parameters:

interface:
  default: "eth0"
  promiscuous: true

display:
  refresh_rate: 4          # TUI refresh rate (Hz)
  packet_history_size: 100 # Max packets in TUI feed

alerts:
  log_file: "./alerts.json"
  enable_notifications: true
  notification_cooldown: 5  # Seconds between desktop notifications

thresholds:
  port_scan: 100
  syn_flood: 100
  connection_flood: 50
  port_sweep: 5

ip_reputation:
  score_threshold: 50      # Score to auto-promote to malicious
  state_file: "ip_reputation.json"

rules.yaml

Define custom detection rules:

rules:
  - name: "SSH Bruteforce Detection"
    description: "Detects multiple SSH connection attempts"
    condition: "tcp.dst_port == 22 and tcp.flags.syn and not tcp.flags.ack"
    threshold: 10
    window: 60
    severity: "HIGH"
    enabled: true

Condition syntax supports: tcp, udp, icmp (protocol gates), tcp.flags.syn, tcp.flags.fin, tcp.flags.rst, not tcp.flags.ack, dst_port == N, dst_port in [N,M,...], packet.size > N.


Detection Capabilities

Threat Detector Alert Type
SYN port scan ScanDetector SYN_SCAN
FIN port scan ScanDetector FIN_SCAN
XMAS port scan ScanDetector XMAS_SCAN
TCP connect scan ScanDetector CONNECT_SCAN
SYN flood SYNFloodDetector SYN_FLOOD
Traffic surge TrafficBaseline TRAFFIC_SURGE
Protocol surge TrafficBaseline {PROTO}_SURGE
Port sweep PortSweepDetector PORT_SWEEP
Connection flood ConnectionFloodDetector CONNECTION_FLOOD
Custom rules RuleEngine CUSTOM_RULE

License

See LICENSE for details.

About

A network monitoring and intrusion detection tool

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors