Skip to main content

SQL Injection Scanning

AxonFlow provides built-in SQL injection (SQLi) detection for MCP connector responses to protect against data exfiltration and manipulation attacks.

Detection vs Policy

Detection identifies what happened. Policies determine what action to take.

For example, SQL injection detection can be enabled while policies are configured to log-only during development, and later switched to block or require_approval in production — without changing application code.

This separation allows AxonFlow to support experimentation, audits, and enforcement within the same architecture.

Overview

SQL injection scanning monitors responses from MCP connectors for patterns that indicate SQL injection attempts. This protects against scenarios where:

  • Malicious data injected into databases is returned in query results
  • LLM-generated queries inadvertently include injection payloads
  • External data sources contain compromised content

Scanning Modes

AxonFlow offers three scanning modes to balance security and performance:

ModeDescriptionEditionPerformance
offScanning disabledCommunityN/A
basicPattern-based regex detectionCommunitySingle-digit ms
advancedHeuristic analysis with confidence scoringEnterprise<10ms

Basic Mode (Community)

Basic mode uses compiled regex patterns to detect common SQL injection techniques:

  • Union-based injection - UNION SELECT statements for data extraction
  • Boolean-blind injection - OR 1=1 and similar always-true conditions
  • Time-based blind injection - SLEEP(), WAITFOR DELAY, PG_SLEEP()
  • Stacked queries - DROP TABLE, DELETE FROM, INSERT INTO
  • Comment injection - SQL commands after --, /**/, or #
  • Error-based injection - EXTRACTVALUE, UPDATEXML

Advanced Mode (Enterprise)

Advanced mode extends basic detection with:

  • Heuristic analysis for obfuscation detection
  • Confidence scoring (0.0-1.0) to reduce false positives
  • Context-aware detection that recognizes documentation/code blocks
  • Multi-stage pipeline for comprehensive analysis

Enterprise Edition includes additional heuristic analysis capabilities. Contact Sales for details.

Configuration

Default Configuration

sqli:
input_mode: basic # Scan user inputs
response_mode: basic # Scan connector responses
block_on_detection: false # Monitoring mode (set true to enforce blocking)
log_detections: true
audit_trail_enabled: true
max_content_length: 1048576 # 1MB
Monitoring Mode

By default, SQL injection scanning runs in monitoring mode - detections are logged but responses are not blocked. This allows you to validate detection accuracy in your environment before enabling enforcement. Set block_on_detection: true to enable blocking.

Per-Connector Configuration

sqli:
response_mode: basic
connector_overrides:
# Disable for trusted internal cache
redis_cache:
enabled: false
# Use advanced mode for sensitive data (Enterprise)
postgresql_main:
response_mode: advanced

Programmatic Configuration

import "axonflow/platform/agent/sqli"

cfg := sqli.DefaultConfig().
WithResponseMode(sqli.ModeBasic).
WithBlockOnDetection(true).
WithConnectorOverride("redis", sqli.ConnectorConfig{
Enabled: false,
})

middleware, err := sqli.NewScanningMiddleware(
sqli.WithMiddlewareConfig(cfg),
)

Environment Variable Configuration

For Docker and containerized deployments, configure SQL injection scanning using environment variables:

VariableValuesDefaultDescription
SQLI_SCANNER_MODEoff, basic, advancedbasicSets the scanning mode for both input and response
SQLI_ACTIONblock, warn, logblockControls action when SQL injection is detected
Deprecated Variable

SQLI_BLOCK_MODE is deprecated. Use SQLI_ACTION instead. The old variable still works for backwards compatibility but will log a deprecation warning.

Example: docker-compose.yml

services:
axonflow-agent:
environment:
# Scanning mode: off, basic, advanced
SQLI_SCANNER_MODE: ${SQLI_SCANNER_MODE:-basic}
# Action on detection: block (reject), warn (log+allow), log (audit only)
SQLI_ACTION: ${SQLI_ACTION:-block}

Usage Examples:

# Default: basic scanning with blocking enabled
docker compose up -d

# Disable scanning entirely
SQLI_SCANNER_MODE=off docker compose up -d

# Enable scanning in warn-only mode (log but don't block)
SQLI_ACTION=warn docker compose up -d

# Use advanced scanning (Enterprise only) with blocking
SQLI_SCANNER_MODE=advanced SQLI_ACTION=block docker compose up -d
Security-First Defaults

