Container Escape in Restify with Bearer Tokens
Container Escape in Restify with Bearer Tokens — how this specific combination creates or exposes the vulnerability
A container escape in Restify combined with Bearer Tokens typically arises when token handling logic is exposed through an API endpoint, allowing an attacker who obtains or manipulates a token to break out of the intended execution context. Restify is commonly used to serve HTTP APIs, and if endpoints that accept or introspect Bearer Tokens are not properly isolated, they can become a path for unauthorized access across container boundaries.
Consider a scenario where a Restify service validates Bearer Tokens by calling an identity provider’s introspection endpoint. If the service does not correctly scope token permissions and fails to enforce strict transport and host validation, an attacker may leverage SSRF or header manipulation to redirect introspection requests to internal metadata services (e.g., 169.254.169.254 on many cloud containers). Successful redirection can reveal instance metadata, including temporary security credentials that lead to a container escape.
Another pattern involves token leakage through logs, error messages, or misconfigured CORS. Restify applications that echo the Authorization header value in responses or logs can inadvertently expose Bearer Tokens. If the container runs with elevated privileges or shares namespaces with other containers, leaked tokens can be reused to impersonate services and move laterally, effectively escaping the container sandbox.
Insecure default configurations can exacerbate the issue. For example, if a Restify server is bound to 0.0.0.0 inside the container and no network segmentation is enforced, an attacker who reaches the API can probe for token-related endpoints. Combined with missing input validation on token format and scope, this can lead to privilege escalation within the containerized environment, violating the principle of least privilege.
middleBrick’s API security checks can surface these risks by scanning unauthenticated attack surfaces and correlating findings across the Authentication, BOLA/IDOR, and Data Exposure checks. The scanner does not fix the container boundary, but its findings highlight where token handling intersects with network exposure, helping teams understand how a misconfigured Restify service and Bearer Tokens may weaken isolation.
Bearer Tokens-Specific Remediation in Restify — concrete code fixes
Remediation focuses on tightening how Restify handles Bearer Tokens, ensuring tokens are never over-trusted and are protected at every layer. Below are concrete code examples that demonstrate secure patterns.
1. Validate token format and scope before use
Always validate the structure and claims of a Bearer Token. Do not trust the token’s presence alone. Use a library to parse and verify the token, and enforce scope checks.
const jwt = require('jsonwebtoken');
const restify = require('restify');
function verifyToken(token) {
const publicKey = process.env.JWKS_PUBLIC_KEY;
const options = {
algorithms: ['RS256'],
issuer: 'https://auth.example.com/',
audience: 'api.example.com',
};
try {
return jwt.verify(token, publicKey, options);
} catch (err) {
throw new restify.UnauthorizedError('Invalid token');
}
}
const server = restify.createServer();
server.pre(restify.plugins.preValidation((req, res, next) => {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return next(new restify.UnauthorizedError('Authorization header required'));
}
const token = auth.split(' ')[1];
try {
req.user = verifyToken(token);
return next();
} catch (err) {
return next(err);
}
}));
2. Avoid logging or echoing Bearer Tokens
Ensure Authorization header values are never logged, and filter them from any error or diagnostic output.
const safeSerializer = (req) => {
const headers = { ...req.headers };
if (headers.authorization) {
headers.authorization = '[Filtered]';
}
return headers;
};
server.on('after', (req, res, route, err) => {
console.log({
method: req.method,
url: req.url,
headers: safeSerializer(req),
responseCode: res.statusCode,
});
});
3. Enforce network policies and token binding
Bind tokens to specific audiences and use mTLS where possible. Configure Restify to reject tokens issued for other audiences and enforce strict transport security.
server.opts({ tls: {
cert: '/path/to/cert.pem',
key: '/path/to/key.pem',
ca: '/path/to/ca.pem',
requestCert: true,
rejectUnauthorized: true,
}});
4. Use short-lived tokens and refresh controls
Configure token lifetimes to be short and implement refresh flows securely. Do not allow Bearer Tokens to be used for long-running operations without re-validation.
const server = restify.createServer();
server.use(restify.plugins.authorizationParser({
tokenType: 'Bearer',
scopeSeparator: ' ', // if space-separated scopes are used
}));