HIGH dictionary attackfiberbasic auth

Dictionary Attack in Fiber with Basic Auth

Dictionary Attack in Fiber with Basic Auth — how this specific combination creates or exposes the vulnerability

A dictionary attack against an API using HTTP Basic Authentication in a Fiber-based service attempts many username and password combinations to find valid credentials. Because Basic Auth sends credentials in an Authorization header encoded as Base64 (not encrypted) on each request, an attacker who can intercept traffic or observe server logs may obtain these credentials. If the service does not enforce rate limiting or account lockout, an attacker can systematically submit credentials from a wordlist via repeated requests to the login or an otherwise protected endpoint.

In a typical Fiber application, routes may be guarded with Basic Auth middleware that checks a hardcoded or single username/password pair. If the credentials are weak and reused elsewhere, a dictionary attack becomes feasible. For example, an attacker might target an unauthenticated endpoint that reveals whether a given username exists through timing differences or error messages, then use that information to refine guesses. Because the scan tests unauthenticated attack surfaces, middleBrick can detect endpoints that accept Basic Auth credentials without enforcing sufficient protections such as rate limiting, which is one of the 12 parallel security checks.

Another risk arises when credentials are passed in URLs or configuration files that are accidentally exposed (for example, in logs or error traces). Even when TLS is used, poor credential hygiene and lack of additional controls like rate limiting or multi-factor authentication amplify the impact of leaked credentials. The scan’s authentication checks look for missing or weak rate limiting, cleartext transmission risks, and whether the authentication mechanism can be abused via credential guessing.

Using middleBrick’s scans, you can identify whether your Fiber endpoints using Basic Auth expose behaviors that facilitate dictionary attacks. The findings include severity ratings and remediation guidance mapped to frameworks such as OWASP API Top 10 and PCI-DSS, helping you understand the risk without implying automatic fixes are provided by the tool.

Basic Auth-Specific Remediation in Fiber — concrete code fixes

To reduce the risk of dictionary attacks when using Basic Auth in Fiber, apply stronger credential handling, rate limiting, and transport protections. Below are concrete code examples you can adapt.

1. Use middleware to enforce rate limiting and avoid leaking username validity

Apply a rate-limiting middleware to limit the number of requests per IP or user within a time window. This helps slow down automated dictionary attacks. Combine this with constant-time comparison to avoid timing-based username enumeration.

const fastify = require('fastify')();
const rateLimit = require('fastify-rate-limit');

const authMiddleware = (request, reply, done) => {
  const auth = request.headers.authorization || '';
  const token = auth.split(' ')[1];
  if (!token) return done(new Error('unauthorized'));
  const [username, password] = Buffer.from(token, 'base64').toString().split(':');
  // Use constant-time checks where possible and avoid early username-specific errors
  const validUser = timingSafeEqual(username, 'admin');
  const validPass = timingSafeEqual(password, 'correct-horse-battery-staple');
  if (validUser && validPass) return done();
  return done(new Error('unauthorized'));
};

// Apply rate limiting to protect authentication endpoints
fastify.register(rateLimit, {
  max: 10,
  timeRange: 1000,
  prefixKey: (request) => request.ip
});

fastify.addHook('onRequest', (request, reply, next) => {
  // Apply auth selectively to sensitive routes
  if (request.url === '/secure') {
    authMiddleware(request, reply, next);
  } else {
    next();
  }
});

fastify.get('/secure', async (request, reply) => {
  reply.send({ ok: true });
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log('server listening on port 3000');
});

// timingSafeEqual is a simplified example; in production use crypto.timingSafeEqual
const timingSafeEqual = (a, b) => {
  const bufA = Buffer.from(a);
  const bufB = Buffer.from(b);
  if (bufA.length !== bufB.length) return false;
  return crypto.timingSafeEqual(bufA, bufB);
};

2. Enforce HTTPS and avoid credentials in URLs

Ensure TLS is mandatory and reject cleartext HTTP. Do not embed credentials in URLs, as they may be logged in full. Instead, rely on headers and secure storage.

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
};

https.createServer(options, (req, res) => {
  const auth = req.headers.authorization || '';
  if (!auth.startsWith('Basic ')) {
    res.statusCode = 401;
    res.end('Unauthorized');
    return;
  }
  // Validate credentials securely
  res.end('OK');
}).listen(443);

3. Use stronger authentication mechanisms when possible

Consider replacing static Basic Auth tokens with dynamic tokens or session-based flows, and combine with additional checks such as multi-factor authentication. If you must use Basic Auth, rotate credentials frequently and monitor for repeated failed attempts.

4. Leverage middleBrick scans to validate improvements

After applying mitigations, run middleBrick scans (via the CLI, Web Dashboard, or GitHub Action) to verify that rate limiting is detected and that authentication endpoints are not overly permissive. The CLI can be used as follows:

middlebrick scan https://api.example.com/secure

Use the dashboard to track scores over time and integrate the GitHub Action to fail builds if the security score drops below your chosen threshold.

Frequently Asked Questions

Can middleBrick fix dictionary attack issues in my Fiber Basic Auth setup?
middleBrick detects and reports findings with remediation guidance but does not fix, patch, block, or remediate issues. You should apply the suggested mitigations, such as rate limiting and secure credential handling, based on the findings.
How often should I rescan my Fiber API after making Basic Auth changes?
Rescan after each significant change, especially when you modify authentication logic or add rate limiting. With the Pro plan you can enable continuous monitoring so your API is scanned on a configurable schedule, and the GitHub Action can fail builds if the risk score exceeds your threshold.