HIGH replay attackecho gobearer tokens

Replay Attack in Echo Go with Bearer Tokens

Replay Attack in Echo Go with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A replay attack in the Echo Go ecosystem with Bearer Tokens occurs when an attacker intercepts a valid HTTP request containing an Authorization header (e.g., Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9) and re-sends it to the same or another service endpoint to gain unauthorized access or re-execute an action. This risk is pronounced when APIs rely solely on static or long-lived tokens without additional protections such as nonce, timestamp, or per-request signatures. Echo Go services that expose endpoints accepting Bearer Tokens over HTTP, or even over TLS without strict session binding, can be vulnerable because the token itself is reusable unless the application enforces one-time use or tight context binding.

In a typical Echo Go API, routes are defined using the net/http handler pattern, and middleware is often used to extract and validate the Bearer Token. If the validation step checks only the token’s signature and expiration but does not enforce a nonce or a per-request unique value, an attacker who captures the request (for example, via a compromised network segment or a misconfigured proxy) can replay the exact HTTP call, including headers and body, to perform actions such as transferring funds, changing user settings, or escalating privileges. This becomes more critical in unauthenticated scan scenarios where an endpoint inadvertently accepts Bearer Tokens without binding the token to the request context, effectively turning intercepted tokens into reusable credentials.

Consider an Echo Go handler that processes a payment request with a Bearer Token but does not validate the token against the request payload or a server-side nonce. An attacker who obtains the token via side-channel exposure or a misconfigured logging system can replay the exact POST request, causing duplicate transactions or unauthorized operations. The vulnerability is not in the token format itself but in the lack of anti-replay controls at the API layer, which is especially dangerous when combined with weak transport security or overly permissive CORS policies that allow cross-origin misuse. MiddleBrick’s unauthenticated scan can surface such weaknesses by testing endpoints that accept Bearer Tokens without enforcing request uniqueness, highlighting the need for contextual validation beyond simple token verification.

Bearer Tokens-Specific Remediation in Echo Go — concrete code fixes

To mitigate replay attacks in Echo Go when using Bearer Tokens, implement per-request uniqueness and strict validation. Below are concrete code examples that demonstrate how to bind a token to a request using a nonce and timestamp, and how to structure the middleware and handler safely.

// Echo Go middleware to validate Bearer Token and enforce nonce/timestamp
package main

import (
	"net/http"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
)

// NonceStore can be a thread-safe map or external cache (e.g., Redis) in production
type NonceStore struct {
	used map[string]bool
}

func NewNonceStore() *NonceStore {
	return &NonceStore{used: make(map[string]bool)}
}

func (s *NonceStore) IsUsed(nonce string) bool {
	_, exists := s.used[nonce]
	return exists
}

func (s *NonceStore) MarkUsed(nonce string) {
	s.used[nonce] = true
}

// BearerAuthMiddleware validates the token and checks replay protection
func BearerAuthMiddleware(nonceStore *NonceStore) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			auth := c.Request().Header.Get("Authorization")
			if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
				return echo.ErrUnauthorized
			}
			token := strings.TrimPrefix(auth, "Bearer ")
			// In practice, validate token signature and claims with jwt.Parse
			// For replay protection, extract nonce and timestamp from headers
			nonce := c.Request().Header.Get("X-Request-Nonce")
			timestampStr := c.Request().Header.Get("X-Request-Timestamp")
			if nonce == "" || timestampStr == "" {
				return echo.NewHTTPError(http.StatusBadRequest, "missing nonce or timestamp")
			}
			// Reject replayed nonce
			if nonceStore.IsUsed(nonce) {
				return echo.NewHTTPError(http.StatusForbidden, "replay detected")
			}
			// Reject stale requests (e.g., older than 2 minutes)
			timestamp, err := time.Parse(time.RFC3339, timestampStr)
			if err != nil || time.Since(timestamp) > 2*time.Minute {
				return echo.NewHTTPError(http.StatusBadRequest, "invalid timestamp")
			}
			nonceStore.MarkUsed(nonce)
			// Proceed with token validation logic here
			return next(c)
		}
	}
}

// Example handler using the middleware
func PaymentHandler(c echo.Context) error {
	// Business logic here; token already validated and replay checks passed
	return c.JSON(http.StatusOK, map[string]string{"status": "processed"})
}

func main() {
	e := echo.New()
	store := NewNonceStore()
	e.Use(BearerAuthMiddleware(store))
	e.POST("/payment", PaymentHandler)
	e.Start(":8080")
}

In this example, the client must include X-Request-Nonce (a unique value per request) and X-Request-Timestamp in RFC3339 format alongside the Authorization header. The server maintains a short-lived store of used nonces to reject duplicates and checks timestamp freshness to limit the window for replay. For production, replace the in-memory NonceStore with a distributed cache with TTL and add proper JWT validation for the Bearer Token. This approach directly addresses replay risks by ensuring each request is unique and time-bound, even when Bearer Tokens are used.

Frequently Asked Questions

How can I test my Echo Go API for replay vulnerabilities without a Bearer Token interception scenario?
Use the middleBrick CLI to scan your endpoint: middlebrick scan https://your-api.example.com. The scan will include checks for missing replay protections on endpoints that accept Bearer Tokens, helping you identify whether nonces and timestamps are enforced.
Does middleBrick’s LLM/AI Security testing apply to replay attacks in Echo Go APIs?
No. The LLM/AI Security checks focus on prompt injection, jailbreaks, and system prompt leakage. Replay attacks are covered under standard API security checks such as Authentication, BOLA/IDOR, and Input Validation, which validate token handling and request uniqueness.