AI-Powered Web Attack Detection & Monitoring Dashboard
ThreatLens is a machine learning-based security monitoring system that detects and classifies web attacks in real-time. It uses a trained ML model to identify SQL Injection, XSS, Command Injection, and File Inclusion attacks with high accuracy.
- π€ ML-Powered Detection - Trained classifier using TF-IDF + LinearSVC
- π― Multi-Attack Classification - Detects SQLi, XSS, Command Injection, File Inclusion
- π Real-time Dashboard - Modern dark-themed UI with live monitoring
- π Analytics & Insights - Attack trends, patterns, and statistics
- π Sound Alerts - Audio notifications for detected attacks
- π₯ Export Logs - Download attack logs as CSV
- π³ Docker Ready - One-command deployment with Docker Compose
- π Easy Integration - Simple REST API for any web application
Main dashboard with attack statistics, recent activity, and threat distribution
Detailed attack logs with filtering, search, and export functionality
Visual analytics with charts showing attack patterns and trends
Real-time request monitoring with live updates and sound alerts
- Docker & Docker Compose
- Git
-
Clone the repository
git clone https://github.com/yassertioursi/ml-attack-detector.git cd threat-lens -
Start the containers
docker-compose up -d --build
-
Run database migrations
docker exec ml_laravel php artisan migrate -
Generate application key (first time only)
docker exec ml_laravel php artisan key:generate -
Access the dashboard
- Dashboard: http://localhost:8000/dashboard
- ML API: http://localhost:5000
| Service | Port | Description |
|---|---|---|
| Dashboard | 8000 | Laravel + React web interface |
| ML API | 5000 | FastAPI prediction endpoint |
| PostgreSQL | 5432 | Database for attack logs |
docker-compose downTo remove all data (including database):
docker-compose down -v- Dashboard - Overview of attack statistics and recent activity
- Attack Logs - Browse, filter, and export all logged requests
- Analytics - Visual charts and attack pattern analysis
- Live Monitor - Real-time request feed with sound alerts
Send test payloads to see the detection in action:
# SQL Injection
curl -X POST http://localhost:8000/api/logs \
-H "Content-Type: application/json" \
-d '{"payload": "SELECT * FROM users WHERE id=1 OR 1=1--"}'
# XSS Attack
curl -X POST http://localhost:8000/api/logs \
-H "Content-Type: application/json" \
-d '{"payload": "<script>alert(document.cookie)</script>"}'
# Command Injection
curl -X POST http://localhost:8000/api/logs \
-H "Content-Type: application/json" \
-d '{"payload": "; cat /etc/passwd"}'
# File Inclusion
curl -X POST http://localhost:8000/api/logs \
-H "Content-Type: application/json" \
-d '{"payload": "../../etc/passwd"}'
# Benign Request
curl -X POST http://localhost:8000/api/logs \
-H "Content-Type: application/json" \
-d '{"payload": "user@example.com"}'{
"id": 1,
"type": "sqli",
"confidence": 0.95,
"is_attack": true
}| Type | Description |
|---|---|
benign |
Safe, non-malicious request |
sqli |
SQL Injection attempt |
xss |
Cross-Site Scripting |
cmdi |
Command Injection |
file_inclusion |
Local/Remote File Inclusion |
Integrate ThreatLens with any web application to monitor and detect attacks in real-time.
POST http://localhost:8000/api/logs
Content-Type: application/json
{
"payload": "user input to analyze",
"source_ip": "192.168.1.1" // optional
}
POST http://localhost:5000/predict
Content-Type: application/json
{
"payload": "user input to analyze"
}
@Service
public class ThreatLensService {
private final RestTemplate restTemplate;
private final String threatLensUrl = "http://localhost:8000/api/logs";
public ThreatLensService(RestTemplateBuilder builder) {
this.restTemplate = builder
.setConnectTimeout(Duration.ofSeconds(2))
.setReadTimeout(Duration.ofSeconds(2))
.build();
}
@Async
public CompletableFuture<Void> analyzeRequest(String payload, String sourceIp) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> body = new HashMap<>();
body.put("payload", payload);
body.put("source_ip", sourceIp);
HttpEntity<Map<String, String>> request = new HttpEntity<>(body, headers);
restTemplate.postForObject(threatLensUrl, request, String.class);
} catch (Exception e) {
log.warn("ThreatLens analysis failed: {}", e.getMessage());
}
return CompletableFuture.completedFuture(null);
}
}
// Filter to intercept requests
@Component
public class ThreatLensFilter implements Filter {
@Autowired
private ThreatLensService threatLensService;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Collect data to analyze
String queryString = httpRequest.getQueryString();
String sourceIp = httpRequest.getRemoteAddr();
// Send async (non-blocking)
if (queryString != null) {
threatLensService.analyzeRequest(queryString, sourceIp);
}
chain.doFilter(request, response);
}
}const axios = require('axios');
const THREAT_LENS_URL = 'http://localhost:8000/api/logs';
// Middleware for Express
const threatLensMiddleware = (req, res, next) => {
const payload = req.originalUrl + JSON.stringify(req.body || {});
const sourceIp = req.ip || req.connection.remoteAddress;
// Non-blocking async call
axios.post(THREAT_LENS_URL, {
payload: payload,
source_ip: sourceIp
}, { timeout: 2000 })
.catch(err => console.log('ThreatLens error:', err.message));
next();
};
// Usage
app.use(threatLensMiddleware);import requests
from django.utils.deprecation import MiddlewareMixin
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=2)
THREAT_LENS_URL = 'http://localhost:8000/api/logs'
def send_to_threatlens(payload, source_ip):
try:
requests.post(THREAT_LENS_URL, json={
'payload': payload,
'source_ip': source_ip
}, timeout=2)
except Exception as e:
print(f'ThreatLens error: {e}')
class ThreatLensMiddleware(MiddlewareMixin):
def process_request(self, request):
payload = request.get_full_path()
source_ip = request.META.get('REMOTE_ADDR', '')
# Non-blocking
executor.submit(send_to_threatlens, payload, source_ip)
return NoneAdd to settings.py:
MIDDLEWARE = [
'yourapp.middleware.ThreatLensMiddleware',
# ... other middleware
]import requests
from flask import Flask, request, g
from concurrent.futures import ThreadPoolExecutor
app = Flask(__name__)
executor = ThreadPoolExecutor(max_workers=2)
THREAT_LENS_URL = 'http://localhost:8000/api/logs'
def send_to_threatlens(payload, source_ip):
try:
requests.post(THREAT_LENS_URL, json={
'payload': payload,
'source_ip': source_ip
}, timeout=2)
except:
pass
@app.before_request
def analyze_request():
payload = request.full_path + (request.data.decode() if request.data else '')
executor.submit(send_to_threatlens, payload, request.remote_addr)<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ThreatLensMiddleware
{
public function handle(Request $request, Closure $next)
{
// Non-blocking async call
dispatch(function () use ($request) {
try {
Http::timeout(2)->post('http://localhost:8000/api/logs', [
'payload' => $request->fullUrl() . json_encode($request->all()),
'source_ip' => $request->ip(),
]);
} catch (\Exception $e) {
\Log::warning('ThreatLens error: ' . $e->getMessage());
}
})->afterResponse();
return $next($request);
}
}Register in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\ThreatLensMiddleware::class,
// ...
];If your application runs in Docker, add it to the same network:
# your-app/docker-compose.yml
services:
your-app:
build: .
networks:
- threat_lens_default
environment:
- THREAT_LENS_URL=http://ml_laravel:80/api/logs
networks:
threat_lens_default:
external: trueβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Your Web Application β
β (Spring Boot, Express, Django, etc.) β
βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β POST /api/logs
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ThreatLens β
β βββββββββββββββ βββββββββββββββ βββββββββββββββββββββββ β
β β Laravel βββββΆβ ML API β β PostgreSQL β β
β β Dashboard β β (FastAPI) β β (Attack Logs) β β
β β Port 8000 β β Port 5000 β β Port 5432 β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The attack classifier is trained using:
- Algorithm: LinearSVC with TF-IDF vectorization
- Features: Character-level n-grams (1-3)
- Classes: benign, sqli, xss, cmdi, file_inclusion
- Confidence: Softmax-normalized decision function scores
cd ml_api
python train_attack_classifier.pythreat_lens/
βββ docker-compose.yml # Docker orchestration
βββ ml_api/ # ML prediction service
β βββ app.py # FastAPI application
β βββ train_attack_classifier.py
β βββ attack_classifier.pkl # Trained model
β βββ tfidf_vectorizer.pkl # TF-IDF vectorizer
β βββ Dockerfile
βββ ml_dashboard/ # Web dashboard
β βββ app/
β β βββ Http/Controllers/ # API & page controllers
β β βββ Services/ # Attack detection service
β βββ resources/js/ # React components
β β βββ pages/dashboard/ # Dashboard pages
β β βββ components/ # Reusable components
β βββ routes/
β β βββ web.php # Web routes
β β βββ api.php # API routes
β βββ Dockerfile
βββ screenshots/ # Documentation images
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- scikit-learn - Machine learning library
- FastAPI - Modern Python web framework
- Laravel - PHP web framework
- Inertia.js - Modern monolith architecture
- Recharts - React charting library
- Tailwind CSS - Utility-first CSS framework
Made with β€οΈ by Yasser Tioursi for web security
