Header Injection in Fiber
How Header Injection Manifests in Fiber
Header injection vulnerabilities in Fiber applications occur when user-controlled data flows into HTTP response headers without proper validation. In Fiber, this typically manifests through three primary attack vectors:
1. Dynamic Header Construction
Fiber's Context.Set() method allows developers to set response headers programmatically. When header names or values incorporate user input, attackers can manipulate the header structure. For example:
func (r *Router) SetCustomHeader(c *fiber.Ctx) error {
headerName := c.Query("header_name")
headerValue := c.Query("header_value")
c.Set(headerName, headerValue)
return c.SendStatus(fiber.StatusOK)
}
An attacker could request /set-header?header_name=Content-Type%0ASet-Cookie:%20session=evil, injecting a newline character (%0A) to create multiple headers. This breaks the header structure, potentially allowing cookie injection or content-type manipulation.
2. Header Reflection in Error Responses
Fiber applications often reflect request headers in error messages or debugging output. Consider:
func (r *Router) EchoUserAgent(c *fiber.Ctx) error {
userAgent := c.Get("User-Agent")
c.Set("X-Reflected-UA", userAgent)
return c.SendStatus(fiber.StatusOK)
}
If an attacker sends a User-Agent with newline characters, they can inject arbitrary headers. The vulnerability becomes more severe when combined with error handlers that echo request data.
3. Template-Based Header Generation
Fiber's template rendering can inadvertently create header injection points when user data flows into header-related templates:
func (r *Router) RenderWithHeaders(c *fiber.Ctx) error {
data := map[string]string{
"customHeader": c.Query("header"),
}
return r.Templates.Render(c, "header-template", data)
}
If the template includes {{.customHeader}} in a context that generates HTTP headers, newline injection becomes possible.
Fiber-Specific Detection
Detecting header injection in Fiber requires both manual code review and automated scanning. Here's how to identify these vulnerabilities:
Static Analysis Patterns
Search your Fiber codebase for these patterns that indicate potential header injection:
# Look for Set() calls with user input
grep -r "c\.Set(" --include="*.go" | grep -E "(Query|Get|Params|Body)">
# Find header reflection patterns
grep -r "Get(" --include="*.go" | grep -E "(Set|Response|Header)"
Dynamic Testing with middleBrick
middleBrick's black-box scanning approach is particularly effective for detecting header injection in Fiber applications. The scanner tests for:
- Newline character injection in header names and values
- CRLF injection attempts
- Header splitting via %0A and %0D encodings
- Response splitting attacks
To scan your Fiber API:
npm install -g middlebrick
middlebrick scan https://your-fiber-app.com/api
The scanner returns a security score with specific findings. For header injection, you'll see:
- Authentication bypass attempts via header manipulation
- Response splitting vulnerabilities
- Header injection severity levels (Critical/High/Medium)
- Exact request payloads that triggered the vulnerability
Manual Testing Methodology
Complement automated scanning with targeted manual testing:
# Test header injection endpoints
curl -v "https://your-fiber-app.com/api/set-header?header_name=Content-Type%0AX-XSS-Protection:%200" \
-H "User-Agent: Mozilla/5.0%0ASet-Cookie:%20evil=1"
Look for unexpected headers in the response. If you see injected headers like X-XSS-Protection: 0 or Set-Cookie: evil=1, you have a header injection vulnerability.
Fiber-Specific Remediation
Fixing header injection in Fiber requires input validation and secure coding practices. Here are Fiber-specific remediation techniques:
1. Input Validation and Sanitization
Always validate header names and values before setting them:
import (
"regexp"
"github.com/gofiber/fiber/v2"
)
var validHeaderName = regexp.MustCompile(`^[a-zA-Z0-9-]+$`)
var validHeaderValue = regexp.MustCompile(`^[^\n\r]*$`)
func safeSetHeader(c *fiber.Ctx, name, value string) error {
if !validHeaderName.MatchString(name) {
return c.Status(fiber.StatusBadRequest).SendString("Invalid header name")
}
if !validHeaderValue.MatchString(value) {
return c.Status(fiber.StatusBadRequest).SendString("Invalid header value")
}
c.Set(name, value)
return nil
}
2. Use Fiber's Built-in Security Middleware
Fiber provides security middleware that helps prevent header injection:
import "github.com/gofiber/fiber/v2/middleware/protectheader"
func setupRouter() *fiber.App {
app := fiber.New()
// Protect against header injection
app.Use(protectheader.New())
return app
}
The protectheader middleware automatically validates and sanitizes headers, blocking injection attempts.
3. Safe Header Construction Pattern
func (r *Router) SetCustomHeaderSafe(c *fiber.Ctx) error {
// Only allow predefined header names
allowedHeaders := map[string]bool{
"X-Custom-Header": true,
"X-Request-ID": true,
}
headerName := c.Query("header_name")
if !allowedHeaders[headerName] {
return c.Status(fiber.StatusBadRequest).SendString("Invalid header name")
}
// Sanitize value
headerValue := c.Query("header_value")
headerValue = strings.ReplaceAll(headerValue, "\n", "")
headerValue = strings.ReplaceAll(headerValue, "\r", "")
c.Set(headerName, headerValue)
return c.SendStatus(fiber.StatusOK)
}
4. Error Handler Security
func errorHandler(c *fiber.Ctx, err error) error {
// Never reflect raw headers in error responses
safeResponse := map[string]interface{}{
"error": err.Error(),
"status": c.Response().StatusCode(),
}
return c.Status(fiber.StatusInternalServerError).JSON(safeResponse)
}
5. Continuous Monitoring with middleBrick
After implementing fixes, use middleBrick's Pro plan for continuous monitoring:
# GitHub Action for CI/CD integration
name: API Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install -g middlebrick
- run: middlebrick scan https://staging.your-fiber-app.com --fail-below B
This ensures header injection vulnerabilities are caught before deployment. The GitHub Action can fail builds if security scores drop below your threshold, maintaining security standards throughout development.
Frequently Asked Questions
How does middleBrick detect header injection in Fiber applications?
Can header injection in Fiber lead to authentication bypass?
Set-Cookie header or manipulate Authorization headers, they might hijack sessions or elevate privileges. For example, injecting Set-Cookie: sessionid=valid-session could allow an attacker to authenticate as another user. Similarly, manipulating X-Forwarded-User or custom authentication headers could bypass access controls. This is why middleBrick includes authentication bypass testing in its scanning methodology, specifically looking for header injection vectors that could compromise authentication mechanisms.