HIGH brute force attacksailsbearer tokens

Brute Force Attack in Sails with Bearer Tokens

Brute Force Attack in Sails with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A brute force attack against a Sails.js API that uses Bearer tokens attempts to gain unauthorized access by systematically guessing valid tokens. In Sails, authentication logic often lives in policies (e.g., api/policies/authenticate.js) that validate the Authorization: Bearer <token> header. If the endpoint lacks strong rate limiting, account lockout, or token entropy checks, an attacker can iterate through many token values or iterate through user identities and tokens in an effort to find a valid match.

When tokens are predictable (e.g., low-entropy strings, or derived from user data without sufficient randomness), or when Sails routes do not enforce per-user rate limits, brute force becomes feasible. The attacker may probe routes like GET /api/account with different Bearer tokens and observe differences in response (e.g., 200 vs 403), enabling token discovery or account compromise. This risk is compounded if tokens are long-lived, if logging reveals token patterns, or if identical tokens are shared across users.

The 12 parallel security checks in a middleBrick scan include Authentication, Rate Limiting, and Input Validation, which help detect weak token handling, missing throttling, or overly permissive route matchers that facilitate brute force against Bearer token endpoints. Findings include whether token validation is performed early in the request lifecycle, whether responses leak information about token validity, and whether the API exposes unauthenticated endpoints that weaken token-based security.

For example, a misconfigured Sails policy might skip token verification for certain HTTP methods or routes, allowing attackers to brute force user IDs while using a known token format. Proper defenses include cryptographically random tokens, per-user rate limiting, short token lifetimes, and consistent error handling that does not disclose token status.

Bearer Tokens-Specific Remediation in Sails — concrete code fixes

Remediation focuses on token generation, validation, and request handling in Sails. Use a cryptographically secure source of randomness for token creation and enforce strict validation in policies. Below are concrete code examples for a Sails API using Bearer tokens.

1. Generate high-entropy Bearer tokens

Use Node’s crypto module to generate tokens that are hard to guess. Store only a hash of the token in the database, similar to passwords.

// api/services/tokenService.js
const crypto = require('crypto');

module.exports = {
  generateToken: function() {
    return crypto.randomBytes(48).toString('base64url');
  },
  hashToken: function(token) {
    return crypto.createHash('sha256').update(token).digest('hex');
  }
};

2. Secure token policy with rate limiting and constant-time comparison

Create an authentication policy that extracts the Bearer token, compares it safely, and enforces rate limits per identity. Use a library like boom for consistent error responses.

// api/policies/bearerAuth.js
const crypto = require('crypto');
const tokenService = require('../services/tokenService');
const Boom = require('@hapi/boom');

module.exports = async function(req, res, next) {
  const authHeader = req.headers.authorization || '';
  const match = authHeader.match(/^Bearer\s+(\S+)$/i);
  if (!match) {
    return res.unauthorized(Boom.badRequest('Authorization header required'));
  }
  const token = match[1];
  const tokenHash = tokenService.hashToken(token);

  // Look up user by token hash; ensure this lookup uses a constant-time comparison
  const user = await User.findOne({ tokenHash });
  if (!user) {
    // Return generic message to avoid leaking token validity
    return res.unauthorized(Boom.unauthorized('Invalid credentials'));
  }

  // Attach user to request for downstream policies/controllers
  req.user = user;
  return next();
};

3. Apply per-user rate limiting in config/policies.json

Ensure sensitive endpoints are protected by rate limits keyed by user or token hash to hinder brute force attempts.

// config/policies.json
{
  "UserController@me": [
    "bearerAuth",
    "rateLimit" // custom rate limiter keyed by user identifier
  ],
  "AccountController@update": [
    "bearerAuth",
    "rateLimit"
  ]
}

4. Example token usage in a client request

Clients must include the token in the Authorization header. Demonstrate with curl and JavaScript fetch.

# curl example
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSJ9.example" \
  https://api.example.com/api/account
// JavaScript fetch example
fetch('https://api.example.com/api/account', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSJ9.example'
  }
}).then(r => r.json()).then(console.log);

5. Complementary measures

  • Short token lifetimes and refresh token rotation to reduce the impact of token leakage.
  • Consistent error responses that do not distinguish between missing and invalid tokens.
  • Logging without exposing raw tokens; log only token identifiers or hashes.

middleBrick scans can validate these practices by checking Authentication and Rate Limiting configurations, ensuring token handling aligns with security expectations.

Frequently Asked Questions

How does middleBrick detect brute force risks around Bearer tokens in Sails?
middleBrick runs parallel checks including Authentication, Rate Limiting, and Input Validation to identify weak token handling, missing throttling, or information leakage that could enable brute force attacks.
Can I test my Sails API for Bearer token issues without signing up?
Yes; the free tier allows 3 scans per month. Use the CLI with middlebrick scan <url> or paste your endpoint into the web dashboard to get a security risk score and findings.