HIGH header injectionfiberbasic auth

Header Injection in Fiber with Basic Auth

Header Injection in Fiber with Basic Auth — how this specific combination creates or exposes the vulnerability

Header Injection in a Fiber application using HTTP Basic Auth occurs when untrusted input is reflected into HTTP response headers without validation or sanitization. Because Basic Auth credentials are typically transmitted in the Authorization header as a base64-encoded string, developers sometimes decode and reuse parts of that value in downstream headers, logs, or redirects. If user-controlled data (e.g., a request header, query parameter, or body field) is concatenated into these values without strict allow-listing, an attacker can inject newline characters (CRLF, %0D%0A or \r\n) to split headers and inject additional ones, such as Set-Cookie, Location, or custom headers.

In Fiber, this can arise when route handlers use decoded Basic Auth values to construct headers dynamically. For example, parsing the Authorization header and inserting a username into a custom X-User header without sanitization enables header injection. Because Fiber is a fast, expressive web framework for Go, developers may assume that the framework’s built-in middleware handles safety, but input validation and header handling remain the application’s responsibility. Attackers exploit this to inject malicious headers that can lead to HTTP response splitting, cache poisoning, cross-site scripting (XSS) in browsers that interpret injected HTML via non-HTTP vectors, or manipulation of authentication flows via crafted cookies or redirects.

The risk is compounded when applications log or echo authorization context without sanitization, as newline characters in injected headers can fragment log entries and bypass log parsers. In a black-box scan, middleBrick tests such scenarios by submitting base64-encoded Basic Auth strings combined with newline sequences in other inputs, checking whether additional headers appear in the response. Because the attack leverages improper handling of user data in header construction rather than a flaw in Basic Auth itself, the vulnerability is classified under Input Validation and Data Exposure checks in the 12 parallel security checks. Remediation focuses on strict input validation, avoiding reflection of untrusted data into headers, and using framework-native mechanisms for authentication rather than manual header assembly.

Basic Auth-Specific Remediation in Fiber — concrete code fixes

To prevent Header Injection when using Basic Auth in Fiber, avoid manually parsing and reusing the Authorization header value to construct other headers. Instead, rely on middleware or standard library functions for authentication, and ensure any user-controlled data is validated and sanitized before being used in headers.

Example of vulnerable code that decodes Basic Auth and uses the username in a custom header, enabling header injection:

const authHeader = req.Get("Authorization")
if authHeader != "" {
    // Basic Auth: "Basic base64(credentials)"
    parts := strings.SplitN(authHeader, " ", 2)
    if len(parts) == 2 && parts[0] == "Basic" {
        decoded, _ := base64.StdEncoding.DecodeString(parts[1])
        credentialPair := strings.SplitN(string(decoded), ":", 2)
        if len(credentialPair) == 2 {
            username := credentialPair[0]
            // Vulnerable: user-controlled data reflected into a header
            req.Header.Set("X-User", username)
        }
    }
}

An attacker can supply a username containing \r\nSet-Cookie: to inject a cookie. The safer approach is to avoid echoing decoded credentials into headers. If you must pass identity information, use context values or strongly typed session management instead of headers.

Secure remediation using Fiber’s context and structured authentication without header reflection:

func BasicAuthMiddleware() fiber.Handler {
    return func(c *fiber.Ctx) error {
        auth := c.Get("Authorization")
        if auth == "" {
            return c.SendStatus(fiber.StatusUnauthorized)
        }
        const prefix = "Basic "
        if !strings.HasPrefix(auth, prefix) {
            return c.SendStatus(fiber.StatusUnauthorized)
        }
        payload, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
        if err != nil {
            return c.SendStatus(fiber.StatusUnauthorized)
        }
        parts := strings.SplitN(string(payload), ":", 2)
        if len(parts) != 2 || parts[0] != "validUser" || parts[1] != "validPass" {
            return c.SendStatus(fiber.StatusUnauthorized)
        }
        // Authenticated: store identity in context, not headers
        c.Locals("user", parts[0])
        return c.Next()
    }
}

app.Get("/profile", BasicAuthMiddleware(), func(c *fiber.Ctx) error {
    // Safe: no user-controlled header injection
    user := c.Locals("user").(string)
    return c.JSON(fiber.Map{"user": user})
})

Key practices:

  • Validate and parse Basic Auth server-side; do not reflect raw or partially decoded values into response headers.
  • Use context locals or secure session cookies for identity propagation instead of custom headers derived from credentials.
  • Apply strict allow-listing for any data that may end up in headers, and reject or encode newline characters if reflection is unavoidable.
  • Leverage Fiber’s built-in error handling to return consistent, non-informative status codes for authentication failures.

These steps reduce the attack surface for header injection and align with secure handling of authentication data in HTTP services.

Frequently Asked Questions

Can header injection via Basic Auth lead to session fixation or cookie theft?
Yes. If an attacker injects a Set-Cookie header via unsanitized Basic Auth-derived data, they can set arbitrary cookies in the victim’s browser, potentially leading to session fixation or theft depending on how the application uses those cookies.
Does middleBrick detect header injection in scans that include Basic Auth credentials?
middleBrick tests unauthenticated attack surfaces and can detect header injection patterns when newline sequences are reflected in headers. It does not store or transmit credentials; scans focus on response header manipulation to identify injection points.