Search by

rafalmasiarek / threat-detector

rafalmasiarek

Heuristic, modular threat detection (signal-only) with weighted float scoring, predefined thresholds, and PSR-15 middleware for PSR-7 apps.

Package info

github.com/rafalmasiarek/php-threat-detector

pkg:composer/rafalmasiarek/threat-detector

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 2

v1.0.0 2025-09-07 21:35 UTC

This package is auto-updated.

Last update: 2026-11-17 23:37:37 UTC


README

Latest Version License PHP

Heuristic, modular threat detection (signal-only) with weighted float scoring, predefined thresholds, and PSR-15 middleware for PSR-7 applications.

⚠️ This library is a signal generator. It does not replace proper validation/sanitization/escaping, CSP, prepared statements, etc.

License

License: MIT

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.

Source: https://opensource.org/licenses/MIT

See LICENSE for full details.

Authors

Features

  • 🧩 Modular scanners — each category (XSS, SQLi, SSRF, …) in a separate class.
  • ⚖️ Weighted float scoring — per-category weights; combine multiple signals.
  • 🎚️ Predefined thresholds — LOW, MEDIUM, HIGH (or custom floats).
  • 🧵 PSR-15 middleware — scan query, body, headers, cookies; annotate request; optional header X-Threat-Suspect.
  • 📝 phpDocs & comments — production-friendly code with clear docs.
  • ✅ Unit tests — a couple of quick checks to get you started.
  • 📂 Examples — basic HTML form + PSR-15 middleware demo.

Requirements

  • PHP 8.1+
  • ext-mbstring

Installation

Using Composer:

composer require rafalmasiarek/threat-detector

If you are using this repository locally (path repo):

composer config repositories.threat-detector path ./threat-detector
composer require rafalmasiarek/threat-detector:dev-main

Quick Start (Core)

use rafalmasiarek\Threat\Core\ThreatDetector;
use rafalmasiarek\Threat\Core\ScoringPolicy;
use rafalmasiarek\Threat\Core\Thresholds;

// Create a policy with default weights and MEDIUM threshold
$policy = ScoringPolicy::withDefaults()
    ->withThreshold(Thresholds::MEDIUM)  // or 'LOW' | 'HIGH' | 3.5 (float)
    ->withWeight('SQLI', 2.25);          // optional: override category weights

$detector = ThreatDetector::default($policy);

// Scan a string
$input = "<script>alert(1)</script>";
$result = $detector->scanString($input);

var_dump($result->suspect); // bool
var_dump($result->score);   // float
var_dump($result->hits);    // array{category => list<string>}
var_dump($result->norm);    // normalized input

Example output:

bool(true)
float(3)
array(1) {
  ["XSS"]=>
  array(2) {
    [0]=> string(10) "TAG_SCRIPT"
    [1]=> string(9)  "HTML_TAGS"
  }
}
string(23) "<script>alert(1)</script>"

Quick Start (PSR-15 Middleware)

use rafalmasiarek\Threat\Middleware\ThreatDetectMiddleware;

$middleware = new ThreatDetectMiddleware([
    'threshold'    => 'MEDIUM',          // 'LOW' | 'MEDIUM' | 'HIGH' | float
    'weights'      => ['SQLI' => 2.1],   // optional overrides
    'scan_query'   => true,
    'scan_body'    => true,
    'scan_headers' => false,             // true or array of headers to scan
    'scan_cookies' => false,
    'attribute'    => 'threat.result',   // request attribute name
    'set_header'   => true,              // add X-Threat-Suspect: 1 when suspect
]);

// Add to your PSR-15 stack (Slim/Mezzio/etc.)
$result = $request->getAttribute('threat.result'); 

Example result:

[
  'suspect' => true,
  'score'   => 3.5,
  'hits'    => ['XSS' => ['TAG_SCRIPT','HTML_TAGS']],
]

Scoring

  • Weights: per category (e.g., SQLI=2.0, CMD_INJECTION=2.5, CRLF=1.0).
  • Score formula:
    score = Σ ( weight(category) × unique_hits(category) )
    
  • Threshold: request is suspect when score ≥ threshold.

Predefined thresholds

Name Value Sensitivity
LOW 1.0 Very sensitive
MEDIUM 2.5 Balanced (default)
HIGH 5.0 Strict

