Xpath Injection with Basic Auth
How Xpath Injection Manifests in Basic Auth
XPath injection in Basic Auth scenarios occurs when authentication logic uses user-supplied credentials to construct XPath queries without proper sanitization. The vulnerability manifests in API endpoints that implement Basic Auth but internally query XML data stores or configuration files using XPath.
Consider a typical Basic Auth API endpoint that validates credentials against an XML user store:
const xmlDoc = new DOMParser().parseFromString(xmlString, 'application/xml');
const username = req.headers.authorization.split(' ')[1].split(':')[0];
const password = req.headers.authorization.split(' ')[1].split(':')[1];
const xpath = `//user[username='${username}' and password='${password}']`;
const node = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (node) {
// Authentication successful
} else {
// Authentication failed
}The critical vulnerability lies in the XPath construction. An attacker can craft a username like admin' or '1'='1 and any password. The resulting XPath becomes:
//user[username='admin' or '1'='1' and password='anything']Due to XPath operator precedence, this always evaluates to true, bypassing authentication entirely.
Basic Auth-specific attack patterns include:
- Boolean injection:
admin' or '1'='1(always true) - Comment injection:
admin' or 1=1 or ''='(bypasses password check) - XPath function injection:
admin' or contains(username, 'admin')(finds any admin user) - Namespace injection:
admin' or namespace-uri()='http://evil.com'(exploits namespace handling)
The attack surface expands when Basic Auth APIs use XML for configuration, role definitions, or permission stores. An attacker might extract sensitive data beyond authentication, such as:
//user[username='admin' and password='wrong']/permissionsThis could reveal admin permissions even without valid credentials. The combination of Basic Auth's simplicity and XPath's query flexibility creates a dangerous attack vector when XML data stores are involved.
Basic Auth-Specific Detection
Detecting XPath injection in Basic Auth implementations requires examining both the authentication flow and XML query construction. The most effective detection combines static analysis with runtime scanning.
Static analysis should focus on authentication middleware that processes Basic Auth headers. Look for patterns where credentials are extracted and directly interpolated into XPath strings:
const credentials = Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
const xpath = `//user[username='${credentials[0]}' and password='${credentials[1]}']`;Dynamic detection with middleBrick specifically targets this vulnerability through its black-box scanning approach. The scanner sends crafted Basic Auth headers designed to trigger XPath injection:
Authorization: Basic YWRtaW4nIG9yICcxPT0nMToncm9vdA==
// Decodes to: admin' or '1'='1:rootmiddleBrick's XPath injection detection module analyzes API responses for authentication bypass indicators:
| Detection Technique | Basic Auth Context | What It Reveals |
|---|---|---|
| Boolean Injection Testing | Sends ' or '1'='1 | Authentication bypass success |
| XPath Function Testing | Uses contains(), starts-with() | Data extraction capabilities |
| Comment Injection | Appends or ''=' | Query structure weaknesses |
middleBrick's LLM/AI security module also checks for Basic Auth endpoints that might expose system prompts or configuration data through XML responses, though this is a secondary concern compared to authentication bypass.
Runtime detection should monitor for unusual authentication success patterns. If an API accepts any Basic Auth header with specific payload patterns, it indicates XPath injection vulnerability. The scanner tracks response patterns across multiple injection attempts to confirm the vulnerability with statistical confidence.
Compliance mapping shows XPath injection in Basic Auth contexts maps to multiple OWASP API Top 10 categories: Broken Object Level Authorization (BOLA), Injection, and Cryptographic Failures (if credentials are exposed).
Basic Auth-Specific Remediation
Remediating XPath injection in Basic Auth implementations requires eliminating the injection vector while maintaining authentication functionality. The most secure approach replaces XPath-based authentication entirely with parameterized queries or modern authentication mechanisms.
For APIs that must maintain Basic Auth with XML data stores, implement proper input sanitization and use XPath variables:
const xmlDoc = new DOMParser().parseFromString(xmlString, 'application/xml');
const username = req.headers.authorization.split(' ')[1].split(':')[0];
const password = req.headers.authorization.split(' ')[1].split(':')[1];
// Use XPath variables instead of string concatenation
const xpath = '//user[username=$user and password=$pass]';
const resolver = (prefix) => {
if (prefix === 'user') return 'http://example.com/user';
return null;
};
const result = xmlDoc.evaluate(
xpath,
xmlDoc,
resolver,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
);
// Set variable values safely
result.setContext({
user: username,
pass: password
});
However, this approach still has limitations. A more robust solution migrates away from XML-based authentication entirely:
// Modern Basic Auth with secure password hashing
const users = {
'admin': hashPassword('correct-horse-battery-staple'),
'user1': hashPassword('password123')
};
function authenticateBasic(req) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
return false;
}
const credentials = Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
if (credentials.length !== 2) return false;
const [username, password] = credentials;
const storedHash = users[username];
if (!storedHash) return false;
return verifyPassword(password, storedHash);
}
Key remediation principles for Basic Auth XPath injection:
- Eliminate string concatenation in XPath queries
- Use parameterized queries or XPath variables
- Implement proper input validation and sanitization
- Consider migrating to modern authentication frameworks
- Add rate limiting to Basic Auth endpoints
- Log and monitor authentication failures
For existing APIs, middleBrick's remediation guidance includes specific code patterns to replace vulnerable XPath construction with secure alternatives. The scanner provides severity-based recommendations, prioritizing complete authentication mechanism replacement over partial fixes.
Testing the remediation involves sending the same injection payloads that previously succeeded and verifying authentication failure. middleBrick can be used post-remediation to confirm the vulnerability is resolved and provide a new security score reflecting the improved posture.