Xss Cross Site Scripting in Echo Go
How XSS Cross Site Scripting Manifests in Echo Go
XSS vulnerabilities in Echo Go applications typically occur when user input is rendered without proper sanitization. Echo Go's templating system and HTTP handling create several attack vectors that developers must guard against.
The most common XSS pattern in Echo Go involves directly echoing user input in HTML templates. Consider this vulnerable code:
func handler(c echo.Context) error {
userInput := c.QueryParam("search")
return c.HTML(http.StatusOK, "<p>You searched for: "+userInput+"</p>")
}If a user submits search?q=<script>alert('xss')</script>, the script executes in victims' browsers. This basic reflected XSS pattern is particularly dangerous in Echo Go applications that echo query parameters, form data, or URL path parameters without validation.
Echo Go's context binding can also introduce XSS risks. When using struct binding with JSON or form data:
type User struct {
Name string `json:"name"`
}
func handler(c echo.Context) error {
user := new(User)
if err := c.Bind(user); err != nil {
return err
}
return c.JSON(http.StatusOK, map[string]string{"message": "Hello " + user.Name})
}The JSON response here is safe from XSS, but if this data is later rendered in a template without escaping, the vulnerability persists.
Echo Go's HTML template rendering requires explicit attention. By default, Echo Go's template engine doesn't automatically escape all output. A vulnerable template might look like:
<div>{{.UserInput}}</div>Without the {{html .UserInput}} function, malicious scripts execute. Stored XSS can occur when user input is saved to databases and later rendered in Echo Go templates without proper escaping.
DOM-based XSS is less common in Echo Go since it's primarily a server-side framework, but can occur when Echo Go serves JavaScript files that dynamically insert user data into the DOM without proper sanitization.
Echo Go-Specific Detection
Detecting XSS in Echo Go applications requires both manual code review and automated scanning. middleBrick's black-box scanner is particularly effective at finding XSS vulnerabilities in Echo Go endpoints without requiring source code access.
middleBrick tests Echo Go applications by submitting payloads to all input parameters and analyzing responses. For Echo Go specifically, the scanner examines:
- Query parameters (
c.QueryParam()) - Form data (
c.FormValue()) - JSON body fields (
c.Bind()) - URL path parameters (
c.Param()) - Cookie values
The scanner injects XSS payloads like <script>alert(1)</script>, '"><img src=x onerror=alert(1)>, and HTML entity-encoded variants, then checks if scripts execute in the response.
For Echo Go applications with OpenAPI specifications, middleBrick performs enhanced analysis by correlating the spec's parameter definitions with actual runtime behavior. This catches cases where Echo Go's automatic binding might introduce unexpected XSS vectors.
Manual detection techniques for Echo Go developers include:
// Test endpoint - look for unescaped output
func testXSS(c echo.Context) error {
input := c.QueryParam("data")
// Vulnerable: direct output without escaping
return c.HTML(http.StatusOK, "<div>"+input+"</div>")
}
// Safe version
func safeHandler(c echo.Context) error {
input := c.QueryParam("data")
return c.HTML(http.StatusOK, "<div>"+html.EscapeString(input)+"</div>")
}middleBrick's scanning process for Echo Go applications takes 5-15 seconds and provides severity ratings with specific remediation guidance. The scanner identifies whether vulnerabilities are reflected, stored, or DOM-based, and maps findings to OWASP API Top 10 categories.
Echo Go-Specific Remediation
Securing Echo Go applications against XSS requires a defense-in-depth approach. The most effective remediation combines proper output encoding, input validation, and secure template usage.
Echo Go's built-in HTML escaping functions provide the first line of defense. Always use html.EscapeString() when rendering user input:
import "html"
func safeHandler(c echo.Context) error {
userInput := c.QueryParam("search")
escaped := html.EscapeString(userInput)
return c.HTML(http.StatusOK, "<p>You searched for: "+escaped+"</p>")
}
// For template rendering
func templateHandler(c echo.Context) error {
data := map[string]string{"userInput": c.QueryParam("data")}
return c.Render(http.StatusOK, "template", data)
}
// In your template file (template.tmpl):
<div>{{html .userInput}}</div>
<div>{{.userInput | html}}</div>
Echo Go's template engine supports multiple escaping strategies. Use the html pipeline function for HTML content, urlquery for URL parameters, and js for JavaScript contexts.
For JSON responses that might be consumed by browsers, ensure proper content-type headers and consider using a JSON encoder that escapes HTML entities:
import "github.com/valyala/fastjson"
func jsonHandler(c echo.Context) error {
data := map[string]interface{}{
"userInput": c.QueryParam("data"),
}
// Fastjson automatically escapes HTML in strings
return c.JSON(http.StatusOK, data)
}
// Input validation as defense-in-depth
func validateInput(input string) bool {
// Allow only alphanumeric and basic punctuation
for _, r := range input {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && !strings.ContainsRune(" ,.!?", r) {
return false
}
}
return true
}
Echo Go's middleware system enables global XSS protection. Create a middleware that automatically escapes all HTML responses:
func XSSMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := next(c)
if err != nil {
return err
}
// Check if response is HTML
if strings.Contains(c.Response().Header().Get("Content-Type"), "text/html") {
body := c.Response().Body()
// Read and escape HTML content
// (implementation depends on Echo Go version and response buffering)
}
return err
}
}
// Apply middleware globally
e := echo.New()
e.Use(XSSMiddleware)
For stored XSS prevention in Echo Go applications with databases, always sanitize data before storage or ensure proper escaping during retrieval and rendering. middleBrick's continuous monitoring in the Pro plan can alert you to new XSS vulnerabilities introduced in code changes.
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 |