HIGH dns rebindingginbearer tokens

Dns Rebinding in Gin with Bearer Tokens

Dns Rebinding in Gin with Bearer Tokens — how this specific combination creates or exposes the vulnerability

DNS rebinding is a client-side network attack that manipulates DNS responses to make a browser believe a remote host is reachable at an attacker-controlled IP after the initial page load. When combined with an API framework like Gin and bearer token authentication, the attack can bypass same-origin protections and exploit overly permissive CORS or trust-on-first-request logic to act on behalf of an authenticated user.

Consider a Gin service that protects endpoints with bearer tokens in the Authorization header and uses a per-request token validation approach. An attacker crafts a webpage that loads an image or script from the target API domain (e.g., https://api.example.com). After the browser makes an initial request and receives a 200 with a valid Authorization header, the attacker’s DNS infrastructure quickly switches the domain’s A record to point to an internal or attacker-controlled IP (e.g., 127.0.0.1 or 10.0.0.2). Because the browser does not re-validate the bearer token after the DNS change, subsequent requests from the same page may still include the token and be accepted by Gin as legitimate.

In practice, this can lead to unauthorized actions if the API does not validate the host origin on each request and relies only on the presence of a bearer token. For example, an authenticated request to change an email or reset a password could be issued from the attacker’s page without the user’s knowledge. Gin routes like POST /api/account/update-email that accept JSON and bearer tokens are at risk if CORS is misconfigured to allow credentials or broad origins, enabling the attacker’s page to make cross-origin requests that include cookies or authorization headers.

middleBrick scans would flag such combinations under the Authentication and BOLA/IDOR checks, identifying whether token validation is coupled with origin verification and whether per-request authorization is enforced. The scanner also highlights related issues like missing CSRF protections for state-changing methods when cookies are used alongside bearer tokens.

Bearer Tokens-Specific Remediation in Gin — concrete code fixes

To mitigate DNS rebinding risks when using bearer tokens in Gin, enforce origin and host validation on every request, avoid trusting the request Host header for authorization decisions, and ensure token validation is independent of DNS-derived endpoints. Below are concrete, realistic code examples for a Gin service that implements robust bearer token handling with additional defenses relevant to rebinding scenarios.

1. Strict Host and Origin Validation Middleware

Add middleware that checks the request Host against an allowlist and validates the Origin header for cross-origin requests. This prevents the server from processing requests that appear to come from unexpected hosts, a key vector in rebinding attacks.

package main

import (
    "net/http"
    "strings"

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

func HostValidationMiddleware(allowedHosts []string) gin.HandlerFunc {
    return func(c *gin.Context) {
        host := c.Request.Host
        allowed := false
        for _, h := range allowedHosts {
            if host == h {
                allowed = true
                break
            }
        }
        if !allowed {
            c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "host not allowed"})
            return
        }

        origin := c.Request.Header.Get("Origin")
        if origin != "" && !strings.HasPrefix(origin, "https://api.example.com") {
            c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "origin not allowed"})
            return
        }
        c.Next()
    }
}

2. Per-Request Token Validation with Reject Expired Tokens

Ensure each request validates the bearer token independently, including checks for expiry and revocation. Do not cache authorization decisions based on DNS or IP. Use a JWT parser with explicit verification and reject unsigned or malformed tokens.

package main

import (
    "net/http"
    "strings"

    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
)

func BearerAuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        auth := c.GetHeader("Authorization")
        if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
            return
        }
        tokenString := strings.TrimPrefix(auth, "Bearer ")
        token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
            if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
                return nil, http.ErrAbortHandler
            }
            return []byte("your-secret-key"), nil
        })
        if err != nil || !token.Valid {
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
            return
        }
        c.Set("claims", token.Claims)
        c.Next()
    }
}

3. Secure CORS Configuration

Configure CORS to avoid allowing credentials from arbitrary origins. Do not use AllowCredentials with wildcard origins, as this can make bearer token–protected endpoints usable from malicious sites during a rebinding scenario.

package main

import (
    "github.com/gin-golang/cors"
    "github.com/gin-gonic/gin"
)

func SetupRouter() *gin.Engine {
    r := gin.Default()
    r.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"https://app.example.com"},
        AllowMethods:     []string{"GET", "POST", "PUT", "OPTIONS"},
        AllowHeaders:     []string{"Authorization", "Content-Type"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        MaxAge:           300,
    }))
    r.GET("/api/health", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"status": "ok"})
    })
    r.POST("/api/account/update-email", BearerAuthMiddleware(), func(c *gin.Context) {
        var req struct {
            Email string `json:"email"`
        }
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
            return
        }
        // additional checks: compare request host vs origin, re-validate token, etc.
        c.JSON(http.StatusOK, gin.H{"message": "email update scheduled"})
    })
    return r
}

By combining host and origin validation, per-request bearer token verification, and strict CORS settings, Gin services can reduce the impact of DNS rebinding attempts. middleBrick’s checks for Authentication, BOLA/IDOR, and CORS misconfigurations help surface these weaknesses in scans.

Frequently Asked Questions

Does middleBrick fix DNS rebinding vulnerabilities in Gin APIs?
middleBrick detects and reports DNS rebinding-related risks and provides remediation guidance, but it does not fix, patch, or block issues. Apply the suggested code-level mitigations in your Gin service to reduce risk.
Can middleware alone prevent token misuse in DNS rebinding scenarios?
Middleware that validates hosts, origins, and bearer tokens on every request helps, but you must also enforce strict CORS rules, avoid wildcard origins with credentials, and ensure token validation is independent of DNS or IP assumptions.