Xpath Injection with Bearer Tokens
How Xpath Injection Manifests in Bearer Tokens
Xpath injection occurs when untrusted input is incorporated into Xpath queries without proper sanitization, allowing attackers to manipulate the query logic. In Bearer Token implementations, this vulnerability often appears in authentication and authorization workflows where Xpath queries are used to validate token claims or retrieve user permissions.
A common attack pattern involves manipulating the token's payload to inject Xpath syntax. Consider an API endpoint that validates Bearer Tokens by querying a user database:
const token = req.headers.authorization.replace('Bearer ', '');
const payload = jwt.decode(token);
const xpathQuery = `/users[user_id=${payload.sub} and active='true']`;
const result = xpath.evaluate(xpathQuery, document);
An attacker can craft a token with a manipulated sub claim:
{
"sub": "1234' or '1'='1"
}
This transforms the Xpath query into:
/users[user_id=1234' or '1'='1' and active='true']
The injected or '1'='1' clause makes the condition always true, potentially bypassing authentication checks and exposing all user records.
Another manifestation occurs in role-based access control systems where Xpath queries evaluate permissions:
const roleQuery = `/permissions[role='${userRole}' and resource='${resource}']`;
An attacker could inject Xpath functions or axes to traverse the XML document unexpectedly:
{
"role": "admin",
"resource": "document" or @privileged='true' or starts-with(name, 'secret_')"
}
This might expose privileged resources beyond the intended scope.
Bearer Token implementations using XML-based token formats (like SAML) are particularly vulnerable when the token content is directly used in Xpath queries without validation. The XML structure itself can contain Xpath injection vectors through element content or attribute values.
Bearer Tokens-Specific Detection
Detecting Xpath injection in Bearer Token workflows requires examining both the token validation logic and the Xpath query construction patterns. Here are Bearer Tokens-specific detection strategies:
Static Analysis Detection:
Review code that processes Bearer Tokens for Xpath query construction patterns. Look for these red flags:
// Vulnerable patterns to flag
const xpathQuery = `/users[user_id=${payload.sub}]`;
const query = `/permissions[role='${role}']`;
const expr = xpath.compile(`/data[${condition}]`);
Tools like ESLint with custom rules can detect string concatenation in Xpath queries where variables are inserted without sanitization.
Dynamic Testing with middleBrick:
middleBrick's black-box scanning approach is particularly effective for Bearer Token Xpath injection detection. The scanner automatically:
- Generates malformed Bearer Tokens with Xpath injection payloads
- Tests authentication endpoints by injecting boolean logic and Xpath functions
- Analyzes API responses for information disclosure patterns
- Maps findings to OWASP API Top 10 (A1: Injection)
- Provides severity ratings based on exploitability and impact
Using middleBrick CLI for Bearer Token Xpath injection testing:
npx middlebrick scan https://api.example.com/auth
The scanner tests with payloads like:
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0J3wgJ3JlZ2lzdGVyJ30.
Where the sub claim contains Xpath injection attempts.
Runtime Monitoring:
Implement logging to detect suspicious Xpath query patterns at runtime:
function validateXpathInput(input) {
const suspiciousPatterns = [
/'or['1'=]/i,
/or\s+['"].*['"]\s*=/i,
/\b(and|or|union|select)\b/i
];
if (suspiciousPatterns.some(pattern => pattern.test(input))) {
console.warn('Potential Xpath injection attempt:', input);
return false;
}
return true;
}
This helps identify attempted Xpath injections in production Bearer Token processing.
Bearer Tokens-Specific Remediation
Remediating Xpath injection in Bearer Token implementations requires a defense-in-depth approach. Here are Bearer Tokens-specific fixes:
Input Validation and Whitelisting:
Validate token claims before using them in Xpath queries. For numeric IDs:
function validateUserId(userId) {
const userIdNum = parseInt(userId, 10);
if (isNaN(userIdNum) || userIdNum.toString() !== userId) {
throw new Error('Invalid user ID format');
}
return userIdNum;
}
For role-based access:
const validRoles = ['admin', 'user', 'guest'];
function validateRole(role) {
if (!validRoles.includes(role)) {
throw new Error('Invalid role');
}
return role;
}
Parameterized Xpath Queries:
Where possible, use parameterized Xpath queries instead of string concatenation:
function getUserById(userId) {
const xpathDoc = new DOMParser().parseFromString(xmlData, 'application/xml');
const xpathResult = xpathDoc.evaluate(
'/users/user[id=$id]/name',
xpathDoc,
null,
XPathResult.STRING_TYPE,
null
);
xpathResult.iterateNext().setParameter('id', userId);
return xpathResult.stringValue;
}
Least Privilege Principle:
Implement the principle of least privilege in Xpath queries:
function buildSecureXpathQuery(userId, resource) {
const safeUserId = validateUserId(userId);
const safeResource = validateResource(resource);
return `
/users[user_id=${safeUserId} and
permissions/resource='${safeResource}' and
status='active']
`;
}
Schema Validation:
Validate Bearer Token payloads against a strict schema before processing:
const tokenSchema = {
type: 'object',
properties: {
sub: { type: 'string', pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$' },
role: { type: 'string', enum: ['admin', 'user', 'guest'] }
},
required: ['sub']
};
middleBrick Integration for Continuous Security:
Integrate middleBrick into your Bearer Token implementation workflow:
// GitHub Action workflow
name: API Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick scan
run: |
npx middlebrick scan https://api.example.com/auth
continue-on-error: true
- name: Fail on critical issues
if: failure()
run: |
echo "Security scan failed - please review middleBrick report"
exit 1
This ensures Xpath injection vulnerabilities are caught before deployment.