AIWAF-PHP Architecture Deep Dive
Source and package versions
One AIWAF repository.
Python: py/aiwaf/ · Node.js: js/ · Rust/WASM: rust/ · Java: java/.
Source and canonical README.
Versions shown describe the source checkout; package releases are independent.
Current Python/Node source targets are aiwaf 1.1.8 (Python) and
aiwaf 1.1.5 (npm), with Rust/Python 0.2.7 and
WASM 0.2.5 and Java 1.3.5. Sandbox guides retain their separately pinned builds.
How AIWAF works: system architecture
1-4. Purpose, Snapshot, Structure, Architecture
- Package:
aayushgauba/aiwaf, Composer library, PHP>=7.4. - Primary runtime entry:
AIWAF::protect(); training entry:cli/detect_and_train.php. - Top-level focus:
src/,src/Core/,src/Adapters/,src/RateLimit/,resources/,tests/. - Design traits: defense-in-depth, exemption-first, conservative AI guardrails, flexible persistence backends.
5. Runtime Entry And Integration Surface
Primary API (src/AIWAF.php)
AIWAF::protect()executes per-request security controls.AIWAF::setPathExistsResolver()enables route-awareness for framework integrations.AIWAF::setMiddlewareDecisionResolver()supports custom middleware gating logic.AIWAF::getLastTrainingTelemetry()exposes latest trainer telemetry snapshot.
Typical Bootstrap
- Load Composer autoload.
- Initialize selected rate-limit adapter.
- Call
AIWAF::protect()early in front-controller lifecycle.
6. Request Protection Flow (AIWAF::protect)
- Build runtime config via
Config::toRuntimeConfig(). - Configure rate limiter via
configureRateLimiter()(auto-detects db, apcu, redis, or falls back to memory). - Resolve request identity (
ip,path). - Exemption short-circuit (skips remaining checks if IP or Path is exempt via configurations or CIDR matches).
- Method validation (ensures request method is allowed).
- Header validation (evaluates
trust_legitimate_bots,custom_suspicious_patterns, andquality_threshold). - Blocked-IP enforcement.
- Geo policy checks (compares IP against allow/block countries).
- AI Anomaly Scoring: Extracts an 8-dimensional feature vector:
strlen($path)DynamicKeywordManager::detect($path)0.5(baseline structural complexity)- Status code anomaly (
1if 404/500, else0) - Reserved (
0) - Reserved (
0) - Honeypot trigger (
isset($_POST['aiwaf_honeytrap']) ? 1 : 0) - UUID tamper check (
UUIDTamperProtector::isSuspicious($path) ? 1 : 0)
forest_model.json. If score exceeds threshold, it runs a post-prediction guard ensuring at least one strong signal (e.g., keyword hits ≥ 2.0 or direct honeypot/UUID triggers) before blocking. - Rate-limit enforcement (checks
max_requestsperwindow_seconds). - Dynamic keyword checks.
- UUID tamper checks.
- Honeypot checks (evaluates
$_POSTpayloads).
Block responses use 403 for deny cases and 429 for rate-limit violations.
AST Static Analysis (src/Core/ApiDetection.php)
PHP dynamically analyzes controller logic during startup using Abstract Syntax Trees to determine endpoint intent (API vs. Form vs. Auth). This is heavily utilized when native framework routes don't strictly typehint their return models.
- Parsing: Uses
nikic/php-parser(PhpParser\ParserFactory) to construct an AST directly from the controller's source file, using reflection (ReflectionMethod,ReflectionFunction) to locate the exact start and end lines of the closure or method. - Traversal: A custom
NodeVisitorAbstracttraverses the statements strictly within the bounded line numbers. - Call Inspection: Inspects
MethodCall,FuncCall, andStaticCallnodes.- Increases API confidence if it detects
json,json_encode,JsonResponse, orjsonify. - Increases Form confidence if it detects
view,render,redirect,back, orrender_template.
- Increases API confidence if it detects
- Object Instantiation: Inspects
New_nodes. InstantiatingJsonResponseyields a high API score. - Payload Type: Scans for
post,all,input, orfilemethod calls on request objects to flagrequestBody = trueand classify the expected payload.
Path Generation and Auto Middleware (MiddlewarePlan.php)
AIWAF for PHP includes intelligent path generation and middleware auto-negotiation to dynamically optimize the protection pipeline per endpoint:
- Route Classification (
PathManifest::classifyRoute): The manifest generator infers the primary intent of any given route, categorizing paths asapi,form,admin,upload,static, orauth. - Auto Middleware Planning: Based on the route classification, the engine automatically toggles specific middlewares on or off. For example:
- API Endpoints: Disables HTML Honeypots, enforces strict JSON payload validation, and allocates a high rate-limit ceiling (120 req/min).
- Form Endpoints: Enables Honeypot validation, sets strict rate limits (30 req/min), and enforces POST payload sizes.
- Static Assets: Automatically disables AI Anomaly scoring, Honeypots, and Header Validation to drastically reduce CPU overhead on
/static/or.pngroutes.
- Config Sentinels: If
requested_middlewaresis set to['auto'],MiddlewarePlan::planEnabledMiddlewares()dynamically strips out unnecessary middlewares (e.g., completely unloadinguuid_tamperif no UUIDs exist, or disablinggeo_blockif the MMDB isn't configured).
Deep Dive: Core Functions and Methods
A reference of the core internal functions powering the PHP AIWAF engine.
| Module / Class | Function / Method | Description |
|---|---|---|
AIWAF.phpAIWAF | protect() | The primary execution gate. Iterates through the resolved middleware plan, terminating the request with a 403 or 429 payload if any middleware rejects. |
PathManifest.phpPathManifest | classifyRoute($path, $methods) | Matches standard heuristic signatures (e.g., /api/* or /login) and combines them with AST outputs to bin the route type. |
ApiDetection.phpRouteVisitor | enterNode(Node $node) | Implements PhpParser\NodeVisitorAbstract to inspect method calls like json() or validate() to build confidence scores for API intents. |
MiddlewarePlan.phpMiddlewarePlan | resolve($path, $category) | Yields the final array of active middlewares. Trims expensive operations (like HTML honing) when $category === 'api'. |
detect_and_train.php(CLI Script) | extractFeatures($logLine) | Parses a line of access logs into the 6-dimension float array needed for training the Isolation Forest. |
detect_and_train.php(CLI Script) | calculateThresholds() | Evaluates historical traffic baselines to automatically tune max_req and flood_req dynamically. |
7. Core Modules Responsibility Map
src/
AIWAF.php,Config.php,Utils.phpRateLimiter.php,IPBlocker.phpDynamicKeywordManager.php,UUIDTamperProtector.php,HoneypotChecker.phpFeatureExtractor.php,IsolationForest.php,Logger.php
src/Core/
RuntimeConfig.php,HeaderValidation.php,GeoIP.php,Exemptions.phpLogs.php,Training.php,TrainingLogic.phpStorageOps.php,StorageCsvImpl.php,StorageSchema.php,BlocklistManager.php
Rate-Limit Layers
- Adapters in
src/Adapters/bridge runtime usage. - Drivers in
src/RateLimit/provide backend-specific persistence behavior.
8-9. Storage, Artifacts, Training Lifecycle
Artifacts (default under resources/)
blocked_ips.json,dynamic_keywords.json,request_features.csv,forest_model.json.php setup.phpensures required baseline files exist.
Training Pipeline (AIWAF::detectAndTrain)
The training pipeline executes robust anomaly detection and keyword learning strategies via CLI (php cli/detect_and_train.php):
- Source Processing: Reads from
AIWAF_ACCESS_LOG, automatically parsing rotated and gzipped logs viaLogs::readRotatedLogs. - Feature Extraction: Capable of parallelized feature extraction via
FeatureExtractor::pythonFeaturesBatchedif Python is available (managed byAIWAF_PYTHON_PARALLEL_WORKERS). - Training Matrix: Extracted per request for the
IsolationForest(configured with 200 trees, 32 sample size). The matrix maps 6 dimensions:path_lenkw_hitsresp_timestatus_idxburst_counttotal_404
- Anomaly Evaluation: Evaluates the matrix against the model using
AIWAF_AI_ANOMALY_THRESHOLD. Identifies anomalous IPs and runs a strict conservative check: keeps burst-only traffic with no suspicious footprint unblocked. Blocks only if: average keyword hits ≥ 2.0, max 404s ≥ 10.0, average burst ≥ 15.0, or total requests ≥ 100. - Keyword Learning: Extracts suspicious path segments into the dynamic keyword store, skipping paths that match
exempt_pathsorknown_paths.
Telemetry Includes
- line counts, parse failures, feature rows
- keyword candidate/learned counts
- anomalous/blocked IP totals and top-country summaries
