HIGH credential stuffinghapimutual tls

Credential Stuffing in Hapi with Mutual Tls

Credential Stuffing in Hapi with Mutual Tls — how this specific combination creates or exposes the vulnerability

Credential stuffing is an automated attack where adversaries use stolen username and password pairs to gain unauthorized access to accounts. In a Hapi application protected by Mutual Transport Layer Security (mTLS), the presence of client certificates can create a false sense of strong authentication while the server still relies primarily on password-based validation. If the API endpoint accepts both certificate-based authentication and traditional password login, an attacker who obtains credentials can attempt to authenticate using a valid client certificate to bypass weaker or misconfigured checks.

Mutual TLS binds the client identity to a certificate, but if the server does not enforce certificate-to-user mapping consistently, credential stuffing can still succeed against password-only endpoints or fallback authentication paths. For example, if a Hapi route uses a cookie or bearer token after an initial password login, an attacker can reuse those session tokens while presenting a valid client certificate to evade IP-based or certificate-based rate limiting. Because middleBrick tests unauthenticated attack surfaces, it can detect whether credential-based routes remain reachable when mTLS is advertised but not strictly required for all authentication-sensitive operations.

During a scan, middleBrick evaluates whether authentication checks are applied uniformly across login, token exchange, and sensitive endpoints. Findings may include missing certificate validation on certain routes, inconsistent enforcement of mTLS, or lack of binding between certificate subject attributes and server-side user roles. These gaps allow credential stuffing to be combined with a valid certificate to escalate impact, especially when session tokens are long-lived or improperly invalidated. Proper remediation requires that every route enforcing user permissions also validates the presented certificate and maps it to an authoritative identity before processing credentials.

Mutual Tls-Specific Remediation in Hapi — concrete code fixes

To secure a Hapi application with Mutual TLS, enforce certificate validation for all routes and tightly bind certificate fields to user identities. Below are concrete code examples that demonstrate how to configure the TLS server and validate client certificates within route handlers.

// server.js
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('/etc/ssl/private/server.key'),
      cert: fs.readFileSync('/etc/ssl/certs/server.crt'),
      ca: [fs.readFileSync('/etc/ssl/certs/ca.crt')],
      requestCert: true,
      rejectUnauthorized: true
    }
  });

  server.route({
    method: 'POST',
    path: '/login',
    options: {
      tls: {
        // Require and validate client certificate for this route
        requestCert: true,
        rejectUnauthorized: true
      },
      handler: (request, h) => {
        const cert = request.info.clientCert;
        if (!cert) {
          throw Boom.unauthorized('Client certificate required');
        }
        // Map certificate subject to user identity
        const username = mapCertToUser(cert.subject);
        if (!username) {
          throw Boom.forbidden('Certificate not mapped to an account');
        }
        // Proceed with password-based auth, ensuring certificate identity matches
        const { password } = request.payload;
        if (!validatePassword(username, password)) {
          throw Boom.unauthorized('Invalid credentials');
        }
        const token = issueSessionToken(username, cert.subject);
        return h.response({ token }).state('session', token, { isSecure: true });
      }
    }
  });

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

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

function mapCertToUser(subject) {
  // Example: extract CN or SAN matching internal directory
  const cnMatch = subject.match(/CN=([^,]+)/);
  return cnMatch ? cnMatch[1] : null;
}

function validatePassword(username, password) {
  // Replace with secure password verification, e.g., bcrypt.compare
  return password === 'correct-hashed-password';
}

function issueSessionToken(username, certSubject) {
  // Issue a short-lived token bound to cert subject
  return { username, certSubject };
}

In this setup, requestCert: true and rejectUnauthorized: true ensure that only clients with trusted certificates can complete the TLS handshake. Within the handler, you explicitly check for the presence of request.info.clientCert and map its subject to an internal user. This mapping prevents attackers from using valid credentials alone without a corresponding authorized certificate. You should also enforce certificate revocation checks against CRLs or OCSP where applicable and avoid fallback authentication paths that skip mTLS validation.

For broader protection, integrate these checks across all routes and use the CLI tool to scan your API surface with middlebrick scan <url>. The dashboard can help track how often mTLS-related findings appear and supports remediation guidance tied to frameworks such as OWASP API Top 10. If your pipeline requires automated enforcement, the Pro plan’s GitHub Action can fail builds when risk scores degrade, while the MCP Server allows you to run scans directly from your AI coding assistant within the development environment.

Frequently Asked Questions

Does mTLS fully prevent credential stuffing in Hapi?
Mutual TLS binds client identity to certificates, but credential stuffing can still succeed if password-only endpoints or fallback authentication paths bypass certificate checks. You must enforce certificate validation on every route that handles credentials and map certificates to user identities consistently.
How can I verify that my Hapi routes require client certificates?
Use middleBrick’s unauthenticated scan with the CLI: middlebrick scan . The findings will indicate whether routes expose authentication-sensitive operations without mTLS enforcement and provide remediation guidance aligned with OWASP API Top 10 and related compliance frameworks.