A real-time Web Application Firewall, Security Information & Event Manager, and Intrusion Detection System
DefendX is a lightweight, self-hosted security gateway that sits between your application and the outside world. It ingests every incoming HTTP request, runs it through 18 independent threat detectors (SQL injection, XSS, SSRF, command injection, XXE, and more), assigns a composite risk score, and takes graduated enforcement actions from silent logging to automatic IP bans. A built-in React dashboard provides real-time visibility into detections, incidents, blocked IPs, and traffic trends, so security operators can monitor and respond without leaving the browser.
The DefendX security dashboard real-time threat monitoring with interactive charts and drill-down detail.
- ๐ Features
- ๐ฏ All Detected Vulnerabilities
- ๐ Architecture
- ๐ฅ Demo
- ๐ Case Study
- โ๏ธ Installation
- ๐ Usage
- ๐ Project Structure
- โ Challenges & Solutions
- ๐ฎ Future Improvements
- ๐ Technologies Used
- ๐ License
- โ Disclaimer
- ๐ซ Contact
- 18 independent detectors running in sequence SQL injection, XSS, command injection, SSRF, XXE, LDAP injection, NoSQL injection, template injection, CRLF injection, open redirect, path traversal, sensitive file access, admin panel discovery, backup file discovery, config file discovery, cookie tampering, session abuse, and bot scanning
- Each detector inspects query parameters, request body, form data, headers, cookies, and URL path independently, flagging matches with field-level precision
- Pattern-based detection using 26+ regex signatures for SQL injection alone (UNION SELECT, SLEEP(), BENCHMARK(), extractvalue, updatexml, ORDER BY, stacked queries) and 30+ patterns for XSS (event handlers, data URIs, eval, document.cookie)
| # | Vulnerability | Category | Severity | Score |
|---|---|---|---|---|
| 1 | Command Injection | Injection Attacks | ๐ด Critical | 60 |
| 2 | SSRF (Server-Side Request Forgery) | Injection Attacks | ๐ด Critical | 60 |
| 3 | XXE (XML External Entity) | Injection Attacks | ๐ด Critical | 60 |
| 4 | Path Traversal | Path Analysis | ๐ด Critical | 50 |
| 5 | SQL Injection | Injection Attacks | ๐ด Critical | 50 |
| 6 | XSS (Cross-Site Scripting) | Injection Attacks | ๐ด Critical | 50 |
| 7 | LDAP Injection | Injection Attacks | ๐ด Critical | 50 |
| 8 | NoSQL Injection | Injection Attacks | ๐ด Critical | 50 |
| 9 | Template Injection (SSTI) | Injection Attacks | ๐ด Critical | 50 |
| 10 | Brute Force | Authentication Attacks | ๐ High | 40 |
| 11 | Credential Stuffing | Authentication Attacks | ๐ High | 40 |
| 12 | CRLF Injection | Injection Attacks | ๐ High | 40 |
| 13 | Open Redirect | Injection Attacks | ๐ High | 40 |
| 14 | Password Spraying | Authentication Attacks | ๐ High | 35 |
| 15 | Sensitive Files Access | Path Analysis | ๐ High | 30 |
| 16 | Session Abuse | Session & Cookie Attacks | ๐ High | 30 |
| 17 | Burst Traffic | Rate Limiting | ๐ High | 25 |
| 18 | Cookie Tampering | Session & Cookie Attacks | ๐ High | 25 |
| 19 | Account Enumeration | Authentication Attacks | ๐ก Medium | 30 |
| 20 | Admin Panel Discovery | Path Analysis | ๐ก Medium | 25 |
| 21 | Backup File Discovery | Path Analysis | ๐ก Medium | 25 |
| 22 | Configuration File Discovery | Path Analysis | ๐ก Medium | 25 |
| 23 | Suspicious User-Agent | Request Layer | ๐ก Medium | 20 |
| 24 | Rate Limit โ RPM | Rate Limiting | ๐ก Medium | 20 |
| 25 | Rate Limit โ RPS | Rate Limiting | ๐ก Medium | 20 |
| 26 | Suspicious Host Header | Request Layer | ๐ก Medium | 15 |
| 27 | Bot Scanning | Bot & Scanning | ๐ก Medium | 15 |
| 28 | Invalid HTTP Method | Request Layer | ๐ข Low | 10 |
| 29 | Large Request Size | Request Layer | ๐ข Low | 10 |
| 30 | Too Many Headers | Request Layer | ๐ข Low | 10 |
| 31 | Duplicate Headers | Request Layer | ๐ข Low | 10 |
| 32 | Missing User-Agent | Request Layer | ๐ข Low | 5 |
- All detector scores are summed into a single composite risk score per request
- A 5-tier action table maps scores to enforcement: log (0โ20), warning (21โ40), soft rate limit (41โ60), temporary ban (61โ80), permanent ban (81+)
- IP blocking uses escalating ban durations 10 minutes โ 1 hour โ 24 hours โ permanent after 4+ offenses
- Accumulated score threshold (100 points) triggers automatic blocking for repeat offenders even if individual requests score low
- Brute force detection flags IPs with 5+ login attempts within a 15-minute sliding window
- Credential stuffing detection triggers when the same IP hits 3+ different login paths with 10+ attempts
- Account enumeration detection identifies IPs probing multiple login endpoints with 3+ attempts across 2+ paths
- Password spraying detection catches slow-and-low attacks spread across 5+ minutes with 8+ attempts
- RPM threshold flags IPs exceeding 100 requests per minute
- RPS threshold flags IPs exceeding 20 requests per second
- Burst traffic detection catches 50+ requests in a single 1-second window
- In-memory sliding window counters with automatic cleanup every 60 seconds
- Real-time geolocation via ip-api.com resolves country and city for every request IP
- Private network detection automatically classifies RFC 1918 ranges (10.x, 172.16โ31.x, 192.168.x)
- IP statistics tracking total requests, failed/successful logins, cumulative risk score, total blocks, first/last seen timestamps
- Whitelist management trusted IPs bypass all analysis and logging entirely
- Overview page traffic & threat charts, top offending IPs, top attack types, recent detections
- Request Logs filterable, searchable archive with CSV export and drill-down detail modals
- Detections severity breakdown (critical/high/medium/low counts), detector-level filtering, search across IPs and paths
- Incidents security event log with severity, action taken, and resolution status
- Access Control IP ban management with manual block/unblock and block type selection
- Whitelist trusted node management with cross-list detection (auto-unblocks if an IP is both blocked and whitelisted)
- Security headers HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy, COOP, CORP, Origin-Agent-Cluster, CSP
- API key authentication all endpoints (except
/health) require adefendx-api-keyheader - Health check endpoint database connectivity monitoring with uptime reporting
- CORS enabled for frontend integration
- GSAP page transitions smooth entrance animations on route changes
- Mobile detection notice prompts desktop use for optimal experience
โโโโโโโโโโโโโโโโ
โ Client / โ
โ Reverse โ
โ Proxy โ
โโโโโโโโฌโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโ
โ Hono API โ
โ (Backend) โ
โ โ
โ Middleware: โ
โ โข CORS โ
โ โข Security โ
โ Headers โ
โ โข Logger โ
โ โข API Key โ
โ โข Error โ
โ Handler โ
โโโโโโโโฌโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโ
โ Request โ โ Geo โ โ Block โ
โ Processorโ โ Lookup โ โ Check โ
โโโโโโฌโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Detection Engine โ
โ (18 detectors) โ
โ โ
โ Request Layer โ
โ Rate Limiter โ
โ Auth Attacks โ
โ Path Analysis โ
โ SQL Injection โ
โ XSS โ
โ Command Injection โ
โ SSRF โ
โ LDAP Injection โ
โ NoSQL Injection โ
โ Template Injection โ
โ XXE โ
โ CRLF Injection โ
โ Open Redirect โ
โ Cookie Tampering โ
โ Session Abuse โ
โ Bot Scanning โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Risk Scorer โ
โ score โ action table โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Action Handler โ
โ โข log / warning โ
โ โข soft_rate_limit โ
โ โข temporary_ban โ
โ โข permanent_ban โ
โ โข IP stats update โ
โ โข Incident logging โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโ
โ PostgreSQL โ
โ (Drizzle) โ
โโโโโโโโโโโโโโโโ
A non-obvious design decision: the system uses in-memory sliding window counters for rate limiting rather than database-backed counters, trading persistence for sub-millisecond evaluation speed. Rate limit data is ephemeral and resets on server restart a deliberate choice since persistent rate limiting would require a Redis/Memcached dependency.
1. Submit a log entry:
curl -X POST http://localhost:3000/api/logs \
-H "Content-Type: application/json" \
-H "defendx-api-key: YOUR_API_KEY" \
-d '{
"ip": "192.168.1.100",
"method": "GET",
"path": "/admin",
"user_agent": "Mozilla/5.0",
"host": "example.com"
}'2. Submit an attack payload:
curl -X POST http://localhost:3000/api/logs \
-H "Content-Type: application/json" \
-H "defendx-api-key: YOUR_API_KEY" \
-d '{
"ip": "10.0.0.50",
"method": "POST",
"path": "/login",
"query_string": "user=admin%27+OR+1%3D1--",
"body": {"username": "admin' OR '1'='1"},
"user_agent": "sqlmap/1.0",
"host": "example.com"
}'3. Check the response:
{
"success": true,
"request_id": "...",
"risk_score": 90,
"action_taken": "temporary_ban",
"detections_count": 2,
"detections": [
{ "detector_name": "SQL Injection", "severity": "critical", "score": 50 },
{ "detector_name": "Suspicious User-Agent", "severity": "medium", "score": 20 }
]
}The case study covers the design and implementation of the multi-layer threat detection engine, the risk scoring model, and the graduated enforcement system.
- Node.js โฅ 20
- PostgreSQL โฅ 14
- npm โฅ 10
git clone https://github.com/usfa7med/DefendX.git
cd DefendXcd backend
npm installcd ../frontend
npm installcd ../backend
cp .env.example .envEdit backend/.env:
| Variable | Description | Example |
|---|---|---|
DATABASE_URL |
PostgreSQL connection string | postgresql://user:pass@localhost:5432/defendx |
PORT |
API server port | 3000 |
NODE_ENV |
Runtime environment | development |
DEFENDX_API_KEY |
API key for authentication | your-secret-key-here |
Edit frontend/.env:
| Variable | Description | Example |
|---|---|---|
VITE_DEFENDX_API_KEY |
API key (must match backend) | your-secret-key-here |
cd backend
npm run db:pushcd backend
npm run devThe server starts at http://localhost:3000 and displays a startup banner with the port and mode.
cd frontend
npm run devThe dashboard is available at http://localhost:5173.
cd backend && npm run build && npm start
cd frontend && npm run build && npm run preview- Open the dashboard at
http://localhost:5173 - The Overview page displays real-time traffic and threat data
- Use the Logs page to search, filter, and export request logs
- The Detections page shows all flagged threats with severity breakdown
- Use Access Control to manually block/unblock IPs
- Use Whitelist to exempt trusted IPs from analysis
DefendX/
โโโ backend/
โ โโโ drizzle.config.ts # Drizzle Kit configuration
โ โโโ package.json
โ โโโ tsconfig.json
โ โโโ src/
โ โโโ index.ts # Server entry point
โ โโโ app.ts # Hono app with middleware & routes
โ โโโ config/
โ โ โโโ index.ts # Environment variable loader
โ โ โโโ detectors.ts # Detector configurations & thresholds
โ โ โโโ protection.ts # IP protection rules, ban durations, exclusions
โ โโโ db/
โ โ โโโ index.ts # Drizzle client + PostgreSQL connection
โ โ โโโ schema.ts # Full database schema (10 tables)
โ โโโ engine/
โ โ โโโ processor.ts # Request processing pipeline
โ โ โโโ risk-scorer.ts # Score โ action mapping
โ โ โโโ action-handler.ts # Ban/whitelist/incident logic
โ โ โโโ detectors/ # 18 independent threat detectors
โ โ โโโ index.ts # Detector registry & runner
โ โ โโโ sql-injection.ts
โ โ โโโ xss.ts
โ โ โโโ command-injection.ts
โ โ โโโ ssrf.ts
โ โ โโโ path-analysis.ts
โ โ โโโ auth-attacks.ts
โ โ โโโ rate-limiter.ts
โ โ โโโ bot-scanning.ts
โ โ โโโ ... (8 more)
โ โโโ middleware/
โ โ โโโ api-key.ts # API key authentication
โ โ โโโ security-headers.ts # Security header injection
โ โ โโโ logger.ts # Request logging middleware
โ โ โโโ error-handler.ts # Global error handler
โ โโโ routes/
โ โ โโโ logs.ts # Log ingestion + retrieval + detail
โ โ โโโ detections.ts # Detection query + search
โ โ โโโ incidents.ts # Incident log
โ โ โโโ blocked-ips.ts # IP ban CRUD
โ โ โโโ whitelist.ts # Whitelist CRUD
โ โ โโโ stats.ts # Dashboard + aggregation endpoints
โ โ โโโ health.ts # Health check
โ โโโ utils/
โ โโโ types.ts # TypeScript interfaces
โ โโโ helpers.ts # ID generation, string parsing
โ โโโ ip-utils.ts # IP validation, CIDR matching, localhost detection
โ โโโ geo.ts # GeoIP lookup via ip-api.com
โโโ frontend/
โ โโโ vite.config.ts # Vite + React + TailwindCSS
โ โโโ index.html
โ โโโ src/
โ โโโ main.tsx # React entry point
โ โโโ App.tsx # Router, page transitions, mobile notice
โ โโโ index.css # TailwindCSS + custom theme
โ โโโ lib/
โ โ โโโ api.ts # Fetch wrapper with API key injection
โ โ โโโ utils.ts # cn(), formatNumber(), timeAgo()
โ โโโ types/
โ โ โโโ index.ts # Frontend TypeScript interfaces
โ โโโ components/
โ โ โโโ Layout.tsx # Sidebar + header + Outlet wrapper
โ โ โโโ StatsCard.tsx # Stats card with trend + sparkline
โ โ โโโ LogDetailModal.tsx # Portal-based log detail with tabs
โ โ โโโ ActionBadge.tsx # Action taken badge
โ โ โโโ SeverityBadge.tsx # Severity indicator badge
โ โ โโโ Pagination.tsx # Pagination controls
โ โ โโโ Table.tsx # Reusable table wrapper
โ โ โโโ ConfirmDialog.tsx # Confirmation dialog
โ โโโ pages/
โ โโโ Dashboard.tsx # Overview with charts, top IPs, attacks
โ โโโ Logs.tsx # Request log archive + filters
โ โโโ Detections.tsx # Detection list with severity counts
โ โโโ Incidents.tsx # Incident log
โ โโโ BlockedIPs.tsx # IP ban management
โ โโโ Whitelist.tsx # Trusted IP management
โ โโโ NotFound.tsx # 404 page
โโโ .gitignore
The risk scoring model needed to balance sensitivity (catching real threats) against false positives (legitimate requests flagged as malicious). A single high-scoring detector could trigger an aggressive ban on a mostly-clean request.
DefendX uses a cumulative scoring model where all detector scores are summed, combined with a 5-tier graduated enforcement table. This means a single low-confidence detection (score 10) logs quietly, while multiple overlapping detections escalate naturally. The system also maintains IP-level accumulated scores that trigger automatic bans only after repeated offenses preventing one-off false positives from causing permanent damage.
Rate limiting needs to evaluate hundreds of requests per second without adding database latency. Traditional database-backed rate limiters introduce query overhead that becomes a bottleneck under high traffic.
DefendX uses in-memory sliding window counters with Map<string, timestamps[]> structures for RPM, RPS, and burst detection. Entries are cleaned up on every evaluation (filtering expired timestamps) and periodically purged every 60 seconds. This keeps rate limit evaluation under sub-millisecond performance at the cost of ephemeral state acceptable for a single-instance WAF.
The frontend needed to display detailed log information (headers, cookies, fields, detections) without navigating away from the log list, and the data volume could be large (hundreds of fields per request).
A React Portal-based modal (LogDetailModal) renders outside the main layout with a tabbed interface (detections, headers, cookies, fields). This keeps the log table interactive while providing drill-down detail. The modal also includes a risk gauge SVG that visually represents the composite score with color-coded thresholds.
- Move rate limiting to Cloudflare Durable Objects or Redis for distributed, persistent rate limiting across multiple instances
- Add WebSocket support for real-time dashboard updates without polling
- Implement ML-based anomaly detection using historical request patterns to identify zero-day attack vectors
- Add webhook integrations to notify Slack, Discord, or email on critical detections
- Support IPv6 address range blocking and CIDR notation in the ban system
- Add custom detector plugins allow users to write and register their own detection rules via configuration
- Implement log retention policies with automatic archival and cleanup of old request data
- Add multi-tenant support with per-project API keys and isolated databases
- Runtime: Node.js 22, TypeScript 5.8
- Framework: Hono 4.7 (ultra-lightweight, edge-ready)
- Database: PostgreSQL 16, Drizzle ORM 0.44
- Validation: Native TypeScript type guards
- Framework: React 19, TypeScript 6.0
- Build Tool: Vite 8.1
- Styling: TailwindCSS 4.3, custom Material Design 3-inspired theme
- Charts: Recharts 3.9 (AreaChart for traffic trends)
- Animation: GSAP 3.15 (page transitions, brand animation)
- Icons: Lucide React 1.24, Phosphor Icons 2.1
- Database Driver: postgres.js 3.4
- GeoIP: ip-api.com (free, no API key required)
- Schema Migrations: Drizzle Kit 0.30
This project is licensed under the Educational / All Rights Reserved License. Unauthorized copying, redistribution, or commercial use is prohibited. See the LICENSE file for full details.
DefendX is provided strictly for educational and research purposes. It is not a production-grade WAF and should not be used as the sole security layer for any real-world application. The detection patterns are heuristic-based and may produce false positives or miss novel attack vectors. Users are solely responsible for any damage, data loss, or security incidents resulting from the use or misuse of this software. Always complement DefendX with a proven production WAF (e.g., Cloudflare, AWS WAF, ModSecurity) in any real deployment.
Youssef Ahmed Abdelfatah
๐ Portfolio https://usfahmed.dev
๐ป GitHub https://github.com/usfa7med
๐ผ LinkedIn https://linkedin.com/in/usfahmed
โ๏ธ Email hello@usfahmed.dev
