HIGH injection flawsbearer tokens

Injection Flaws with Bearer Tokens

How Injection Flaws Manifest in Bearer Tokens

When an application extracts the value from an Authorization: Bearer header and then uses that raw token string in a downstream operation without proper sanitization, the token becomes an injection vector. Because the Bearer scheme places no restrictions on the characters that can appear in the token, an attacker can embed SQL, shell, LDAP, or header‑injection payloads that get interpreted by the server.

Common code paths where this occurs include:

  • Building SQL queries by string concatenation: db.query(`SELECT * FROM tokens WHERE value = '${token}'`)
  • Passing the token to a shell command: exec(`curl -H \"Authorization: Bearer ${token}\" https://internal.example.com/validate`)
  • Embedding the token in LDAP filter strings or XML/JSON that is later parsed.
  • Writing the token directly into HTTP response headers (e.g., Set-Cookie: auth=${token}) which can lead to CRLF/header injection if the token contains newline characters.

For example, a vulnerable Node.js endpoint might look like this:

const express = require('express');
const { Client } = require('pg');
const app = express();
const db = new Client({ connectionString: process.env.DATABASE_URL });

app.get('/profile', (req, res) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) return res.status(401).send();
  const token = auth.slice(7); // Bearer 

  // VULNERABLE: direct concatenation into SQL
  db.query(`SELECT * FROM users WHERE api_token = '${token}'`, (err, rows) => {
    if (err) return res.status(500).send(err.message);
    res.json(rows);
  });
});

app.listen(3000);

If an attacker sends Authorization: Bearer ' OR '1'='1, the resulting query becomes SELECT * FROM users WHERE api_token = '' OR '1'='1', returning all rows and potentially exposing sensitive data. Similar risks exist when the token is fed into child_process.exec, LDAP filters, or response headers, enabling command injection, LDAP injection, or CRLF attacks.

Bearer Tokens-Specific Detection

middleBrick detects injection flaws in Bearer Token handling by sending a series of specially crafted tokens in the Authorization header and observing the target’s behavior. The scanner does not need a valid token; it looks for signs that the injected payload was interpreted as code or syntax.

The active checks include:

  • SQL injection payloads (e.g., ' OR 1=1--, '; DROP TABLE users;--) and monitoring for database error messages, changes in response size, or timing differences.
  • Command injection payloads (e.g., ; id, && cat /etc/passwd) and checking for unexpected output in the response or side‑effects such as delayed responses.
  • LDAP injection payloads (e.g., *)(|(uid=*) and looking for authentication bypass or directory errors.
  • Header injection payloads containing %0d%0a (CR/LF) to see if they appear in response headers, indicating potential CRLF splitting.
  • SSRF‑style probes where the token is placed in a URL that the server might fetch (e.g., http://169.254.169.254/latest/meta-data/) and monitoring for outbound requests.

When middleBrick observes a response that matches an error pattern, returns unexpected data, or shows a timing shift, it flags the finding as an injection flaw with a severity rating and provides the exact payload that triggered the issue.

Running a scan from the CLI is straightforward:

npx middlebrick scan https://api.example.com/users

The output includes a breakdown per OWASP API Top 10 category, with the injection finding listed under “A3: Injection” and remediation guidance.

Bearer Tokens-Specific Remediation

The core principle is to never treat the Bearer token value as executable code or query syntax. Instead, validate its format, use parameterized APIs, and rely on trusted libraries for any cryptographic verification.

Fixing the SQL injection example:

const express = require('express');
const { Client } = require('pg');
const app = express();
const db = new Client({ connectionString: process.env.DATABASE_URL });

app.get('/profile', (req, res) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) return res.status(401).send();
  const token = auth.slice(7);

  // Validate token format – allow only alphanumerics, hyphen, underscore, dot
  if (!/^[A-Za-z0-9_.-]+$/.test(token)) {
    return res.status(400).send('Invalid token format');
  }

  // SAFE: parameterized query
  db.query('SELECT * FROM users WHERE api_token = $1', [token], (err, rows) => {
    if (err) return res.status(500).send(err.message);
    res.json(rows);
  });
});

app.listen(3000);

Similar mitigations apply to other injection vectors:

  • Command injection: avoid building shell strings with the token. Use an HTTP client library (e.g., axios) and pass the token as a header object, not concatenated into a command line.
  • LDAP injection: escape the token according to LDAP escaping rules or, better, avoid using the token in LDAP filters altogether.
  • Header injection: never insert raw token values into response headers. If you must echo the token (e.g., for debugging), ensure it is stripped of CR/LF characters or use a safe header‑setting API that automatically encodes values.
  • SSRF: validate any outbound URLs that incorporate the token; restrict destinations to an allowlist of internal services.

When the token is a JWT, rely on a well‑maintained library for verification:

const jwt = require('jsonwebtoken');

app.get('/protected', (req, res) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) return res.status(401).send();
  const token = auth.slice(7);

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
    // payload is now safe to use
    res.json({ user: payload.sub });
  } catch (err) {
    return res.status(401).send('Invalid token');
  }
});

By combining strict format validation, parameterized queries or safe APIs, and proper cryptographic verification, you eliminate the injection surface while still allowing legitimate Bearer Token authentication.

Frequently Asked Questions

Can middleBrick detect injection flaws in Bearer Tokens even if the endpoint expects a correctly signed JWT?
Yes. middleBrick’s active probes send malformed tokens (including valid‑looking strings with injection payloads) in the Authorization header. It analyzes the application’s responses for error messages, behavioral changes, or timing differences that indicate the payload was interpreted as code, regardless of whether the token passes signature verification.
What is the difference between token validation and injection prevention in the context
What is the difference between token validation and injection prevention in the context of Bearer Tokens?
Token validation ensures the token is correctly formatted, signed, and has not expired—it confirms the token’s authenticity. Injection prevention ensures the token’s raw value is never interpreted as code, SQL, shell commands, or header syntax. A token can pass validation yet still be dangerous if concatenated into a query or command; both checks are required for robust security.