SQL Injection Protection
Protection Module: SqlInjection
Intercepts and validates SQL queries in real-time to prevent SQL injection attacks.
Available for:
- ASP.NET Core (Web APIs, MVC, Razor Pages)
- ASP.NET Framework 4.6.2+
- Blazor Server
- Any web application using SQL databases
How It Works
SQL Injection protection uses runtime interception (via HarmonyLib) to hook into database execution methods and analyze SQL queries before they execute.
Detection Methods:
- SQL syntax analysis for malicious patterns
- Dangerous keyword detection (UNION, DROP, xp_cmdshell, etc.)
- Comment-based injection detection (--, /*, */)
- String concatenation vulnerability analysis
- Encoded payload detection (URL encoding, hex encoding)
- Time-based blind injection patterns
- Boolean-based blind injection patterns
Supported ORMs and Libraries:
- ADO.NET (SqlCommand, SqlDataAdapter, SqlDataReader)
- Entity Framework Core (all versions)
- Entity Framework 6
- Dapper
- NHibernate
- Raw SQL queries
Interception Points:
SqlCommand.ExecuteReader()SqlCommand.ExecuteScalar()SqlCommand.ExecuteNonQuery()DbContext.Database.ExecuteSqlRaw()DbContext.Database.ExecuteSqlInterpolated()
Configuration
JSON Configuration
{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block"
}
}
}{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block"
}
}
}ASP.NET Core Middleware
builder.Services.AddBytehideMonitor(monitor => monitor
.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);builder.Services.AddBytehideMonitor(monitor => monitor
.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);Advanced Configuration
{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high",
"blockStoredProcedures": false,
"allowDynamicSql": false
}
}
}
}{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high",
"blockStoredProcedures": false,
"allowDynamicSql": false
}
}
}
}Available Actions
| Action | Behavior | Recommended For |
|---|---|---|
| Block | Return HTTP 403, prevent query execution | Production web applications |
| Log | Record incident, allow query | Development, low-risk environments |
| Custom | Execute custom handler | Enterprise logging, SIEM integration |
Web Applications Only
SQL Injection protection uses the Block action which is only available for web applications. Close and Erase actions are not applicable.
Attack Examples Detected
Traditional SQL Injection
// Vulnerable code
var userId = Request.Query["id"];
var sql = $"SELECT * FROM Users WHERE Id = {userId}";
var users = db.ExecuteQuery(sql);
// Attack: ?id=1 OR 1=1--
// Status: BLOCKED// Vulnerable code
var userId = Request.Query["id"];
var sql = $"SELECT * FROM Users WHERE Id = {userId}";
var users = db.ExecuteQuery(sql);
// Attack: ?id=1 OR 1=1--
// Status: BLOCKEDUNION-Based Injection
// Vulnerable code
var search = Request.Query["search"];
var sql = $"SELECT Name FROM Products WHERE Name LIKE '%{search}%'";
// Attack: search=' UNION SELECT password FROM Users--
// Status: BLOCKED// Vulnerable code
var search = Request.Query["search"];
var sql = $"SELECT Name FROM Products WHERE Name LIKE '%{search}%'";
// Attack: search=' UNION SELECT password FROM Users--
// Status: BLOCKEDBlind SQL Injection
// Vulnerable code
var username = Request.Form["username"];
var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
// Attack: username=admin' AND SLEEP(5)--
// Status: BLOCKED// Vulnerable code
var username = Request.Form["username"];
var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
// Attack: username=admin' AND SLEEP(5)--
// Status: BLOCKEDStored Procedure Abuse
// Vulnerable code
var input = Request.Query["input"];
var sql = $"EXEC xp_cmdshell '{input}'";
// Attack: input=whoami
// Status: BLOCKED// Vulnerable code
var input = Request.Query["input"];
var sql = $"EXEC xp_cmdshell '{input}'";
// Attack: input=whoami
// Status: BLOCKEDConfiguration Parameters
Sensitivity Levels
{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high"
}
}
}
}{
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high"
}
}
}
}| Level | Description | False Positives | Recommended For |
|---|---|---|---|
| low | Basic pattern matching | Very few | Complex queries, reporting systems |
| medium | Standard detection | Few | Most applications |
| high | Aggressive detection | Possible | High-security applications, financial systems |
Allow Dynamic SQL
{
"config": {
"allowDynamicSql": true
}
}{
"config": {
"allowDynamicSql": true
}
}When enabled: Allows certain dynamic SQL patterns (use with caution) Default: false
Custom Response Handler
builder.Services.AddBytehideMonitor(monitor => monitor
.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);builder.Services.AddBytehideMonitor(monitor => monitor
.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);Endpoint-Specific Configuration
Configure different sensitivity per route:
{
"cloud": {
"endpoints": [
{
"method": "POST",
"route": "/api/admin/*",
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high"
}
}
}
},
{
"method": "GET",
"route": "/api/public/search",
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "medium"
}
}
}
}
]
}
}{
"cloud": {
"endpoints": [
{
"method": "POST",
"route": "/api/admin/*",
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "high"
}
}
}
},
{
"method": "GET",
"route": "/api/public/search",
"protections": {
"SqlInjection": {
"enabled": true,
"action": "block",
"config": {
"sensitivityLevel": "medium"
}
}
}
}
]
}
}Best Practices
Use Parameterized Queries
Vulnerable:
var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
var users = db.ExecuteQuery(sql);var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
var users = db.ExecuteQuery(sql);Recommended:
var sql = "SELECT * FROM Users WHERE Username = @username";
var users = db.ExecuteQuery(sql, new { username });var sql = "SELECT * FROM Users WHERE Username = @username";
var users = db.ExecuteQuery(sql, new { username });Monitor provides defense-in-depth even when using parameterized queries.
Entity Framework Best Practices
Avoid raw SQL when possible:
// Instead of raw SQL
var users = context.Users.FromSqlRaw($"SELECT * FROM Users WHERE Id = {id}");
// Use LINQ
var user = context.Users.FirstOrDefault(u => u.Id == id);// Instead of raw SQL
var users = context.Users.FromSqlRaw($"SELECT * FROM Users WHERE Id = {id}");
// Use LINQ
var user = context.Users.FirstOrDefault(u => u.Id == id);Use interpolated strings safely:
// Safe - EF Core automatically parameterizes
var users = context.Users
.FromSqlInterpolated($"SELECT * FROM Users WHERE Username = {username}");// Safe - EF Core automatically parameterizes
var users = context.Users
.FromSqlInterpolated($"SELECT * FROM Users WHERE Username = {username}");Performance Impact
Overhead: <1ms per query Memory: Minimal (~100 KB for detection engine) Throughput Impact: <2% in high-load scenarios
Benchmarks:
| Scenario | Without Monitor | With Monitor | Overhead |
|---|---|---|---|
| Simple SELECT | 2ms | 2.1ms | +5% |
| Complex JOIN | 15ms | 15.2ms | +1.3% |
| Bulk INSERT | 50ms | 50.5ms | +1% |
Platform Compatibility
| Platform | Support | Notes |
|---|---|---|
| ASP.NET Core 6+ | ✔ | Full support |
| ASP.NET Core 3.1-5.0 | ✔ | Full support |
| ASP.NET Framework 4.6.2+ | ✔ | Full support via HttpModule |
| Blazor Server | ✔ | Server-side protection |
| Entity Framework Core | ✔ | All versions |
| Entity Framework 6 | ✔ | Full support |
| Dapper | ✔ | Full support |
| NHibernate | ✔ | Full support |
Threat Detection Details
When an attack is detected, the ThreatInfo object contains:
{
"threatId": "SQL-2025-12-28-5678",
"description": "SQL injection attempt detected in query",
"moduleType": "SqlInjection",
"detectedAt": "2025-12-28T14:22:10Z",
"confidence": 0.95,
"metadata": {
"query": "SELECT * FROM Users WHERE Id = 1 OR 1=1--",
"attackType": "boolean-based",
"maliciousPattern": "OR 1=1",
"requestPath": "/api/users",
"clientIp": "192.168.1.100",
"userAgent": "Mozilla/5.0..."
}
}{
"threatId": "SQL-2025-12-28-5678",
"description": "SQL injection attempt detected in query",
"moduleType": "SqlInjection",
"detectedAt": "2025-12-28T14:22:10Z",
"confidence": 0.95,
"metadata": {
"query": "SELECT * FROM Users WHERE Id = 1 OR 1=1--",
"attackType": "boolean-based",
"maliciousPattern": "OR 1=1",
"requestPath": "/api/users",
"clientIp": "192.168.1.100",
"userAgent": "Mozilla/5.0..."
}
}Related Protections
- NoSQL Injection - MongoDB, Redis protection
- Cross-Site Scripting - XSS prevention
- Command Injection - OS command protection
Next Steps
NoSQL Injection
MongoDB/Redis protection
Actions
Configure responses
JSON Configuration
Advanced configuration