HIGH cors wildcardginbasic auth

Cors Wildcard in Gin with Basic Auth

Cors Wildcard in Gin with Basic Auth — how this specific combination creates or exposes the vulnerability

In Gin, configuring CORS with a wildcard origin (*) while also using HTTP Basic Authentication can unintentionally expose authenticated endpoints to any website. When AllowOrigins is set to *, the browser sends requests without credentials unless the server explicitly opts in with AllowCredentials. However, if the server both uses wildcard origins and expects Basic Auth (via Authorization: Basic header), the browser may still include credentials on cross-origin requests if the frontend explicitly sets withCredentials. This mismatch can lead to unauthorized cross-origin authenticated calls, effectively bypassing intended access restrictions.

For example, a JavaScript frontend hosted at https://example.com can make a fetch call to a Gin endpoint protected by Basic Auth with withCredentials: true. If Gin responds with Access-Control-Allow-Origin: * and does not validate the origin against an allowlist, the browser treats the response as accessible to the foreign origin, exposing authenticated data or actions. This pattern is often seen in misconfigured APIs intended for internal use but inadvertently exposed to the web.

During a black-box scan, middleBrick checks whether CORS responses include wildcard origins in the presence of credentialed authentication mechanisms. The tool detects whether the server includes Vary: Origin and validates that credentials are not inadvertently shared across origins. Without strict origin validation, an authenticated API can leak sensitive information or allow unauthorized cross-site requests that carry user credentials.

Basic Auth-Specific Remediation in Gin — concrete code fixes

To secure a Gin API using HTTP Basic Authentication, avoid wildcard origins and explicitly define allowed origins. You should also ensure that credentials are only shared with trusted origins and that the Authorization header is protected against cross-origin leakage.

Correct CORS configuration in Gin involves specifying exact origins and enabling credentials selectively. Below is a complete, working example that combines Basic Auth middleware with safe CORS settings.

// main.go
package main

import (
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
)

// BasicAuthMiddleware validates Authorization: Basic header
func BasicAuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        user, pass, ok := c.Request.BasicAuth()
        if !ok || !validateUserPass(user, pass) {
            c.Header("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
            return
        }
        c.Set("username", user)
        c.Next()
    }
}

func validateUserPass(user, pass string) bool {
    // Replace with secure lookup, e.g., constant-time compare against a store
    return user == "admin" && pass == "s3cr3t"
}

func main() {
    r := gin.Default()

    // Safe CORS configuration: specific origins, credentials allowed
    allowedOrigins := []string{"https://trusted.example.com", "https://app.example.com"}
    r.Use(func(c *gin.Context) {
        origin := c.GetHeader("Origin")
        for _, o := range allowedOrigins {
            if origin == o {
                c.Header("Access-Control-Allow-Origin", origin)
                break
            }
        }
        if c.Writer.Header().Get("Access-Control-Allow-Origin") == "" {
            // Block request if origin not allowed
            c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "origin not allowed"})
            return
        }
        c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        c.Header("Access-Control-Allow-Headers", "Authorization,Content-Type")
        c.Header("Access-Control-Allow-Credentials", "true")
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }
        c.Next()
    })

    r.GET("/secure", BasicAuthMiddleware(), func(c *gin.Context) {
        username := c.MustGet("username").(string)
        c.JSON(http.StatusOK, gin.H{"message": "authenticated", "user": username})
    })

    r.Run(":8080")
}

In this setup, the server never returns * for Access-Control-Allow-Origin when credentials are involved. The middleware checks the Origin header against an explicit allowlist, preventing unauthorized domains from receiving authenticated responses. The Vary: Origin header should also be included to ensure proper HTTP caching behavior, which middleBrick verifies during scans.

Additionally, always serve your API over HTTPS to protect the Base64-encoded credentials in transit. middleBrick’s checks include verifying the presence of Strict-Transport-Security headers and ensuring that no mixed-content requests are allowed, complementing the CORS and Basic Auth configuration.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Why is using Access-Control-Allow-Origin: * with Basic Auth risky?
Using a wildcard origin while requiring credentials allows any website to make authenticated requests if the frontend explicitly sets withCredentials. This can expose protected endpoints to malicious sites, leading to unauthorized access or data exfiltration.
How does middleBrick check CORS and authentication configurations?
middleBrick performs black-box scans, testing unauthenticated endpoints for CORS header correctness and checking whether wildcard origins coexist with credentialed authentication. It also verifies the presence of Vary: Origin and secure transport recommendations.