HIGH log injectionbearer tokens

Log Injection with Bearer Tokens

How Log Injection Manifests in Bearer Tokens

Log injection in Bearer Tokens contexts occurs when unvalidated user input containing newline characters or control sequences is logged without sanitization. In Bearer token authentication systems, this often manifests in authorization middleware where tokens are logged for debugging or audit purposes.

The most common pattern involves newline injection through the Authorization header. When a malicious actor submits a token like:

Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJjb21tZW50IjoiSGVsbG8sIHdvdCBsb2cgZmlsZQ==.cGFzc3dvcmQ=

The base64 payload might contain newline characters that, when decoded and logged, break the log structure. This creates two primary attack vectors:

  • Log forging: Injecting fake log entries that appear legitimate to security teams
  • Log injection: Injecting malicious content that executes when logs are processed by log aggregation tools

Consider this vulnerable Express.js middleware:

const jwt = require('jsonwebtoken');

const authenticateJWT = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
// Vulnerable: token logged without sanitization
console.log(`Processing token: ${token}`);
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);// Unauthorized
}
req.user = user;
next();
});
} else {
res.sendStatus(401);// No token provided
}
};

A malicious token containing characters could inject arbitrary log content:

Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJjb21tZW50IjoiXG4jIEZha2UgTG9nIEludm9jYXRpb24gXG4jIFJlc3BvbnNlIFRpbWU6IDIwMjQtMDUtMjQgMDA6MDA6MDAgXG4jIENsaWVudCBJZDogMTIzNDU2XG4jIFJlcXVlc3QgVVJMIOiBodHRwOi8vd2Vic2VydmljZS5jb20vcHVibGljL3Rlc3QuanNwXG4jIFJlc3BvbnNlIFZlcnNpb246IDANCmVuYWJsZSBlcnJvcl9iYXNlNjRfZGVjb2RpbmcKXG4jIEVycm9yOiBObyBTZWN1cml0eSBTdGF0ZW1lbnQK

When logged, this creates fake entries that appear in log analysis tools, potentially masking real security events or triggering false alerts.

Bearer Tokens-Specific Detection

Detecting log injection in Bearer token systems requires examining both the token parsing logic and logging mechanisms. The vulnerability typically exists in middleware that processes Authorization headers without proper input validation.

Key detection patterns include:

  • Newline characters in Authorization headers: Tokens containing , , or … characters
  • Base64 padding abuse: Malicious tokens exploiting padding characters (=) to inject content
  • JSON Web Token manipulation: Tokens with crafted payloads that decode to malicious content

middleBrick scans for these patterns through black-box testing of your API endpoints. The scanner sends crafted Authorization headers containing various injection patterns and analyzes the resulting logs and responses.

Here's what middleBrick tests for:

Test PatternAttack VectorDetection Method
Newline injectionBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJjb21tZW50IjoiXG4=Response analysis, log structure validation
Base64 padding abuseBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJjb21tZW50Ijoi=Payload size analysis, character frequency
JSON manipulationBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJjb21tZW50Ijoi{

Manual detection involves auditing your authentication middleware:

# Check for vulnerable patterns in your auth middleware
grep -r "authorization\|authHeader" routes/ | grep -E "(console\.log|logger\.)"

Look for patterns where tokens are logged without sanitization. The vulnerability often appears in custom middleware or authentication libraries that log token contents for debugging.

middleBrick's API security scanner specifically tests for log injection by:

  1. Sending crafted Authorization headers with injection payloads
  2. Analyzing response times and error messages for injection indicators
  3. Checking if log entries appear malformed or contain injected content
  4. Verifying that token parsing doesn't crash or behave unexpectedly

The scanner runs these tests in under 15 seconds and provides a severity score with specific remediation guidance for Bearer token implementations.

Bearer Tokens-Specific Remediation

Remediating log injection in Bearer token systems requires a defense-in-depth approach. The primary strategies focus on input validation, secure logging practices, and proper token handling.

1. Input Validation and Sanitization

Always validate and sanitize Authorization headers before processing or logging:

const jwt = require('jsonwebtoken');

const sanitizeToken = (token) => {
if (!token) return null;
// Remove any non-base64 characters and control sequences
const sanitized = token.replace(/[^-]+/g, '')
.replace(/[ …

]/g, '');
return sanitized;
};

const authenticateJWT = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
const sanitizedToken = sanitizeToken(token);

// Secure logging: never log raw tokens
console.log(`Processing token: ${sanitizedToken ? sanitizedToken.substring(0, 10) + '...' : 'invalid'}`);

jwt.verify(sanitizedToken, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);// Unauthorized
}
req.user = user;
next();
});
} else {
res.sendStatus(401);// No token provided
}
};

2. Structured Logging

Use structured logging instead of string concatenation to prevent injection:

const logger = require('pino');

const authenticateJWT = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
// Log as structured data, not concatenated strings
logger.info({
auth_attempt: true,
token_length: token.length,
token_prefix: token.substring(0, 10)
});

jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
logger.warn({
auth_failure: true,
reason: err.message
});
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
logger.warn({auth_missing: true});
res.sendStatus(401);
}
};

3. Rate Limiting and Anomaly Detection

Implement rate limiting on authentication endpoints to prevent automated injection attempts:

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

const authRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // limit each IP to 10 requests per windowMs
message: 'Too many authentication attempts',
standardHeaders: true,
legacyHeaders: false
});

// Apply rate limiting to authentication routes
app.use('/api/auth', authRateLimiter);

4. Testing with middleBrick

Integrate middleBrick into your CI/CD pipeline to automatically scan for log injection vulnerabilities:

jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run middleBrick scan
run: middlebrick scan https://your-api.com/api/auth
continue-on-error: true
- name: Check security score
run: |
score=$(middlebrick report --format=json | jq '.overall_score')
if [ $score -lt 80 ]; then
echo

Frequently Asked Questions

How can I tell if my Bearer token authentication middleware is vulnerable to log injection?

Look for patterns where Authorization headers are logged without sanitization, especially using string concatenation. Check if your middleware logs the raw token value or uses vulnerable logging patterns like console.log(`Token: ${token}`). middleBrick can automatically detect these vulnerabilities by sending crafted injection payloads and analyzing the responses and log structure.

Does middleBrick scan for log injection vulnerabilities in Bearer token systems?

Yes, middleBrick specifically tests for log injection by sending Authorization headers containing newline characters, control sequences, and crafted payloads. The scanner analyzes how your API handles these inputs, checking for malformed log entries, unexpected behavior, or successful injection. middleBrick runs these tests in under 15 seconds and provides a security score with detailed remediation guidance.