Xml External Entities in Restify with Mongodb
Xml External Entities in Restify with Mongodb — how this specific combination creates or exposes the vulnerability
XML External Entity (XXE) injection occurs when an application processes XML input and allows an attacker to define external entities that are resolved by the XML parser. In a Restify service that accepts XML payloads and interacts with a Mongodb backend, this can expose internal files, trigger SSRF against internal services, or consume excessive resources. The combination is risky because Restify may parse XML bodies (for example via a plugin or custom middleware) and then construct Mongodb queries using data derived from the XML without proper sanitization or schema validation.
Consider a Restify endpoint that receives an XML document containing user-controlled fields that map to Mongodb update or aggregation stages. If the XML parser resolves external DTDs or parameter entities, an attacker can supply an entity like &file SYSTEM 'file:///etc/passwd' that gets expanded and included in the XML tree. If the application then passes this expanded data into a Mongodb operation (e.g., as part of a $set or as a query filter), the sensitive content may be reflected in logs, error messages, or responses. Even if Mongodb itself does not parse XML, the vulnerability exists at the application layer: untrusted XML input reaching database operations enables information disclosure and can facilitate further attacks such as Server-Side Request Forgery (SSRF) when external entities point to internal endpoints.
An attack scenario specific to Restify and Mongodb: a POST route accepts an XML body, transforms it into a Mongodb document, and inserts it into a collection. If the XML parser is configured to resolve external entities, an attacker can reference a local file or an internal metadata service. For example, an entity defined as &ssrf SYSTEM 'http://169.254.169.254/latest/meta-data/' can cause the server to make HTTP requests to the instance metadata service. The resulting data may then be stored in Mongodb or used in subsequent queries, exposing sensitive cloud credentials or configuration. Because Restify may not explicitly enable XML parsing by default, the risk depends on dependencies and plugins that introduce an XML parser with insecure settings.
Additionally, XXE can lead to denial of service when external entities cause exponential entity expansion or recursive parsing, which can degrade Restify performance and affect Mongodb availability due to resource exhaustion. Even when the database is not directly processing XML, application-level handling of malicious XML can overload service threads, trigger timeouts, or spike CPU usage, indirectly impacting database responsiveness.
To detect such issues, middleBrick’s checks for Input Validation and Data Exposure can surface unsafe XML handling and unintended data flows to Mongodb. The scanner reviews whether user-controlled data reaches database operations without strict validation and whether error messages disclose internal paths or configurations. This is important because developers may assume that Mongodb is immune to XML-centric attacks, while the real issue lies in how XML is parsed and transformed before reaching the database.
Mongodb-Specific Remediation in Restify — concrete code fixes
Remediation focuses on preventing untrusted XML from reaching Mongodb operations and ensuring that data transformations are explicit and validated. The safest approach is to avoid parsing XML entirely or to disable external entity resolution in the parser. If XML support is required, use a parser with secure defaults and validate/sanitize all inputs before constructing Mongodb documents.
Example of a vulnerable Restify route that parses XML unsafely and forwards data to Mongodb:
// Vulnerable: XML parser may resolve external entities
const restify = require('restify');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const server = restify.createServer();
server.use(bodyParser.xml()); // Potentially risky if parser resolves entities
server.post('/users', async (req, res, next) => {
const xml = req.body; // XML string or parsed object depending on plugin
const userData = transformXmlToObject(xml); // custom mapping
const client = new mongodb.MongoClient(uri);
await client.connect();
await client.db('test').collection('users').insertOne(userData);
res.send(200);
return next();
});
Secure alternative: disable external entities in the XML parser and validate/sanitize input before database insertion. If you do not need XML, avoid XML parsing middleware entirely.
Secure Restify route with controlled parsing and Mongodb insertion:
const restify = require('restify');
const { MongoClient } = require('mongodb');
const xml2js = require('xml2js');
const server = restify.createServer();
// Configure a secure parser that does not resolve external entities
const parser = new xml2js.Parser({
explicitArray: false,
ignoreAttrs: false,
// Ensure no external DTD or entity expansion
externalEntitiesResolver: (entity, cb) => cb(new Error('External entities are not allowed'))
});
server.post('/users', async (req, res, next) => {
try {
// Parse XML with restricted options; reject external entities
const result = await parser.parseStringPromise(req.body);
// Strict validation of expected shape
if (!result.user || typeof result.user.name !== 'string') {
return next(new restify.InvalidContentError('Invalid user data'));
}
const userData = {
name: result.user.name.trim(),
email: result.user.email ? result.user.email.trim() : null
};
const client = new MongoClient(uri);
await client.connect();
await client.db('test').collection('users').insertOne(userData);
res.send(200);
} catch (err) {
return next(new restify.InternalError('Failed to process data'));
}
return next();
});
Additional measures:
- Use a schema validation library (e.g., Joi or Zod) to enforce required fields, types, and length constraints before building Mongodb operations.
- Apply principle of least privilege to the Mongodb connection used by Restify: restrict write permissions to only required collections and consider using parameterized updates instead of raw document insertion.
- Sanitize and encode any data extracted from XML before including it in responses to prevent injection into HTML or JavaScript contexts (e.g., XSS via reflected data).
- Log rejected requests and monitor for patterns that suggest probing for XXE or SSRF, integrating alerts with your existing observability stack.
By combining secure XML parser settings, strict input validation, and controlled Mongodb interactions, you reduce the attack surface for XXE and prevent unsafe data from affecting your database operations.