DB Monitoring
Monitoring for SQL injection is detective control behind the preventive control (parameterised queries). The signals to alert on are query-shape anomalies in your DB logs, WAF rule hits, and unusually long response times. None of this replaces fixing the bug — it tells you which app to patch first.
A minimal detection pipeline for suspicious queries
EXAMPLE
<?php
// Defensive logging middleware: wraps DB calls, watches for suspicious shapes.
// Intended for an authorised test environment to verify alerts fire.
function looksSuspicious(string $sql, array $bindings): bool {
// Concrete heuristics — tune for your app, not for the internet.
$flags = [
'/\bunion\s+select\b/i',
'/\bor\s+1\s*=\s*1\b/i',
'/--\s|#\s/',
'/\bsleep\s*\(/i',
'/\bbenchmark\s*\(/i',
'/\binformation_schema\b/i',
];
$haystack = $sql . ' ' . implode(' ', array_map('strval', $bindings));
foreach ($flags as $rx) {
if (preg_match($rx, $haystack)) return true;
}
return false;
}
// Laravel: hook into the query event listener.
DB::listen(function ($query) {
if (looksSuspicious($query->sql, $query->bindings)) {
Log::channel('security')->warning('sqli_suspect', [
'sql' => $query->sql,
'bindings' => $query->bindings,
'time_ms' => $query->time,
'user_id' => optional(auth()->user())->id,
'ip' => request()->ip(),
'route' => optional(request()->route())->getName(),
]);
}
});
// Pair with: parameterised queries everywhere, least-privileged DB user,
// and a WAF rule set (ModSecurity OWASP CRS) in front of the app.
Why it matters
Heuristic detection has false positives — analytics queries do legitimately reference information_schema. Send the signal to a SIEM and pair it with response-time anomaly detection rather than auto-blocking; a hair-trigger block on a search box becomes a self-DoS.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Watch for: spikes in DB errors, sudden table-wide SELECTs, blocked queries. // Tools: pgBadger, Percona Audit, Datadog DBM, CloudWatch RDS metrics.Try it Yourself »
Discussion
Loading…