Integer Overflow in Fiber
How Integer Overflow Manifests in Fiber
Integer overflow in Fiber applications occurs when arithmetic operations exceed the maximum value representable by a numeric type, causing the value to wrap around to a negative number or zero. In Go-based web frameworks like Fiber, this vulnerability often appears in authentication, pagination, and rate-limiting logic where integer values control access or resource allocation.
A common Fiber-specific pattern involves pagination parameters. Consider this vulnerable endpoint:
func getUsers(c *fiber.Ctx) error {
page := c.Query("page", "1")
limit := c.Query("limit", "10")
pageInt, _ := strconv.Atoi(page)
limitInt, _ := strconv.Atoi(limit)
// Vulnerable: no bounds checking on limit
offset := (pageInt - 1) * limitInt
// Database query with calculated offset
users := db.GetUsers(offset, limitInt)
return c.JSON(users)
}If an attacker submits page=1&limit=2147483647 (max int32), the multiplication could overflow, producing a negative offset. This might cause the database to return unexpected records or trigger errors that leak information.
Another Fiber-specific scenario involves JWT token generation where claims like exp or nbf are calculated:
func generateToken(c *fiber.Ctx) error {
ttl := c.Query("ttl", "3600") // seconds
ttlInt, _ := strconv.Atoi(ttl)
// Vulnerable: no validation of TTL size
expiration := time.Now().Unix() + int64(ttlInt)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": expiration,
})
signed, err := token.SignedString(secret)
return c.JSON(fiber.Map{"token": signed})
}With a large ttl value, expiration could overflow, creating tokens that expire in the past or never expire, breaking authentication logic.
Rate limiting in Fiber apps also suffers from this issue:
func rateLimitMiddleware(c *fiber.Ctx) error {
requests := c.Locals("requestCount").(int)
window := c.Locals("windowSize").(int)
// Vulnerable: no check for window overflow
remaining := window - requests
if remaining < 0 {
return c.Status(429).SendString("Rate limit exceeded")
}
return c.Next()
}If window is set to a negative value through integer overflow or improper configuration, the calculation window - requests could produce unexpected results, potentially allowing unlimited requests.
Fiber-Specific Detection
Detecting integer overflow in Fiber applications requires both static analysis and runtime scanning. Static analysis tools can identify vulnerable code patterns, but runtime scanning with middleBrick provides comprehensive coverage by testing actual API behavior.
middleBrick's black-box scanning approach is particularly effective for Fiber applications because it tests the unauthenticated attack surface without requiring source code access. The scanner sends crafted requests with boundary values to trigger potential overflows:
GET /api/users?page=1&limit=2147483647
GET /api/data?offset=2147483647&count=1000
POST /api/auth/token?ttl=999999999
During scanning, middleBrick monitors for several indicators of integer overflow:
- Unexpected HTTP status codes (500, 400 with specific error messages)
- Database errors indicating invalid offsets or limits
- Authentication bypass where tokens with overflowed expiration times are accepted
- Resource exhaustion from processing overflowed calculations
- Memory allocation errors from oversized array creation
middleBrick's 12 security checks include Input Validation testing specifically for numeric overflow scenarios. The scanner attempts to submit values at the boundaries of integer types and analyzes the application's response patterns.
For Fiber applications using JWT tokens, middleBrick's LLM/AI Security checks include system prompt leakage detection, but the core integer overflow detection focuses on the authentication and authorization logic that might be compromised by overflowed timestamp values.
middleBrick's OpenAPI spec analysis can identify endpoints with numeric parameters that lack proper validation constraints. When scanning a Fiber application with an OpenAPI spec, the tool cross-references documented parameter types and ranges with actual runtime behavior, flagging discrepancies that suggest overflow vulnerabilities.
The CLI tool makes it easy to scan Fiber APIs during development:
npx middlebrick scan https://api.yourservice.com --output json
This command runs all 12 security checks, including the specific integer overflow tests for pagination, authentication, and rate limiting scenarios common in Fiber applications.
Fiber-Specific Remediation
Remediating integer overflow in Fiber applications requires defensive coding practices and proper input validation. The Go language provides several mechanisms to prevent overflow vulnerabilities in Fiber middleware and handlers.
For pagination endpoints, implement strict bounds checking and use Go's math.MaxInt32 or math.MaxInt64 constants:
import (
"math"
"strconv"
"github.com/gofiber/fiber/v2"
)
func safePagination(c *fiber.Ctx) error {
page := c.Query("page", "1")
limit := c.Query("limit", "10")
pageInt, err := strconv.Atoi(page)
if err != nil || pageInt < 1 {
return c.Status(400).JSON(fiber.Map{"error": "Invalid page number"})
}
limitInt, err := strconv.Atoi(limit)
if err != nil || limitInt < 1 || limitInt > 100 {
return c.Status(400).JSON(fiber.C{"error": "Invalid limit, must be 1-100"})
}
// Safe calculation with bounds checking
if pageInt > math.MaxInt32/limitInt {
return c.Status(400).JSON(fiber.Map{"error": "Page number too large"})
}
offset := (pageInt - 1) * limitInt
users := db.GetUsers(offset, limitInt)
return c.JSON(users)
}For JWT token generation, validate TTL values before calculation:
func generateSecureToken(c *fiber.Ctx) error {
ttl := c.Query("ttl", "3600")
ttlInt, err := strconv.Atoi(ttl)
if err != nil || ttlInt <= 0 || ttlInt > 86400 {
return c.Status(400).JSON(fiber.Map{"error": "Invalid TTL, must be 1-86400 seconds"})
}
now := time.Now().Unix()
maxExpiration := now + 86400 // 24 hours max
if now > maxExpiration - int64(ttlInt) {
return c.Status(400).JSON(fiber.Map{"error": "TTL too large"})
}
expiration := now + int64(ttlInt)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": expiration,
})
signed, err := token.SignedString(secret)
return c.JSON(fiber.Map{"token": signed})
}Implement a reusable validation middleware for Fiber:
func validateIntRange(param string, min, max int) fiber.Handler {
return func(c *fiber.Ctx) error {
value := c.Query(param, "")
if value == "" {
return c.Status(400).JSON(fiber.Map{"error": param + " is required"})
}
intVal, err := strconv.Atoi(value)
if err != nil || intVal < min || intVal > max {
return c.Status(400).JSON(fiber.Map{
"error": fmt.Sprintf("%s must be between %d and %d", param, min, max),
})
}
c.Locals(param, intVal)
return c.Next()
}
}
// Usage in route
app.Get("/api/users", validateIntRange("page", 1, 10000), validateIntRange("limit", 1, 100), getUsers)For rate limiting, use Go's math.MaxInt64 for window calculations and implement safe arithmetic:
func safeRateLimit(c *fiber.Ctx) error {
requests := c.Locals("requestCount").(int)
window := c.Locals("windowSize").(int)
if window <= 0 || requests < 0 {
return c.Status(500).SendString("Invalid rate limit state")
}
if requests >= window {
return c.Status(429).SendString("Rate limit exceeded")
}
return c.Next()
}middleBrick's Pro plan includes continuous monitoring that can detect if these remediations are bypassed through regression testing. The GitHub Action integration allows you to fail builds when security scans detect overflow vulnerabilities in your Fiber application.