HIGH arp spoofinghapijwt tokens

Arp Spoofing in Hapi with Jwt Tokens

Arp Spoofing in Hapi with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Arp spoofing is a network-layer attack where an attacker sends falsified Address Resolution Protocol (ARP) responses to associate their MAC address with the IP address of another host, typically the default gateway. In a Hapi application that uses JWT tokens for authentication, arp spoofing does not directly break the cryptographic integrity of the tokens, but it creates conditions that undermine the trust assumptions of the authentication flow.

When a Hapi service validates JWTs, it typically relies on the assumption that communication between the client and server occurs over trusted network paths. If an attacker performs arp spoofing on this path, they can intercept, modify, or replay HTTP requests. While JWTs signed with strong algorithms (e.g., RS256 or ES256) resist tampering, the attacker can still capture valid tokens from legitimate requests and reuse them (token replay). Because the token itself is valid, server-side validation passes, allowing the attacker to impersonate the victim user without needing to know the secret or private key.

This combination is particularly risky in scenarios where short-lived tokens are used without additional transport protections. An attacker who successfully spoofs ARP frames can position themselves as a man-in-the-middle on the local network segment, capturing JWTs transmitted over seemingly secure HTTP (or even HTTPS if certificate validation is improperly implemented in client-side code). The server sees requests with valid signatures and correct claims, but the context of the request has been manipulated. This exposes the application to session hijacking, where stolen tokens are used to gain unauthorized access until expiration or revocation occurs.

Moreover, in clustered or containerized deployments where Hapi services communicate internally, arp spoofing between services can expose service-to-service endpoints that accept JWTs with broad scopes. If a service does not enforce strict source validation or mutual TLS in addition to JWT verification, an attacker on the internal network can forge ARP responses to redirect traffic and abuse overly permissive token validation logic. The vulnerability is not in the JWT implementation itself, but in the network perimeter assumptions that allow unauthenticated network-layer manipulation to intersect with authenticated API calls.

Jwt Tokens-Specific Remediation in Hapi — concrete code fixes

To reduce risk when using JWT tokens in Hapi, implement strict transport and token validation controls. These code examples demonstrate hardened configurations that mitigate the impact of potential network-layer attacks like arp spoofing.

1. Enforce HTTPS and strict transport security

Ensure all endpoints are served over HTTPS and reject insecure connections. This prevents token interception on untrusted networks.

const Hapi = require('@hapi/hapi');
const tlsOptions = {
  key: fs.readFileSync('/path/to/server.key'),
  cert: fs.readFileSync('/path/to/server.crt')
};

const init = async () => {
  const server = Hapi.server({
    port: 443,
    host: '0.0.0.0',
    tls: tlsOptions
  });

  server.route({
    method: 'GET',
    path: '/secure',
    handler: (request, h) => ({ message: 'Authenticated' }),
    options: {
      auth: 'jwt'
    }
  });

  await server.register(require('hapi-auth-jwt2'));
  server.auth.strategy('jwt', 'jwt', {
    key: process.env.JWT_PUBLIC_KEY,
    validate: async (decoded, request) =>
      ({
        isValid: true,
        credentials: decoded
      }),
    verifyOptions: {
      algorithms: ['RS256'],
      clockTolerance: 10
    }
  });

  await server.start();
};

2. Validate token context and binding

Bind JWT validation to request properties such as IP or TLS session information to detect anomalies that may indicate interception.

server.auth.strategy('jwt', 'jwt', {
  key: process.env.JWT_PUBLIC_KEY,
  validate: async (decoded, request) =>
  {
    const ip = request.info.remoteAddress;
    const expectedAudience = 'https://api.yourdomain.com';

    if (decoded.aud !== expectedAudience) {
      return { isValid: false };
    }

    // Optional: bind token to session or client metadata if available
    return {
      isValid: true,
      credentials: decoded,
      artifacts: { ip },
    };
  },
  verifyOptions: {
    algorithms: ['RS256'],
    audience: 'https://api.yourdomain.com',
    issuer: 'https://auth.yourdomain.com'
  }
});

3. Implement short expiry and token binding

Use short-lived tokens and avoid storing them insecurely. Combine with mechanisms such as one-time use identifiers where feasible.

const generateToken = (user) => {
  return jwt.sign(
    { sub: user.id, scope: 'read write' },
    process.env.JWT_PRIVATE_KEY,
    { algorithm: 'RS256', expiresIn: '15m', issuer: 'https://auth.yourdomain.com' }
  );
};

4. Apply route-level security and CORS restrictions

Limit origins and enforce strict CORS policies to reduce exposure from browser-based contexts where arp spoofing may be more effective.

Hapi JWT Example — full server setup

The following complete example shows a Hapi server configured with JWT authentication using RS256, audience and issuer validation, and secure transport settings.

const Hapi = require('@hapi/hapi');
const jwt = require('hapi-auth-jwt2');
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')
    }
  });

  await server.register(jwt);

  server.auth.strategy('jwt', 'jwt', {
    key: process.env.JWT_PUBLIC_KEY,
    validate: async (decoded, request) => ({
      isValid: true,
      credentials: decoded
    }),
    verifyOptions: {
      algorithms: ['RS256'],
      audience: 'https://api.yourdomain.com',
      issuer: 'https://auth.yourdomain.com'
    }
  });

  server.route({
    method: 'GET',
    path: '/profile',
    handler: (request, h) => ({
      userId: request.auth.credentials.sub,
      scope: request.auth.credentials.scope
    }),
    options: {
      auth: 'jwt'
    }
  });

  await server.start();
  console.log('Server running on port 443');
};

init();

Frequently Asked Questions

Can arp spoofing bypass JWT signature validation in Hapi?
No. JWT signature validation relies on cryptographic checks that are not affected by ARP spoofing. However, arp spoofing can enable token replay, where a captured valid JWT is reused, bypassing the need to break the signature. Mitigations include enforcing HTTPS, short token lifetimes, and binding tokens to request context.
Does middleBrick scan detect risks related to JWT usage in Hapi APIs?
middleBrick scans the unauthenticated attack surface of your Hapi API and includes checks related to authentication mechanisms, data exposure, and encryption. While it does not test network-layer attacks such as arp spoofing directly, it assesses whether JWT-related configurations expose tokens or lack transport protections, providing remediation guidance aligned with frameworks like OWASP API Top 10.