Claude skill log injection security — SA-SKL-LOGINJECT
Logs feel safe — they are write-only append files far from the sensitive database. In practice, log files are read by engineers, forwarded to SIEMs, stored in cloud log sinks with broad IAM bindings, and retained indefinitely. When an MCP skill writes console.log(req.body) before an auth check, every password ever submitted lands in that append log. LOGINJECT-001 through LOGINJECT-004 cover the four patterns SkillAudit finds most often: credentials in request body logs, JWT tokens in access log URLs, PII without a GDPR retention policy, and CRLF newlines that forge SIEM events.
Why MCP skill logs are a high-value attack target
An MCP skill's database is typically protected by VPC rules, IAM policies, and an application-layer auth check. The same skill's log files are often forwarded to a centralized log platform (Datadog, CloudWatch, GCP Logging, Elastic) where the access control model is much flatter — any engineer in the organization can read them, and many retention periods are measured in years rather than days. Credentials, tokens, and personal data written to logs therefore have a much larger effective attack surface than the same data at rest in the database. Beyond confidentiality, logs that accept user-controlled input without sanitization can be injected with forged log lines, allowing an attacker to spoof administrator actions, inject malicious content into log-analysis pipelines, or trigger false-positive SIEM alerts that mask real incidents.
SA-SKL-LOGINJECT in scope: LOGINJECT-001 (credentials in request body log), LOGINJECT-002 (JWT access token in URL access log), LOGINJECT-003 (PII logged without GDPR retention TTL), LOGINJECT-004 (CRLF log injection via user-controlled field). Each includes SkillAudit detection rules, ESLint ban patterns, and redaction helpers ready to drop into an Express MCP skill.
LOGINJECT-001 — Credentials logged in request body
Debug logging during development is routine: a developer adds logger.debug('POST /auth body:', JSON.stringify(req.body)) or simply console.log(req.body) above the validation logic so they can see incoming payloads. When req.body is { email: 'alice@example.com', password: 'hunter2' }, the plaintext password is serialized to JSON and written to stdout, which is captured by the container runtime and forwarded to whatever log sink the deployment uses. That log entry persists for as long as the log retention policy allows — often months. Anyone with read access to the log sink, which in practice includes the entire engineering team and any log-forwarding integration, can retrieve every plaintext password ever submitted to the endpoint. The fix is a redactBody() helper that creates a shallow copy of req.body with known-sensitive field names replaced with the string '[REDACTED]' before any log call.
// VULNERABLE: plaintext password written to stdout on every login attempt
const express = require('express');
const logger = require('pino')();
app.post('/api/auth/login', (req, res, next) => {
// VULNERABLE: req.body includes { email, password } — both written to log
logger.debug({ body: req.body }, 'POST /api/auth/login body');
// Also common:
// console.log('login attempt', JSON.stringify(req.body));
// logger.info('POST /auth body:', req.body);
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ error: 'Missing fields' });
// ... validate credentials ...
});
// FIXED: redactBody() scrubs sensitive fields before any log call
const SENSITIVE_FIELDS = new Set([
'password', 'passwd', 'pass', 'secret', 'token',
'apiKey', 'api_key', 'accessToken', 'access_token',
'refreshToken', 'refresh_token', 'card', 'cvv', 'ssn',
'creditCard', 'credit_card',
]);
function redactBody(body) {
if (!body || typeof body !== 'object') return body;
const safe = { ...body };
for (const key of Object.keys(safe)) {
if (SENSITIVE_FIELDS.has(key)) {
safe[key] = '[REDACTED]';
}
}
return safe;
}
app.post('/api/auth/login', (req, res, next) => {
// Safe: only the redacted copy is logged — password field replaced with '[REDACTED]'
logger.debug({ body: redactBody(req.body) }, 'POST /api/auth/login');
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ error: 'Missing fields' });
// ... validate credentials ...
});
// Add ESLint rule to catch raw body logging:
// "no-restricted-syntax": ["error", {
// "selector": "CallExpression[callee.property.name=/log|debug|info|warn|error/][arguments]",
// "message": "Do not log req.body directly — use redactBody(req.body)"
// }]
req.body directly via console.log, logger.*, or JSON.stringify(req.body) before or during authentication; plaintext passwords, API keys, and card numbers are written to stdout and forwarded to log sinks with broad read access; anyone with log access can harvest credentials. Fix: introduce a redactBody() helper that replaces known-sensitive field names with '[REDACTED]'; add an ESLint rule that bans unguarded req.body in log calls; never log raw request bodies on auth or payment endpoints. Detection: SkillAudit flags console.log(req.body), logger.*(JSON.stringify(req.body)), and logger.*({ body: req.body }) patterns on routes with password, token, or secret in the request schema.LOGINJECT-002 — JWT access token in logged URL
Some API clients — including several Claude skill SDKs and legacy frontend integrations — pass the bearer token as a query parameter rather than an Authorization header: GET /api/audits?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.... This is explicitly discouraged by RFC 6750 (section 2.3) but remains common because it makes curl testing easier. Express's morgan access log format includes the full request URL including query string by default: GET /api/audits?access_token=eyJ... 200 142ms. Caddy's structured access log includes uri in its default JSON format. The JWT appears in plaintext in every access log line for that request. Access logs are forwarded to log aggregators, retained far longer than session TTLs, and are often less tightly scoped than application logs. A single log file can contain thousands of valid, unexpired JWTs. The correct fix is to reject query-parameter tokens at the API boundary and scrub those fields from the access log format as a defence-in-depth measure.
// VULNERABLE: access_token in query param logs the JWT in every access log line
// Morgan log output: GET /api/audits?access_token=eyJhbGciOiJIUzI1NiJ9.eyJ1c2... 200 48ms
// Caddy log output: {"uri":"/api/audits?access_token=eyJhbGciOiJIUzI1NiJ9.eyJ1c2..."}
// auth middleware that accepts token in query string
function requireAuth(req, res, next) {
// VULNERABLE: token read from query string — will appear in access logs
const token =
(req.headers.authorization || '').replace('Bearer ', '') ||
req.query.access_token; // accepts token in URL — VULNERABLE
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
// FIXED: reject tokens in query parameters; scrub from access log format
// 1. Auth middleware: header-only token acceptance
function requireAuth(req, res, next) {
const authHeader = req.headers.authorization || '';
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
if (!token) {
// If client sent access_token in query param, explain migration path
if (req.query.access_token) {
return res.status(400).json({
error: 'access_token query parameter is not supported — use Authorization: Bearer ',
});
}
return res.status(401).json({ error: 'Unauthorized' });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
// 2. Scrub sensitive query params from morgan access log format
function scrubUrl(url) {
const SCRUB_PARAMS = ['access_token', 'token', 'api_key', 'apikey', 'secret'];
try {
const u = new URL(url, 'http://x');
for (const param of SCRUB_PARAMS) {
if (u.searchParams.has(param)) u.searchParams.set(param, '[REDACTED]');
}
return u.pathname + (u.search !== '?' ? u.search : '');
} catch {
return url;
}
}
morgan.token('scrubbed-url', (req) => scrubUrl(req.originalUrl));
app.use(morgan(':method :scrubbed-url :status :response-time ms'));
// 3. Caddy: filter access_token from uri in access log
// Caddyfile fragment:
// log {
// format filter {
// wrap json
// fields {
// uri query_string_redact access_token
// }
// }
// }
?access_token= or ?token=); Express, Caddy, and nginx access log formats include the full URI by default; valid JWTs appear verbatim in access logs and are retained far beyond the token's expiry TTL; an attacker with log-read access can replay unexpired tokens. Fix: reject query-parameter tokens with 400 Bad Request; scrub access_token, token, and api_key query params from access log format using a URL-scrub helper or Caddy log filter; require all tokens in the Authorization header per RFC 6750. Detection: SkillAudit flags auth middleware that reads from req.query.access_token, req.query.token, or any query parameter that is passed to jwt.verify().LOGINJECT-003 — PII logged without GDPR retention policy
MCP skills that log the full request context for debugging commonly emit a structured log object on every request: { requestId, userId, email, ipAddress, userAgent, route, durationMs }. Email addresses and IP addresses are personal data under GDPR and equivalent regulations. Without a declared retention TTL and an automated deletion mechanism, these logs accumulate indefinitely and become a compliance liability in three scenarios: a data subject access request (DSAR) requires producing all records referencing a user's email or IP address; a right-to-erasure request requires deleting those records from every location they were stored, including log sinks; a data breach notification assessment must account for every system where personal data was retained. Debug logs retained for years fail all three scenarios. The fix is pseudonymization at the point of emission — not retention-on-ingest — combined with an explicit log TTL policy.
// VULNERABLE: PII logged on every request with no declared retention TTL
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
// VULNERABLE: email and IP address are GDPR personal data
// These log lines accumulate indefinitely in cloud log sinks
logger.info({
requestId: req.id,
userId: req.user?.id,
email: req.user?.email, // VULNERABLE: personal data, no TTL
ipAddress: req.ip, // VULNERABLE: personal data, no TTL
userAgent: req.headers['user-agent'],
route: req.route?.path,
status: res.statusCode,
durationMs: Date.now() - start,
}, 'request completed');
});
next();
});
// FIXED: pseudonymize PII fields before logging; document retention TTL
const crypto = require('crypto');
// Pseudonymize IP: mask last octet for IPv4, last 80 bits for IPv6
function maskIp(ip) {
if (!ip) return null;
if (ip.includes(':')) {
// IPv6: keep first 48 bits (3 groups), zero the rest
const parts = ip.split(':');
return parts.slice(0, 3).join(':') + ':0:0:0:0:0';
}
// IPv4: replace last octet with 0
return ip.replace(/\.\d+$/, '.0');
}
// Hash email to a stable pseudonymous identifier (non-reversible without salt)
// Use a consistent per-deployment salt stored in env — allows correlation within
// a deployment but prevents cross-deployment linkage
function pseudonymizeEmail(email) {
if (!email) return null;
const salt = process.env.LOG_PSEUDONYM_SALT || 'default-change-me';
return crypto.createHmac('sha256', salt).update(email.toLowerCase()).digest('hex').slice(0, 16);
}
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
logger.info({
requestId: req.id,
userId: req.user?.id, // internal ID — not personal data
emailHash: pseudonymizeEmail(req.user?.email), // pseudonymized
ipMasked: maskIp(req.ip), // pseudonymized
route: req.route?.path,
status: res.statusCode,
durationMs: Date.now() - start,
// Note: userAgent omitted — it can be personal data under some interpretations
}, 'request completed');
// Log retention: set TTL to 30 days max on the log sink (CloudWatch, GCP Logging, Datadog)
// Document in privacy policy: "Request logs retained for 30 days, pseudonymized"
});
next();
});
email, ipAddress, or other GDPR personal data on every request without pseudonymization and without a declared log retention TTL; logs become a compliance liability for DSARs, right-to-erasure requests, and breach notification scope assessments; indefinite retention fails GDPR data minimization principles. Fix: pseudonymize IP address (mask last octet) and email (HMAC-SHA256 with per-deployment salt) at the point of emission; set log TTL to 30 days or less on the cloud log sink; document retention period in privacy policy. Detection: SkillAudit flags log statements that emit email, ipAddress, ip, or phoneNumber fields in request middleware without a pseudonymization wrapper.LOGINJECT-004 — Log injection via CRLF in user-controlled field
When a skill interpolates user-controlled input directly into a log line — a username, a filename, an error message from a third-party API — an attacker can embed newline characters (\n, \r\n) in that value to inject additional log lines. The injected lines appear as legitimate system log entries to log-analysis tools, SIEMs, and human readers. A simple example: the skill logs logger.info(`User ${req.body.username} logged in`). If the attacker submits username = "alice\n[WARN] admin logged in with elevated privileges from IP 203.0.113.1", the log sink receives two lines. The second line is indistinguishable from a real log entry. If the SIEM has an alert rule for [WARN] admin logged in, it fires on the injected line. If a security engineer reviews the log, they see a false admin login event. The defence is a structured logger that JSON-encodes all field values, making \n harmless because it is serialized as \\n within a JSON string.
// VULNERABLE: user-controlled username interpolated directly into log string
app.post('/api/auth/login', async (req, res) => {
const { username, password } = req.body;
// VULNERABLE: if username = "alice\n[WARN] admin logged in with elevated privileges"
// the log file receives two separate lines — the second is a spoofed WARN entry
console.log(`User ${username} attempted login`);
// Also vulnerable with winston text transport:
// logger.info('User ' + username + ' logged in');
const user = await db.users.findByUsername(username);
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
console.log(`Failed login for ${username}`); // VULNERABLE
return res.status(401).json({ error: 'Invalid credentials' });
}
logger.info(`User ${username} logged in successfully`); // VULNERABLE
res.json({ token: issueJwt(user) });
});
// FIXED: use structured logger (pino) — field values are JSON-encoded, newlines are escaped
const pino = require('pino');
const logger = pino({ level: 'info' });
// pino serializes all object fields as JSON — newlines in strings become \\n, never raw \n
// { "msg": "login attempt", "username": "alice\\n[WARN] admin logged in..." }
// The injected content is visible as data, not as a spoofed log line
// Sanitize function as defence-in-depth for text-format transports
function sanitizeLogField(value) {
if (typeof value !== 'string') return value;
// Replace CR, LF, and other control characters with a safe placeholder
// U+FFFD (replacement character) is visually distinct from normal text
return value.replace(/[\r\n\t\x00-\x1f\x7f]/g, '�');
}
app.post('/api/auth/login', async (req, res) => {
const { username, password } = req.body;
// Safe: pino JSON-encodes username — CRLF injection is impossible
logger.info({ username: sanitizeLogField(username) }, 'login attempt');
const user = await db.users.findByUsername(username);
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
// Safe: structured field, not string interpolation
logger.warn({ username: sanitizeLogField(username) }, 'failed login');
return res.status(401).json({ error: 'Invalid credentials' });
}
logger.info({ userId: user.id }, 'login success');
// Note: do NOT log username on success — log userId (internal, non-personal)
res.json({ token: issueJwt(user) });
});
\r\n to inject additional log lines that appear as legitimate system events; spoofed entries trigger SIEM alert rules and mislead incident responders. Fix: use a structured logger (pino, winston JSON transport) that serializes all field values as JSON — newlines in strings are escaped as \\n and cannot create new log lines; additionally strip control characters with a sanitizeLogField() helper as defence-in-depth for any text-format transports. Detection: SkillAudit flags template literal or string concatenation log calls where one or more interpolated values derives from req.body, req.query, req.params, or any other external-data source.SkillAudit detection summary — SA-SKL-LOGINJECT
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| LOGINJECT-001 | HIGH | console.log(req.body), logger.*(JSON.stringify(req.body)), logger.*({ body: req.body }) on auth or payment routes | redactBody() helper replacing sensitive fields with '[REDACTED]' |
| LOGINJECT-002 | HIGH | Auth middleware reading req.query.access_token, req.query.token, or passing any query param to jwt.verify() | Reject query-param tokens with 400; scrub params from access log format |
| LOGINJECT-003 | MEDIUM | Log statements emitting email, ipAddress, or ip fields in request middleware without pseudonymization | Mask last IP octet; HMAC-SHA256 email; set 30-day log TTL |
| LOGINJECT-004 | HIGH | Template literal or string concatenation log calls with values from req.body, req.query, or req.params | Structured logger (pino JSON); sanitizeLogField() strips control characters |
Related patterns: For secrets and API keys exposed in error response bodies, see SA-SKL-SECRETEXPOSE. For information disclosure via stack traces and verbose error responses, see SA-SKL-INFODISCLOSURE. For escape sequence injection in terminal output, see SA-SKL-ESCAPE.