Sql Injection in Gin with Basic Auth
Sql Injection in Gin with Basic Auth — how this specific combination creates or exposes the vulnerability
SQL injection in a Gin service that also uses HTTP Basic Auth can occur when user-controlled input is concatenated into SQL strings, even when credentials are verified. Basic Auth supplies a username and password in the Authorization header; if the handler uses these values directly in queries without parameterization, the attack surface expands. For example, an attacker could supply a crafted username like admin' OR '1'='1 and, if the code builds SQL by string concatenation, the query may return unauthorized rows. The presence of Basic Auth does not prevent SQL injection; it only adds a perimeter that may be bypassed if the backend logic is flawed.
Consider a login handler that reads username and password from the Basic Auth header and then builds a query like "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'". This pattern is vulnerable regardless of whether credentials are correct, because special characters in the username can change query semantics. In Gin, if the handler uses db.Raw or string formatting to build queries, an attacker may bypass authentication or extract data. Even when passwords are hashed, leaking a username can aid further attacks. The combination therefore creates a scenario where authentication is present but the data layer remains unsafe.
Real-world patterns matter. An endpoint that accepts an ID via URL query parameters and merges it with Basic Auth-derived context can suffer Insecure Direct Object Reference (IDOR) or authorization bypass if the SQL does not enforce tenant or user scope. For instance, a query like "SELECT * FROM documents WHERE id = " + id ignores row-level security, and Basic Auth alone does not fix this. Attack patterns such as second-order injection can also appear when values extracted from headers are stored and later used unsafely. Because middleBrick tests unauthenticated attack surfaces, it can surface SQL injection risks even when Basic Auth is in use, emphasizing the need to treat headers as untrusted inputs.
Compliance mappings are relevant here. Findings may align with OWASP API Top 10 (2023) API1:2023 Broken Object Level Authorization and API5:2023 Injection, and can map to PCI-DSS requirements around data integrity. The scanner tests endpoints for SQL injection indicators and reports findings with severity and remediation guidance, helping teams understand how headers and query construction interact to increase risk.
Basic Auth-Specific Remediation in Gin — concrete code fixes
Remediation focuses on never mixing credentials or user input directly into SQL strings. Use parameterized queries or prepared statements, validate and normalize usernames, and enforce least privilege for database accounts. The following examples show insecure patterns and their secure counterparts in Go with Gin.
Insecure example that builds SQL by concatenation:
// DO NOT DO THIS
username, password, ok := req.BasicAuth()
if !ok {
c.AbortWithStatusJSON(401, gin.H{"error": "missing auth"})
return
}
query := fmt.Sprintf("SELECT id FROM users WHERE username = '%s' AND password = '%s'", username, password)
var id int
if err := db.Raw(query).Scan(&id).Error; err != nil {
c.AbortWithStatusJSON(401, gin.H{"error": "invalid credentials"})
return
}
c.JSON(200, gin.H{"id": id})
Secure example using parameterized queries with GORM:
username, password, ok := req.BasicAuth() if !ok { c.AbortWithStatusJSON(401, gin.H{"error": "missing auth"}) return } var user User // Use placeholders to avoid SQL injection result := db.Where("username = ? AND password = ?", username, password).First(&user) if result.Error != nil { c.AbortWithStatusJSON(401, gin.H{"error": "invalid credentials"}) return } c.JSON(200, gin.H{"id": user.ID})Additional hardening steps include hashing passwords (using bcrypt), avoiding inclusion of credentials in logs, and applying principle of least privilege to the database user used by the service. When using middleware to extract Basic Auth, ensure the extracted values are treated strictly as inputs and never interpolated into dynamic SQL. The CLI tool (middlebrick) can scan endpoints to verify that such unsafe patterns are absent, and the Web Dashboard helps track risk scores over time.
For teams with many services, the Pro plan supports continuous monitoring and can integrate with GitHub Actions to fail builds if risk thresholds are exceeded. The MCP Server allows you to scan APIs directly from your AI coding assistant, helping catch unsafe SQL construction before code reaches production.
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 |