HIGH timing attackfiber

Timing Attack in Fiber

How Timing Attack Manifests in Fiber — specific attack patterns, Fiber-specific code paths where this appears

A timing attack in the context of Go Fiber exploits variations in response time to infer sensitive information, such as whether a user exists or whether a cryptographic comparison succeeded. In Fiber, these patterns most commonly arise in authentication endpoints where branching logic depends on secret-sensitive comparisons. For example, an endpoint that compares a user-supplied token or password hash with a stored value using a naive equality check can leak information through timing differences.

Consider a login route that retrieves a user by email and then compares the provided password hash with the stored hash. If the comparison short-circuits on the first mismatched byte, an attacker can measure response times to progressively learn the correct hash. In Fiber, this often occurs in handlers written with app.Post("/login", ...) where the logic branches based on database lookup results and byte-by-byte comparison functions. Another common pattern is conditional error messaging: returning a distinct error when a user is not found versus when the password is incorrect creates a distinguishable timing delta. Even when the route uses middleware for rate limiting or logging, the branching inside the handler can still introduce measurable variance. Fiber’s tightly structured router and chainable handlers make it straightforward to inadvertently create these branches, especially when combining database calls, hashing, and response writing in the same handler function.

Specific code paths where timing issues surface include the handler chain for authentication, custom error handlers, and any use of string or byte comparisons without constant-time guarantees. For instance, using []byte(plain) == []byte(secret) in Go is not safe because it short-circuits on the first mismatch. Similarly, branching on user == nil after a database query can expose whether a record exists. Even response status code paths — such as returning 401 vs 404 — can be leveraged by an attacker to infer validity of credentials when combined with precise network timing measurements.

Fiber-Specific Detection — how to identify this issue, including scanning with middleBrick

Detecting timing attack risks in Fiber applications involves reviewing handler logic for data-dependent branches and variable-time operations, and validating that responses are consistent in both behavior and timing. Look for patterns such as conditional error messages, early returns based on database lookups, and non-constant-time comparisons of secrets. Static analysis can highlight suspicious string or byte comparisons, but runtime testing is essential to confirm timing variance.

Using middleBrick, you can scan an unauthenticated Fiber endpoint to observe timing-based inconsistencies as part of its 12 parallel security checks, particularly under Authentication, Input Validation, and Data Exposure. The scanner submits varied inputs and measures behavioral differences, helping to surface endpoints where response times correlate with secret-dependent conditions. For example, submitting valid versus invalid credentials and analyzing response distributions can indicate whether the endpoint leaks existence information through timing. middleBrick’s report will include findings with severity ratings and remediation guidance, presented alongside a per-category breakdown and a letter-grade risk score derived from a 0–100 scale.

To scan a Fiber API with the CLI, you would run:

middlebrick scan https://api.example.com/api/login

This triggers black-box tests against the endpoint, including probes that can detect timing-related deviations. The dashboard and JSON output (available via middlebrick scan <url> --format json) provide prioritized findings that map to frameworks such as OWASP API Top 10, helping teams identify authentication endpoints that require constant-time handling.

Fiber-Specific Remediation — code fixes using Fiber's native features/libraries

Remediation focuses on ensuring that all branches and comparisons execute in constant time, regardless of secrets or lookup results. In Fiber, this means adjusting handlers to avoid early branching on sensitive conditions and using cryptographic libraries that provide constant-time comparison functions.

For authentication handlers, always perform the hash comparison and user existence check in a way that does not branch on secret data. Instead of returning 404 when a user is not found, use a uniform flow that includes a dummy hash comparison to mask timing differences. Below is an example of a safer login handler in Fiber that uses bcrypt’s constant-time comparison via bcrypt.CompareHashAndPassword, which is designed to avoid early exits based on secret data:

package main

import (
    "github.com/gofiber/fiber/v2"
    "golang.org/x/crypto/bcrypt"
)

type LoginRequest struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

func main() {
    app := fiber.New()
    app.Post("/login", func(c *fiber.Ctx) error {
        var req LoginRequest
        if err := c.BodyParser(&req); err != nil {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
        }

        // In production, fetch user by email. For constant-time safety,
        // ensure the lookup path and comparison path do not leak existence via timing.
        storedHash := "..." // retrieve hash for the email if user exists; otherwise use a dummy hash
        if err := bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(req.Password)); err != nil {
            // Return a generic error without revealing whether user existence or password was the issue
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid credentials"})
        }
        return c.JSON(fiber.Map{"status": "ok"})
    })
    app.Listen(":3000")
}

Additionally, avoid branching on user == nil by using a consistent code path. If your data layer returns nil, proceed with a dummy computation to consume similar time. Also ensure that HTTP status codes do not reveal validation differences; prefer a generic 401 for authentication failures rather than mixing 401 and 404 based on lookup results.

For token or secret comparisons not covered by standard library functions, use explicit constant-time byte comparison utilities. While Go’s standard library does not include a built-in constant-time bytes.Equal, you can implement or use a vetted utility to compare HMACs or tokens without early exit:

// Constant-time byte comparison to avoid timing leaks
func constantTimeCompare(a, b []byte) bool {
    if len(a) != len(b) {
        return false
    }
    var equal byte
    for i := range a {
        equal |= a[i] ^ b[i]
    }
    return equal == 0
}

Integrate these practices across your Fiber routes and validate with middleBrick scans to confirm that timing-related findings are addressed. The combination of code-level fixes and continuous scanning helps reduce the risk of timing-based information disclosure.

Frequently Asked Questions

Can timing attacks affect any Fiber endpoint, or only authentication routes?
While authentication endpoints are common targets, any Fiber endpoint that branches on secret-sensitive data or performs non-constant-time comparisons can be vulnerable, including token validation, password reset, and profile lookup routes.
Does middleBrick actively probe for timing differences, and what does it report for these findings?
middleBrick runs checks that include timing-based anomaly detection by comparing responses across varied inputs. Findings are reported with severity levels and remediation guidance, focusing on reducing data-dependent timing variance in handlers and comparisons.