HIGH replay attackfiber

Replay Attack in Fiber

How Replay Attack Manifests in Fiber

Replay attacks in Fiber applications typically occur when authentication tokens, API keys, or session identifiers are transmitted without proper replay protection mechanisms. In Go/Fiber applications, this vulnerability often manifests in several specific patterns.

The most common scenario involves JWT tokens being transmitted over HTTP without additional protections. Consider a typical Fiber authentication flow:

app.Post("/login", func(c *fiber.Ctx) error {
    // Authenticate user
    token := jwt.New(jwt.SigningMethodHS256)
    claims := token.Claims.(jwt.MapClaims)
    claims["sub"] = userID
    claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
    
    signedToken, _ := token.SignedString([]byte("secret"))
    
    return c.JSON(fiber.Map{"token": signedToken})
})

The critical issue here is that the same JWT token can be captured via network sniffing and reused indefinitely until expiration. An attacker who intercepts this token can replay it to access protected endpoints:

app.Get("/protected", func(c *fiber.Ctx) error {
    token := c.Get("Authorization")
    // No replay protection - same token works repeatedly
    return c.JSON(fiber.Map{"data": "sensitive information"})
})

Another Fiber-specific manifestation occurs with session-based authentication using cookie stores. When using Fiber's default session middleware:

store := memory.New()
app.Use(sessions.New(sessions.Config{
    Store: store,
}))

If session IDs are not properly protected, an attacker can capture a session cookie and replay it to maintain unauthorized access. This becomes particularly dangerous in public Wi-Fi scenarios where traffic is unencrypted.

API key replay attacks also commonly appear in Fiber applications. Developers often implement simple API key validation:

app.Use(func(c *fiber.Ctx) error {
    apiKey := c.Get("X-API-Key")
    if apiKey != "valid-key" {
        return c.Status(401).SendString("Unauthorized")
    }
    return c.Next()
})

This pattern is vulnerable because the same API key can be captured and replayed indefinitely without any usage limits or expiration mechanisms.

Fiber-Specific Detection

Detecting replay attacks in Fiber applications requires both static code analysis and runtime monitoring. For static analysis, middleBrick's scanner examines your Fiber application for several replay attack indicators:

Token Validation Patterns - The scanner identifies JWT implementations that lack replay protection mechanisms. It looks for patterns where tokens are validated without checking for token reuse or implementing token blacklisting.

Session Management - middleBrick analyzes your session configuration to detect if you're using insecure session stores or if session IDs are transmitted without additional protections like HTTPS-only flags.

API Key Handling - The scanner flags simple API key validation patterns that don't implement rate limiting or usage tracking, which are essential for preventing replay attacks.

Transport Layer Security - middleBrick checks if your Fiber application enforces HTTPS and if sensitive headers/cookies are marked as Secure and HttpOnly.

To actively test for replay vulnerabilities, middleBrick performs runtime scanning that captures authentication tokens and attempts to reuse them across different endpoints. The scanner specifically tests:

  • JWT token reuse across multiple requests
  • Session cookie replay after logout/login cycles
  • API key replay with modified request parameters
  • Timestamp-based replay attacks on signed requests

For Fiber applications, middleBrick provides detailed findings including the exact endpoints vulnerable to replay attacks, the specific tokens or credentials that can be replayed, and the potential impact of each vulnerability.

Development teams can integrate middleBrick's CLI into their testing workflow:

middlebrick scan https://api.yourfiberapp.com --profile api-security

The scanner will identify replay attack vulnerabilities and provide remediation guidance specific to Fiber's architecture and common Go patterns.

Fiber-Specific Remediation

Securing Fiber applications against replay attacks requires implementing multiple defensive layers. Here are Fiber-specific remediation strategies:

Implement JWT Replay Protection - Add a token blacklist or sliding window mechanism:

type tokenStore struct {
    mu    sync.RWMutex
    tokens map[string]time.Time
}

func (ts *tokenStore) isReplayed(token string) bool {
    ts.mu.Lock()
    defer ts.mu.Unlock()
    if _, exists := ts.tokens[token]; exists {
        return true
    }
    ts.tokens[token] = time.Now()
    return false
}