Examples

  • <script>alert(1)</script>
    Hits: XSS=[TAG_SCRIPT, HTML_TAGS]
    Score: 1.5 × 2 = 3.0 → suspect at MEDIUM

  • UNION SELECT password FROM users
    Hits: SQLI=[UNION_SELECT]
    Score: 2.0 × 1 = 2.0 → not suspect at MEDIUM, suspect at LOW

Categories & Scanners

  • XSS — inline event handlers, <script>, javascript: URIs.
  • SQLI — UNION SELECT, SLEEP(), INFORMATION_SCHEMA, etc.
  • CMD_INJECTION — subshells, ;, &&, wget/curl, redirects.
  • PATH_TRAVERSAL — ../, URL-encoded traversal, file://, wrappers.
  • CRLF — header injection sequences.
  • SSRF — URLs to localhost, 127.0.0.1, RFC1918 ranges.
  • XXE — <!DOCTYPE>, <!ENTITY>, external SYSTEM.
  • NOSQL — Mongo-like operators $where, $regex.
  • LDAP — wildcards, null bytes.
  • SERIALIZATION — PHP serialized payload patterns.

Integration Ideas

  • Add to Slim/Mezzio pipeline as PSR-15 middleware.
  • Run against form input before sending mail (contact forms).
  • Log suspect inputs into a security audit trail.
  • Flag suspicious requests in rate-limiting / WAF logic.

Tests & Examples

  • PHPUnit tests included (tests/):
    • TruePositiveDetectionsTest.php
    • FalsePositiveHeuristicsTest.php
  • Example apps in examples/:
    • basic/ (HTML form demo)
    • psr15/ (middleware demo)

Run tests:

./vendor/bin/phpunit --colors=always

Security Notice

This library generates signals only.
Always combine with:

  • Prepared statements for SQL queries
  • Proper HTML escaping and CSP
  • Strong input validation

Folder Structure

src/
  Contracts/ScannerInterface.php
  Core/{ThreatDetector.php, ThreatResult.php, ScoringPolicy.php, Thresholds.php}
  Scanner/{XssScanner.php, SqliScanner.php, CmdInjectionScanner.php, PathTraversalScanner.php, CrlfScanner.php, SsrfScanner.php, XxeScanner.php, NoSqlScanner.php, LdapScanner.php, SerializationScanner.php}
  Middleware/ThreatDetectMiddleware.php
tests/
  ModularThreatDetectorTest.php
examples/
  basic/
  psr15/

Index

Classes

Interfaces

ScannerInterface

interface — rafalmasiarek\Threat\Contracts\ScannerInterface · source

Interface ScannerInterface Represents a single-category scanner (e.g., XSS, SQLI). Implementations must be stateless and fast.

Method Visibility Returns Summary
category() public string Get the category name this scanner represents (e.g., 'XSS', 'SQLI').
scan() public array<int, string> Scan normalized input and return unique hit codes.
category()

ScannerInterface category()

source

public function category(): string

Get the category name this scanner represents (e.g., 'XSS', 'SQLI').

Returns: string — Category name

scan()

ScannerInterface scan()

source

public function scan(string $normalized): array

Scan normalized input and return unique hit codes.

Param Type Description
$normalized string Normalized input (HTML entities and URL-encodings already decoded).

Returns: array<int, string> — List of hit codes (empty when no hits).

ScoringPolicy

final class — rafalmasiarek\Threat\Core\ScoringPolicy · source

Class ScoringPolicy Holds category weights and global threshold for suspicion decisions.

Property Type Visibility Description
$weights array<string, float> private —
$threshold float private —
Method Visibility Returns Summary
__construct() public — —
withDefaults() public static self Create policy with baseline weights and MEDIUM threshold.
withWeight() public self Return a cloned policy with an overridden weight for a category.
withThreshold() public self Return a cloned policy with a new threshold.
weights() public array<string, float> Get all weights.
weightFor() public float Get weight for a specific category.
threshold() public float Get the active threshold.
__construct()

ScoringPolicy __construct()

source

public function __construct(array $weights, float $threshold)
Param Type Description
$weights array<string, float> Per-category weights
$threshold float Float threshold for 'suspect'
withDefaults()

ScoringPolicy withDefaults()

source

public static function withDefaults(): self

Create policy with baseline weights and MEDIUM threshold.

Returns: self

withWeight()

ScoringPolicy withWeight()

source

public function withWeight(string $category, float $weight): self

Return a cloned policy with an overridden weight for a category.

Param Type Description
$category string Category name
$weight float Weight value

Returns: self — New policy instance

withThreshold()

ScoringPolicy withThreshold()

source

public function withThreshold(float|string $threshold): self

Return a cloned policy with a new threshold.

Param Type Description
$threshold float|string Float or 'LOW'|'MEDIUM'|'HIGH'

Returns: self — New policy instance

weights()

ScoringPolicy weights()

source

public function weights(): array

Get all weights.

Returns: array<string, float>

weightFor()

ScoringPolicy weightFor()

source

public function weightFor(string $category): float

Get weight for a specific category.

Param Type Description
$category string Category name

Returns: float — Weight value

threshold()

ScoringPolicy threshold()

source

public function threshold(): float

Get the active threshold.

Returns: float

ThreatDetector

final class — rafalmasiarek\Threat\Core\ThreatDetector · source

Class ThreatDetector Orchestrates scanners, normalization and weighted scoring.

Depends on: ScoringPolicy

Property Type Visibility Description
$scanners list<ScannerInterface> private Ordered scanner instances
$policy ScoringPolicy private Active scoring policy
Method Visibility Returns Summary
__construct() public — —
default() public static self Build a detector with the default scanner set and a policy (default weights + MEDIUM threshold).
scanString() public ThreatResult Scan a raw string.
scanToArray() public array{suspect: bool, score: float, hits: array<string, array<int, string>>, norm: string} Convenience method: scan and export as array.
normalize() private string Normalize a string by limited HTML-entity & URL decoding, whitespace collapse, and trim.
__construct()

ThreatDetector __construct()

source

public function __construct(array $scanners, ScoringPolicy $policy)
Param Type Description
$scanners list<ScannerInterface> List of scanners to run
$policy ScoringPolicy Scoring policy
default()

ThreatDetector default()

source

public static function default(?ScoringPolicy $policy): self

Build a detector with the default scanner set and a policy (default weights + MEDIUM threshold).

Param Type Description
$policy ScoringPolicy|null Optional policy

Returns: self

scanString()

ThreatDetector scanString()

source

public function scanString(string $input): ThreatResult

Scan a raw string.

Param Type Description
$input string Raw input value

Returns: ThreatResult — Immutable result object

scanToArray()

ThreatDetector scanToArray()

source

public function scanToArray(string $input): array

Convenience method: scan and export as array.

Param Type Description
$input string Raw input value

Returns: array{suspect: bool, score: float, hits: array<string, array<int, string>>, norm: string}

normalize()

ThreatDetector normalize()

source

private function normalize(string $s): string

Normalize a string by limited HTML-entity & URL decoding, whitespace collapse, and trim.

Param Type Description
$s string Raw input

Returns: string — Normalized input

ThreatResult

final class — rafalmasiarek\Threat\Core\ThreatResult · source

Class ThreatResult Immutable result of a scan operation.

Property Type Visibility Description
$suspect bool public Whether the input meets or exceeds the active threshold
$score float public Weighted float score across categories
$hits array<string, array<int, string>> public Map of category => list of hit codes
$norm string public Normalized input string used for scanning
Method Visibility Returns Summary
__construct() public — —
toArray() public array{suspect: bool, score: float, hits: array<string, array<int, string>>, norm: string} Export the result to a well-typed array (handy for logs).
__construct()

ThreatResult __construct()

source

public function __construct(bool $suspect, float $score, array $hits, string $norm)
Param Type Description
$suspect bool —
$score float —
$hits array<string, array<int, string>> —
$norm string —
toArray()

ThreatResult toArray()

source

public function toArray(): array

Export the result to a well-typed array (handy for logs).

Returns: array{suspect: bool, score: float, hits: array<string, array<int, string>>, norm: string}

Thresholds

final class — rafalmasiarek\Threat\Core\Thresholds · source

Class Thresholds Predefined float thresholds for suspicion decisions.

Method Visibility Returns Summary
resolve() public static float Resolve a string keyword into a float threshold.
resolve()

Thresholds resolve()

source

public static function resolve(string $name): float

Resolve a string keyword into a float threshold.

Param Type Description
$name string 'LOW'|'MEDIUM'|'HIGH'

Returns: float — The resolved threshold

ThreatDetectMiddleware

final class — rafalmasiarek\Threat\Middleware\ThreatDetectMiddleware · source

Class ThreatDetectMiddleware PSR-15 middleware that scans selected parts of the request and attaches a compact result as request attribute. Options: - threshold: 'LOW'|'MEDIUM'|'HIGH'|float (default: 'MEDIUM') - weights: array<string,float> per-category overrides - scan_query (bool) - scan_body (bool) - scan_headers (bool|array) true or list of header names - scan_cookies (bool) - attribute (string) request attribute name (default: 'threat.result') - set_header (bool) set 'X-Threat-Suspect: 1' when suspect (default: true)

implements MiddlewareInterface

Property Type Visibility Description
$config array<string, mixed> private —
Method Visibility Returns Summary
__construct() public — —
process() public ResponseInterface {@inheritDoc}
scanArray() private void Scan nested arrays and accumulate score/hits.
mergeHits() private void Merge hit maps (category => codes[]) in-place.
__construct()

ThreatDetectMiddleware __construct()

source

public function __construct(array $config)
Param Type Description
$config array<string, mixed> Middleware configuration
process()

ThreatDetectMiddleware process()

source

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

{@inheritDoc}

Param Type Description
$request ServerRequestInterface —
$handler RequestHandlerInterface —

Returns: ResponseInterface

scanArray()

ThreatDetectMiddleware scanArray()

source

private function scanArray(array $arr, ThreatDetector $detector, float $accScore, array $accHits): void

Scan nested arrays and accumulate score/hits.

Param Type Description
$arr array<string, mixed> —
$detector ThreatDetector —
$accScore float (by-ref)
$accHits array<string, array<int, string>> (by-ref)
mergeHits()

ThreatDetectMiddleware mergeHits()

source

private function mergeHits(array $into, array $from): void

Merge hit maps (category => codes[]) in-place.

Param Type Description
$into array<string, array<int, string>> —
$from array<string, array<int, string>> —

CmdInjectionScanner

final class — rafalmasiarek\Threat\Scanner\CmdInjectionScanner · source

Class CmdInjectionScanner Detects shell/command injection indicators.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

CmdInjectionScanner category()

source

public function category(): string

Returns: string

scan()

CmdInjectionScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

CrlfScanner

final class — rafalmasiarek\Threat\Scanner\CrlfScanner · source

Class CrlfScanner Detects CRLF/header injection attempts.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

CrlfScanner category()

source

public function category(): string

Returns: string

scan()

CrlfScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

LdapScanner

final class — rafalmasiarek\Threat\Scanner\LdapScanner · source

Class LdapScanner Detects LDAP filter injection artifacts.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

LdapScanner category()

source

public function category(): string

Returns: string

scan()

LdapScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

NoSqlScanner

final class — rafalmasiarek\Threat\Scanner\NoSqlScanner · source

Class NoSqlScanner Detects Mongo-like operator usage in input.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

NoSqlScanner category()

source

public function category(): string

Returns: string

scan()

NoSqlScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

PathTraversalScanner

final class — rafalmasiarek\Threat\Scanner\PathTraversalScanner · source

Class PathTraversalScanner Detects path traversal and file wrapper indicators.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

PathTraversalScanner category()

source

public function category(): string

Returns: string

scan()

PathTraversalScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

SerializationScanner

final class — rafalmasiarek\Threat\Scanner\SerializationScanner · source

Class SerializationScanner Detects PHP serialization patterns.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

SerializationScanner category()

source

public function category(): string

Returns: string

scan()

SerializationScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

SqliScanner

final class — rafalmasiarek\Threat\Scanner\SqliScanner · source

Class SqliScanner Detects common SQL injection patterns.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

SqliScanner category()

source

public function category(): string

Returns: string

scan()

SqliScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

SsrfScanner

final class — rafalmasiarek\Threat\Scanner\SsrfScanner · source

Class SsrfScanner Detects SSRF indicators (localhost, RFC1918 networks).

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

SsrfScanner category()

source

public function category(): string

Returns: string

scan()

SsrfScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

XssScanner

final class — rafalmasiarek\Threat\Scanner\XssScanner · source

Class XssScanner Detects common indicators of Cross-Site Scripting (XSS).

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

XssScanner category()

source

public function category(): string

Returns: string

scan()

XssScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array

XxeScanner

final class — rafalmasiarek\Threat\Scanner\XxeScanner · source

Class XxeScanner Detects XML External Entity (XXE) indicators.

implements ScannerInterface

Method Visibility Returns Summary
category() public string —
scan() public array —
category()

XxeScanner category()

source

public function category(): string

Returns: string

scan()

XxeScanner scan()

source

public function scan(string $normalized): array
Param Type Description
$normalized string —

Returns: array