HIGH xml external entitieshapibasic auth

Xml External Entities in Hapi with Basic Auth

Xml External Entities in Hapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Xml External Entity (XXE) injection becomes more impactful in Hapi when Basic Authentication is used in an unauthenticated scan context. XXE occurs when an XML parser is configured to process external entities, allowing an attacker to force the parser to read local files, trigger SSRF to internal services, or consume excessive resources. In Hapi, this typically arises when request payloads or route configurations accept XML input and forward it to a parser such as libxml2 via packages that expose XML parsing without disabling external entity resolution.

When combined with Basic Auth in an unauthenticated black-box scan, middleBrick tests endpoints that accept credentials but still expose XML parsing paths. The scanner submits requests that include Basic Auth headers while sending malicious XML bodies containing external entity declarations (e.g., <!ENTITY file SYSTEM "file:///etc/passwd">). If the Hapi route does not explicitly disable external entities, the parser may read sensitive files or interact with internal endpoints reachable from the server. Because the scan is unauthenticated, it probes the attack surface without credentials, yet the presence of Basic Auth challenges highlights routes where authentication is required; an attacker with stolen credentials could escalate impact by leveraging XXE to access protected resources or exfiltrate data via server-side requests.

Key risk patterns specific to this combination include:

  • XML payloads sent over HTTPS with Basic Auth headers, where the server trusts the client-supplied XML without validation.
  • Use of generic XML parsing libraries in Hapi routes that do not explicitly prohibit DOCTYPE declarations and external entity resolution.
  • Exposure of internal services (e.g., metadata services on 169.254.169.254) through XML-driven SSRF when external entities are not sandboxed.

An example curl command that demonstrates a malicious XML payload with Basic Auth illustrates the request structure the scanner validates:

curl -u admin:password -X POST https://api.example.com/import \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd" >]%>
<root><data>&xxe;</data></root>'

middleBrick detects whether such payloads trigger unauthorized file reads or SSRF behavior by inspecting responses for signs of sensitive data exposure while correlating findings with the presence of authentication mechanisms. The scanner does not fix the parsing logic but highlights the need to treat XML input as untrusted and to apply strict parser hardening in routes that require credentials.

Basic Auth-Specific Remediation in Hapi — concrete code fixes

Remediation in Hapi focuses on disabling external entity processing in any XML parser and ensuring authentication does not inadvertently widen the attack surface. Even when Basic Auth is required, you must validate and sanitize all inputs and configure parsers to reject or ignore external entities.

Use an XML parser that disables DTDs and external entities by default. For example, with xmldom in a Hapi route, avoid the default constructor and explicitly configure the parser to not process external entities:

const { DOMParser } = require('@xmldom/xmldom');
const options = {
  { feature: 'http://apache.org/xml/features/disallow-doctype-decl', value: true },
  { feature: 'http://xml.org/sax/features/external-general-entities', value: false },
  { feature: 'http://xml.org/sax/features/external-parameter-entities', value: false },
  { feature: 'http://apache.org/xml/features/nonvalidating/load-external-dtd', value: false },
  { feature: 'xerces-default-has-external-general-entities', value: false }
};

const parser = new DOMParser(options);
const doc = parser.parseFromString(xmlString);

Additionally, reject XML content types where unnecessary, or enforce strict schema validation before parsing. With Hapi, you can reject XML outright if your API uses JSON, or validate against a schema using a library like joi for payloads that must conform to a contract.

When Basic Auth is required, combine it with strong route validation. Here is an example of a Hapi route with Basic Auth that safely handles only JSON and explicitly rejects XML content types:

const Hapi = require('@hapi/hapi');
const auth = require('@hapi/basic');

const validate = (request, username, password, h) => {
  const isValid = username === 'admin' && password === 'strongpassword';
  return { isValid, credentials: { id: username } };
};

const init = async () => {
  const server = Hapi.server({ port: 3000 });
  await server.register(auth);

  server.auth.strategy('simple', 'basic', { validate });

  server.route({
    method: 'POST',
    path: '/import',
    options: {
      auth: {
        strategy: 'simple',
        mode: 'required'
      },
      validate: {
        options: {
          stripUnknown: true
        },
        payload: Joi.object({
          // Expect JSON only, reject XML content-type
        }).unknown()
      },
      handler: (request, h) => {
        // Safe processing of JSON payload
        return { status: 'ok' };
      }
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

init();

If XML must be accepted, enforce parser hardening and avoid passing raw user input directly to system or internal endpoints. Combine these measures with rate limiting and monitoring to reduce the impact of abuse. middleBrick’s scans will flag endpoints that accept XML without disabling external entities, providing remediation guidance mapped to frameworks such as OWASP API Top 10 and relevant compliance standards.

Frequently Asked Questions

Does middleBrick attempt to exploit XXE or use stolen credentials during scans?
No. middleBrick detects and reports XXE indicators and authentication requirements but does not exploit vulnerabilities or use any credentials. It reports findings and provides remediation guidance only.
How can I verify that my Hapi routes are hardened against XXE when using Basic Auth?
Review parser configuration to ensure external entities and DOCTYPE declarations are disabled. Use automated scans like middleBrick to check unauthenticated attack surfaces, and validate that routes rejecting XML or enforcing strict schema parsing remain the default.