Path Traversal in Restify with Hmac Signatures
Path Traversal in Restify with Hmac Signatures — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an API allows user-supplied paths to traverse directories, enabling access to files outside the intended directory. In Restify, this risk can be amplified when endpoints that accept file or resource identifiers also use Hmac Signatures for request authentication without properly validating or sanitizing inputs. The Hmac signature is typically computed over selected parts of the request—such as query parameters, headers, or a canonical string that includes a file path. If the path parameter is not strictly constrained, an attacker can supply sequences like ../../../etc/passwd and, if the server concatenates that path into the data covered by the Hmac, the signature may still validate while the resolved file location becomes unauthorized.
Consider a Restify endpoint that serves files from a configured base directory. If the route uses a path parameter (e.g., /files/:name) and the server builds the filesystem path by joining the base directory with req.params.name before computing or verifying an Hmac over the request, an attacker can attempt directory traversal payloads. Since the Hmac is often computed before path resolution, the signature may remain valid even as the resolved path escapes the intended scope. This mismatch between signature coverage and runtime path resolution creates a scenario where authentication (Hmac) does not prevent traversal: the request is authenticated, but authorization fails because the resolved file is outside the allowed directory. Common real-world CVEs in similar frameworks highlight patterns where signature schemes cover input fields that an attacker can manipulate, enabling path traversal when canonicalization or normalization is incomplete.
Moreover, if the API exposes metadata or error details, attackers can leverage Path Traversal to infer directory structure or discover sensitive files. The Hmac mechanism itself does not introduce the traversal; it is the integration point—how the path is used after signature validation—that determines risk. For instance, if the server normalizes the path after signature verification but before file access, and the normalization does not fully resolve .. sequences, traversal remains viable. This highlights the importance of validating and constraining path input before using it in filesystem operations, regardless of the presence of Hmac Signatures.
Hmac Signatures-Specific Remediation in Restify — concrete code fixes
To mitigate Path Traversal in Restify when using Hmac Signatures, ensure that path inputs are validated and sanitized independently of signature verification. The Hmac should cover only safe, canonical inputs, and file paths must be resolved within a strictly confined directory using platform-safe operations. Below are concrete remediation steps with code examples for Restify.
1. Validate and sanitize path inputs before signature verification
Normalize and validate the path parameter early in the request lifecycle. Reject paths containing traversal sequences or absolute references, and resolve the final path against a fixed base directory only after validation.
const path = require('path');
const url = require('url');
function sanitizeFilePath(input) {
// Normalize and remove any attempt to traverse directories
const normalized = path.normalize(input).replace(/^(\/|\.\.(\/|\$))/, '');
if (normalized.includes('..') || path.isAbsolute(normalized)) {
throw new Error('Invalid path');
}
return normalized;
}
server.pre((req, res, next) => {
try {
req.sanitizedPath = sanitizeFilePath(req.params.name || '');
} catch (err) {
return next(new restify.InvalidArgumentError('Invalid path'));
}
next();
});
2. Compute Hmac over safe, canonical data
When creating or verifying the Hmac, use only the validated, sanitized path and other non-mutable parameters. Avoid including raw user input that could be manipulated to alter the resolved file location.
const crypto = require('crypto');
function computeHmac(secret, method, urlPath, body) {
const canonical = `${method.toUpperCase()}|${urlPath}|${body || ''}`;
return crypto.createHmac('sha256', secret).update(canonical).digest('hex');
}
server.use((req, res, next) => {
const expected = computeHmac(process.env.HMAC_SECRET, req.method, req.url.split('?')[0], req.body);
const provided = req.headers['x-hmac'];
if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(provided))) {
return next(new restify.UnauthorizedError('Invalid signature'));
}
next();
});
3. Resolve file paths safely after validation
After signature validation, resolve the file path using a fixed base directory and platform-safe operations. Do not allow user input to escape this base directory.
server.get('/files/:name', (req, res, next) => {
const base = '/var/api/files';
const filePath = path.join(base, req.sanitizedPath);
if (!filePath.startsWith(path.resolve(base))) {
return next(new restify.ForbiddenError('Access denied'));
}
// Proceed to read filePath securely
fs.readFile(filePath, (err, data) => {
if (err) return next(new restify.InternalError('File error'));
res.send(data);
return next();
});
});
4. Use strict route definitions and avoid wildcard path components
Define routes with explicit constraints where possible and avoid passing raw user input directly into filesystem operations. If you use a pattern like /files/*, ensure that the resolved path is checked against the allowed base directory before any I/O.
5. Leverage the middlebrick CLI for continuous scanning
Use the middlebrick CLI (middlebrick scan <url>) to include unauthenticated scans in your workflow. It can detect Path Traversal and signature-related misconfigurations as part of its 12 checks, helping you catch issues early without requiring credentials.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |