HIGH buffer overflowhapimutual tls

Buffer Overflow in Hapi with Mutual Tls

Buffer Overflow in Hapi with Mutual Tls — how this specific combination creates or exposes the vulnerability

A buffer overflow in a Hapi server becomes more severe when Mutual TLS (mTLS) is in use because the TLS layer terminates before application logic runs, and the server may process untrusted client certificates and payloads as part of the handshake. In Hapi, incoming requests pass through the TLS layer and then route to handlers that may read streams or parse payloads without strict length checks. If a handler or an underlying dependency copies untrusted input into a fixed-size stack or heap buffer, an attacker can craft oversized headers, cookies, or message bodies to overflow the buffer. The presence of mTLS does not prevent this; it only shifts the trust boundary to the client certificate, which the server still validates and then passes into potentially unsafe code paths.

Attack patterns enabled by this combination include:

  • Oversized HTTP headers (e.g., long cookies or authorization values) that overflow a buffer during parsing.
  • Large request bodies or multipart/form-data payloads that exceed expected sizes and are copied without validation.
  • Exploiting certificate or session state handling in mTLS flows where buffers are reused across handshake steps.

These issues map to common weaknesses such as CWE-120 (Buffer Copy without Checking Size of Input) and CWE-119 (Improper Restriction of Operations within the Bounds of a Memory Buffer). While Hapi does not inherently introduce buffer overflows, frameworks and plugins that process streams or headers must apply strict size limits. middleBrick scans for input validation failures and unsafe consumption patterns, which include scenarios where large payloads reach application code unchecked, even when mTLS is enforced.

Real-world references: CVE-2019-15605 (Node.js HTTP parser buffer edge case), CVE-2020-8203 (http-proxy request smuggling leading to buffer issues). These illustrate how improperly bounded input can lead to memory corruption. OWASP API Security Top 10 #1 (Broken Object Level Authorization) and #5 (Broken Function Level Authorization) are relevant when access controls around mTLS-authenticated requests are insufficient to prevent abuse of large or malformed payloads.

Mutual Tls-Specific Remediation in Hapi — concrete code fixes

To mitigate buffer overflow risks in Hapi with mTLS, enforce strict size limits on headers and bodies, validate certificate metadata, and avoid unsafe copying of payloads. Below are concrete code examples that combine mTLS setup with defensive handling.

1. Hapi server with mTLS and size-constrained payload parsing

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

const init = async () => {
  const server = Hapi.server({
    port: 443,
    host: '0.0.0.0',
    tls: {
      key: fs.readFileSync('/path/to/server-key.pem'),
      cert: fs.readFileSync('/path/to/server-cert.pem'),
      ca: [fs.readFileSync('/path/to/ca-cert.pem')],
      requestCert: true,
      rejectUnauthorized: true
    }
  });

  // Limit header size by rejecting large headers early
  server.ext('onRequest', (request, h) => {
    const maxHeaderSize = 8 * 1024; // 8 KB
    for (const key of Object.keys(request.headers)) {
      if (Buffer.byteLength(request.headers[key], 'utf8') > maxHeaderSize) {
        return h.response({ error: 'Header size too large' }).code(431);
      }
    }
    return h.continue;
  });

  // Limit payload size for JSON and multipart
  server.ext('onPreHandler', (request, h) => {
    const maxBodySize = 128 * 1024; // 128 KB
    if (request.payload && request.payload.length && request.payload.length > maxBodySize) {
      return h.response({ error: 'Payload size exceeds limit' }).code(413);
    }
    return h.continue;
  });

  server.route({
    method: 'POST',
    path: '/api/data',
    handler: (request, h) => {
      // Process validated request with mTLS client certificate info
      const { clientCert } = request.server.app; // stored during onRequest
      const safeData = request.payload ? request.payload.slice(0, 1024) : Buffer.alloc(0);
      return { received: safeData.length, peer: request.info.localAddress };
    }
  });

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

process.on('unhandledRejection', (err) => {
  console.error(err);
  process.exit(1);
});

This example shows mTLS enforced via requestCert and rejectUnauthorized, with onRequest and onPreHandler extensions to cap header and body sizes, reducing overflow risk. The handler uses bounded slices instead of unbounded concatenation.

2. Hapi with explicit certificate validation and safe stream handling

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

const validateClientCert = (cert) => {
  // Implement policy checks: issuer, expiry, fingerprint allowlist
  const allowedFingerprints = ['AA:BB:CC:...'];
  return allowedFingerprints.includes(cert.fingerprint);
};

const server = Hapi.server({
  port: 443,
  host: '0.0.0.0',
  tls: {
    key: fs.readFileSync('/path/to/server-key.pem'),
    cert: fs.readFileSync('/path/to/server-cert.pem'),
    ca: [fs.readFileSync('/path/to/ca-cert.pem')],
    requestCert: true,
    rejectUnauthorized: false // We validate manually to inspect cert
  }
});

server.ext('onRequest', (request, h) => {
  const { req } = request.raw;
  if (req.client.authorized) {
    const cert = req.client.authorized;
    if (!validateClientCert(cert)) {
      return h.response({ error: 'Unauthorized certificate' }).code(403);
    }
    request.server.app.clientCert = cert;
  } else {
    return h.response({ error: 'Client certificate required' }).code(401);
  }
  return h.continue;
});

server.route({
  method: 'GET',
  path: '/status',
  handler: (request, h) => {
    // Safe: using prevalidated certificate metadata, no large buffer allocations
    return { ok: true, issuer: request.server.app.clientCert.issuer };
  }
});

In this variant, mTLS is accepted but manually validated to avoid processing unauthorized clients, and handlers avoid operations that can grow buffers unboundedly. middleBrick’s LLM/AI Security and Input Validation checks help surface endpoints where size limits or certificate handling may be inconsistent.

Frequently Asked Questions

Does mTLS prevent buffer overflow vulnerabilities in Hapi?
No. Mutual TLS authenticates clients and secures transport, but it does not stop oversized headers or bodies from being processed unsafely in application code. Buffer overflow risks must be addressed by validating and bounding all input, regardless of mTLS.
How can I test for buffer overflow issues in my Hapi API with mTLS?
Use middleBrick to scan your endpoint. It runs input validation and unsafe consumption checks against the unauthenticated attack surface, including large headers and payloads, and reports findings with remediation guidance. Combine this with manual code review of header and body handling.