Core Design

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.

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)

  1. Build runtime config via Config::toRuntimeConfig().
  2. Configure rate limiter via configureRateLimiter() (auto-detects db, apcu, redis, or falls back to memory).
  3. Resolve request identity (ip, path).
  4. Exemption short-circuit (skips remaining checks if IP or Path is exempt via configurations or CIDR matches).
  5. Method validation (ensures request method is allowed).
  6. Header validation (evaluates trust_legitimate_bots, custom_suspicious_patterns, and quality_threshold).
  7. Blocked-IP enforcement.
  8. Geo policy checks (compares IP against allow/block countries).
  9. AI Anomaly Scoring: Extracts an 8-dimensional feature vector:
    • strlen($path)
    • DynamicKeywordManager::detect($path)
    • 0.5 (baseline structural complexity)
    • Status code anomaly (1 if 404/500, else 0)
    • Reserved (0)
    • Reserved (0)
    • Honeypot trigger (isset($_POST['aiwaf_honeytrap']) ? 1 : 0)
    • UUID tamper check (UUIDTamperProtector::isSuspicious($path) ? 1 : 0)
    Scores the vector against 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.
  10. Rate-limit enforcement (checks max_requests per window_seconds).
  11. Dynamic keyword checks.
  12. UUID tamper checks.
  13. Honeypot checks (evaluates $_POST payloads).

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 NodeVisitorAbstract traverses the statements strictly within the bounded line numbers.
  • Call Inspection: Inspects MethodCall, FuncCall, and StaticCall nodes.
    • Increases API confidence if it detects json, json_encode, JsonResponse, or jsonify.
    • Increases Form confidence if it detects view, render, redirect, back, or render_template.
  • Object Instantiation: Inspects New_ nodes. Instantiating JsonResponse yields a high API score.
  • Payload Type: Scans for post, all, input, or file method calls on request objects to flag requestBody = true and 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 as api, form, admin, upload, static, or auth.
  • 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 .png routes.
  • Config Sentinels: If requested_middlewares is set to ['auto'], MiddlewarePlan::planEnabledMiddlewares() dynamically strips out unnecessary middlewares (e.g., completely unloading uuid_tamper if no UUIDs exist, or disabling geo_block if the MMDB isn't configured).

Deep Dive: Core Functions and Methods

A reference of the core internal functions powering the PHP AIWAF engine.

Module / ClassFunction / MethodDescription
AIWAF.php
AIWAF
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.php
PathManifest
classifyRoute($path, $methods)Matches standard heuristic signatures (e.g., /api/* or /login) and combines them with AST outputs to bin the route type.
ApiDetection.php
RouteVisitor
enterNode(Node $node)Implements PhpParser\NodeVisitorAbstract to inspect method calls like json() or validate() to build confidence scores for API intents.
MiddlewarePlan.php
MiddlewarePlan
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.php
  • RateLimiter.php, IPBlocker.php
  • DynamicKeywordManager.php, UUIDTamperProtector.php, HoneypotChecker.php
  • FeatureExtractor.php, IsolationForest.php, Logger.php

src/Core/

  • RuntimeConfig.php, HeaderValidation.php, GeoIP.php, Exemptions.php
  • Logs.php, Training.php, TrainingLogic.php
  • StorageOps.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.php ensures 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 via Logs::readRotatedLogs.
  • Feature Extraction: Capable of parallelized feature extraction via FeatureExtractor::pythonFeaturesBatched if Python is available (managed by AIWAF_PYTHON_PARALLEL_WORKERS).
  • Training Matrix: Extracted per request for the IsolationForest (configured with 200 trees, 32 sample size). The matrix maps 6 dimensions:
    1. path_len
    2. kw_hits
    3. resp_time
    4. status_idx
    5. burst_count
    6. total_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_paths or known_paths.

Telemetry Includes

  • line counts, parse failures, feature rows
  • keyword candidate/learned counts
  • anomalous/blocked IP totals and top-country summaries