HIGH cache poisoningfiber

Cache Poisoning in Fiber

How Cache Poisoning Manifests in Fiber

Cache poisoning in Fiber applications typically exploits the framework's flexible routing and parameter handling. A common attack vector involves manipulating query parameters that aren't properly validated before being cached. Consider a Fiber endpoint that caches user-specific data:

app := fiber.New()

app.Get("/api/user/:id", func(c *fiber.Ctx) error {
    id := c.Params("id")
    // No validation of 'id' parameter
    cacheKey := fmt.Sprintf("user-%s", id)
    
    if cached, ok := cache.Get(cacheKey); ok {
        return c.JSON(cached)
    }
    
    user := getUserFromDB(id)
    cache.Set(cacheKey, user, 300*time.Second)
    return c.JSON(user)
})

An attacker can exploit this by requesting /api/user/1?role=admin where the role parameter is ignored in the logic but included in the cache key. This creates a poisoned cache entry that serves admin data to any user requesting ID 1.

Another Fiber-specific pattern involves the framework's built-in cache middleware. When improperly configured, it can cache responses containing sensitive data:

app.Use(cache.New(cache.Config{
    Expiration:  30 * time.Second,
    KeyGenerator: func(c *fiber.Ctx) string {
        // Uses raw URL without normalizing parameters
        return c.OriginalURL()
    },
}))

The default KeyGenerator includes query parameters verbatim, so /api/data?token=abc and /api/data?token=xyz create separate cache entries. An attacker can force the cache to store responses with manipulated parameters, then serve these poisoned entries to other users.

Fiber-Specific Detection

Detecting cache poisoning in Fiber applications requires examining both the routing logic and caching implementation. middleBrick's black-box scanning approach is particularly effective here because it can identify unvalidated parameters that might be used in cache keys.

When scanning a Fiber API, middleBrick tests for cache poisoning by:

  • Modifying query parameters that appear in the URL but aren't validated in the response
  • Testing for cache hits with manipulated parameters
  • Checking if sensitive data appears in cached responses

For Fiber applications using the standard cache middleware, middleBrick analyzes the KeyGenerator function to see if it includes unvalidated parameters. The scanner looks for patterns like:

// Vulnerable KeyGenerator that includes raw query params
func(c *fiber.Ctx) string {
    return c.OriginalURL()
}

middleBrick's OpenAPI analysis also helps detect cache poisoning risks by cross-referencing parameter definitions in your spec with the actual runtime behavior. If your OpenAPI spec defines a parameter as optional but the implementation caches it without validation, this mismatch is flagged.

During a scan, middleBrick will test endpoints like:

GET /api/user/123?debug=true
GET /api/data?token=invalid
GET /api/search?q=

The scanner checks if these manipulated requests create cache entries that are then served to other users, which would indicate a cache poisoning vulnerability.

Fiber-Specific Remediation

Securing Fiber applications against cache poisoning requires both proper input validation and careful cache key construction. Here's how to implement these fixes in Fiber:

1. Validate and Normalize Parameters

app.Get("/api/user/:id", func(c *fiber.Ctx) error {
    id := c.Params("id")
    
    // Validate ID format
    if !isValidUserID(id) {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "error": "Invalid user ID",
        })
    }
    
    // Normalize query parameters
    queryParams := c.Query()
    normalizedParams := make(map[string]string)
    for k, v := range queryParams {
        normalizedParams[normalizeKey(k)] = normalizeValue(v)
    }
    
    cacheKey := fmt.Sprintf("user-%s-%s", id, hashParams(normalizedParams))
    
    if cached, ok := cache.Get(cacheKey); ok {
        return c.JSON(cached)
    }
    
    user := getUserFromDB(id)
    cache.Set(cacheKey, user, 300*time.Second)
    return c.JSON(user)
})

2. Use Safe Cache Key Generation

app.Use(cache.New(cache.Config{
    Expiration:  30 * time.Second,
    KeyGenerator: func(c *fiber.Ctx) string {
        // Only include whitelisted, validated parameters
        params := c.Query()
        safeParams := make(map[string]string)
        
        for _, allowedKey := range []string{"page", "limit"} {
            if val := params[allowedKey]; val != "" {
                safeParams[allowedKey] = sanitize(val)
            }
        }
        
        return fmt.Sprintf("%s-%s", c.Path(), hashParams(safeParams))
    },
}))

3. Implement Cache Invalidation

app.Post("/api/user/:id/update", func(c *fiber.Ctx) error {
    id := c.Params("id")
    
    // Process update...
    updateUser(id, c.Body())
    
    // Invalidate related cache entries
    cache.DeletePrefix(fmt.Sprintf("user-%s", id))
    
    return c.JSON(fiber.Map{"status": "updated"})
})

4. Use Cache-Control Headers

app.Get("/api/sensitive-data", func(c *fiber.Ctx) error {
    data := getSensitiveData()
    
    // Prevent caching of sensitive responses
    c.Set(fiber.HeaderCacheControl, "no-store, no-cache, must-revalidate")
    c.Set(fiber.HeaderPragma, "no-cache")
    c.Set(fiber.HeaderExpires, "0")
    
    return c.JSON(data)
})

For comprehensive protection, integrate middleBrick's continuous scanning into your Fiber application's CI/CD pipeline. The GitHub Action can automatically scan your staging API after each deployment, ensuring cache poisoning vulnerabilities are caught before production release.

Frequently Asked Questions

How can I tell if my Fiber application has cache poisoning vulnerabilities?
Look for endpoints that cache responses based on unvalidated parameters. middleBrick can automatically detect this by testing if manipulated query parameters create cache entries that are served to other users. Check your cache key generation logic to ensure it only includes validated, normalized parameters.
Does middleBrick's scanning work with Fiber's built-in cache middleware?
Yes, middleBrick's black-box scanning can detect vulnerabilities in applications using Fiber's cache middleware. The scanner tests how the middleware handles various parameter combinations and identifies if sensitive data or manipulated responses are being cached and served to other users.