HIGH xml external entitiesrestifyapi keys

Xml External Entities in Restify with Api Keys

Xml External Entities in Restify with Api Keys — 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 cause other unintended side effects. In Restify, if an endpoint accepts XML payloads and does not explicitly disable external entity processing, an attacker can craft malicious XML that references local or remote resources. When Api Keys are used for authorization, the presence of a valid key can influence how the request is handled internally (e.g., switching behavior from unauthenticated to authenticated code paths) but does not inherently prevent XXE if parsing remains permissive.

Consider a Restify service that parses incoming XML to extract parameters. If the parser is configured to resolve external entities, an attacker can supply an API key in an Authorization header or as a query parameter and still exploit XXE. The key may grant access to a more privileged handler or change logging and error behavior, but the core vulnerability lies in XML parsing rather than key validation. For example, an attacker could send:

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

If the Restify XML parser resolves the external entity, the contents of /etc/passwd may be included in the response or logged. The API key validates the caller but does not sanitize or restrict the XML input itself, so sensitive data can be exfiltrated. In other scenarios, XXE can lead to SSRF by referencing internal metadata services, especially when combined with trusted internal network assumptions behind authenticated endpoints.

Because middleBrick tests the unauthenticated attack surface by default, it can detect XXE indicators even when endpoints require Api Keys, provided the key is supplied or the endpoint relaxes validation for certain inputs. The scanner checks for XML parsing configurations that allow external entity resolution and highlights cases where sensitive file reads or SSRF are possible. Findings include references to real-world attack patterns such as CVE-2021-21343-style parsing risks and guidance to disable DTD and external entity resolution in XML processors.

Api Keys-Specific Remediation in Restify — concrete code fixes

To remediate XXE in Restify while continuing to use Api Keys for authorization, ensure XML parsing is hardened to reject or ignore external entities. This typically involves configuring the XML parser to disable DTDs and external entity resolution. Below are two concrete Restify examples: one insecure (for illustration) and one secure.

Insecure example (vulnerable to XXE):

const restify = require('restify');
const bodyParser = require('body-parser');

const server = restify.createServer();
server.use(bodyParser.xml({
  xmlParseOptions: {
    // Missing: external entity and DTD disabled
  }
}));

server.post('/webhook', (req, res, next) => {
  const apiKey = req.headers['authorization'];
  // Authorization handled separately; XML parsing remains unsafe
  const data = req.body; // req.body may contain parsed XML with external entities
  // Process data...
  res.send(200);
  return next();
});

server.listen(8080, () => console.log('listening'));

The above uses body-parser with permissive XML options, allowing external entity resolution. An API key in the headers does not mitigate this.

Secure example (XXE mitigation with Api Keys):

const restify = require('restify');
const bodyParser = require('body-parser');

const server = restify.createServer();

// Configure XML parsing to disable external entities and DTDs
server.use(bodyParser.xml({
  xmlParseOptions: {
    parserOptions: {
      externalEntityRef: () => {
        // Reject external entity references
        throw new Error('External entities are not allowed');
      },
      processEntities: false,       // Do not expand entities
      loadDTDs: false,              // Do not load DTDs
      validate: false               // Disable validation that may trigger entity resolution
    }
  }
}));

server.post('/webhook', (req, res, next) => {
  const apiKey = req.headers['authorization'];
  if (!apiKey || !isValidApiKey(apiKey)) {
    return res.send(401, { error: 'Unauthorized' });
  }
  const data = req.body;
  // Safe processing: no external entities
  res.send(200);
  return next();
});

function isValidApiKey(key) {
  // Replace with your key validation logic, e.g., lookup or constant-time compare
  return key === 'SECRET_API_KEY';
}

server.listen(8080, () => console.log('listening'));

In the secure example, the XML parser is configured to reject external entities and avoid DTD loading. Api Keys are still validated before processing, but the XML input cannot trigger file reads or SSRF via entity references. For production, store API keys securely and consider additional checks such as input size limits and schema validation.

When using the middleBrick CLI (middlebrick scan <url>) or the GitHub Action, you can verify that XXE indicators are flagged and that your configuration aligns with secure parsing practices. The dashboard and continuous monitoring (Pro plan) help track these settings over time, while the MCP Server allows quick scans from AI coding assistants during development.

Frequently Asked Questions

Can an API key stop XXE if the XML parser is misconfigured?
No. Api Keys handle authorization and may change code paths, but they do not alter XML parsing behavior. XXE is a parsing issue; you must disable external entities and DTDs in the XML parser regardless of authentication.
Does middleBrick fix XXE or other parsing issues automatically?
middleBrick detects and reports findings with remediation guidance, but it does not fix, patch, block, or remediate. You must apply the recommended secure parser settings in your Restify service.