Zip Slip in Fiber with Jwt Tokens
Zip Slip in Fiber with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Zip Slip is a path traversal vulnerability that occurs when an application constructs file paths using user-supplied input without proper validation. In the context of a Fiber application that uses JWT tokens for authentication, the combination can expose security risks when token handling logic interacts with file system operations. For example, if an endpoint decodes a JWT payload and uses claims such as a filename or user identifier to build local file paths, an attacker may provide a specially crafted token containing path sequences like ../. Because the validation may focus on token authenticity and signature checks, it can overlook malicious path components embedded in claims. This mismatch between token trust and unsafe path construction can allow directory traversal, potentially exposing configuration files, logs, or other sensitive resources on the server.
Consider a scenario where a Fiber route uses middleware that extracts a username from a JWT claim and appends it to a directory for storing user artifacts. If the token is accepted solely based on signature validity, an attacker who obtains or guesses a valid token can modify the username claim to include traversal patterns. During runtime, the application may resolve paths outside the intended base directory. Even though the JWT itself is cryptographically verified, the unchecked use of its claims in filesystem interactions creates a bypass of logical access boundaries. This illustrates how JWT tokens, while reliable for identity and session management, do not inherently protect against insecure path handling. The vulnerability is not in JWT verification libraries but in the developer’s failure to sanitize and restrict paths derived from token data.
In a black-box scan, middleBrick examines such combinations by analyzing OpenAPI specifications and runtime behavior without requiring credentials. It checks whether endpoints that accept or decode JWT tokens also perform file operations with unsanitized inputs. The tool identifies risky patterns where claims influence filesystem paths and highlights missing safeguards like path normalization and strict base directory enforcement. Because the scan runs against the unauthenticated attack surface, it can surface these design weaknesses even when authentication appears intact. Developers should treat JWT tokens as a trusted source of identity, but never as a safe source for filesystem routing decisions without additional validation.
Jwt Tokens-Specific Remediation in Fiber — concrete code fixes
To remediate Zip Slip risks when using JWT tokens in Fiber, ensure that any data derived from token claims is sanitized before being used in file paths. Do not directly concatenate claims such as usernames or file names into filesystem paths. Instead, use a strict allowlist of permitted characters, resolve paths with functions that eliminate traversal sequences, and enforce a base directory boundary. Below are concrete code examples demonstrating secure handling in a Fiber application.
First, validate and sanitize the claim before path construction:
// Go
package main
import (
"path/filepath"
"strings"
"github.com/gofiber/fiber/v2"
)
func sanitizeFileName(input string) string {
// Remove path elements and non-alphanumeric characters except dot and underscore
base := filepath.Base(input)
return strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' || r == '_' {
return r
}
return -1
}, base)
}
func uploadHandler(c *fiber.Ctx) error {
token := c.Locals("userToken") // Assume JWT validated middleware sets this
// Example: extract claim safely (pseudocode)
username, err := extractClaimAsString(token, "username")
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid claims"})
}
safeName := sanitizeFileName(username)
targetPath := filepath.Join("/var/uploads", safeName)
// Proceed with file operations using targetPath
return c.JSON(fiber.Map{"path": targetPath})
}
Second, use a dedicated middleware to validate JWT tokens and ensure claims conform to expectations before they reach route handlers:
// Go
jwtMiddleware := func(c *fiber.Ctx) error {
auth := c.Get("Authorization")
if auth == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "authorization header required"})
}
tokenString := strings.TrimPrefix(auth, "Bearer ")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return []byte(os.Getenv("JWT_SECRET")), nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid token"})
}
// Validate expected claims and reject suspicious ones
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if username, ok := claims["username"].(string); ok {
c.Locals("username", sanitizeUsername(username))
} else {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "missing username claim"})
}
}
return c.Next()
}
app.Use(jwtMiddleware)
These examples demonstrate how to integrate JWT token handling with secure path construction. By sanitizing inputs from claims and using filepath.Clean and filepath.Base, you eliminate traversal sequences. middleBrick can verify such implementations by scanning the API definition and detecting whether endpoints that use JWT data also apply path normalization and boundary checks.