Out Of Bounds Write in Fiber
How Out Of Bounds Write Manifests in Fiber
Out Of Bounds Write (OOBW) in Fiber applications occurs when code attempts to write data beyond allocated memory boundaries, often through unsafe array operations or improper validation of user-controlled inputs. In Go-based Fiber applications, this typically manifests through several Fiber-specific patterns.
A common scenario involves improper handling of JSON request bodies where array indices are directly used without validation. For example:
func handleUpdateUsers(c *fiber.Ctx) error {
var updateReq struct {
UserIDs []int `json:"user_ids"`
Changes map[string]interface{} `json:"changes"`
}
if err := c.BodyParser(&updateReq); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "Invalid JSON"})
}
// Vulnerable: No bounds checking on UserIDs
for _, id := range updateReq.UserIDs {
if id < 0 || id >= len(usersDB) { // usersDB is a slice
continue // silently skip - potential information leakage
}
usersDB[id] = applyChanges(usersDB[id], updateReq.Changes)
}
return c.JSON(fiber.Map{"status": "updated"})
}
This code is vulnerable because negative indices or indices exceeding the slice length could cause panics or, in some cases, allow writing to unintended memory locations through Go's slice semantics.
Another Fiber-specific pattern involves improper file path handling with user-controlled indices:
func serveFileByIndex(c *fiber.Ctx) error {
index := c.Params("index")
// Vulnerable: index not validated as integer or bounds-checked
fileIndex, _ := strconv.Atoi(index)
files := []string{"file1.txt", "file2.txt", "file3.txt"}
// Potential OOBW if fileIndex is negative or >= len(files)
return c.SendFile(files[fileIndex])
}
Middleware chaining in Fiber can also introduce OOBW risks when request data is passed through multiple handlers without proper validation at each stage. The flexible context storage in Fiber (c.Locals(), c.Freeze()) can propagate malformed data through the chain.
Fiber-Specific Detection
Detecting Out Of Bounds Write vulnerabilities in Fiber applications requires both static analysis and runtime testing. middleBrick's scanner specifically targets these patterns in Go/Fiber applications through its black-box scanning approach.
middleBrick's API security scanner tests for OOBW by sending boundary-condition requests to your Fiber endpoints. For array-based endpoints, it sends:
- Negative indices (-1, -999)
- Extremely large indices (999999)
- Non-integer values where integers are expected
- Empty arrays when single values are expected
The scanner analyzes HTTP responses for indicators of OOBW, including:
- 500 Internal Server Error responses (often from panics)
- Unexpected data exposure
- Application crashes or timeouts
- Memory corruption symptoms in repeated requests
For Fiber applications specifically, middleBrick's scanner examines the OpenAPI/Swagger spec (if provided) to understand parameter types and expected ranges, then crafts targeted boundary tests. The scanner's 12 security checks include Input Validation testing that specifically looks for missing bounds checking in array parameters and path variables.
Development-time detection in Fiber can be enhanced using Go's built-in testing tools:
func TestServeFileByIndex(t *testing.T) {
app := fiber.New()
app.Get("/files/:index", serveFileByIndex)
// Test normal case
req := httptest.NewRequest("GET", "/files/1", nil)
resp, _ := app.Test(req)
// Test OOBW cases
negativeReq := httptest.NewRequest("GET", "/files/-1", nil)
negResp, _ := app.Test(negativeReq)
if negResp.StatusCode != 400 {
t.Errorf("Negative index should return 400, got %d", negResp.StatusCode)
}
largeReq := httptest.NewRequest("GET", "/files/9999999", nil)
largeResp, _ := app.Test(largeReq)
if largeResp.StatusCode != 400 {
t.Errorf("Large index should return 400, got %d", largeResp.StatusCode)
}
}
middleBrick's CLI tool makes this testing seamless:
npm install -g middlebrick
middlebrick scan https://your-fiber-app.com/api/users/ --format json
The scanner runs in 5-15 seconds and provides a security score with specific findings about OOBW vulnerabilities, if detected.
Fiber-Specific Remediation
Remediating Out Of Bounds Write vulnerabilities in Fiber requires implementing proper bounds checking and input validation at the API boundary. Fiber provides several native features that facilitate secure coding practices.
The most effective approach is explicit bounds validation before array access:
func handleUpdateUsers(c *fiber.Ctx) error {
var updateReq struct {
UserIDs []int `json:"user_ids"`
Changes map[string]interface{} `json:"changes"`
}
if err := c.BodyParser(&updateReq); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "Invalid JSON"})
}
// Strict bounds checking
maxID := len(usersDB)
for _, id := range updateReq.UserIDs {
if id < 0 || id >= maxID {
return c.Status(400).JSON(fiber.Map{
"error": "User ID out of bounds",
"max_id": maxID - 1,
})
}
usersDB[id] = applyChanges(usersDB[id], updateReq.Changes)
}
return c.JSON(fiber.Map{"status": "updated"})
}
For path parameters in Fiber, use middleware for consistent validation:
func validateIndexBounds(next fiber.Handler) fiber.Handler {
return func(c *fiber.Ctx) error {
indexStr := c.Params("index")
index, err := strconv.Atoi(indexStr)
if err != nil || index < 0 || index >= len(files) {
return c.Status(400).JSON(fiber.Map{"error": "Invalid index"})
}
c.Locals("validatedIndex", index)
return next(c)
}
}
// Usage in route
app.Get("/files/:index", validateIndexBounds(func(c *fiber.Ctx) error {
index := c.Locals("validatedIndex").(int)
return c.SendFile(files[index])
}))
middleBrick's Pro plan includes continuous monitoring that can alert you when new OOBW vulnerabilities are introduced. The GitHub Action integration allows you to fail builds automatically if security scores drop:
- name: Run middleBrick Scan
uses: middlebrick/middlebrick-action@v1
with:
target: http://localhost:3000
fail-on-severity: high
output-format: json
For comprehensive protection, combine these remediation techniques with middleBrick's scanning:
# Scan before deployment
middlebrick scan https://staging.your-app.com/api --output report.json
# Check if OOBW findings exist
if grep -q "Out Of Bounds Write" report.json; then
echo "OOBW vulnerabilities detected!"
exit 1
fi
Remember that OOBW vulnerabilities often co-occur with other input validation issues. middleBrick's scoring methodology (0-100 scale, A-F grades) helps prioritize which vulnerabilities to fix first based on severity and exploitability.