Description
XPath injection occurs when user input is inserted directly into an XPath expression. An attacker may add quotes, logical operators or wildcards to select unintended nodes or bypass an authentication check. This applies to dynamically assembled expressions passed to methods such as select, select1 or evaluate in the Node.js xpath library.
Potential impact
- XML-based authentication or lookup logic may be bypassed.
- Sensitive XML nodes or additional records may be exposed.
- Reusing the expression across endpoints may repeat the same vulnerability.
Remediation
- Do not concatenate user input into an XPath expression.
- Keep the expression fixed and compare values in application code, or use variable bindings supported by the library.
- Do not expose arbitrary XPath construction. Allow only the query types the application needs.
- Minimize the nodes and fields returned, and separately verify the requester's data-access permissions.
Examples
Before
javascript
const express = require("express");
const xpath = require("xpath");
const app = express();
app.get("/bad", (req, res) => {
const expr = "//users/user[@name='" + req.query.user + "']";
const result = xpath.select(expr, doc);
res.json(result.map((node) => ({ name: node.getAttribute("name") })));
});
After
javascript
const express = require("express");
const xpath = require("xpath");
const app = express();
app.get("/good", (req, res) => {
const user = req.query.user;
if (typeof user !== "string" || user.length > 100) {
return res.status(400).json({ error: "invalid user" });
}
const result = xpath.select("//users/user", doc)
.filter((node) => node.getAttribute("name") === user);
res.json(result.map((node) => ({ name: node.getAttribute("name") })));
});
The first example lets input alter XPath structure. The second selects nodes with a fixed expression and compares the name as a value, preserving the lookup condition without injection. doc is an existing XML document; parsing and data-access checks are omitted. A name lookup alone does not authenticate a user.