← Blog

Second-Order Injection Attacks in MCP Skills: When Safe Storage Creates Unsafe Context

First-order injection attacks are the ones developers learn first: a user submits malicious input, the application uses it directly in a dangerous context, the attack fires immediately. Second-order injection is subtler and significantly harder to catch in code review. The user submits data that is safely stored — often correctly parameterized into the database, properly escaped, cleanly validated at the boundary. The injection does not fire at registration time. It fires hours or days later, when the now-trusted stored value is retrieved from the database and used in a different context that was never sanitized to handle it: a SQL query that interpolates a stored username string, an HTML response served without a Content-Type header, an LDAP distinguished name built from a stored field, or a server-side template engine that renders a stored display name as template code at email generation time. The developer who wrote the retrieval code trusts the data because it came from their own database. That trust is the vulnerability.

By SkillAudit  |  9 Nov 2026
CVSS 9.8 — INJECTION7-001 second-order SQL privilege escalation  |  CVSS 8.8 — INJECTION7-004 stored template RCE at email time

Second-order injection is in some ways more dangerous than first-order injection because it systematically defeats the most common defensive reflex: "I parameterized the INSERT, so the data is safe." Parameterization protects the INSERT. It says nothing about every subsequent use of that stored value. The database faithfully stores admin'-- as a literal string — parameterization was designed to do exactly that — and then hands it back unmodified whenever the row is queried. Any downstream code that then uses that string in a concatenated SQL query, renders it as template code, or builds a protocol identifier from it without re-sanitizing has a vulnerability. The developer who wrote that downstream code has no visibility into what strings might arrive from the database; the developer who wrote the INSERT had no visibility into how the stored value would be used downstream. Second-order injection exploits the gap between these two visibility domains.

In MCP skill codebases, this pattern appears with particular frequency because skills typically have multiple execution paths: a registration or configuration path that accepts user data, an operational path that runs scheduled jobs or processes audits, and a notification path that sends emails or webhooks. These three paths are often written by the same developer at different times, with the implicit assumption that data flowing through them has been validated somewhere upstream. SA-SKL-INJECTION7 covers the four most common second-order injection patterns that SkillAudit's scanner detects in Claude skill repositories.

INJECTION7-001: Second-order SQL via stored username

Correctly parameterized INSERT stores admin'--. A subsequent UPDATE uses string concatenation with the stored username as a WHERE key, targeting a different user's row and changing their password.

INJECTION7-002: MIME-sniffed stored HTML

HTML is sanitized at storage time. The API endpoint serves the stored HTML as a plain text body but omits the Content-Type header. The browser MIME-sniffs the response as HTML and executes any embedded script tags.

INJECTION7-003: LDAP DN injection from stored username

A stored username containing LDAP special characters is used to construct a Distinguished Name for a directory lookup. The DN resolves to a different object in the directory tree, granting access as a different user or exposing admin group membership.

INJECTION7-004: Nunjucks stored template injection

A display name containing {{7*7}} is stored safely. The email generation path uses nunjucks.renderString() with the display name interpolated directly into the template string rather than passed as a variable. Template code executes at send time.

Why code review misses second-order injection: The INSERT looks correct — parameterized, no concatenation. The SELECT looks correct — it queries by ID. The UPDATE that uses the stored username looks like normal application logic. The email template looks like normal Nunjucks code. Only when you trace the full data flow from initial storage through every subsequent use does the vulnerability become visible. Static analysis tools that check query calls in isolation without tracing the origin of their string arguments will not flag it. SkillAudit's SA-SKL-INJECTION7 check specifically traces data from database retrieval sites into dangerous sinks in the same call graph.

Why MCP skills are especially vulnerable to second-order injection

Three architectural characteristics of MCP skill codebases make second-order injection unusually common:

Short registration-to-execution paths. A skill that accepts a webhook URL at configuration time and later uses that URL in a scheduled job has a two-step second-order injection path. The webhook URL is validated at registration (must be HTTPS, must respond to a probe request). The job worker trusts it implicitly on execution. If the job worker builds a SQL log entry using the URL string without parameterization, or passes it to an LDAP query as a DN component, the second-order attack fires on every job execution.

Multiple notification channels built after the main application. Email notifications, webhook deliveries, and Slack integrations are typically added to MCP skills after the core functionality. Developers building these channels retrieve stored user data — display names, email addresses, organization names — and use it in the notification context. Because the notification code was written after the core code, the developers often assume the data has been "processed" by the main application and is therefore clean. This assumption is incorrect: the stored display name that looks like Alice in the user interface looks like {{7*7}} in the database if the user chose to register with that display name.

Template engine adoption for HTML emails. MCP skills that generate HTML email notifications frequently adopt server-side template engines — Nunjucks, Handlebars, Pug, EJS — specifically because they make HTML generation easy. These engines all support some form of expression evaluation ({{ expr }}, <%- expr %>). When stored user data is interpolated into the template string rather than passed as a template variable, the template engine processes the user data as template code. This is the difference between nunjucks.renderString(template, { name: userName }) (safe, variable substitution) and nunjucks.renderString('Dear ' + userName + ',', {}) (vulnerable, template code in input).

INJECTION7-001 — Second-order SQL injection via stored username

The classic second-order SQL injection pattern. An MCP skill that allows users to set their own username or display name stores the value correctly using parameterized queries. A separate code path — a password reset flow, a profile update handler, an administrative action — later uses the stored username as a string key in a SQL query that is constructed by concatenation rather than parameterization.

The exploit: the attacker registers with the username admin'--. The INSERT is parameterized; the value is stored verbatim as the string admin'--. When the attacker later triggers a password reset for their own account, the application retrieves their username from the database and uses it in a string-concatenated UPDATE query. The resulting SQL becomes UPDATE users SET password='...' WHERE username='admin'--'. The -- comments out the rest of the WHERE clause. The UPDATE applies to the admin row rather than the attacker's row. The attacker has just set the admin account's password to a value they know, achieving full privilege escalation without ever exploiting the initial INSERT.

Wrong
// VULNERABLE — INJECTION7-001 (CVSS 9.8)
// Parameterized INSERT stores malicious username safely.
// String-concatenated UPDATE is exploitable via the stored value.
import { db } from './db.js';

// REGISTRATION — correctly parameterized
// Stores "admin'--" safely as a literal string
export async function registerUser(username: string, hashedPassword: string): Promise<void> {
  await db.run(
    'INSERT INTO users (username, password) VALUES (?, ?)',
    [username, hashedPassword]
  );
}

// PASSWORD RESET — VULNERABLE: retrieves stored username, concatenates into SQL
export async function resetPassword(userId: number, newHashedPassword: string): Promise<void> {
  // Fetches the row that was safely inserted — trusts the stored value
  const user = await db.get('SELECT username FROM users WHERE id = ?', [userId]);

  // VULNERABLE: concatenated SQL using the stored username as a WHERE key
  // If username = "admin'--", query becomes:
  //   UPDATE users SET password='...' WHERE username='admin'--'
  // The -- comments out the rest; targets the admin row instead
  await db.run(
    `UPDATE users SET password='${newHashedPassword}' WHERE username='${user.username}'`
  );
}
Fixed
// FIXED — INJECTION7-001
// Never use stored strings in concatenated SQL — parameterize EVERY query.
// Use the row's primary key (id) as the WHERE predicate, never a string field.
import { db } from './db.js';

export async function registerUser(username: string, hashedPassword: string): Promise<void> {
  await db.run(
    'INSERT INTO users (username, password) VALUES (?, ?)',
    [username, hashedPassword]
  );
}

export async function resetPassword(userId: number, newHashedPassword: string): Promise<void> {
  // FIX 1: Use the numeric primary key (unforgeable by the attacker) as WHERE predicate
  // FIX 2: Parameterize the new password too — defense-in-depth
  // This query is correct regardless of what the stored username contains
  await db.run(
    'UPDATE users SET password = ? WHERE id = ?',
    [newHashedPassword, userId]
  );

  // If a username WHERE clause is genuinely required (unusual), parameterize it:
  // await db.run('UPDATE users SET password = ? WHERE username = ?', [newPwd, storedName]);
  // But primary key is always preferable — it cannot be confused with another user's row.
}

See also: SA-SKL-INJECTION7 for the full detection rule and all four patterns in this vulnerability class. The second-order SQL injection pattern is classified CVSS 9.8 (Critical) because it achieves privilege escalation — full admin access — in a single POST request, without requiring any special permissions, via a username string that any user can register.

INJECTION7-002 — MIME-sniffed stored HTML XSS via missing Content-Type

This pattern exploits the browser's MIME-type sniffing behavior. The application correctly HTML-sanitizes user-submitted content at storage time — tags stripped, attributes allowlisted. The API endpoint that serves the stored content sets the HTTP body correctly but omits (or incorrectly sets) the Content-Type header. When the browser receives a response without a Content-Type: text/plain or Content-Type: application/json header, it examines the response body and infers a MIME type. If the body begins with <!DOCTYPE, <html, or any tag-like structure, Chrome, Firefox, and Safari will all interpret the response as HTML and render it on the page's origin — including executing any <script> tags that survive sanitization or that the sanitizer has a bug allowing through.

The second-order aspect: the attacker registers with a "bio" or "description" that contains a script payload. The sanitizer runs and stores what it believes is a safe version. Later, when any user visits a page that loads the stored bio from the API and injects it into the DOM via innerHTML, the MIME-sniffed response body executes. Even if the sanitizer is correct and all script tags are stripped, the missing Content-Type means the stored text is interpreted as HTML rather than plain text — which opens a second sanitizer bypass path: HTML attributes on otherwise-innocent tags.

Wrong
// VULNERABLE — INJECTION7-002 (HIGH)
// API endpoint serves stored HTML without Content-Type header.
// Browser MIME-sniffs the response as text/html and executes script tags.
import express from 'express';
import { db } from './db.js';

const router = express.Router();

router.get('/api/users/:id/bio', async (req, res) => {
  const user = await db.get('SELECT bio FROM users WHERE id = ?', [req.params.id]);
  if (!user) return res.status(404).end();

  // VULNERABLE: no Content-Type header set.
  // If bio contains <script>...</script>, Chrome MIME-sniffs as text/html
  // and executes the script tag on skillaudit.dev origin.
  res.send(user.bio);
  // Also vulnerable: res.set('Content-Type', 'text/html').send(user.bio)
  // — serving stored HTML as text/html is always XSS-able
});
Fixed
// FIXED — INJECTION7-002
// Set Content-Type explicitly. Add X-Content-Type-Options to block sniffing.
// Never serve raw HTML from user data — wrap it in JSON or encode it.
import express from 'express';
import { db } from './db.js';

const router = express.Router();

router.get('/api/users/:id/bio', async (req, res) => {
  const user = await db.get('SELECT bio FROM users WHERE id = ?', [req.params.id]);
  if (!user) return res.status(404).end();

  // FIX 1: Explicit JSON wrapper — Content-Type: application/json, not text/html
  // Browser will not render the body as HTML even if it contains script tags
  res.json({ bio: user.bio });

  // FIX 2 (if plain text is required): explicit text/plain + nosniff
  // res.set('Content-Type', 'text/plain; charset=utf-8');
  // res.set('X-Content-Type-Options', 'nosniff');   // blocks MIME sniffing in all browsers
  // res.send(user.bio);
});

INJECTION7-003 — LDAP distinguished name injection from stored username

MCP skills that integrate with enterprise directory services — LDAP, Active Directory, or LDAP-backed SSO providers — often construct LDAP queries or Distinguished Names by string interpolation from stored user fields. LDAP has its own special characters that must be escaped: commas, equals signs, plus signs, angle brackets, hash signs, semicolons, and backslashes all have meaning within a DN or filter string. A stored username of Alice,CN=admin,OU=admins causes the constructed DN CN=Alice,CN=admin,OU=admins,OU=users,DC=corp,DC=com to resolve to the admin object in the admins organizational unit rather than the expected user object — granting the attacker the directory access of the admin object.

The second-order aspect: the registration flow may validate that the username contains only alphanumeric characters. The LDAP DN construction happens on a different code path — when the user logs in, when they access a protected resource that checks group membership, or when an admin exports a directory listing. The validation at registration time protects against direct LDAP filter injection in registration but does not protect the downstream DN construction in paths that trust the stored value.

Wrong
// VULNERABLE — INJECTION7-003 (HIGH)
// LDAP DN constructed by string concatenation from stored username.
// LDAP special chars in stored username redirect to attacker-controlled directory object.
import ldap from 'ldapjs';
import { db } from './db.js';

const ldapClient = ldap.createClient({ url: 'ldap://corp.internal' });

export async function checkUserGroupMembership(userId: number): Promise<boolean> {
  const user = await db.get('SELECT username FROM users WHERE id = ?', [userId]);

  // VULNERABLE: DN constructed by string interpolation from stored username
  // If username = "alice,CN=Domain Admins,OU=groups" the DN resolves differently
  const userDN = `CN=${user.username},OU=users,DC=corp,DC=com`;

  return new Promise((resolve, reject) => {
    ldapClient.search(userDN, { scope: 'base', filter: '(objectClass=person)' }, (err, res) => {
      if (err) return resolve(false);
      res.on('searchEntry', () => resolve(true));
      res.on('error', () => resolve(false));
      res.on('end', () => resolve(false));
    });
  });
}
Fixed
// FIXED — INJECTION7-003
// Escape DN components using the ldapjs escape function before interpolation.
// Also escape filter values using ldap.escapeFilter().
import ldap from 'ldapjs';
import { db } from './db.js';

const ldapClient = ldap.createClient({ url: 'ldap://corp.internal' });

export async function checkUserGroupMembership(userId: number): Promise<boolean> {
  const user = await db.get('SELECT username FROM users WHERE id = ?', [userId]);

  // FIX: Escape the username before including it in the DN.
  // ldap.escapeDN() escapes: , = + < > # ; \ characters with backslash prefix
  const escapedDN = ldap.escapeDN(user.username);
  const userDN = `CN=${escapedDN},OU=users,DC=corp,DC=com`;

  // Also escape any user-derived values in filter strings:
  // const escapedFilter = ldap.escapeFilter(user.username);
  // const filter = `(sAMAccountName=${escapedFilter})`;

  return new Promise((resolve, reject) => {
    ldapClient.search(userDN, { scope: 'base', filter: '(objectClass=person)' }, (err, res) => {
      if (err) return resolve(false);
      let found = false;
      res.on('searchEntry', () => { found = true; });
      res.on('error', () => resolve(false));
      res.on('end', () => resolve(found));
    });
  });
}

See also: SA-SKL-INJECTION6 covers NoSQL operator injection patterns in MongoDB, Redis, and Elasticsearch. When a stored field that was inserted via a parameterized operation is later passed to a NoSQL query builder without schema validation, the $ne, $gt, and $where operators can be injected as object keys rather than string values, bypassing authentication and authorization checks.

INJECTION7-004 — Nunjucks stored template injection via display name at email send time

Server-side template injection via stored data is in some ways the most surprising second-order pattern, because the developer who writes the email generation code fully intends to use a template engine — the vulnerability is not "using a template engine wrong" but rather "interpolating untrusted data into the template source string rather than passing it as a template variable." Nunjucks, Handlebars, Pug, EJS, and Python's Jinja2 all share this distinction: there is a safe API (render a fixed template file or string with variables) and an unsafe API (render a dynamically constructed string that includes user data). The unsafe API is appealing because it looks like normal string interpolation that developers use everywhere.

The exploit: the attacker registers with the display name {{ range(1,1000000000) | list }} (Nunjucks/Jinja2 for creating a 1-billion-element list, causing out-of-memory). Or with {{ process.env.DATABASE_URL }}, exfiltrating the connection string into the email. The registration flow stores the display name as a plain string. The email generation path constructs a Nunjucks template string by concatenating the stored display name into it, then calls nunjucks.renderString(). The template engine processes the display name as template code, executing the expression at email send time — which may be triggered by any user action, a scheduled job, or an admin notification.

Wrong
// VULNERABLE — INJECTION7-004 (CVSS 8.8)
// Stored display name interpolated into Nunjucks template string.
// Nunjucks processes {{ }} expressions in the display name as template code.
import nunjucks from 'nunjucks';
import { db } from './db.js';
import { sendEmail } from './email.js';

export async function sendWelcomeEmail(userId: number): Promise<void> {
  const user = await db.get('SELECT email, display_name FROM users WHERE id = ?', [userId]);

  // VULNERABLE: display_name is concatenated into the template string.
  // If display_name = "{{ process.env.DATABASE_URL }}", Nunjucks evaluates it.
  // This executes at email send time — not at registration time.
  const template = `
    Dear ${user.display_name},

    Welcome to SkillAudit. Your account is now active.

    Best regards,
    The SkillAudit team
  `;

  // nunjucks.renderString() receives a template that contains the user-controlled expression.
  // The expression is executed in the Nunjucks sandbox (which is not a security sandbox).
  const body = nunjucks.renderString(template, {});
  await sendEmail(user.email, 'Welcome to SkillAudit', body);
}
Fixed
// FIXED — INJECTION7-004
// Pass user data as template VARIABLES, never concatenate into the template string.
// The template string is a fixed literal; Nunjucks substitutes {{ displayName }} safely.
import nunjucks from 'nunjucks';
import { db } from './db.js';
import { sendEmail } from './email.js';

// Fixed template string — does NOT include any user-supplied content
// User data is passed as a variable, so Nunjucks treats it as a string value,
// not as template code. {{ displayName }} outputs the string safely (HTML-escaped by default).
const WELCOME_TEMPLATE = `
  Dear {{ displayName }},

  Welcome to SkillAudit. Your account is now active.

  Best regards,
  The SkillAudit team
`;

export async function sendWelcomeEmail(userId: number): Promise<void> {
  const user = await db.get('SELECT email, display_name FROM users WHERE id = ?', [userId]);

  // FIX: Pass user.display_name as a variable — it is treated as a plain string
  // {{ displayName }} in the template renders the value, it does not execute it
  const body = nunjucks.renderString(WELCOME_TEMPLATE, {
    displayName: user.display_name   // safe: variable substitution, not code execution
  });
  await sendEmail(user.email, 'Welcome to SkillAudit', body);

  // Additional hardening: configure a Nunjucks Environment with autoescape: true (default)
  // const env = new nunjucks.Environment(null, { autoescape: true });
  // const body = env.renderString(WELCOME_TEMPLATE, { displayName: user.display_name });
}

See also: SA-SKL-NOSQL2 for MongoDB operator injection patterns that share the same second-order retrieval risk — when stored user data is spread into Mongoose queries or aggregation pipelines, MongoDB operators like $ne and $where in the stored fields execute as query operators rather than being treated as literal values.

Detection and prevention strategy

The common thread across all four patterns is data flow: input from an untrusted source passes through one or more storage and retrieval cycles before reaching a dangerous sink. Static analysis tools that trace data flows from source (database reads, in this case) to sink (SQL query builder, response send, LDAP client, template engine) can detect all four patterns without requiring any special treatment of the second-order aspect. The key insight is that database retrieval operations are themselves sources of untrusted data — the data stored in the database may have been sanitized for one context (the initial INSERT) but is arriving unsanitized for the current context (the downstream use).

Practical prevention at the application level:

PatternWrong approachCorrect approach
Second-order SQLUse stored string as WHERE predicate via concatenationAlways use primary key (integer) as WHERE predicate; parameterize every query regardless of data source
MIME-sniffed HTMLServe stored content without Content-Type headerExplicit Content-Type: text/plain or JSON wrapper + X-Content-Type-Options: nosniff
LDAP DN injectionInterpolate stored field into DN stringldap.escapeDN(storedField) before every DN component and ldap.escapeFilter() before every filter value
Template injectionConcatenate stored value into template source string before renderPass stored values as template variables — the template source is always a fixed literal

SkillAudit's SA-SKL-INJECTION7 rule performs taint tracking across database retrieval sites, following stored strings into SQL query builders, LDAP client calls, response writes without explicit Content-Type, and template engine render calls. It flags every path where a database-sourced string reaches one of these sinks without an intervening parameterization, escaping, or variable-substitution step. The rule is designed to find the second retrieval and use, not just the initial storage — which is where most vulnerability scanners stop looking.

The core mental model that prevents second-order injection: treat every database row as untrusted input. The database is a trust boundary, not a sanitization step. Data that enters the database from user input remains user input for the purpose of every downstream injection check, regardless of how safely it was stored. Every time a stored value crosses into a new execution context — a SQL query, an LDAP lookup, a template render, an HTTP response — apply the sanitization appropriate to that context from scratch.

← Previous
Path Traversal via Zip Slip in MCP Skill File Extraction
All posts →
View the full SkillAudit blog