Description
Check whether your application needs DTDs before accepting untrusted XML. Entity expansion can turn a small request into a much larger document in memory. With node-expat, check the deployed Expat version and its expansion limits.
Potential impact
Excessive expansion can consume memory or keep the CPU busy while other requests wait. It may cause process restarts or unnecessary scaling.
Remediation
- Reject
DOCTYPEif DTDs are unnecessary. Choose a parser such as sax that does not expand custom DTD entities, or bound expansion in your deployed parser. Validate against the required schema where applicable. - Limit body size at the proxy and application. Set limits on nodes, depth, text length, processing time, concurrent requests and queued requests.
Examples
Before
javascript
const express = require("express");
const expat = require("node-expat");
const app = express();
app.use(express.text({ type: "application/xml" }));
app.post("/parse", (req, res) => {
const xml = req.body; // Untrusted input
const p = new expat.Parser();
p.on("startElement", () => {});
p.on("text", () => {});
// Entity expansion can enable XML bombs without adequate limits.
p.write(xml);
res.send("parsed");
});
module.exports = app;
After
javascript
const express = require("express");
const sax = require("sax");
const app = express();
// Limit the body size.
app.use(express.text({ type: "application/xml", limit: "200kb" }));
app.post("/safe-parse", (req, res) => {
const xml = req.body || "";
// Reject DTD declarations such as DOCTYPE/ENTITY.
const suspicious = /<!DOCTYPE|<!ENTITY/i.test(xml);
if (suspicious) {
return res.status(400).send("DTD/ENTITY not allowed");
}
// sax does not expand custom DTD entities.
const parser = sax.parser(true); // strict mode
parser.onopentag = () => {};
parser.ontext = () => {};
parser.onerror = (e) => {
throw e;
};
try {
parser.write(xml).close();
} catch {
return res.status(400).send("invalid xml");
}
return res.send("ok");
});
module.exports = app;
Express caps the application/xml body at 200kb. The handler rejects DTD and ENTITY declarations in the decoded string and parses it with sax.parser(true). A parse error returns one 400 response. Apply node, depth and time limits separately.