app.Use(func(c *fiber.Ctx) error {
    authHeader := c.Get("Authorization")
    if authHeader == "" {
        return c.Status(401).SendString("Missing token")
    }
    
    parts := strings.SplitN(authHeader, " ", 2)
    if len(parts) != 2 || parts[0] != "Bearer" {
        return c.Status(401).SendString("Invalid token format")
    }
    
    token := parts[1]
    if tokenStoreInstance.isReplayed(token) {
        return c.Status(401).SendString("Token replay detected")
    }
    
    return c.Next()
})

Secure Session Management - Use secure session configuration with Fiber:

app.Use(sessions.New(sessions.Config{
    Store:      redis.New(), // Use Redis for persistence and revocation
    CookieName: "session_id",
    Secure:     true,       // Only send over HTTPS
    HttpOnly:   true,       // Prevent JS access
    SameSite:   "lax",     // Mitigate CSRF
    Expires:    time.Hour * 24,
}))

API Key with Replay Protection - Implement API key usage tracking:

type apiKeyStore struct {
    mu      sync.RWMutex
    keys    map[string]time.Time
    history map[string][]time.Time
}

func (aks *apiKeyStore) validateAndTrack(key string) bool {
    aks.mu.Lock()
    defer aks.mu.Unlock()
    
    lastUsed, exists := aks.keys[key]
    if !exists {
        return false
    }
    
    // Check for rapid replay (within 100ms)
    if time.Since(lastUsed) < 100*time.Millisecond {
        return false
    }
    
    aks.keys[key] = time.Now()
    aks.history[key] = append(aks.history[key], time.Now())
    return true
}

Transport Layer Security - Enforce HTTPS and secure headers in Fiber:

app.Use(func(c *fiber.Ctx) error {
    if !c.IsTLS() {
        return c.Status(400).SendString("HTTPS required")
    }
    
    c.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
    c.Set("X-Frame-Options", "DENY")
    c.Set("X-Content-Type-Options", "nosniff")
    c.Set("X-XSS-Protection", "1; mode=block")
    
    return c.Next()
})

Request Signing - Implement request signing to prevent replay of modified requests:

app.Use(func(c *fiber.Ctx) error {
    timestamp := c.Get("X-Timestamp")
    signature := c.Get("X-Signature")
    
    if timestamp == "" || signature == "" {
        return c.Status(400).SendString("Missing signature headers")
    }
    
    // Verify timestamp is recent (within 5 minutes)
    ts, err := strconv.ParseInt(timestamp, 10, 64)
    if err != nil || time.Since(time.Unix(ts, 0)) > 5*time.Minute {
        return c.Status(400).SendString("Invalid timestamp")
    }
    
    // Verify signature
    payload := c.Body()
    expectedSig := hmacSha256(secretKey, payload, timestamp)
    if !hmac.Equal([]byte(signature), []byte(expectedSig)) {
        return c.Status(401).SendString("Invalid signature")
    }
    
    return c.Next()
})

These remediation strategies, when combined, create multiple layers of defense against replay attacks in Fiber applications. middleBrick's continuous monitoring can verify that these protections remain effective over time.

Frequently Asked Questions

How does middleBrick detect replay attack vulnerabilities in Fiber applications?

middleBrick performs black-box scanning of your Fiber API endpoints, testing for replay vulnerabilities by capturing authentication tokens and attempting to reuse them across different requests. The scanner identifies patterns like JWT tokens without replay protection, session IDs that remain valid after logout, and API keys that can be reused indefinitely. It provides specific findings with severity levels and remediation guidance tailored to Go/Fiber applications.

Can middleBrick scan my Fiber application if it's behind authentication?

Yes, middleBrick can scan authenticated Fiber endpoints. You can provide test credentials or API keys during the scan configuration. The scanner will use these credentials to authenticate and then test for replay vulnerabilities across your protected endpoints. For CI/CD integration, you can store credentials securely in your pipeline secrets and configure middleBrick to use them automatically.