MEDIUM log injectionexpresshmac signatures

Log Injection in Express with Hmac Signatures

Log Injection in Express with Hmac Signatures — how this specific combination creates or exposes the vulnerability

Log injection occurs when untrusted input is written directly into application logs without validation or sanitization. In Express applications that use Hmac signatures for request integrity or webhook verification, the interplay between signature validation, request data, and logging creates specific risks.

Consider an Express endpoint that validates an Hmac signature from a request header and then logs details from the request body or headers. If the logged data includes attacker-controlled values (e.g., a user-supplied message or userId) and those values are concatenated into the log line in an uncontrolled way, the log entry can be polluted with fabricated newlines or structured log delimiters. This is classic log injection: an attacker can inject additional log lines or metadata that may be interpreted as separate log events by log aggregation tools.

When Hmac signatures are used, a subtle exposure occurs if the signature or parts of the signed payload are logged without care. For example, logging the raw signature alongside request parameters can inadvertently disclose information used for integrity verification. More critically, if log entries are formatted with delimiters like newline characters and an attacker injects a newline via a parameter (e.g., message: "hello\nX-Api-Key: stolen"), the injected content can be parsed as a separate log entry. This may lead to log forging, where fabricated entries appear legitimate due to consistent formatting, complicating forensic analysis and potentially bypassing log-based monitoring rules.

In the context of OWASP API Top 10, log injection maps to security logging and monitoring gaps. Real attack patterns include attackers attempting to evade detection by inserting fake log entries that look benign or by hiding command-like strings inside injected data. Since middleBrick tests input validation and data exposure in parallel, it can surface cases where log-sensitive data (such as Hmac-related metadata) is written without sanitization. Note that middleBrick detects and reports these findings with severity and remediation guidance, but it does not fix or block the behavior.

Hmac Signatures-Specific Remediation in Express — concrete code fixes

To mitigate log injection when using Hmac signatures in Express, ensure that all data written to logs is sanitized and that structured logging uses safe serialization. Below are concrete, working code examples that demonstrate secure practices.

First, avoid logging raw user input or Hmac metadata directly. Instead, explicitly construct log payloads with controlled fields and escape or serialize values. Using a structured logger (like a JSON logger) reduces delimiter-based injection because each log entry is a single JSON string.

const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());

const SHARED_SECRET = process.env.HMAC_SECRET;
function verifyHmac(req, res, next) {
  const signature = req.headers['x-hmac-signature'];
  const payload = JSON.stringify(req.body);
  const expected = crypto.createHmac('sha256', SHARED_SECRET).update(payload).digest('hex');
  if (!signature || !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  next();
}

// Safe structured logging: serialize once, log sanitized JSON
app.post('/webhook', verifyHmac, (req, res) => {
  const logEntry = {
    level: 'info',
    message: 'webhook_received',
    method: req.method,
    path: req.path,
    // Do NOT include raw user input; include only business identifiers
    eventId: req.body.eventId || null,
    timestamp: new Date().toISOString()
  };
  console.log(JSON.stringify(logEntry));
  res.json({ received: true });
});

app.listen(3000);

If you must include potentially unsafe strings (e.g., for debugging), sanitize newlines and control characters. For example, replace newline characters with a safe placeholder before logging:

function sanitizeForLog(value) {
  if (typeof value !== 'string') return value;
  return value.replace(/[\r\n]+/g, ' ').trim();
}

app.post('/endpoint', verifyHmac, (req, res) => {
  const userMessage = sanitizeForLog(req.body.message);
  const logLine = `[${new Date().toISOString()}] message="${userMessage}" signature_present=${Boolean(req.headers['x-hmac-signature'])}`;
  console.log(logLine);
  res.sendStatus(200);
});

Additionally, ensure that any Hmac-related metadata (e.g., computed signature or nonce) is not written to logs. If your logging library supports structured formats, prefer JSON over plain text to avoid delimiter injection. middleBrick’s checks for input validation and data exposure can highlight places where Hmac-sensitive data might leak into logs, providing prioritized findings and remediation guidance.

Frequently Asked Questions

Can log injection via Hmac metadata lead to authentication bypass?
It can contribute to confusion in log-based monitoring but does not directly bypass Hmac verification. However, forged log entries may obscure real security events, reducing detection effectiveness.
Does middleBrick test for log injection in Express endpoints that use Hmac signatures?
Yes, middleBrick runs checks for input validation and data exposure in parallel and can detect scenarios where user-controlled data is written to logs without sanitization, including Hmac-related metadata.