HIGH header injectionchi

Header Injection in Chi

How Header Injection Manifests in Chi

Header injection vulnerabilities in Chi-based APIs occur when user-controlled input flows into HTTP response headers without proper validation. This manifests in several Chi-specific patterns that developers should recognize.

The most common vector is through path parameters that get reflected in Location headers. Consider this vulnerable Chi route:

r := chi.NewRouter()
r.Get("/redirect/{path}", func(w http.ResponseWriter, r *http.Request) {
    path := chi.URLParam(r, "path")
    http.Redirect(w, r, "/"+path, http.StatusFound)
})

An attacker can inject newline characters to add arbitrary headers:

GET /redirect/foo%0d%0aSet-Cookie:%20evil=true HTTP/1.1

This results in:

HTTP/1.1 302 Found
Location: /foo
Set-Cookie: evil=true

Another Chi-specific pattern involves context values that flow into headers. Chi's middleware pattern makes this particularly dangerous:

r.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        userID := r.URL.Query().Get("user_id")
        ctx := context.WithValue(r.Context(), "userID", userID)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
})

r.Get("/profile", func(w http.ResponseWriter, r *http.Request) {
    userID := r.Context().Value("userID").(string)
    w.Header().Set("X-User-ID", userID) // Vulnerable if userID contains newlines
})

Middleware that logs request information can also create injection points:

r.Use(middleware.RequestLogger(&middleware.DefaultLogFormatter{
    Logger: log.New(os.Stdout, "", 0),
    NoColor: true,
}))

While Chi's RequestLogger doesn't directly write headers, it demonstrates how request data flows through the middleware chain where subsequent handlers might use it insecurely.

Chi-Specific Detection

Detecting header injection in Chi applications requires both manual code review and automated scanning. middleBrick's black-box scanner is particularly effective at finding these vulnerabilities in Chi APIs.

middleBrick scans Chi endpoints by sending payloads with newline characters and observing header responses. For example, it tests:

GET /api/resource?param=value%0d%0aX-Injected:%20test HTTP/1.1

The scanner then analyzes responses for unexpected headers like X-Injected, Set-Cookie, or other injected values. middleBrick's parallel scanning tests all 12 security categories simultaneously, including authentication bypass attempts that might reveal header injection.

For development environments, middleBrick's CLI tool provides immediate feedback:

middlebrick scan https://api.example.com/user/123

This returns a security score with specific findings about header injection vulnerabilities, if present. The tool tests the unauthenticated attack surface that Chi applications expose.

Manual detection in Chi code involves searching for these patterns:

  • Direct use of URL parameters in header values
  • Context values derived from user input that flow to headers
  • Middleware that captures request data without sanitization
  • Reflection of any user-controlled data in response headers

Chi's middleware stack makes this particularly important to review, as data flows through multiple layers before reaching the final handler.

Chi-Specific Remediation

Remediating header injection in Chi requires input validation and safe header construction. Chi provides several patterns for secure implementation.

The most fundamental fix is validating header values before setting them. Chi's middleware ecosystem supports this through validation middleware:

func sanitizeHeader(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Validate and sanitize header values
        userID := chi.URLParam(r, "userID")
        if strings.ContainsAny(userID, "\r\n") {
            http.Error(w, "invalid input", http.StatusBadRequest)
            return
        }
        next.ServeHTTP(w, r)
    })
}

r := chi.NewRouter()
r.Use(sanitizeHeader)

For context-based header setting, validate before storing:

r.Use(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        userID := r.URL.Query().Get("user_id")
        if strings.ContainsAny(userID, "\r\n") {
            http.Error(w, "invalid user_id", http.StatusBadRequest)
            return
        }
        ctx := context.WithValue(r.Context(), "userID", userID)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
})

Chi's built-in middleware provides safer alternatives. Use middleware.DefaultCompress instead of custom compression middleware that might mishandle headers:

r.Use(middleware.DefaultCompress)

For redirects, validate the target path explicitly:

func safeRedirect(w http.ResponseWriter, r *http.Request, path string) {
    if strings.ContainsAny(path, "\r\n") || strings.Contains(path, "..") {
        http.Error(w, "invalid redirect", http.StatusBadRequest)
        return
    }
    http.Redirect(w, r, path, http.StatusFound)
}

middleBrick's GitHub Action can enforce these fixes in CI/CD:

- name: Scan API Security
  uses: middlebrick/middlebrick-action@v1
  with:
    url: ${{ secrets.API_URL }}
    fail-on-severity: high
    token: ${{ secrets.MIDDLEBRICK_TOKEN }}

This ensures header injection vulnerabilities are caught before deployment, with the scan running in 5-15 seconds without requiring credentials or configuration.

Frequently Asked Questions

How does middleBrick detect header injection in Chi APIs?
middleBrick sends payloads containing newline characters (%0d%0a) to Chi endpoints and analyzes responses for unexpected headers. The scanner tests the unauthenticated attack surface in 5-15 seconds without requiring credentials, making it ideal for Chi applications where header injection often occurs through unauthenticated endpoints.
Can middleBrick scan Chi APIs in my CI/CD pipeline?
Yes, middleBrick's GitHub Action integrates directly into Chi-based CI/CD pipelines. You can fail builds if security scores drop below thresholds, ensuring header injection and other vulnerabilities are caught before deployment. The Pro plan includes continuous monitoring that scans APIs on configurable schedules with alerts.