Invalid environment variable values are logged and fall back to defaults (basic mode, blocking enabled) to ensure security-first behavior.

Detection Categories

CategorySeverityDescription
stacked_queriesCriticalCan modify or delete data
dangerous_queryCriticalDDL operations (DROP, TRUNCATE, ALTER, CREATE USER, GRANT)
union_basedHighCan extract sensitive data
time_basedHighConfirms SQL injection vulnerability
boolean_blindMediumMay have false positives
error_basedMediumError message extraction
comment_injectionMediumQuery manipulation
genericLowGeneral suspicious patterns

Response Handling

When SQL injection is detected, behavior depends on the configured action:

Block Mode (SQLI_ACTION=block)

This is the default mode. Returns HTTP 403 Forbidden and rejects the request:

{
"success": false,
"error": "Response blocked: potential SQL injection detected (pattern: union_select)"
}

Warn Mode (SQLI_ACTION=warn)

Logs the detection but allows the request through. Useful for:

  • Initial deployment to assess false positive rates
  • Testing detection patterns before enabling enforcement
  • Environments where availability is prioritized over strict blocking

Example log output:

[SQLi] WARNING: SQL injection attempt detected but not blocked (warn mode): pattern=union_select, category=union_based

Audit Trail

When audit_trail_enabled: true, detections are logged for compliance:

{
"type": "sqli_detection",
"timestamp": "2025-12-14T15:30:00Z",
"severity": "high",
"connector_name": "postgresql_main",
"scan_type": "response",
"pattern": "union_select",
"category": "union_based",
"confidence": 0.95,
"blocked": true
}

Compliance Integration

SQL injection scanning supports compliance requirements:

  • EU AI Act Art. 15: Accuracy logging for AI system outputs
  • RBI FREE-AI: Data integrity monitoring for financial AI
  • SEBI AIF: Security audit trail for investment platforms

SDK Integration

Use the AxonFlow SDK to detect SQL injection in user queries before they reach your LLM or database.

Community Examples

See complete working examples in the AxonFlow examples repository.

TypeScript

import { AxonFlow } from '@axonflow/sdk';

const axonflow = new AxonFlow({
endpoint: 'http://localhost:8080',
tenant: 'your-tenant',
});

const result = await axonflow.getPolicyApprovedContext({
userToken: 'user-123',
query: "SELECT * FROM users; DROP TABLE users;--",
});

if (!result.approved) {
console.log(`SQLi blocked: ${result.blockReason}`);
// Output: SQLi blocked: SQL injection attempt detected...
}

Go

result, err := client.GetPolicyApprovedContext(
"user-123",
"SELECT * FROM users; DROP TABLE users;--",
nil, nil,
)

if !result.Approved {
log.Printf("SQLi blocked: %s", result.BlockReason)
}

Java

PolicyApprovalResult result = client.getPolicyApprovedContext(
PolicyApprovalRequest.builder()
.query("SELECT * FROM users; DROP TABLE users;--")
.userToken("user-123")
.build()
);

if (!result.isApproved()) {
System.out.println("SQLi blocked: " + result.getBlockReason());
}

Best Practices

  1. Enable scanning by default - Use basic mode for all connectors initially
  2. Tune per-connector - Disable for trusted internal services
  3. Use advanced mode for sensitive data stores (Enterprise)
  4. Monitor audit logs for detection patterns and false positives
  5. Set appropriate thresholds - Adjust confidence threshold for advanced mode

Performance Impact

ModeAverage LatencyP99 LatencyThroughput Impact
off0ms0ms0%
basic<1ms2ms<1%
advanced3-5ms10ms2-5%

Metrics

The middleware exposes metrics for monitoring:

metrics := sqli.GetGlobalMiddleware().GetMetrics()
// metrics.ScansTotal - Total scans performed
// metrics.DetectionsTotal - Total detections
// metrics.BlockedTotal - Total blocked responses

Troubleshooting

False Positives

If legitimate SQL content is being blocked:

  1. Check if content contains SQL-like patterns (documentation, logs)
  2. Consider using advanced mode for better context awareness (Enterprise)
  3. Disable scanning for specific connectors with known safe data

Performance Issues

If scanning adds unacceptable latency:

  1. Reduce max_content_length to limit scanned data
  2. Disable scanning for high-throughput connectors
  3. Use basic mode instead of advanced