Sql Injection in Aspnet
How Sql Injection Manifests in Aspnet
SQL Injection in ASP.NET applications typically occurs when user input is concatenated directly into SQL queries without proper sanitization. In ASP.NET, this vulnerability often appears in several common patterns that developers should recognize.
The most frequent manifestation is dynamic SQL construction using string concatenation. For example:
protected void LoginButton_Click(object sender, EventArgs e) {
string username = UsernameTextBox.Text;
string password = PasswordTextBox.Text;
string query = "SELECT * FROM Users WHERE Username = '" + username + "' AND Password = '" + password + "'";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) {
// Authentication success
}
}
}This code is vulnerable because an attacker can input ' OR '1'='1 as the username, causing the query to return all users regardless of password.
Another common ASP.NET pattern is using SqlDataSource with unvalidated parameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="..."
SelectCommand="SELECT * FROM Products WHERE Category = {0}">
</asp:SqlDataSource>When the parameter {0} comes from user input without validation, it creates the same vulnerability.
Entity Framework, while generally safer, can still be vulnerable when using raw SQL or improperly constructed LINQ queries. For instance:
public IEnumerable<Product> GetProductsByCategory(string category) {
string query = "SELECT * FROM Products WHERE Category = '" + category + "'";
return context.Products.FromSqlRaw(query).ToList();
}Stored procedure calls in ASP.NET can also be vulnerable if parameters are concatenated rather than properly passed:
using (SqlCommand cmd = new SqlCommand("GetUser", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "EXEC GetUser '" + username + "'"; // Vulnerable
}The vulnerability manifests differently depending on the database backend (SQL Server, MySQL, PostgreSQL) but the ASP.NET code patterns remain consistent across implementations.
Aspnet-Specific Detection
Detecting SQL Injection in ASP.NET applications requires both static analysis of the codebase and dynamic runtime testing. Here's how to identify these vulnerabilities specifically in ASP.NET contexts.
Code Review Patterns: Look for these red flags in your ASP.NET codebase:
- String concatenation with SQL keywords (SELECT, INSERT, UPDATE, DELETE, WHERE, OR, AND)
- Dynamic SQL construction using
StringBuilderor string interpolation - Raw SQL queries in Entity Framework (
FromSqlRaw,ExecuteSqlRaw) - Unvalidated
SqlDataSourceparameters - Stored procedure calls with concatenated parameters
middleBrick Scanner Detection: middleBrick's black-box scanning approach is particularly effective for ASP.NET applications because it tests the actual running API endpoints without requiring source code access. The scanner:
- Identifies ASP.NET endpoints by examining HTTP responses (X-AspNet-Version, X-AspNetMvc-Version headers)
- Tests for SQL Injection by sending payloads like
' OR '1'='1,'; DROP TABLE Users--, and time-based payloads - Analyzes response patterns to detect successful injection (error messages, timing differences, data leakage)
- Maps findings to OWASP API Top 10 categories for compliance reporting
Manual Testing Steps:
1. Identify all API endpoints that accept user input
2. For each parameter, test with: ' OR '1'='1
3. Look for: authentication bypass, error messages, different response times
4. Test with: '; WAITFOR DELAY '0:0:5'--
5. Check if response takes ~5 seconds longer
6. Test with: ' UNION SELECT ... --
7. Look for data leakage in responsesmiddleBrick CLI Example:
npm install -g middlebrick
middlebrick scan https://yourapi.com/api/users/login
The scanner returns a security score (0-100) with specific findings about SQL Injection vulnerabilities, including severity levels and remediation guidance. For ASP.NET applications, it specifically checks for patterns common to the framework and provides actionable recommendations.
Aspnet-Specific Remediation
Remediating SQL Injection in ASP.NET applications requires adopting parameterized queries and leveraging the framework's built-in security features. Here are the specific approaches for ASP.NET.
Parameterized Queries with SqlCommand:
protected void LoginButton_Click(object sender, EventArgs e) {
string username = UsernameTextBox.Text;
string password = PasswordTextBox.Text;
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Users WHERE Username = @username AND Password = @password",
conn
);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password); // Note: still hash passwords in production
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) {
// Authentication success
}
}
}Entity Framework Best Practices:
// Safe LINQ queries
public IEnumerable<Product> GetProductsByCategory(string category) {
return context.Products
.Where(p => p.Category == category)
.ToList();
}
// Safe raw SQL with parameters
public IEnumerable<Product> GetProductsByCategory(string category) {
return context.Products
.FromSqlRaw("SELECT * FROM Products WHERE Category = {0}", category)
.ToList();
}
// Even safer with SqlParameter
public IEnumerable<Product> GetProductsByCategory(string category) {
return context.Products
.FromSqlRaw("SELECT * FROM Products WHERE Category = @p0",
new SqlParameter("@p0", category))
.ToList();
}Using SqlDataSource with Parameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="..."
SelectCommand="SELECT * FROM Products WHERE Category = @Category">
<SelectParameters>
<asp:QueryStringParameter Name="@Category" QueryStringField="category" Type="String" />
</SelectParameters>
</asp:SqlDataSource>Stored Procedure Security:
using (SqlCommand cmd = new SqlCommand("GetUser", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
// Safe parameter passing
cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
using (SqlDataReader reader = cmd.ExecuteReader()) {
// Process results
}
}Input Validation and Sanitization:
public bool IsValidInput(string input) {
// Simple whitelist approach
return Regex.IsMatch(input, @"^[[email protected]]{1,50}$");
}
// In your methods:
if (!IsValidInput(username)) {
throw new ArgumentException("Invalid username format");
}middleBrick Integration for Continuous Security:
// In your CI/CD pipeline (GitHub Action)
- name: Run middleBrick Security Scan
uses: middlebrick/middlebrick-action@v1
with:
api-url: 'https://staging.yourapp.com'
fail-on-severity: 'high'
token: ${{ secrets.MIDDLEBRICK_TOKEN }}
This ensures SQL Injection vulnerabilities are caught before deployment. The middleBrick scanner specifically tests for these patterns in ASP.NET applications and provides detailed remediation guidance for each finding.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |