Claude MCP skill second-order injection in stored data retrieval — SA-SKL-INJECTION7
Second-order injection attacks exploit a time gap between when user input is stored and when it is used. The input arrives safely — it passes validation, it is stored via parameterized queries, it is sanitized before writing to the database. The vulnerability surfaces later, in a completely separate code path, when that stored value is retrieved and used in a new context without being re-treated as untrusted. Because the data appears to come from "our database" rather than directly from the user, developers often forget to apply the same escaping and parameterization they would apply at the input boundary. SA-SKL-INJECTION7 covers the four second-order patterns found most frequently in MCP skill repositories.
Why "stored safely" does not mean "safe to use anywhere"
A common mental model in web development is: validate and sanitize at the input boundary, then trust the database. This model breaks down whenever the stored value is used in a context with a different escaping requirement. A string that is safe in SQL (properly parameterized) may be unsafe as an LDAP DN component (requires LDAP escaping), unsafe as a template variable (requires HTML or template escaping), and unsafe as a process environment value (requires shell escaping). Each injection sink requires escaping appropriate to that sink — and the fact that the data was safely stored is irrelevant to whether it is safely consumed. The correct mental model is: treat data from the database as untrusted in every new context, just as you would treat data from the HTTP request.
Content-Type: text/html; browser MIME-sniffs as script; stored XSS via content-type confusionCN=admin,OU=admins); LDAP query returns admin user record{{7*7}}; template rendered at email generation time (not at storage time); Jinja2 or Handlebars template engine executes stored payloadINJECTION7-001 — Stored input interpolated into second SQL query
The classic second-order SQL injection scenario: a user registers with a username of admin'--. The registration handler uses a parameterized INSERT, so the string is stored verbatim in the database without being interpreted as SQL. Later, a password reset handler retrieves the username from the database and builds a new SQL query by string interpolation: `SELECT id FROM users WHERE username = '${storedUsername}'`. Because storedUsername came from "the database" rather than "the request", the developer did not parameterize the second query. The stored injection payload admin'-- closes the string literal and comments out the remainder of the query, causing the WHERE clause to match the admin account rather than the attacker's account.
The fix is to parameterize every SQL query that includes a variable — regardless of whether the variable came from the HTTP request, the database, a cache, or a configuration file. The source of the value is irrelevant; what matters is whether the query is constructed by string concatenation with that value.
// VULNERABLE — parameterized INSERT; second query built by string interpolation
import pg from 'pg';
const pool = new pg.Pool();
// Step 1: safe registration (parameterized) — stores attacker username verbatim
async function registerUser(username: string, hashedPassword: string) {
// Parameterized — no SQL injection at insert time
await pool.query(
'INSERT INTO users (username, password_hash) VALUES ($1, $2)',
[username, hashedPassword]
);
}
// Step 2: vulnerable password reset — retrieves stored username, interpolates into new query
async function resetPassword(userId: string, newHashedPassword: string) {
// Retrieve username from DB — attacker's value: "admin'--"
const { rows } = await pool.query('SELECT username FROM users WHERE id = $1', [userId]);
const username = rows[0].username;
// VULNERABLE: storedUsername interpolated directly into SQL string
// attacker username "admin'--" turns this into:
// UPDATE users SET password_hash = '...' WHERE username = 'admin'--'
// Comment (--) drops the rest; updates admin's password, not attacker's
const result = await pool.query(
`UPDATE users SET password_hash = '${newHashedPassword}' WHERE username = '${username}'`
);
return result.rowCount;
}
// FIXED — parameterize every query; never interpolate DB-sourced values
import pg from 'pg';
const pool = new pg.Pool();
async function resetPassword(userId: string, newHashedPassword: string) {
// Parameterize using the user ID — no need to retrieve username at all
// The WHERE clause uses the authenticated userId, not any stored string value
const result = await pool.query(
'UPDATE users SET password_hash = $1 WHERE id = $2',
[newHashedPassword, userId]
);
return result.rowCount;
// General rule: never use a value from the DB as a SQL literal.
// If you must join on a retrieved value, parameterize it too:
// pool.query('SELECT * FROM orders WHERE customer_name = $1', [storedName])
}
INJECTION7-002 — Sanitized HTML served without Content-Type triggers MIME sniffing
An MCP skill stores user-generated HTML content (a rich-text note, a formatted description) after sanitizing it with DOMPurify or a similar library at save time. The sanitization correctly removes <script> tags and event handlers. Later, an API endpoint returns the stored HTML as a JSON field value. A second endpoint returns the same stored HTML directly as the response body — without setting a Content-Type header. When a browser fetches this endpoint and receives a response without an explicit content type, it performs MIME sniffing: it reads the response body and infers the content type from the content. If the response body starts with <!DOCTYPE html> or looks sufficiently like HTML, the browser renders it as HTML in the same origin as the application, executing any <script> tags that the sanitizer missed, any event handlers in allowed attributes, or any JavaScript-navigable content. The fix is to always set an explicit Content-Type header and always set X-Content-Type-Options: nosniff.
// VULNERABLE — stored HTML served without Content-Type; browser MIME-sniffs as HTML
import express from 'express';
const app = express();
app.get('/notes/:id/raw', async (req, res) => {
const note = await db.query('SELECT html_content FROM notes WHERE id = $1', [req.params.id]);
// VULNERABLE: no Content-Type header set
// Browser receives raw HTML starting with
// Browser MIME-sniffs and renders as text/html on skillaudit.dev origin
// Any <script> or event handler in the stored HTML executes in our origin
res.send(note.rows[0].html_content);
});
// FIXED — explicit Content-Type; X-Content-Type-Options: nosniff
import express from 'express';
const app = express();
// Global middleware — set nosniff on every response
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});
// Option A: serve as plain text — browser will not render as HTML
app.get('/notes/:id/raw', async (req, res) => {
const note = await db.query('SELECT html_content FROM notes WHERE id = $1', [req.params.id]);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.send(note.rows[0].html_content);
});
// Option B: serve via JSON API — HTML is a string inside a JSON object
// Browser treats the outer response as application/json, never renders as HTML
app.get('/notes/:id', async (req, res) => {
const note = await db.query('SELECT id, html_content FROM notes WHERE id = $1', [req.params.id]);
res.json({ id: note.rows[0].id, htmlContent: note.rows[0].html_content });
// Express automatically sets Content-Type: application/json
});
INJECTION7-003 — LDAP DN constructed from stored username with special characters
MCP skills that authenticate against an enterprise LDAP directory sometimes construct LDAP Distinguished Names or search filters by string concatenation using values stored in their own database — usernames, email addresses, or department names synced from LDAP on a previous login. If a user registered with a username that contains LDAP special characters (,, =, +, <, >, #, ;, \, /, or null bytes), those characters alter the structure of the LDAP query. An attacker who registers as Alice,CN=admin,OU=admins and then triggers an LDAP lookup using their stored username may cause the DN to reference the admin account rather than their own, returning admin group memberships or attributes to the attacker's session.
// VULNERABLE — LDAP DN built from stored username without escaping
import ldap from 'ldapjs';
const ldapClient = ldap.createClient({ url: 'ldap://internal-ldap:389' });
async function getUserGroups(storedUsername: string): Promise {
// storedUsername retrieved from DB: "Alice,CN=admin,OU=admins"
// VULNERABLE: special chars alter the DN structure
// The search now looks up: CN=Alice,CN=admin,OU=admins,DC=corp,DC=internal
// which is the admin DN, not Alice's actual DN
const dn = `CN=${storedUsername},OU=users,DC=corp,DC=internal`;
return new Promise((resolve, reject) => {
ldapClient.search(dn, { scope: 'sub', filter: '(objectClass=group)' }, (err, res) => {
const groups: string[] = [];
res.on('searchEntry', (entry) => groups.push(entry.dn.toString()));
res.on('end', () => resolve(groups));
res.on('error', reject);
});
});
}
// FIXED — ldap-escape library escapes special chars in DN components
import ldap from 'ldapjs';
import { escapeDN, escapeFilter } from 'ldap-escape';
const ldapClient = ldap.createClient({ url: 'ldap://internal-ldap:389' });
async function getUserGroups(storedUsername: string): Promise {
// escapeDN escapes: , = + < > # ; \ / and null bytes in DN components
// "Alice,CN=admin,OU=admins" → "Alice\2CCN\3Dadmin\2COU\3Dadmins"
// The resulting DN refers to a single CN component, not a multi-RDN path
const escapedCn = escapeDN(storedUsername);
const dn = `CN=${escapedCn},OU=users,DC=corp,DC=internal`;
// Also escape the filter value separately if used in a search filter
const escapedFilter = escapeFilter(storedUsername);
const filter = `(&(objectClass=person)(cn=${escapedFilter}))`;
return new Promise((resolve, reject) => {
ldapClient.search(dn, { scope: 'sub', filter }, (err, res) => {
if (err) return reject(err);
const groups: string[] = [];
res.on('searchEntry', (entry) => groups.push(entry.dn.toString()));
res.on('end', () => resolve(groups));
res.on('error', reject);
});
});
}
INJECTION7-004 — Second-order template injection in email generation
Template injection vulnerabilities arise when user-controlled data is passed to a template engine as a template string rather than as a template variable. The second-order variant occurs when the payload is stored in the database at registration time and later used as template content (not template data) during email rendering. An attacker registers with a display name of {{7*7}} (Jinja2/Nunjucks) or {{constructor.constructor('return process.env')()}} (Handlebars with prototype access). When the email generation service retrieves this display name and renders it as part of a template string — template.render(`Dear ${displayName},\n...`) — the template engine evaluates the payload. In Nunjucks and Jinja2, this allows reading server-side environment variables. In Handlebars without prototype property access restrictions, it can achieve remote code execution.
// VULNERABLE — stored display name used as template content (not data)
import nunjucks from 'nunjucks';
async function sendWelcomeEmail(userId: string) {
const user = await db.query('SELECT display_name, email FROM users WHERE id = $1', [userId]);
const { display_name, email } = user.rows[0];
// VULNERABLE: display_name interpolated into the template STRING before rendering
// If display_name = "{{7*7}}" or "{{range.constructor("return process.env")()}}"
// Nunjucks evaluates the payload — arbitrary server-side template execution
const templateStr = `Dear ${display_name},\n\nWelcome to SkillAudit!\nYour email: ${email}`;
const rendered = nunjucks.renderString(templateStr, {});
await sendEmail({ to: email, subject: 'Welcome', body: rendered });
}
// FIXED — pass display_name as a template variable (data), not into the template string
import nunjucks from 'nunjucks';
// Template is a static string — no user data interpolated into it
// display_name and email are passed as variables to the template engine
const WELCOME_TEMPLATE = `Dear {{ displayName }},
Welcome to SkillAudit!
Your email: {{ email }}
Get started at https://skillaudit.dev/#waitlist`;
async function sendWelcomeEmail(userId: string) {
const user = await db.query('SELECT display_name, email FROM users WHERE id = $1', [userId]);
const { display_name, email } = user.rows[0];
// Template string is static — defined above, no user input interpolated into it
// User data passed as variables: Nunjucks HTML-escapes variables by default
// {{ displayName }} renders "{{7*7}}" as the literal string "{{7*7}}", not as 49
const rendered = nunjucks.renderString(WELCOME_TEMPLATE, {
displayName: display_name,
email: email,
});
await sendEmail({ to: email, subject: 'Welcome to SkillAudit', body: rendered });
}
// For Handlebars specifically: also set runtimeOptions.allowProtoPropertiesByDefault = false
// to prevent prototype chain traversal via {{constructor.constructor(...)()}} payloads
import Handlebars from 'handlebars';
const hbs = Handlebars.create();
// Compile template once from static string — not from user-supplied content
const welcomeTemplate = hbs.compile(WELCOME_TEMPLATE);
function renderEmail(data: { displayName: string; email: string }) {
return welcomeTemplate(data, {
allowCallsToHelperMissing: false,
});
}
Detection with SkillAudit
SkillAudit's SA-SKL-INJECTION7 rule set detects second-order injection through cross-function data-flow analysis that tracks values from database read operations through to injection sinks. The SQL check identifies DB query results used in string concatenation that feeds a subsequent SQL query call. The Content-Type check identifies response send calls where the body contains HTML tags but no setHeader('Content-Type') call precedes the send in the same route handler. The LDAP check identifies ldapClient.search calls where the DN or filter string contains a variable sourced from a database query without an intervening escapeDN or escapeFilter call. The template injection check identifies renderString, render, or compile calls where user-sourced data is interpolated into the template string argument using template literals rather than passed as the data context. See also SA-SKL-INJECTION6 for NoSQL and Redis injection patterns.
Run SA-SKL-INJECTION7 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
INJECTION7-001 | Critical | Stored username interpolated into second SQL query without parameterization; second-order SQL injection overwrites admin password | Parameterize every SQL query including those using DB-sourced values; use user ID as WHERE key, not stored strings |
INJECTION7-002 | High | HTML sanitized at storage; served without Content-Type; browser MIME-sniffs as HTML; stored XSS on origin | Always set Content-Type: text/plain or return via JSON; global X-Content-Type-Options: nosniff middleware |
INJECTION7-003 | High | LDAP DN built from stored username; ,CN=admin in username redirects DN to admin object | escapeDN(storedUsername) and escapeFilter(storedUsername) before use in LDAP queries |
INJECTION7-004 | High | Template rendered with renderString(\`Dear ${displayName},...); stored {{7*7}} payload executes at email time | Pass user data as template variables, not into template string; static template string with {{ displayName }} placeholder |