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:
| Mode | Description | Edition | Performance |
|---|---|---|---|
off | Scanning disabled | Community | N/A |
basic | Pattern-based regex detection | Community | Single-digit ms |
advanced | Heuristic analysis with confidence scoring | Enterprise | <10ms |
Basic Mode (Community)
Basic mode uses compiled regex patterns to detect common SQL injection techniques:
- Union-based injection -
UNION SELECTstatements for data extraction - Boolean-blind injection -
OR 1=1and 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
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:
| Variable | Values | Default | Description |
|---|---|---|---|
SQLI_SCANNER_MODE | off, basic, advanced | basic | Sets the scanning mode for both input and response |
SQLI_ACTION | block, warn, log | block | Controls action when SQL injection is detected |
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
Invalid environment variable values are logged and fall back to defaults (basic mode, blocking enabled) to ensure security-first behavior.
Detection Categories
| Category | Severity | Description |
|---|---|---|
stacked_queries | Critical | Can modify or delete data |
dangerous_query | Critical | DDL operations (DROP, TRUNCATE, ALTER, CREATE USER, GRANT) |
union_based | High | Can extract sensitive data |
time_based | High | Confirms SQL injection vulnerability |
boolean_blind | Medium | May have false positives |
error_based | Medium | Error message extraction |
comment_injection | Medium | Query manipulation |
generic | Low | General 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.
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
- Enable scanning by default - Use
basicmode for all connectors initially - Tune per-connector - Disable for trusted internal services
- Use advanced mode for sensitive data stores (Enterprise)
- Monitor audit logs for detection patterns and false positives
- Set appropriate thresholds - Adjust confidence threshold for advanced mode
Performance Impact
| Mode | Average Latency | P99 Latency | Throughput Impact |
|---|---|---|---|
off | 0ms | 0ms | 0% |
basic | <1ms | 2ms | <1% |
advanced | 3-5ms | 10ms | 2-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:
- Check if content contains SQL-like patterns (documentation, logs)
- Consider using
advancedmode for better context awareness (Enterprise) - Disable scanning for specific connectors with known safe data
Performance Issues
If scanning adds unacceptable latency:
- Reduce
max_content_lengthto limit scanned data - Disable scanning for high-throughput connectors
- Use
basicmode instead ofadvanced