Sql Injection in Chi
How Sql Injection Manifests in Chi
SQL injection vulnerabilities in Chi-based applications typically occur when user-supplied data is concatenated directly into SQL queries without proper sanitization. In Chi applications, this often manifests through HTTP handlers that accept query parameters or JSON payloads, which are then interpolated into database queries.
A common pattern in Chi applications involves using chi.URLParam or chi.QueryParam to extract values from requests, then embedding these directly into SQL strings. For example:
func getUserHandler(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", id)
// Vulnerable: id can contain malicious SQL
rows, _ := db.Query(query)
// ...
}
This creates a classic injection point where an attacker could supply 1 OR 1=1 or more destructive payloads. The vulnerability is particularly dangerous in Chi applications because middleware chains often process requests before reaching the vulnerable handler, making detection through simple request inspection more challenging.
Chi's route parameter handling makes it easy to accidentally create injection points. Consider this endpoint:
r.Get("/api/users/{id}", getUserHandler)
If getUserHandler doesn't properly validate or sanitize the id parameter, an attacker can manipulate the URL to inject arbitrary SQL. This is especially problematic when the parameter is expected to be numeric but is treated as a string in the query.
Another Chi-specific manifestation occurs when using middleware that modifies request context. If a middleware injects database connection parameters into the context and a handler constructs queries using those parameters without validation, injection becomes possible through the middleware chain.
Chi-Specific Detection
Detecting SQL injection in Chi applications requires both static analysis and dynamic testing. Static analysis should focus on route handlers that accept parameters and construct SQL queries. Look for patterns where chi.URLParam, chi.QueryParam, or chi.Bind are used in conjunction with string concatenation for SQL construction.
Dynamic testing with middleBrick can identify SQL injection vulnerabilities in Chi applications without requiring source code access. The scanner tests endpoints by submitting payloads designed to trigger SQL syntax errors or unusual response patterns. For Chi applications, middleBrick specifically examines:
- Route parameters extracted via
chi.URLParamthat might be used in queries - Query parameters processed by Chi handlers
- JSON bodies bound to structs that contain fields used in database operations
- Middleware-modified request contexts that could contain injectable data
- Database connection strings or credentials that might be manipulated
middleBrick's SQL injection detection for Chi applications includes testing for classic payloads like ' OR '1'='1, OR 1=1--, and '; DROP TABLE users; --. The scanner also checks for timing-based injections by using payloads that cause conditional delays, which is particularly effective against Chi applications using PostgreSQL or MySQL backends.
For API endpoints defined in OpenAPI specifications used with Chi, middleBrick cross-references the spec's parameter definitions with its runtime findings. If an endpoint declares a numeric ID parameter but the implementation doesn't validate this constraint, the scanner flags this as a potential injection vector.
Chi-Specific Remediation
The most effective remediation for SQL injection in Chi applications is to use parameterized queries or prepared statements exclusively. Chi itself doesn't provide database functionality, but it integrates well with Go's database/sql package, which supports proper parameter binding.
Here's a secure version of the vulnerable handler:
func getUserHandler(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
// Validate that id is a valid integer
if idInt, err := strconv.Atoi(id); err != nil {
http.Error(w, "Invalid ID format", http.StatusBadRequest)
return
}
// Use parameterized query - the database driver handles escaping
query := "SELECT * FROM users WHERE id = $1"
row := db.QueryRow(query, idInt)
var user User
if err := row.Scan(&user.ID, &user.Name, &user.Email); err != nil {
if err == sql.ErrNoRows {
http.Error(w, "User not found", http.StatusNotFound)
} else {
http.Error(w, "Database error", http.StatusInternalServerError)
}
return
}
json.NewEncoder(w).Encode(user)
}
Notice the key changes: input validation ensures the ID is numeric before database interaction, and the query uses $1 placeholder with the actual value passed as a parameter. The database driver handles proper escaping, eliminating injection possibilities.
For more complex queries in Chi applications, use query builders like Squirrel or SQLBoiler that enforce parameterization:
func getUsersByRole(w http.ResponseWriter, r *http.Request) {
role := chi.QueryParam(r, "role")
// Whitelist allowed roles
allowedRoles := map[string]bool{"admin": true, "user": true, "guest": true}
if !allowedRoles[role] {
http.Error(w, "Invalid role", http.StatusBadRequest)
return
}
// Use query builder for complex queries
query, args, _ := sq.Select("*").
From("users").
Where(sq.Eq{"role": role}).
ToSql()
rows, err := db.Query(query, args...)
// ...
}
Chi middleware can also help enforce security policies across all handlers. A validation middleware could check parameters before they reach handlers:
func validationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for SQL injection patterns in all parameters
if containsSQLInjection(r.URL.Query()) {
http.Error(w, "Invalid input detected", http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
}
// Apply to all routes
r.Use(validationMiddleware)
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 |