PHP code example of kanopi / crs-engine

1. Go to this page and download the library: Download kanopi/crs-engine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kanopi / crs-engine example snippets


use Kanopi\Crs\CrsConfig;
use Kanopi\Crs\CrsEngine;
use Kanopi\Crs\Request\RequestData;

$engine = new CrsEngine(new CrsConfig(
    paranoia: 1,
    mode: CrsConfig::MODE_BLOCK,
));

$request = new RequestData(
    method:      'GET',
    uri:         '/login?user=admin&pw=' . rawurlencode("' OR 1=1"),
    rawUri:      $_SERVER['REQUEST_URI'] ?? '/',
    queryString: $_SERVER['QUERY_STRING'] ?? '',
    protocol:    'HTTP/1.1',
    remoteAddr:  $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
    queryArgs:   $_GET,
    postArgs:    $_POST,
    cookies:     $_COOKIE,
    headers:     getallheaders() ?: [],
);

$verdict = $engine->evaluate($request);

if ($verdict->isBlocked()) {
    http_response_code(403);
    error_log(sprintf(
        'CRS blocked request: rule %d (%s)',
        $verdict->blockingRuleId,
        $verdict->matchedRules[0]['msg'] ?? '',
    ));
    exit;
}

new CrsConfig(
    paranoia: 1,                        // 1 (default) - 4. Higher = more strict, more false positives.
    mode: CrsConfig::MODE_BLOCK,        // or MODE_MONITOR (records matches, never blocks)
    anomalyThresholds: [
        'critical' => 5,                // total score >= threshold triggers block
        'error'    => 4,
        'warning'  => 3,
        'notice'   => 2,
    ],
    disabledRules:      [920300, 942130],   // skip these rule IDs
    disabledCategories: ['session_fixation'], // skip whole categories
    rulesPath:          null,                // override location of compiled.php
);

new RequestData(
    method:      'POST',
    uri:         '/api/comments',
    rawUri:      '/api/comments',
    queryString: '',
    protocol:    'HTTP/1.1',
    remoteAddr:  '203.0.113.42',
    queryArgs:   $request->query->all(),         // GET params
    postArgs:    $request->request->all(),       // POST/form params
    cookies:     $request->cookies->all(),
    headers:     $request->headers->all(),       // name => string|string[]
    body:        (string) $request->getContent(),
    files:       [],                              // [{name, filename, mime, size}]
);

$verdict->action;          // 'allow' | 'log' | 'block'
$verdict->isBlocked();     // bool
$verdict->blockingRuleId;  // ?int — the first rule that fired with deny/block/drop
$verdict->totalScore;      // accumulated anomaly score across paranoia levels
$verdict->scores;          // per-category: ['sqli' => 5, 'xss' => 0, ...]
$verdict->matchedRules;    // array of [id, msg, severity, score, tags, category, matched_data]
$verdict->toArray();       // serialisable shape for logging