Skip to content

aratan/myIPS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MyIPS — Intrusion Prevention System

AI-powered network Intrusion Prevention System (IPS) that captures packets in real-time, analyzes traffic patterns through Ollama LLMs, and automatically blocks malicious IPs via iptables firewall rules.


📄 Semantic_Network_Defense.pdf — Documento de arquitectura y fundamentos del sistema.


Features

  • Real-time packet capture via gopacket/pcap with BPF filter support
  • AI-driven threat analysis through Ollama (compatible with llama3.2, gemma, mistral, and other models)
  • Automatic IP blocking with configurable duration and auto-expiry via iptables
  • Concurrent analysis pipeline — configurable worker pool with buffered job queue
  • Multi-protocol identification — TCP, UDP, ICMP, SCTP, GRE, IPSec, IPv6 with 30+ service mappings
  • Threat scoring engine — heuristic pre-filtering with port scan, flood, and brute-force detection
  • Autonomous graduated response — risk-based reaction levels integrated with a whitelist manager
  • Steganography detection — Shannon entropy analysis for covert channel identification
  • Session reconstruction — flow tracking, TCP flag analysis, and forensic data collection
  • PCAP export for offline and forensic analysis
  • Colored console output with structured logging to file

imagen

Requirements

  • Go 1.24+
  • libpcap — packet capture library (libpcap-dev on Debian/Ubuntu, libpcap on Arch Linux)
  • Ollama — running locally with a loaded model (e.g., llama3.2, gemma3:4b, mistral)
  • iptables — for firewall rule management (requires CAP_NET_ADMIN or root)
  • Network interface with promiscuous mode support

Arch Linux Quick Install

sudo pacman -S go libpcap iptables
ollama pull llama3.2

Installation

git clone https://github.com/aratan/myIPS.git
cd myIPS
go build -o myips .

Quick Start

# 1. Listar interfaces disponibles
sudo ./myips -l

# 2. Arrancar con configuración recomendada (análisis cada 10s, 3 workers)
sudo ./myips -i wlan0 --model llama3.2 -t 10s -w 3

Requerimientos:

  • Ejecutar con sudo (necesita CAP_NET_RAW para pcap y CAP_NET_ADMIN para iptables)
  • Ollama corriendo en localhost:11434 con el modelo descargado (ollama pull llama3.2)

Qué esperar:

  1. Los paquetes IPv4 aparecen en terminal con colores ([IN] TCP/HTTP 1.2.3.4 → 192.168.1.11)
  2. Cada 60s se muestran estadísticas de protocolos (📊 Estadísticas de protocolos)
  3. Cada 10s los workers envían el resumen a Ollama (👨‍💻 Worker 0 procesando análisis...)
  4. Si Ollama detecta una amenaza, se bloquea la IP (🛡️ IP BLOQUEADA: 1.2.3.4)

Si no ves nada: verificá que haya tráfico IPv4 en la interfaz, que esté con sudo, y que el nombre de interfaz sea correcto (sudo ./myips -l).


Usage

# List available network interfaces
sudo ./myips -l

# Basic monitoring on an interface
sudo ./myips -i eth0 --model llama3.2

# Custom analysis interval and worker pool
sudo ./myips -i wlan0 --model gemma3:4b -t 15s -w 10

# BPF filter and PCAP output
sudo ./myips -i eth0 -f "tcp port 443" -o capture.pcap

# Extended block duration
sudo ./myips -i eth0 -b 1h --model llama3.2

Note: Root privileges are required for packet capture (pcap) and firewall management (iptables).

Command Line Options

Flag Description Default
-i, --interface Network interface name (e.g., eth0, wlan0) Required
-l, --list-interfaces List available interfaces false
-f, --filter BPF packet filter expression ip
-o, --output PCAP output file path (none)
--model Ollama model name llama3.2
--url Ollama API endpoint http://localhost:11434/api/generate
-t, --interval Analysis interval duration 30s
-b, --block-duration IP block duration before auto-unblock 15m
-w, --workers Number of concurrent analysis workers 5

Architecture

Pipeline Overview

Packet Capture (pcap)
       │
       ▼
┌──────────────────────────────────────────────────┐
│           processAdvancedPacket()                │
│  ┌─────────┐  ┌──────────┐  ┌────────────────┐  │
│  │ Protocol │─▶│ Direction│─▶│ Content        │  │
│  │ Switch   │  │ Analysis │  │ Analysis       │  │
│  │ TCP/UDP/ │  │ IN/OUT/  │  │ HTTP/DNS/TLS   │  │
│  │ ICMP/... │  │ FWD      │  │                │  │
│  └─────────┘  └──────────┘  └────────────────┘  │
│                                                  │
│  ┌──────────────────────────────────────────┐    │
│  │        processMilitaryGradePacket()      │    │
│  │  ┌────────┐  ┌──────────┐  ┌──────────┐  │    │
│  │  │  ML    │─▶│ Protocol │─▶│ Stegano- │  │    │
│  │  │ Engine │  │ Reconst. │  │ graphy   │  │    │
│  │  └────────┘  └──────────┘  └──────────┘  │    │
│  └──────────────────────────────────────────┘    │
└──────────────────────────────────────────────────┘
       │
       ▼
