A production-grade cybersecurity system combining Machine Learning-based threat detection with active prevention through automated firewall management.
This system implements both passive detection (NIDS) and active prevention (NIPS) to protect networks from cyber threats in real-time.
- π Real-time packet capture and analysis using Scapy
- π€ ML-based detection with 95% accuracy (Random Forest, Isolation Forest)
- π Rule-based detection for known attack patterns
- π Real-time traffic visualization and analytics
- π‘οΈ Automatic IP blocking via system firewall (Windows/Linux/macOS)
- β‘ Intelligent threat scoring algorithm (cumulative risk assessment)
- β±οΈ Time-based auto-unblock with configurable durations
- π― Whitelist/blacklist management for manual control
- π Rate limiting for suspicious but non-critical threats
- Port Scanning
- SYN Flood / DDoS
- Brute Force attacks
- SQL Injection attempts
- ARP Spoofing
- DNS Tunneling
- Suspicious port access
- Malware traffic patterns
| Metric | Value |
|---|---|
| Detection Accuracy | 95.2% |
| False Positive Rate | <5% |
| Processing Speed | 10,000+ packets/sec |
| Detection Latency | <100ms |
| Prevention Latency | <50ms |
| Model Training Time | ~3-5 minutes |
| Supported Threats | 8+ types |
- Language: Python 3.11
- Framework: FastAPI + Uvicorn
- ML/AI: scikit-learn, NumPy, Pandas
- Network: Scapy, dpkt
- Database: MongoDB (optional), Redis (optional)
- Monitoring: Prometheus, Grafana
- Framework: React 18 + TypeScript
- UI: Tailwind CSS
- Charts: Recharts
- Icons: Lucide React
- Containerization: Docker, Docker Compose
- Firewall: netsh (Windows), iptables (Linux), pfctl (macOS)
nids-system/
βββ src/ # Core application code
β βββ main.py # FastAPI backend (NIDS + NIPS integrated)
β βββ packet_analyzer.py # Packet capture & ML detection engine
β βββ nips_engine.py # Prevention engine (firewall management)
β βββ train_real.py # Model training with real datasets
β βββ generate_report.py # Security report generator
β
βββ config/ # Configuration files
β βββ config.yaml # System configuration
β βββ .env # Environment variables
β βββ prometheus.yml # Prometheus metrics config
β βββ init-mongo.js # MongoDB initialization
β
βββ docker/ # Docker configuration
β βββ Dockerfile # Main API container
β βββ Dockerfile.capture # Packet capture container
β βββ docker-compose.yml # Multi-container orchestration
β βββ .dockerignore # Docker ignore rules
β
βββ frontend/ # React dashboard
β βββ src/
β β βββ App.tsx # Main app with dashboard toggle
β β βββ components/
β β β βββ NIDSDashboard.tsx # Detection-only dashboard
β β β βββ NIPSDashboard.tsx # Prevention dashboard
β β βββ ...
β βββ package.json
β βββ tailwind.config.js
β
βββ grafana/ # Grafana dashboards
β βββ dashboards/
β β βββ nids-nips-overview.json
β βββ datasources/
β βββ prometheus.yml
β
βββ models/ # Trained ML models
β βββ *.pkl
β
βββ datasets/ # Training datasets
β βββ NF-UNSW-NB15-v3/
β
βββ logs/ # Application logs
βββ alerts/ # Alert storage
βββ reports/ # Generated reports
βββ screenshots/ # Project screenshots
βββ scripts/ # Utility scripts
βββ tests/ # Test suite
β
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ .gitignore # Git ignore rules
- Python 3.11+
- Node.js 18+ & npm
- Docker & Docker Compose (optional)
- Administrator/root privileges (for packet capture & firewall control)
- Npcap (Windows) or libpcap (Linux/macOS)
git clone https://github.com/RayenMalouche/NIPDS.git
cd NIPDS# Create virtual environment
python -m venv venv
# Activate (Windows)
venv\Scripts\activate
# Activate (Linux/macOS)
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Configure environment
cp config/.env.example config/.env
# Edit config/.env with your settings
# Train ML models
cd src
python train_real.py
# Start backend (as Administrator/root)
python main.pycd frontend
# Install dependencies
npm install
# Start development server
npm start- Frontend: http://localhost:3000
- API Docs: http://localhost:8000/docs
- Prometheus: http://localhost:9090
- Grafana: http://localhost:3000 (if using Docker)
# Build and start all services
docker-compose -f docker/docker-compose.yml up -d
# View logs
docker-compose -f docker/docker-compose.yml logs -f
# Stop services
docker-compose -f docker/docker-compose.yml down| Service | Port | Description |
|---|---|---|
| nids-api | 8000 | Main API server |
| nids-capture | - | Packet capture (host network) |
| mongodb | 27017 | Alert storage |
| redis | 6379 | Cache & session management |
| prometheus | 9090 | Metrics collection |
| grafana | 3000 | Data visualization |
# Network
CAPTURE_INTERFACE=Wi-Fi
PROMISCUOUS_MODE=true
# API
API_HOST=0.0.0.0
API_PORT=8000
# CORS
CORS_ORIGINS=["http://localhost:3000"]
# NIPS Settings
ENABLE_AUTO_BLOCKING=False # Set True for active prevention
DEBUG_MODE=True
# Database (optional)
DATABASE_ENABLED=False
MONGO_URL=mongodb://localhost:27017
REDIS_URL=redis://localhost:6379network:
interface: "Wi-Fi"
promiscuous_mode: true
packet_buffer_size: 10000
detection:
ml_threshold: 0.7
ml_based_enabled: true
rule_based_enabled: true
nips:
auto_block_enabled: false
default_block_duration_minutes: 30
permanent_block_threshold: 5
threat_score_threshold: 100
threat_policies:
Port Scan:
action: block
duration_minutes: 60
threat_score: 50
SYN Flood:
action: block
duration_minutes: 120
threat_score: 100
# ... more policiesThe system was trained on the NF-UNSW-NB15-v3 dataset from The University of Queensland.
Dataset Details:
- Source: UQ NIDS Datasets
- Format: NetFlow v3 features
- Samples: 175,341 flows
- Classes: Binary (Benign/Attack)
- Attack Types: 9 categories (Fuzzers, Analysis, Backdoors, DoS, Exploits, Generic, Reconnaissance, Shellcode, Worms)
Training Results:
- Accuracy: 95.2%
- Precision: 0.96 (Normal), 0.95 (Attack)
- Recall: 0.94 (Normal), 0.96 (Attack)
- ROC-AUC: 0.98
The frontend provides two dashboards accessible via toggle:
- Real-time packet statistics
- Threat detection alerts (no blocking)
- Traffic timeline visualization
- Threat type distribution
- Alert severity breakdown
- All NIDS features +
- Active firewall blocks counter
- Blocked IPs management
- Whitelist/blacklist controls
- Prevention action indicators
- Auto-block toggle
- Total packets processed
- Threats detected
- Packets prevented (blocked)
- Active firewall blocks
- Detection rate
- Prevention rate
- System uptime
GET / # System status
GET /stats # System statistics
GET /alerts # Recent alerts
GET /threats/distribution # Threat breakdown
# NIPS Endpoints
GET /nips/status # NIPS engine status
GET /nips/blocked-ips # List blocked IPs
POST /nips/whitelist # Add to whitelist
POST /nips/blacklist # Add to blacklist
POST /nips/block # Manual block
POST /nips/unblock # Manual unblock
POST /nips/config/auto-block # Toggle auto-blocking# Get system stats
curl http://localhost:8000/stats
# Block an IP manually
curl -X POST http://localhost:8000/nips/block \
-H "Content-Type: application/json" \
-d '{"ip": "192.168.1.100", "action": "block"}'
# Add to whitelist
curl -X POST http://localhost:8000/nips/whitelist \
-H "Content-Type: application/json" \
-d '{"ip": "192.168.1.50", "action": "whitelist"}'cd src
pytest tests/ -v
# With coverage
pytest tests/ --cov=. --cov-report=htmlpython tests/benchmark_detection.pypython generate_report.py- Start services:
docker-compose up -d - Open: http://localhost:3000
- Login: admin / admin (change on first login)
- NIDS/NIPS Overview: Real-time metrics, alerts, blocks
- Network Traffic: Packet rates, protocols, bandwidth
- Threat Analysis: Attack types, sources, trends
- System Health: CPU, memory, latency
Always whitelist trusted IPs before enabling auto-blocking:
# In src/main.py
nips.add_to_whitelist('192.168.1.14') # Your PC
nips.add_to_whitelist('192.168.1.1') # Your router
nips.add_to_whitelist('192.168.1.0/24') # Your subnet
nips.add_to_whitelist('8.8.8.8') # DNS servers- Set
ENABLE_AUTO_BLOCKING = Falseinitially - Test detection for 30+ minutes
- Verify no false positives
- Enable blocking only after thorough testing
If system blocks critical IPs:
# Windows (as Admin)
netsh advfirewall firewall delete rule name="NIPS_Block_*"
# Linux
sudo iptables -F
# Or via API
curl -X POST http://localhost:8000/nips/config/auto-block?enabled=falseSolution: Run as Administrator (Windows) or with sudo (Linux)
Solution:
# Check whitelist
curl http://localhost:8000/nips/blocked-ips
# Ensure your network is whitelisted:
# - Your PC IP
# - Router/gateway
# - DNS servers (8.8.8.8, 1.1.1.1)Solution:
- Windows: Install Npcap (check "WinPcap compatibility mode")
- Linux:
sudo apt-get install libpcap-dev - Verify interface name:
ipconfig(Windows) orifconfig(Linux)
Solution:
cd src
python train_real.py # Train new model- API Documentation - Interactive Swagger UI
- Architecture Guide - System design details
- Deployment Guide - Production deployment
- Training Guide - Model training procedures
This project demonstrates:
- Machine Learning: Ensemble methods, anomaly detection, feature engineering
- Network Security: Packet analysis, intrusion detection, threat prevention
- Backend Development: REST APIs, async programming, background tasks
- DevOps: Docker, containerization, monitoring, CI/CD
- System Programming: Firewall integration, OS-level operations
- Data Engineering: Real-time processing, time-series data
If you use this project in your research or publication, please cite:
@software{nids_nips_2024,
author = {Mohamed Rayen Malouche},
title = {Network Intrusion Detection and Prevention System},
year = {2024},
url = {https://github.com/yourusername/nids-system}
}Dataset Citation:
@article{moustafa2015unsw,
title={UNSW-NB15: a comprehensive data set for network intrusion detection systems},
author={Moustafa, Nour and Slay, Jill},
journal={2015 military communications and information systems conference (MilCIS)},
pages={1--6},
year={2015}
}Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see LICENSE file for details.
Mohamed Rayen Malouche
- Email: rayen.malouche@gmail.com
- GitHub: @RayenMalouche
- UNSW-NB15 Dataset providers
- Scapy development team
- FastAPI and React communities
- scikit-learn contributors
- β Detection (NIDS): Production-ready
- β Prevention (NIPS): Production-ready
- β ML Training: Completed (95%+ accuracy)
- β Docker Deployment: Tested
- β Documentation: Comprehensive
- π Cloud Deployment: In progress
- π Mobile App: Planned



