/

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

JSON
{
  "protections": {
    "SqlInjection": {
      "enabled": true,
      "action": "block"
    }
  }
}

ASP.NET Core Middleware

C#
builder.Services.AddBytehideMonitor(monitor => monitor
    .WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);

Advanced Configuration

JSON
{
  "protections": {
    "SqlInjection": {
      "enabled": true,
      "action": "block",
      "config": {
        "sensitivityLevel": "high",
        "blockStoredProcedures": false,
        "allowDynamicSql": false
      }
    }
  }
}

Available Actions

ActionBehaviorRecommended For
BlockReturn HTTP 403, prevent query executionProduction web applications
LogRecord incident, allow queryDevelopment, low-risk environments
CustomExecute custom handlerEnterprise 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

C#
// 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

UNION-Based Injection

C#
// 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

Blind SQL Injection

C#
// Vulnerable code
var username = Request.Form["username"];
var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
// Attack: username=admin' AND SLEEP(5)--
// Status: BLOCKED

Stored Procedure Abuse

C#
// Vulnerable code
var input = Request.Query["input"];
var sql = $"EXEC xp_cmdshell '{input}'";
// Attack: input=whoami
// Status: BLOCKED

Configuration Parameters

Sensitivity Levels

JSON
{
  "protections": {
    "SqlInjection": {
      "enabled": true,
      "action": "block",
      "config": {
        "sensitivityLevel": "high"
      }
    }
  }
}
LevelDescriptionFalse PositivesRecommended For
lowBasic pattern matchingVery fewComplex queries, reporting systems
mediumStandard detectionFewMost applications
highAggressive detectionPossibleHigh-security applications, financial systems

Allow Dynamic SQL

JSON
{
  "config": {
    "allowDynamicSql": true
  }
}

When enabled: Allows certain dynamic SQL patterns (use with caution) Default: false


Custom Response Handler

C#
builder.Services.AddBytehideMonitor(monitor => monitor
    .WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block)
);

Endpoint-Specific Configuration

Configure different sensitivity per route:

JSON
{
  "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:

C#
var sql = $"SELECT * FROM Users WHERE Username = '{username}'";
var users = db.ExecuteQuery(sql);

Recommended:

C#
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:

C#
// 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:

C#
// 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:

ScenarioWithout MonitorWith MonitorOverhead
Simple SELECT2ms2.1ms+5%
Complex JOIN15ms15.2ms+1.3%
Bulk INSERT50ms50.5ms+1%

Platform Compatibility

PlatformSupportNotes
ASP.NET Core 6+Full support
ASP.NET Core 3.1-5.0Full support
ASP.NET Framework 4.6.2+Full support via HttpModule
Blazor ServerServer-side protection
Entity Framework CoreAll versions
Entity Framework 6Full support
DapperFull support
NHibernateFull support

Threat Detection Details

When an attack is detected, the ThreatInfo object contains:

JSON
{
  "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..."
  }
}


Next Steps

NoSQL Injection

MongoDB/Redis protection

Actions

Configure responses

JSON Configuration

Advanced configuration

Previous
Cloud Metadata