Traffic Statistics ──► Analysis Queue (chan, 100 cap)
                              │
                              ▼
                   Worker Pool (N goroutines)
                              │
                              ▼
                    ┌──────────────────┐
                    │   Ollama LLM     │
                    │  (JSON prompt)   │
                    └──────────────────┘
                              │
                              ▼
                    Threat Assessment
                    ├── allow   → log normal traffic
                    ├── monitor → enhanced logging
                    └── block   → iptables DROP rule
                                 └── auto-unblock after TTL

How It Works

  1. Capture: Opens the network interface in promiscuous mode via pcap. Applies the BPF filter to reduce noise. All incoming IPv4 packets enter the processing pipeline.

  2. Classify: Each packet is classified by IP protocol (TCP, UDP, ICMPv4, SCTP, GRE, IPSec, IGMP, IPv6). Transport-layer ports are mapped to well-known services (SSH, HTTP, DNS, RDP, etc.). Traffic direction is determined by comparing against local IPs.

  3. Content Analysis: HTTP payloads are inspected for plaintext content; DNS queries and responses are logged. TLS traffic is noted but cannot be decrypted.

  4. Threat Pre-Screening: The ML Engine runs heuristic checks — port scan thresholds, protocol anomalies — producing a baseline risk score. The Steganography Detector computes Shannon entropy on payloads to flag potential covert channels.

  5. Session Tracking: The Protocol Reconstruction Engine records per-flow sessions with packet-level metadata, TCP flags, and direction tracking for forensic analysis.

  6. Accumulate & Analyze: Traffic statistics are buffered across the configured interval. The aggregated summary is sent as a structured prompt to Ollama, which returns a JSON threat assessment.

  7. Respond: Based on the assessment:

    • allow: Traffic is logged as normal.
    • monitor: IP is flagged for observation.
    • block: An iptables INPUT DROP rule is added for the source IP. The rule is automatically removed after the block duration expires.

Threat Analysis Engines

Component File Purpose
MLEngine engines.go Heuristic pre-filtering — port scan and flood threshold detection
AutonomousResponseSystem engines.go Risk-graduated response — emergency block at score ≥9.0, monitor at ≥4.0
SteganographyDetector engines.go Shannon entropy analysis on application-layer payloads
ProtocolReconstructionEngine protocol_reconstruction.go Flow-based session tracking with packet recording and timeout-based cleanup

Project Structure

myips/
├── main.go                      # CLI (cobra), packet capture, StateManager, iptables operations
├── engines.go                   # MLEngine, AutonomousResponseSystem, SteganographyDetector, core types
├── protocol_reconstruction.go   # Session tracking, flow extraction, forensic analysis
├── go.mod                       # Module: github.com/aratan/myips
├── go.sum                       # Dependency checksums
├── LICENSE                      # MIT License
└── README.md                    # This file

Core Types

Type Description
StateManager Thread-safe IP block/unblock state with iptables integration
MLEngine Heuristic threat scoring with configurable thresholds
AutonomousResponseSystem Graduated risk response with whitelist support
WhitelistManager RWMutex-protected IP whitelist with Add/Remove/IsWhitelisted
SteganographyDetector Entropy-based covert channel detection
ProtocolReconstructionEngine Flow-based session recording and cleanup
SessionTracker Per-flow state: packets, stats, threats, classification

Firewall Integration

The system manages iptables rules directly:

Action Command
Block iptables -A INPUT -s <IP> -j DROP -m comment --comment "IPS_Block_<IP>_<ts>"
Unblock iptables -D INPUT -s <IP> -j DROP -m comment --comment "IPS_Block_<IP>_<ts>"

Rules are automatically cleaned up by manageUnblocks(), which runs on a 30-second ticker. The StateManager ensures thread-safe rule tracking with re-verification before deletion to prevent race conditions.

Supported platforms: Linux only (iptables). Windows support was removed in favor of Linux-native tooling.


Development

Prerequisites

go install golang.org/x/tools/cmd/goimports@latest

Build & Verify

go build ./...
go vet ./...

Code Style

  • Standard Go conventions (gofmt enforced)
  • Single package main monolithic structure
  • Thread safety via sync.Mutex / sync.RWMutex with scoped locking patterns

Known Limitations

  • IPv4 only: IPv6 traffic is filtered at the pcap level (filter: "ip")
  • No unit tests: The project currently lacks a test suite (planned)
  • iptables dependency: Requires root privileges and iptables userspace tools
  • Single-node: No distributed or clustered deployment support

License

MIT — see LICENSE.

Disclaimer

This tool is for authorized security testing and monitoring on networks you own or have explicit permission to audit. Unauthorized network monitoring may violate applicable laws. The authors assume no liability for misuse.

About

con IA sniffer de red

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages