PHAROX SECURITY
AI-Assisted Ethical Penetration Testing and Vulnerability Intelligence Platform
An enterprise-grade, offensive security architecture integrating high-speed asynchronous network reconnaissance, multi-scanner vulnerability discovery, graph-based attack path modeling, and Scikit-learn Random Forest intelligence to empower penetration testers and vulnerability researchers.
Executive Summary & Scope
Executive Summary
PHAROX Security is an AI-assisted ethical penetration testing and vulnerability intelligence platform engineered by Khaled Hani. It unifies high-speed asynchronous network reconnaissance, multi-engine vulnerability scanning, graph-based attack path modeling, and machine-learning risk scoring into a coherent offensive security workstation.
Designed to address the operational friction of modern security audits, PHAROX automates repetitive reconnaissance tasks without flooding target networks or producing unverified alerts. It transforms isolated finding dumps from tools like Nmap, OpenVAS, Nikto, and OWASP ZAP into actionable, graph-correlated compromise vectors.
Problem Statement
During contemporary penetration testing and red-teaming engagements, ethical hackers and security researchers face four chronic bottlenecks:
- Severe Reconnaissance Latency: Traditional scanning scripts operate sequentially, resulting in hour-long delays across large /24 subnets.
- Disjointed Tooling Silos: Results from port scanners, web application fuzzers, and network scanners remain isolated in disparate XML or JSON files, requiring tedious manual correlation.
- Alert Fatigue & Flat CVSS Lists: Standard vulnerability scanners report flat lists of CVEs based solely on base scores, failing to convey whether a vulnerability is actually reachable from external ingress.
- Operational Production Risks: Unthrottled multi-threaded scans frequently trigger target firewall rate-limits or cause denial-of-service disruptions on client assets.
Project Objectives
Build an epoll/asyncio non-blocking socket pool capable of enumerating thousands of ports across /24 subnets in seconds while bounding system file descriptors to 1,024 handles.
Deploy Neo4j to model hosts, ports, exposed services, and discovered CVEs as interconnected graph nodes, allowing Cypher algorithms to compute multi-hop lateral movement chains.
Train an ensemble Random Forest model with TF-IDF text vectorization on curated NVD CVE descriptions to contextualize exploitability beyond static CVSS base scores.
Map all findings directly to MITRE ATT&CK techniques, OWASP Top 10 vulnerabilities, and NIST SP 800-115 testing phases with automated Markdown/PDF report exports.
System Overview
PHAROX Security functions as a modular offensive security ecosystem. An operator submits a target IP, CIDR block, or domain through the React/Tailwind frontend. The FastAPI backend validates scope and permissions, enqueues the engagement into background workers, and orchestrates the security pipeline.
Raw outputs from reconnaissance and vulnerability scans are ingested, normalized into a unified intermediate JSON schema, and persisted simultaneously into PostgreSQL (for transactional history) and Neo4j (for attack graph traversal). In parallel, the Scikit-learn Random Forest model scores each finding's true exploitability based on advisory text and runtime factors.
Architecture & Technologies
System Architecture
The diagram below illustrates PHAROX Security's decoupled modular architecture across presentation, API gateway, async orchestration, dual persistence stores, and machine learning intelligence.
+---------------------------------------------------------------------------------------------------+
| PHAROX SECURITY PLATFORM |
+---------------------------------------------------------------------------------------------------+
|
+--------------------------------------+--------------------------------------+
| |
v v
+-----------------------------+ +---------------------+
| REACT / TAILWIND | <=== Secure WebSocket & REST (OpenAPI 3.0) ===> | FASTAPI ASGI CORE |
| - Chart.js Telemetry Matrix | | - Auth (JWT/Argon2) |
| - Attack Graph Explorer | | - RBAC Guard |
| - Markdown Report Engine | | - Task Orchestrator |
+-----------------------------+ +---------------------+
|
v
+-------------------------------------+
| ASYNC SCAN PIPELINE WORKERS |
| - AsyncIO Port Sweeper (1024 pools) |
| - Nmap Engine (NSE Script Engine) |
| - OpenVAS GMP Integration |
| - OWASP ZAP & Nikto HTTP Engines |
+-------------------------------------+
|
+----------------------------------------------------+
| |
v v
+-----------------------------+ +-----------------------------+
| POSTGRESQL RELATIONAL DB | | NEO4J GRAPH DATABASE |
| - Target Scope & Audit Logs | | - Asset & Service Topology |
| - Normalized CVE Inventory | | - Lateral Movement Hops |
| - User Profiles & Projects | | - Cypher Attack Paths |
+-----------------------------+ +-----------------------------+
| |
+----------------------+-----------------------------+
|
v
+-----------------------------+
| RANDOM FOREST ML ENGINE |
| - TfidfVectorizer (N-grams) |
| - 150 Decision Trees |
| - Exploitability Scoring |
+-----------------------------+Frontend Architecture
The client tier is built with React, Tailwind CSS, and Framer Motion. It provides a dark cyber visual theme engineered specifically for security practitioners:
- State Management & Streaming: Uses React hooks with debounced WebSocket listeners to ingest thousands of real-time socket events without UI frame drops.
- Chart.js Telemetry: Renders CVSS score distributions, port distribution radar charts, and temporal scan velocity graphs.
- Virtualized Scanners: High-density tables render thousands of open ports and CVE hits using virtual windowing.
Backend Architecture
The backend is built with FastAPI (Python 3.11+). FastAPI was selected for its native asynchronous event loop (uvloop), strict Pydantic request/response validation schemas, and automated OpenAPI 3.0 documentation.
Heavy network scans and vulnerability audits execute via asynchronous coroutines and non-blocking background workers, ensuring the API server remains responsive to telemetry requests even during massive CIDR sweeps.
Database Architecture
PHAROX uses a dual-database pattern: PostgreSQL manages ACID transactional data, and Neo4j handles interconnected attack topology.
Stores structured tables: Users, Engagements, Targets, Scans, DiscoveredPorts, Vulnerabilities, and AuditLogs.
Stores network graph topology: Nodes (:Host, :Service, :Vulnerability, :Credential) and Edges (:EXPOSES, :PERMITS_LATERAL).
Graph Database & Attack Path Architecture
Traditional vulnerability scanners treat findings as flat disconnected records. In contrast, PHAROX represents the target environment as an attack graph in Neo4j. This allows security engineers to calculate the shortest path to critical crown jewels and evaluate lateral movement vectors.
1234567891011// Identify multi-hop privilege escalation and lateral movement attack pathsMATCH path = (origin:Host {is_exposed: true})-[:RUNS_SERVICE]->(svc:Service)-[:HAS_VULNERABILITY]->(vuln:Vulnerability {severity: "CRITICAL"})-[:ALLOWS_ACCESS]->(priv:Credential)-[:PERMITS_LATERAL]->(target:Host {is_critical_asset: true})WHERE vuln.cvss >= 9.0 AND vuln.has_public_exploit = trueRETURN path,reduce(risk = 0.0, n IN nodes(path) | risk + coalesce(n.cvss, 1.0)) AS PathCumulativeRiskORDER BY PathCumulativeRisk DESCLIMIT 5;
Technology Stack Matrix
| Layer / Component | Technology Selected | Technical Rationale |
|---|---|---|
| Frontend Tier | React 19, Tailwind CSS, Framer Motion | Responsive cyber digital HQ, sub-millisecond DOM updates, fluid layout |
| Data Telemetry | Chart.js & Native SVG Canvas | Real-time attack surface metrics, radar charts, and CVSS histogram bins |
| Backend API | FastAPI (Python 3.11+), AsyncIO, Uvicorn | Asynchronous epoll socket handling, Pydantic type safety, high I/O throughput |
| Primary Database | PostgreSQL 16 & Prisma ORM | Strict relational integrity, audit trails, and historical engagement tracking |
| Graph Database | Neo4j Community 5.x & Cypher | Graph traversal, attack blast radius modeling, Dijkstra shortest-path calculations |
| Machine Learning | Scikit-learn, Random Forest, TF-IDF | Advisory text classification, exploitability weighting, zero cloud dependencies |
| Security Scanners | Nmap, OpenVAS, Nikto, OWASP ZAP | Industry standard network, web server, and application discovery engines |
API Architecture & Endpoints
The API adheres to RESTful OpenAPI 3.0 conventions with asynchronous BackgroundTask dispatches. Security scans are initiated with HTTP 202 Accepted tokens, allowing clients to stream updates over WebSockets without holding HTTP connections open.
123456789101112131415161718192021222324252627282930313233from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, statusfrom pydantic import BaseModel, IPvAnyAddressfrom typing import Listfrom core.auth import get_current_active_user, require_rolerouter = APIRouter(prefix="/scans", tags=["Scan Orchestration"])class ScanRequest(BaseModel):target: strtarget_cidr: str | None = Noneprofile: str = "comprehensive_recon"ports: List[int] = [21, 22, 25, 80, 443, 3306, 5432, 8080, 8443]@router.post("/dispatch", status_code=status.HTTP_202_ACCEPTED)async def dispatch_security_scan(payload: ScanRequest,background_tasks: BackgroundTasks,user = Depends(require_role(["Lead_Tester", "Security_Admin"]))):"""Enqueues multi-stage security pipeline: Recon -> OpenVAS -> ZAP -> Graph Ingest."""scan_id = generate_cryptographic_uuid()background_tasks.add_task(execute_orchestration_pipeline,scan_id=scan_id,target=payload.target,profile=payload.profile,operator_id=user.id)return {"scan_id": scan_id,"status": "QUEUED","message": "Scan pipeline safely dispatched with non-intrusive rate limits."}
Authentication Architecture
Stateless JWT authentication with short-lived access tokens (15-minute expiry) signed with RS256 private keys, coupled with encrypted HTTP-only refresh tokens stored in PostgreSQL. Passwords hashed using Argon2id with memory-hard parameters.
Role-Based Access Control (RBAC)
Granular permissions mapped across four functional roles: Security_Admin (full management), Lead_Tester (scan dispatch & exploitation), Auditor_Readonly (compliance review), and Client_Stakeholder (executive report viewing only).
Enforces relational integrity across multi-tenant engagements, stores JSONB vulnerability payloads, and maintains immutable audit logs for compliance audits.
Executes sub-second Cypher traversals to identify reachability, crown-jewel blast radius, and privilege escalation vectors across interconnected network entities.
Provides modular, reusable interface components with virtualized tables capable of rendering 10,000+ scan records without browser rendering latency.
Python ASGI core operating with non-blocking coroutines, asynchronous subprocess management, and automatic OpenAPI validation schemas.
Security Pipeline & Tooling
Multi-Stage Security Pipeline
The PHAROX scanning lifecycle operates through five distinct phases to maintain operational security, prevent target disruption, and guarantee verifiable findings:
Reconnaissance Subsystem
Reconnaissance combines passive DNS resolution, reverse PTR lookups, and an asynchronous TCP banner grabber. Using Python's asyncio.open_connection with an adaptive semaphore, it probes target ports without incurring process fork overhead.
123456789101112131415161718192021222324252627282930313233343536import asyncioimport socketfrom typing import Dict, Any, Listclass AsyncPortScanner:"""Non-blocking TCP banner enumerator with concurrency rate-limiting."""def __init__(self, max_concurrency: int = 1024, timeout: float = 1.2):self.semaphore = asyncio.Semaphore(max_concurrency)self.timeout = timeoutasync def scan_port(self, target_ip: str, port: int) -> Dict[str, Any]:async with self.semaphore:conn = asyncio.open_connection(target_ip, port)try:reader, writer = await asyncio.wait_for(conn, timeout=self.timeout)banner = b""try:# Attempt safe banner capturebanner = await asyncio.wait_for(reader.read(512), timeout=0.6)except asyncio.TimeoutError:passwriter.close()await writer.wait_closed()return {"port": port,"state": "open","protocol": "tcp","banner": banner.decode("utf-8", errors="ignore").strip()}except (asyncio.TimeoutError, ConnectionRefusedError, OSError):return {"port": port, "state": "closed", "banner": ""}async def run_scan(self, target_ip: str, ports: List[int]) -> List[Dict[str, Any]]:tasks = [self.scan_port(target_ip, p) for p in ports]results = await asyncio.gather(*tasks)return [r for r in results if r["state"] == "open"]
Vulnerability Discovery
Orchestrates active probes tailored to discovered services. Network services trigger Nmap NSE and OpenVAS audits, while HTTP/HTTPS services trigger Nikto server configuration audits and OWASP ZAP active application spidering.
Vulnerability Analysis
Normalizes disparate findings into a standardized intermediate schema, deduplicating identical CVE records across multiple scanners and attributing verified Common Weakness Enumeration (CWE) categories.
CVSS v3.1 Risk Analysis Engine
PHAROX computes full CVSS v3.1 qualitative equations rather than relying merely on static third-party ratings:
- Base Metrics: Attack Vector (Network, Adjacent, Local, Physical), Attack Complexity, Privileges Required, User Interaction, Scope, and Confidentiality / Integrity / Availability impacts.
- Temporal Metrics: Dynamically adjusted using Exploit Code Maturity (E:U, E:P, E:F, E:H) from active CISA KEV and Exploit-DB feeds.
- Environmental Overrides: Adjusted based on network segmentation and crown-jewel asset criticality defined in the target scope.
Security Tools Orchestration (36-39)
Orchestrates Nmap with custom NSE scripts via non-blocking subprocess pipes, capturing XML output for service fingerprinting and SSL/TLS cipher suite evaluations.
Integrates with the Greenbone Management Protocol (GMP) daemon to dispatch deep unauthenticated and authenticated host vulnerability assessments against enterprise assets.
Targeted HTTP server scanner inspecting over 6,700 potentially dangerous files/programs, outdated web server software versions, and security header misconfigurations.
Automates dynamic application security testing (DAST) via the ZAP Python API client, executing active spidering, CSRF detection, and SQLi / XSS injection checks.
AI & Machine Learning Risk Engine
AI-Assisted Risk Analysis
Traditional CVSS ratings are purely static: a vulnerability discovered on an isolated internal development machine receives the exact same score as one exposed directly to the public internet.
PHAROX introduces an AI-assisted vulnerability triage model that combines textual analysis of vulnerability disclosures with runtime topological parameters (exposure state, service criticality, and port accessibility) to score actionable risk.
Random Forest Vulnerability Risk ClassifierScikit-learn Pipeline
NLP Feature Extraction (TF-IDF) + Ensemble Random Forest for Contextual Exploitability & Severity Classification.
| Class (Severity) | Precision | Recall | F1-Score | Support (Test Samples) |
|---|---|---|---|---|
| LOW | 0.93 | 0.91 | 0.92 | 340 |
| MEDIUM | 0.89 | 0.88 | 0.88 | 620 |
| HIGH | 0.88 | 0.87 | 0.87 | 410 |
| CRITICAL | 0.92 | 0.89 | 0.90 | 180 |
123456789101112131415161718192021222324252627282930313233343536373839404142import numpy as npfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import classification_reportclass VulnerabilityRiskIntelligence:"""AI-Assisted Severity & Exploitability Prioritizer."""def __init__(self):self.pipeline = Pipeline([('tfidf', TfidfVectorizer(max_features=4000,ngram_range=(1, 2),stop_words='english',sublinear_tf=True)),('clf', RandomForestClassifier(n_estimators=150,max_depth=25,class_weight='balanced',random_state=42,n_jobs=-1))])def train(self, texts: list[str], labels: list[int]):"""Trains on curated CVE descriptions and advisory text."""self.pipeline.fit(texts, labels)def predict_risk(self, advisory_text: str) -> dict:probs = self.pipeline.predict_proba([advisory_text])[0]predicted_class = int(np.argmax(probs))confidence = float(np.max(probs))severity_map = {0: "LOW", 1: "MEDIUM", 2: "HIGH", 3: "CRITICAL"}return {"predicted_severity": severity_map.get(predicted_class, "UNKNOWN"),"confidence_score": round(confidence, 4),"class_probabilities": {severity_map[i]: round(float(probs[i]), 4) for i in range(len(probs))}}
Frameworks, Threat Intelligence & Attack Paths
MITRE ATT&CK Enterprise Matrix Mapping
Every automated probe and finding is categorized against specific MITRE ATT&CK tactics and techniques:
Automated network sweeps, IP range enumeration, and port scanning via async coroutines.
Attributing critical CVEs identified on exposed DMZ ports and web application endpoints.
Extracting service banners, TLS handshakes, and application layer protocol signatures.
Modeling reachable hops across internal network segments in the Neo4j graph topology.
Identifying leaked configuration files, exposed .env variables, and default database secrets.
Detecting remote code execution (RCE) vectors and command injection endpoints.
OWASP Top 10 (2021) Mapping
Direct attribution against OWASP categories: A01 Broken Access Control (IDOR detection via ZAP), A03 Injection (SQLi & command injection), A05 Security Misconfiguration (Nikto server headers), and A06 Outdated Components (NVD CVE correlation).
NIST SP 800-115 Alignment
Complies with NIST Information Security Assessment guidelines across all testing phases: Planning Phase (strict scoping guards), Discovery Phase (asynchronous port sweeps), Attack Phase (safe PoC validation), and Reporting Phase (reproducible vulnerability documentation).
Threat Intelligence Feeds
PHAROX aggregates real-time intelligence feeds to contextualize whether discovered vulnerabilities are being actively exploited in the wild:
- NVD JSON 2.0 API: Continuous ingestion of official NIST National Vulnerability Database CVE records and CVSS vectors.
- CISA KEV Catalog: Live correlation against the Cybersecurity and Infrastructure Security Agency Known Exploited Vulnerabilities catalog.
- EPSS (Exploit Prediction Scoring System): Real-time probability ratings indicating the likelihood of active exploitation within 30 days.
Attack Path Visualization Engine
Neo4j Lateral Movement Path SimulationActive Cypher Traversal
Click any node in the attack chain below to inspect Neo4j node properties and graph traversal vectors.
Unauthenticated Remote Code Execution in legacy serialization endpoint.
Automated Reporting Engine
Manual reporting consumes hours of consultant time. PHAROX generates standardized reports formatted for both executive and engineering audiences:
High-level threat scorecards, overall risk posture, critical risk heatmaps, and business impact summaries for C-level leadership.
Reproducible HTTP requests, cURL commands, proof-of-concept steps, CVSS vectors, and developer remediation guidelines.
Project Screenshots & Telemetry
Project Screenshots & Telemetry
Retrospective & Engineering Roadmap
Engineering Challenges
- Socket File Descriptor Limits: Unbounded asyncio coroutines quickly exhausted the OS
ulimit -nlimit when scanning large CIDR blocks. - False-Positive Deceptive Banners: CDN edge catch-alls and web honeypots caused heuristic CVE over-attribution.
- Browser Telemetry Overload: Streaming raw socket events caused UI thread starvation in React.
Implemented Solutions
- Adaptive Concurrency Semaphore: Built an async sliding-window queue capping concurrent descriptors strictly at 1,024 handles.
- Dual-Phase Validation Probes: Implemented active follow-up HTTP/TLS verification to filter out dummy CDN headers before staging CVEs.
- Debounced WebSocket Batching: Ingests socket events into a 150ms buffer, dispatching batched updates to the React virtual DOM.
Lessons Learned
1. Graph context beats flat vulnerability lists: Security teams do not need 500 disconnected CVSS warnings; they need to know which three hops allow an external attacker to pivot to database credentials.
2. AI must be bounded by deterministic validation: In offensive security, unconstrained LLM hallucinations can cause false reports. Using bounded Scikit-learn pipelines with TF-IDF provides auditable, deterministic probability distributions.
3. Rate-limiting is an offensive security discipline: An aggressive, unthrottled scan is a failed assessment. Respecting client network stability through intelligent pacing is paramount.
Future Improvements & Planned Features
Distribute scanning nodes across multiple geo-distributed VPS nodes orchestrated via Redis queues.
Automated Kerberoasting and BloodHound-style domain privilege escalation path modeling.
One-click re-testing harnesses allowing developers to verify whether patches resolved findings.
GitHub Repository
Explore core source modules, architecture documentation, CLI utilities, and Docker Compose configurations on GitHub.
Live Demo & Sandbox
Interactive sandbox instances and live technical walkthroughs are available for security recruiters, research reviewers, and prospective clients upon request.