Cors Wildcard in Fiber
How Cors Wildcard Manifests in Fiber
CORS wildcard misconfigurations in Fiber applications create severe security vulnerabilities by allowing any origin to access protected API endpoints. This manifests through several specific attack patterns that exploit the permissive nature of wildcard CORS policies.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
app := fiber.New()
// Vulnerable: wildcard allows ANY origin
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowCredentials: true, // Critical vulnerability
}))
app.Get("/api/user/secret", func(c *fiber.Ctx) error {
// Returns sensitive user data
return c.JSON(map[string]string{"secret": "user123-data"})
})
app.Listen(":3000")
}
The most critical vulnerability occurs when AllowCredentials is set to true alongside wildcard origins. According to the CORS specification, browsers block requests with credentials when the origin is a wildcard, but many implementations incorrectly allow this combination. This creates a perfect storm where malicious websites can steal authenticated user data.
Attackers exploit this by hosting malicious sites that make cross-origin requests to vulnerable Fiber APIs. The browser sends cookies and authentication tokens, which the server processes and returns sensitive data. Since the CORS policy accepts any origin, the browser allows the malicious site to read the response.
Another manifestation involves missing or overly permissive preflight handling. Fiber's default CORS middleware handles OPTIONS requests automatically, but custom implementations often forget to validate origins during preflight checks:
func customCorsMiddleware(c *fiber.Ctx) error {
origin := c.Get("origin")
if origin != "" {
c.Set("Access-Control-Allow-Origin", origin) // Vulnerable: reflects any origin
c.Set("Access-Control-Allow-Credentials", "true")
}
if c.Method() == "OPTIONS" {
// Missing origin validation for preflight
c.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
c.Set("Access-Control-Allow-Headers", "Content-Type")
return c.SendStatus(200)
}
return c.Next()
}
This reflection pattern is particularly dangerous because it echoes back whatever origin the client provides, creating a dynamic wildcard that's even harder to detect than static asterisks.
Fiber-Specific Detection
Detecting CORS wildcard vulnerabilities in Fiber applications requires both manual code review and automated scanning. The most effective approach combines static analysis with runtime testing.
Manual detection starts with examining CORS middleware configuration. Look for these red flags in your Fiber codebase:
# Search for vulnerable patterns
grep -r "cors\.New" . --include="*.go"
grep -r "AllowOrigins.*\*" . --include="*.go"
grep -r "AllowCredentials.*true" . --include="*.go"
Pay special attention to custom CORS implementations that might not use the standard middleware. These often contain subtle vulnerabilities:
// Dangerous custom implementation
app.Use(func(c *fiber.Ctx) error {
origin := c.Get("origin")
if origin != "" {
c.Set("Access-Control-Allow-Origin", origin) // Reflects any origin
c.Set("Access-Control-Allow-Credentials", "true")
}
return c.Next()
})
Automated detection with middleBrick provides comprehensive coverage by testing the actual runtime behavior. The scanner identifies CORS vulnerabilities through active probing:
# Scan your Fiber API endpoint
middlebrick scan https://your-fiber-api.com
middleBrick tests multiple scenarios: wildcard origins with credentials, reflected origins, missing preflight handling, and overly permissive CORS configurations. The scanner sends requests from various origins and analyzes the server's responses to determine if credentials are accepted.
For development teams, integrating middleBrick into your CI/CD pipeline catches these issues before deployment:
# GitHub Actions workflow
name: API Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick Scan
run: |
npm install -g middlebrick
middlebrick scan https://staging.your-fiber-app.com --fail-on-severity=high
The scanner also analyzes OpenAPI specifications to identify endpoints that should have restricted CORS policies but don't, providing a complete security assessment of your Fiber API surface.
Fiber-Specific Remediation
Remediating CORS wildcard vulnerabilities in Fiber requires a defense-in-depth approach that combines proper configuration with runtime validation. The foundation is implementing strict origin whitelisting:
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
app := fiber.New()
// Secure configuration: explicit whitelist, no credentials
app.Use(cors.New(cors.Config{
AllowOrigins: []string{
"https://yourdomain.com",
"https://app.yourdomain.com",
},
AllowCredentials: false, // Critical: never allow credentials with wildcard
AllowMethods: "GET, POST, PUT, DELETE",
AllowHeaders: "Content-Type, Authorization",
}))
app.Get("/api/user/secret", func(c *fiber.Ctx) error {
// Returns sensitive user data only to authorized origins
return c.JSON(map[string]string{"secret": "user123-data"})
})
app.Listen(":3000")
}
The key security principles: never use wildcard origins with credentials, always use explicit whitelists, and avoid reflecting client-provided origins. If your application legitimately needs credentials across origins, implement a dynamic origin validator:
func originValidator(origin string) (string, bool) {
allowedOrigins := map[string]bool{
"https://yourdomain.com": true,
"https://app.yourdomain.com": true,
"https://partner.com": true,
}
if allowedOrigins[origin] {
return origin, true
}
// Log suspicious origins for security monitoring
log.Printf("Blocked CORS request from unauthorized origin: %s", origin)
return "", false
}
app.Use(cors.New(cors.Config{
AllowOrigins: "https://yourdomain.com",
AllowCredentials: true,
OriginValidator: originValidator,
}))
For applications requiring more complex CORS policies, implement a centralized CORS service that validates origins against a database of authorized domains:
type corsService struct {
originDB map[string]bool
}
func (s *corsService) validateOrigin(origin string) (string, bool) {
if s.originDB[origin] {
return origin, true
}
return "", false
}
func corsMiddleware(cs *corsService) fiber.Handler {
return func(c *fiber.Ctx) error {
origin := c.Get("origin")
if origin == "" {
return c.Next()
}
allowedOrigin, valid := cs.validateOrigin(origin)
if !valid {
return c.SendStatus(fiber.StatusForbidden)
}
c.Set("Access-Control-Allow-Origin", allowedOrigin)
c.Set("Access-Control-Allow-Credentials", "true")
if c.Method() == "OPTIONS" {
c.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.Set("Access-Control-Max-Age", "86400")
return c.SendStatus(200)
}
return c.Next()
}
}
// Initialize with database-backed origins
func main() {
app := fiber.New()
// Load allowed origins from secure storage
originDB := loadAllowedOriginsFromDB()
corsService := &corsService{originDB: originDB}
app.Use(corsMiddleware(corsService))
app.Listen(":3000")
}
Complement these code changes with runtime security testing using middleBrick's continuous monitoring to ensure your CORS policies remain secure as your application evolves.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
Why is allowing credentials with wildcard CORS origins so dangerous?
Credentials (cookies, authorization headers, client certificates) bypass the same-origin policy. When combined with wildcard origins, malicious websites can trick browsers into sending these credentials to your API, then read the sensitive responses. This enables account takeover, data theft, and session hijacking attacks that compromise all authenticated users.
How does middleBrick detect CORS wildcard vulnerabilities in Fiber applications?
middleBrick performs active probing by sending requests from various origins to test how the server responds. It checks for wildcard origins with credentials, reflected origins, missing preflight handling, and overly permissive CORS configurations. The scanner analyzes both runtime behavior and OpenAPI specifications to provide comprehensive coverage of your Fiber API's CORS security posture.