Sql Injection in Gorilla Mux
How Sql Injection Manifests in Gorilla Mux
Sql Injection in Gorilla Mux applications typically occurs when route parameters containing user input are directly interpolated into SQL queries without proper sanitization. The vulnerability manifests through Gorilla Mux's path parameter extraction, where dynamic segments like {id} or {name} are captured and passed to database operations.
Consider this common pattern in Gorilla Mux applications:
router := mux.NewRouter()
router.HandleFunc("/users/{id}", getUserHandler).Methods("GET")
func getUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
// Vulnerable: direct interpolation
query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", id)
// Execute query...
}The vulnerability becomes critical when attackers manipulate the id parameter. A request to /users/1 OR 1=1 transforms the query into SELECT * FROM users WHERE id = 1 OR 1=1, returning all user records. More sophisticated attacks like /users/1; DROP TABLE users; can execute destructive operations.
Another manifestation occurs with string parameters:
router.HandleFunc("/search/{query}", searchHandler).Methods("GET")
func searchHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
query := vars["query"]
// Vulnerable: string interpolation without escaping
sqlQuery := fmt.Sprintf("SELECT * FROM products WHERE name LIKE '%s'", query)
// Execute query...
}An attacker requesting /search/coffee' OR '1'='1 would execute SELECT * FROM products WHERE name LIKE 'coffee' OR '1'='1', bypassing intended filters. The problem compounds when multiple parameters are involved, allowing complex boolean logic injection.
Even when using prepared statements, improper parameter binding in Gorilla Mux handlers can reintroduce vulnerabilities if parameters aren't correctly validated before database operations.
Gorilla Mux-Specific Detection
Detecting Sql Injection in Gorilla Mux applications requires examining how path parameters flow through the request handling pipeline. The first indicator is the use of mux.Vars(r) to extract parameters that subsequently appear in SQL operations without validation.
middleBrick's scanning approach specifically targets this pattern by intercepting HTTP requests to your Gorilla Mux endpoints and injecting SQL payloads into path parameters. The scanner tests common injection patterns like:
- Boolean conditions:
OR 1=1,AND 1=0 - Comment delimiters:
--,#,/* */ - Union-based queries:
UNION SELECT - Stacked queries:
;followed by another SQL statement - Time-based delays:
WAITFOR DELAY,BENCHMARK()
For a Gorilla Mux endpoint like /users/{id}, middleBrick systematically replaces the {id} parameter with SQL payloads and analyzes the response patterns. Indicators of successful injection include:
- Application errors containing SQL syntax
- Response time variations suggesting conditional logic execution
- Unexpected data in responses (union-based data extraction)
- HTTP status code changes indicating different execution paths
The scanner also examines the OpenAPI/Swagger specification if provided, mapping documented parameters to actual runtime behavior. This cross-referencing identifies discrepancies between documented input validation and actual implementation.
middleBrick's LLM/AI Security module adds another layer by detecting if SQL injection payloads are being processed by any AI endpoints within your Gorilla Mux application, preventing model manipulation through crafted inputs.
Gorilla Mux-Specific Remediation
The most effective remediation for Sql Injection in Gorilla Mux applications is using parameterized queries with proper input validation. Here's the secure pattern:
router.HandleFunc("/users/{id}", getUserHandler).Methods("GET")
func getUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
// Validate parameter type and format
if !isValidID(id) {
http.Error(w, "Invalid ID format", http.StatusBadRequest)
return
}
// Use parameterized query
rows, err := db.Query("SELECT * FROM users WHERE id = $1", id)
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
// Process results...
}
func isValidID(id string) bool {
// Example: numeric ID validation
if _, err := strconv.Atoi(id); err != nil {
return false
}
return true
}For string parameters, always use parameterized queries and validate input length and character sets:
router.HandleFunc("/search/{query}", searchHandler).Methods("GET")
func searchHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
query := vars["query"]
// Validate input length and allowed characters
if len(query) > 100 || !isValidSearchQuery(query) {
http.Error(w, "Invalid search query", http.StatusBadRequest)
return
}
// Parameterized query with LIKE
rows, err := db.Query("SELECT * FROM products WHERE name LIKE $1", "%"+query+"%")
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
// Process results...
}
func isValidSearchQuery(query string) bool {
// Allow only alphanumeric and basic punctuation
matched, _ := regexp.MatchString(`^[a-zA-Z0-9\s.,-]*$`, query)
return matched
}middleBrick's Pro plan continuously monitors your Gorilla Mux endpoints, scanning for regression of SQL injection vulnerabilities whenever your application changes. The GitHub Action integration can automatically scan your staging API before deployment, failing the build if new injection points are discovered.
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 |