HIGH container escapehapibasic auth

Container Escape in Hapi with Basic Auth

Container Escape in Hapi with Basic Auth — how this specific combination creates or exposes the vulnerability

A container escape in Hapi when Basic Auth is used typically arises from a server-side request forgery (SSRF) or insecure deserialization chain that allows an attacker to move from the API process into the host runtime or underlying container runtime. Hapi does not inherently introduce this risk, but the framework’s flexible plugin system and request lifecycle hooks can expose dangerous behaviors when combined with misconfigured SSRF-prone endpoints and weak access controls.

Consider a scenario where an authenticated or unauthenticated endpoint in Hapi accepts a user-supplied URL to proxy or fetch metadata, and Basic Auth credentials are passed through or reused without scrubbing. If SSRF exists (an included security check in middleBrick), an attacker can direct the server to access metadata services exposed on the container host, such as http://169.254.169.254 (AWS instance metadata) or the Docker Engine API exposed over a mounted Unix socket or forwarded port. Successful access can reveal credentials, IAM tokens, or Docker socket access that enables container escape.

Basic Auth compounds the issue because credentials are often passed in headers across internal network segments or plugins, and developers may mistakenly trust container network segmentation. If an SSRF flaw permits reaching the Docker Engine API (/containers/create), an attacker can leverage exposed Basic Auth–protected admin endpoints to create privileged containers, mount the host filesystem, or execute processes with elevated privileges. middleBrick’s SSRF and BFLA checks specifically test these paths, mapping findings to OWASP API Top 10 and PCI-DSS requirements to highlight how authentication schemes like Basic Auth can inadvertently facilitate lateral movement and container escape.

Another angle involves unsafe consumption of user input in Hapi route handlers. If user data is passed to shell commands or container management clients without strict validation, attackers can inject escape sequences or malicious flags. Even when endpoints appear to require Basic Auth, bypass techniques or misconfigured route validation can expose dangerous handlers. middleBrick’s Input Validation and Unsafe Consumption checks examine runtime behavior against OpenAPI specs (with full $ref resolution), ensuring that authentication does not obscure injection paths that lead to container escape.

middleBrick detects these patterns by correlating unauthenticated SSRF probes, authentication bypass checks, and runtime responses that indicate access to host-level services. The scanner does not fix the escape but provides remediation guidance, such as disabling metadata access, enforcing strict allowlists, and avoiding credential propagation across internal calls.

Basic Auth-Specific Remediation in Hapi — concrete code fixes

To mitigate container escape risks when using Basic Auth in Hapi, apply strict input validation, avoid credential reuse across internal calls, and enforce least-privilege configurations. Below are concrete code examples that demonstrate secure patterns.

1. Validate and sanitize all inputs before use

Never forward user-controlled data to internal services or shell commands. Use Joi validation to enforce strict rules on headers, query parameters, and payloads.

const Hapi = require('@hapi/hapi');
const Joi = require('joi');

const validateUsername = Joi.string().alphanum().min(3).max(30).required();
const validatePassword = Joi.string().min(8).required();

const server = Hapi.server({ port: 4000, host: 'localhost' });

server.route({
  method: 'POST',
  path: '/login',
  options: {
    validate: {
      headers: Joi.object({
        authorization: Joi.string().required()
      }).unknown(),
      payload: Joi.object({
        username: validateUsername,
        password: validatePassword
      })
    }
  },
  handler: (request, h) => {
    const { username, password } = request.payload;
    // Perform authentication securely without exposing credentials to downstream services
    return h.response({ status: 'ok' }).code(200);
  }
});

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

2. Avoid credential propagation in SSRF-prone endpoints

If your Hapi app must fetch external resources, do not forward Basic Auth headers to user-supplied URLs. Use service accounts with limited scope or token-based delegation instead.

const axios = require('axios');
const Hapi = require('@hapi/hapi');

const server = Hapi.server({ port: 5000, host: 'localhost' });

server.route({
  method: 'GET',
  path: '/fetch-public',
  options: {
    validate: {
      query: Joi.object({
        url: Joi.string().uri().required()
      })
    }
  },
  handler: async (request, h) => {
    const { url } = request.query;
    // Do NOT pass authorization headers to user-provided URLs
    const response = await axios.get(url, {
      timeout: 5000,
      headers: { 'User-Agent': 'middleBrick-secure-proxy' }
    });
    return response.data;
  }
});

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

3. Use middleware to strip or rewrite dangerous headers

Intercept outgoing requests from plugins or internal clients to ensure Basic Auth credentials are not inadvertently exposed to internal services that could be reached via SSRF.

const server = Hapi.server({ port: 6000, host: 'localhost' });

server.ext('onPreResponse', (request, h) => {
  const response = request.response;
  if (response.isBoom) {
    // Example: remove sensitive headers on error
    response.header('www-authenticate', '');
  }
  return h.continue;
});

// Always enforce strict CORS and avoid exposing Authorization in logs
server.route({
  method: 'GET',
  path: '/secure',
  options: {
    auth: false,
    handler: (request, h) => {
      // Ensure no credentials are logged or forwarded
      return { message: 'secure endpoint' };
    }
  }
});

await server.start();

4. Enforce least privilege and disable dangerous routes

Disable unused methods and plugins, and apply route-specific authentication scopes. middleBrick’s Authentication and BOLA checks verify that endpoints do not allow privilege escalation via misconfigured auth scopes.

const server = Hapi.server({ port: 7000, host: 'localhost' });

// Apply strict authentication only where needed
server.auth.strategy('simple', 'basic', {
  validate: (request, username, password, options) => {
    // Use constant-time comparison and avoid logging credentials
    const isValid = username === 'admin' && password === 'StrongPass!2025';
    return { isValid, credentials: { username } };
  }
});

server.route({
  method: 'GET',
  path: '/admin',
  options: {
    auth: 'simple',
    plugins: {
      // Limit exposure
      'hapi-auth-cookie': { redirectTo: false }
    },
    handler: (request, h) => {
      return { message: 'admin area' };
    }
  }
});

await server.start();

These patterns reduce the attack surface that could lead to container escape when Basic Auth is used. Always pair these measures with runtime security checks available through middleBrick’s scans to identify and prioritize findings.

Frequently Asked Questions

Does middleBrick fix container escape vulnerabilities in Hapi?
middleBrick detects and reports container escape risks, including SSRF and unsafe credential handling in Hapi. It provides prioritized findings and remediation guidance but does not automatically fix or patch vulnerabilities.
How often should I scan my Hapi endpoints with middleBrick?
For ongoing risk management, use the Pro plan for continuous monitoring and scheduled scans. The CLI tool allows you to integrate scans into CI/CD pipelines to fail builds if risk scores exceed your threshold.