轉(zhuǎn) http://www.cnitblog.com/yemoo/archive/2008/06/23/45937.html
一、概述
javascript函數(shù)劫持,也就是老外提到的javascript hijacking技術(shù)。最早還是和劍心同學(xué)討論問題時(shí)偶然看到的一段代碼,大概這樣寫的:
window.alert = function(s) {};
覺得這種用法很巧妙新穎,和API Hook異曲同工,索性稱之為javascript function hook,也就是函數(shù)劫持。通過替換js函數(shù)的實(shí)現(xiàn)來達(dá)到劫持這個(gè)函數(shù)調(diào)用的目的,一個(gè)完整的hook alert函數(shù)例子如下:
<!--1.htm-->
<script type="text/javascript">
<!--
var _alert = alert;
window.alert = function(s) {
if (confirm("是否要彈框框,內(nèi)容是\"" + s + "\"?")) {
_alert(s);
}
}
//-->
</script>
<html>
<body>
<input type="button" onclick="javascript: alert('Hello World!')" value="test" />
</body>
</html>
搞過API Hook的同學(xué)們看到這個(gè)代碼一定會(huì)心的一笑,先保存原函數(shù)實(shí)現(xiàn),然后替換為我們自己的函數(shù)實(shí)現(xiàn),添加我們自己的處理邏輯后最終再調(diào)用原來的函數(shù)實(shí)現(xiàn),這樣這個(gè)alert函數(shù)就被我們劫持了。原理非常簡(jiǎn)單,下面舉些典型的應(yīng)用來看看我們能利用它來做些什么。
二、應(yīng)用舉例
1. 實(shí)現(xiàn)一個(gè)簡(jiǎn)易的javascript debugger,這里說是debugger比較標(biāo)題黨,其實(shí)只是有點(diǎn)類似于debugger的功能,主要利用js函數(shù)劫持來實(shí)現(xiàn)函數(shù)的break point,來看看個(gè)簡(jiǎn)單的例子:
<script type="text/javascript">
<!--
var _eval = eval;
eval = function(s) {
if (confirm("eval被調(diào)用\n\n調(diào)用函數(shù)\n" + eval.caller + "\n\n調(diào)用參數(shù)\n" + s)) {
_eval(s);
}
}
//-->
</script>
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
function test() {
var a = "alert(1)";
eval(a);
}
function t() {
test();
}
t();
//-->
</script>
</body>
</html>
通過js函數(shù)劫持中斷函數(shù)執(zhí)行,并顯示參數(shù)和函數(shù)調(diào)用者代碼,來看一個(gè)完整例子的效果:
>help
debug commands:
bp <function name> - set a breakpoint on a function, e.g. "bp window.alert".
bl - list all breakpoints.
bc <breakpoint number> - remove a breakpoint by specified number, e.g. "bc 0".
help - help information.
>bp window.alert
* breakpoint on function "window.alert" added successfully.
>bl
* 1 breakpoints:
0 - window.alert
>bc 0
* breakpoint on function "window.alert" deleted successfully.
這里演示設(shè)置斷點(diǎn),察看斷點(diǎn)和刪除斷點(diǎn),完整代碼在本文附錄[1]給出。
2. 設(shè)置陷阱實(shí)時(shí)捕捉跨站測(cè)試者,搞跨站的人總習(xí)慣用alert來確認(rèn)是否存在跨站,如果你要監(jiān)控是否有人在測(cè)試你的網(wǎng)站xss的話,可以在你要監(jiān)控的頁面里hook alert函數(shù),記錄alert調(diào)用情況:
<script type="text/javascript">
<!--
function log(s) {
var img = new Image();
img.style.width = img.style.height = 0;
img.src = "http://yousite.com/log.php?caller=" + encodeURIComponent(s);
}
var _alert = alert;
window.alert = function(s) {
log(alert.caller);
_alert(s);
}
//-->
</script>
當(dāng)然,你這個(gè)函數(shù)要加到頁面的最開始,而且還要比較隱蔽一些,赫赫,你甚至可以使alert不彈框或者彈個(gè)警告框,讓測(cè)試者抓狂一把。
3.
實(shí)現(xiàn)DOM XSS自動(dòng)化掃描,目前一般的XSS自動(dòng)化掃描的方法是從http返回結(jié)果中搜索特征來確定是否存在漏洞,但是這種方法不適用于掃描DOM
XSS,因?yàn)镈OM XSS是由客戶端腳本造成的,比如前段時(shí)間劍心發(fā)現(xiàn)的google的跨站(見附錄[2])原理如下:
document.write(document.location.hash);
這
樣的跨站無法反映在http
response里,所以傳統(tǒng)掃描方法沒法掃描出來。但是如果你從上個(gè)例子里受到啟發(fā)的話,一定會(huì)想到設(shè)置陷阱的辦法,DOM
XSS最終導(dǎo)致alert被執(zhí)行,所以我們hook
alert函數(shù)設(shè)置陷阱,如果XSS成功則會(huì)去調(diào)用alert函數(shù),觸發(fā)我們的陷阱記錄結(jié)果,這樣就可以實(shí)現(xiàn)DOM
XSS的自動(dòng)化掃描,陷阱代碼類似于上面。
4. 靈活的使用js劫持輔助你的頁面代碼分析工作,比如分析網(wǎng)頁木馬時(shí),經(jīng)常會(huì)有通過eval或者document.write來進(jìn)行加密的情況,于是我們編寫段hook eval和document.write的小工具,輔助解密:
<script type="text/javascript">
<!--
var _eval = eval;
eval = window.execScript = window.document.write = window.document.writeln = function(s) {
document.getElementById("output").value = s;
}
//-->
</script>
<html>
<body>
input:
<textarea id="input" cols="80" rows="10"></textarea>
<input type="button" onclick="javascript: _eval(document.getElementById('input').value);" value="decode" />
<br />
output:
<textarea id="output" cols="80" rows="10"></textarea>
</body>
</html>
在input框里輸入加密的代碼:
eval(unescape("%61%6C%65%72%74%28%31%29%3B"));
在output框里輸出解碼后的代碼:
alert(1);
當(dāng)然你還能想到更多的靈活應(yīng)用:)
三、反劫持
談到劫持也就必然要談?wù)劮唇俪值脑掝},假設(shè)你要寫一個(gè)健壯的xss playload,就需要考慮反劫持,有兩個(gè)問題要解決:
如何判斷是否被劫持了?
如果發(fā)現(xiàn)被劫持了,如何反劫持?
1. 判斷某個(gè)函數(shù)是否被劫持,這個(gè)好辦,寫個(gè)小程序?qū)Ρ纫幌乱粋€(gè)函數(shù)被hook前后,有什么差別:
<textarea id="tb1" cols="80" rows="8"></textarea>
<script type="text/javascript">
<!--
document.getElementById("tb1").value = eval + "\n";
var _eval = eval;
eval = function(s) {
alert(s);
_eval(s);
}
document.getElementById("tb1").value += eval;
//-->
</script>
結(jié)果:
function eval() {
[native code]
}
function(s) {
alert(s);
_eval(s);
}
我們發(fā)現(xiàn)那些內(nèi)置函數(shù)是[native code],而自定義的則是具體的函數(shù)定義,用這個(gè)特征就可以簡(jiǎn)單的檢測(cè)函數(shù)是否被劫持:
function checkHook(proc) {
if (proc.toString().indexOf("[native code]") > 0) {
return false;
} else {
return true;
}
}
2.
如何反劫持,第一個(gè)想法就是恢復(fù)被劫持的函數(shù),如果劫持的人把原函數(shù)保存在某個(gè)變量里那還好辦,直接調(diào)用原函數(shù)就可以了,但是劫持者自己也沒保存副本怎么
辦,只能自己創(chuàng)建個(gè)新的環(huán)境,然后用新環(huán)境里的干凈的函數(shù)來恢復(fù)我們這里被hook了的,怎么創(chuàng)建新環(huán)境?整個(gè)新的iframe好了,里面就是個(gè)全新的環(huán)
境。ok,動(dòng)手吧:
function unHook(proc) {
var f = document.createElement("iframe");
f.style.border = "0";
f.style.width = "0";
f.style.height = "0";
document.body.appendChild(f);
var d = f.contentWindow.document;
d.write("<script type=\"text/javascript\">window.parent.escape = escape;<\/script>");
d.close();
}
綜合1、2節(jié),整個(gè)測(cè)試代碼如下:
<!--antihook.htm-->
<script type="text/javascript">
<!--
escape = function(s) {
return s;
}
//-->
</script>
<html>
<body>
<input type="button" onclick="javascript: test();" value="test" />
<script type="text/javascript">
<!--
function test() {
alert(escape("s y"));
if (checkHook(escape)) {
unHook(escape);
}
alert(escape("s y"));
}
function checkHook(proc) {
if (proc.toString().indexOf("[native code]") > 0) {
return false;
} else {
return true;
}
}
function unHook(proc) {
var f = document.createElement("iframe");
f.style.border = "0";
f.style.width = "0";
f.style.height = "0";
document.body.appendChild(f);
var d = f.contentWindow.document;
d.write("<script type=\"text/javascript\">window.parent.escape = escape;<\/script>");
d.close();
}
//-->
</script>
</body>
</html>
3.
不是上面兩個(gè)問題都解決了么,為什么要有第3節(jié)?因?yàn)槟遣皇莻€(gè)最好的解決辦法,既然我們可以創(chuàng)建全新的iframe,何不把代碼直接放到全新iframe
里執(zhí)行呢,這樣做的話綠色環(huán)保,既不用考慮當(dāng)前context里的hook問題,也不用改動(dòng)當(dāng)前context,不會(huì)影響本身的程序執(zhí)行。給出兩個(gè)比較通
用點(diǎn)的函數(shù):
function createIframe(w) {
var d = w.document;
var newIframe = d.createElement("iframe");
newIframe.style.width = 0;
newIframe.style.height = 0;
d.body.appendChild(newIframe);
newIframe.contentWindow.document.write("<html><body></body></html>");
return newIframe;
}
function injectScriptIntoIframe(f, proc) {
var d = f.contentWindow.document;
var s = "<script>\n(" + proc.toString() + ")();\n</script>";
d.write(s);
}
把你的payload封裝進(jìn)一個(gè)函數(shù),然后調(diào)用這兩個(gè)方法來在iframe里執(zhí)行:
function payload() {
// your code goes here
}
var f = createIframe(top);
injectScriptIntoIframe(f, payload);
四、最后
由于國內(nèi)很少有見文章提及這個(gè)東西,所以才草成這篇,希望能夠拋磚引玉。由于本人水平有限,難免有錯(cuò)誤或者疏漏之處請(qǐng)諒解,沒有說清楚的地方,歡迎和我交流。
還有就是一些不得不感謝的人,感謝劍心一直以來毫無保留的交流,感謝黑鍋多次鼓勵(lì)我把自己的心得體會(huì)寫成文字,感謝幻影所有的朋友們、B.C.T的朋友們以及群里那幫經(jīng)常一起扯淡的朋友們。
廣告一下,沒法幻影blog的朋友,可以添加hosts來突破:
72.14.219.190 pstgroup.blogspot.com
五、附錄
[1] 簡(jiǎn)易的javascript inline debugger代碼
<!--test.htm-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Javascript Inline Debugger</title></head>
<body>
<script language="javascript" type="text/javascript" src="js_inline_debugger.js"></script>
<input type="button" value="hahaha" onclick="javascript: alert(this.value);" style="margin-left: 300px;" />
</body>
</html>
/*
FileName: js_inline_debugger.js
Author: luoluo
Contact: luoluonet_at_yahoo.cn
Date: 2007-6-27
Version: 0.1
Usage:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script language="javascript" type="text/javascript" src="js_inline_debugger.js"></script>
</body>
</html>
Instruction:
It is a simple javascript inline debugger. You must add xhtml1-transitional dtd to your
html document if you wanna to use the script.
*/
//--------------------------------------------------------------------------//
// 公用的函數(shù)
//--------------------------------------------------------------------------//
// 判斷是否是IE
function isIE() {
return document.all && window.external;
}
// 去除字符串兩邊的空格
String.prototype.trim = function() {
var re = /(^\s*)|(\s*)$/g;
return this.replace(re, "");
}
// 刪除數(shù)組中某個(gè)元素
Array.prototype.remove = function(i) {
var o = this[i];
for (var j = i; j < this.length - 1; j ++) {
this[j] = this[j + 1];
}
-- this.length;
return o;
}
// 判斷一個(gè)數(shù)組中是否存在相同的元素
Array.prototype.search = function(o) {
for (var i = 0; i < this.length; i ++) {
if (this[i] == o) {
return i;
}
}
return -1;
}
// html編碼
function htmlEncode(s) {
s = s.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\"/g, """);
s = s.replace(/\'/g, """);
return s;
}
// js編碼
function jsEncode(s) {
s = s.replace(/\\/g, "\\\\");
s = s.replace(/\n/g, "\\n");
s = s.replace(/\"/g, "\\\"");
s = s.replace(/\'/g, "\\\'");
return s;
}
//--------------------------------------------------------------//
// 命令行窗口工具
//--------------------------------------------------------------//
function Console(parentNode, processInputProc) {
// 窗口
var panel = document.createElement("div");
panel.style.width = "250px";
panel.style.height = "250px";
panel.style.borderColor = "#666666";
panel.style.borderWidth = "1px";
panel.style.backgroundColor = "#ffffff";
panel.style.borderStyle = "solid";
panel.style.position = "absolute";
panel.style.zIndex = 100;
parentNode.appendChild(panel);
// 標(biāo)題欄
var title = document.createElement("div");
title.style.width = "250px";
title.style.height = "15px";
title.style.backgroundColor = "#dddddd";
title.style.fontSize = "12px";
title.style.fontFamily = "verdana,tahoma";
panel.appendChild(title);
// 標(biāo)題欄拖動(dòng)窗口功能
var isDragging = false;
var startPos = new Position(panel.offsetLeft, panel.offsetTop);
var startMousePos = new Position(0, 0);
title.onmouseover = function(evt) {
this.style.cursor = "pointer";
}
title.onmousedown = function(evt) {
if (isDragging == true) {
return;
}
var event = evt || window.event;
startMousePos.x = event.clientX;
startMousePos.y = event.clientY;
isDragging = true;
}
title.onmousemove = function(evt) {
if (isDragging == false) {
return;
}
activateWindow();
var event = evt || window.event;
panel.style.left = (event.clientX - startMousePos.x) + startPos.x + "px";
panel.style.top = (event.clientY - startMousePos.y) + startPos.y + "px";
}
title.onmouseup = function(evt) {
if (isDragging == false) {
return;
}
var event = evt || window.event;
startPos.x = (event.clientX - startMousePos.x) + startPos.x;
panel.style.left = startPos.x + "px";
startPos.y = (event.clientY - startMousePos.y) + startPos.y;
panel.style.top = startPos.y + "px";
isDragging = false;
}
// 關(guān)閉窗口功能
var closeButton = document.createElement("div");
closeButton.style.width = "13px";
closeButton.style.height = "13px";
closeButton.style.backgroundColor = "#ffffff";
closeButton.style.styleFloat = closeButton.style.cssFloat = "left";
closeButton.style.fontSize = "12px";
closeButton.style.borderWidth = "1px";
closeButton.style.borderColor = "#999999";
closeButton.style.borderStyle = "solid";
closeButton.style.paddingButton = "2px";
closeButton.innerHTML = "<div style=\"margin-top: -2px;margin-left: 3px;\">x</div>";
title.appendChild(closeButton);
var isVisible = true;
// 窗口關(guān)閉
closeButton.onclick = function(evt) {
isVisible = false;
panel.style.display = "none";
}
// 標(biāo)題欄文字
var titleLabel = document.createElement("div");
titleLabel.style.height = "14px";
titleLabel.style.width = "200px";
titleLabel.style.fontSize = "11px";
titleLabel.style.color = "#ffffff";
titleLabel.style.styleFloat = titleLabel.style.cssFloat = "left";
titleLabel.style.fontFamily = "verdana,tahoma";
titleLabel.innerHTML = "Javascript Inline Debugger";
//titleLabel.style.marginTop = isIE() ? -14 : "-14px";
titleLabel.style.marginLeft = isIE() ? 18 : "18px";
title.appendChild(titleLabel);
// 中間的顯示部分
var showPanel = document.createElement("div");
showPanel.style.width = "250px";
showPanel.style.height = isIE() ? "221px" : "219px";
showPanel.style.fontSize = "11px";
showPanel.style.padding = "0";
showPanel.style.margin = "0";
showPanel.style.overflow = "auto";
showPanel.style.marginTop = isIE() ? -1 : "0";
panel.appendChild(showPanel);
// 命令輸入框
var cmdArea = document.createElement("div");
panel.appendChild(cmdArea);
var cmdTextbox = document.createElement("input");
cmdTextbox.type = "text";
cmdTextbox.style.width = "250px";
cmdTextbox.style.height = "12px";
cmdTextbox.style.fontSize = "12px";
cmdTextbox.style.padding = "0";
cmdTextbox.style.margin = "0";
cmdTextbox.style.marginTop = isIE() ? -2 : "0";
cmdTextbox.style.borderWidth = "0";
cmdTextbox.style.borderTopWidth = "1px";
cmdTextbox.style.paddingTop = "2px";
cmdArea.appendChild(cmdTextbox);
// 窗口激活或者不激活
var isActive = false;
// 激活窗口
var activateWindow = function() {
if (! isVisible) {
return;
}
if (isActive) {
return;
}
cmdTextbox.focus();
title.style.backgroundColor = "#015DF4";
isActive = true;
}
panel.onclick = activateWindow;
// 不激活窗口
var deactivateWindow = function() {
if (! isVisible) {
return;
}
if (! isActive) {
return;
}
title.style.backgroundColor = "#cccccc";
isActive = false;
}
cmdTextbox.onfocus = activateWindow;
cmdTextbox.onblur = deactivateWindow;
// 輸出函數(shù)
var dbgPrint = function(s) {
showPanel.innerHTML += htmlEncode(s).replace(/\n|(\r\n)/g, "<br />");
if (parseInt(showPanel.scrollHeight) > parseInt(showPanel.style.height)) {
showPanel.scrollTop += parseInt(showPanel.scrollHeight) - parseInt(showPanel.style.height);
}
}
// 調(diào)用輸入處理回調(diào)函數(shù)
cmdTextbox.onkeydown = function(evt) {
var event = evt || window.event;
if (event.keyCode == 0x0d) {
processInputProc(this.value, dbgPrint);
this.value = "";
}
}
}
// 坐標(biāo)類
function Position(x, y) {
this.x = x;
this.y = y;
}
//--------------------------------------------------------------------------//
// 內(nèi)聯(lián)調(diào)試器類
//--------------------------------------------------------------------------//
function InlineDebugger() {
var bpList = new Array();
var id_eval;
// 設(shè)置斷點(diǎn)
var bp = function(funcName) {
// 檢查eval是否被hook
if ((new String(eval)).indexOf("[native code]") < 0) {
return "error: eval function was hooked by other codes in the front.\n";
}
// 保存未被hooked的eval
id_eval = eval;
var re = /^[a-zA-Z0-9_\.]+$/i;
if (! re.test(funcName)) {
return "error: bad argument of command bp \"" + funcName + "\".\n";
}
try {
id_eval("if (typeof(" + funcName + ") == \"object\" || typeof(" + funcName + ") == \"function\") {var obj = " + funcName + ";}");
} catch (e) {
return "error: " + e + ", invalid function name \"" + funcName + "\".\n";
}
if (obj == undefined) {
return "error: the argument of command bp \"" + funcName + "\" is not a function object.\n";
}
if ((new String(obj)).indexOf("function") < 0) {
return "error: the argument of command bp \"" + funcName + "\" is a property, a function is required.\n";
}
if (bpList.search(funcName) >= 0) {
return "error: there is a breakpoint on function \"" + funcName + "\"\n";
}
try {
var sc = "window." + funcName.replace(/\./g, "_") + "_bak = " + funcName + ";\n" +
funcName + " = " +
"function() {\n" +
" var args = \"\";\n" +
" for (var i = 0; i < arguments.length; i ++) {\n" +
" args += arguments[i] + (i == (arguments.length - 1) ? \"\" : \",\");\n" +
" }\n" +
" if (confirm(\"function \\\"" + funcName + "\\\" was called, execute it?\\n\\narguments:\\n\" + args + \"\\n\\ncaller:\\n\" + " + funcName + ".caller)) {\n" +
" id_eval(\"" + funcName.replace(/\./g, "_") + "_bak(\\\"\" + jsEncode(args) + \"\\\")\");\n" +
" }\n" +
"};" +
"\n";
id_eval(sc);
bpList.push(funcName);
return "* breakpoint on function \"" + funcName + "\" added successfully.\n";
} catch (e) {
return "unkown error: " + e + ".\n";
}
}
// 枚舉所有的斷點(diǎn)
var bl = function() {
if (bpList.length == 0) {
return "* no breakpoint.\n";
}
var bps = "* " + bpList.length + " breakpoints: \n";
for (var i = 0; i < bpList.length; i ++) {
bps += i + " - " + bpList[i] + "\n";
}
return bps;
}
// 清除某個(gè)斷點(diǎn)
var bc = function(n) {
try {
n = parseInt(n);
} catch (e) {
return "error: bc command requires a numeric argument.\n";
}
if (bpList.length == 0) {
return "error: no breakpoint.\n";
}
var funcName = bpList.remove(n);
try {
eval(funcName + " = window." + funcName.replace(/\./g, "_") + "_bak;");
return "* breakpoint on function \"" + funcName + "\" deleted successfully.\n";
} catch (e) {
return "error: " + e + ".\n";
}
}
// 幫助
var help = function() {
var s = "debug commands:\n\n" +
"bp <function name> - set a breakpoint on a function, e.g. \"bp window.alert\".\n" +
"bl - list all breakpoints.\n" +
"bc <breakpoint number> - remove a breakpoint by specified number, e.g. \"bc 0\".\n" +
"help - help information.\n"
"\n";
return s;
}
// 處理命令
this.exeCmd = function(cmd) {
cmd = cmd.trim();
var cmdParts = cmd.split(/\s+/g);
var cmdName;
var cmdArg;
if (cmdParts.length == 1) {
cmdName = cmd;
} else {
cmdName = cmdParts[0];
cmdArg = cmdParts[1];
}
switch (cmdName) {
case "bp":
if (cmdArg == undefined) {
return "error: bp command requires an argument.\n";
} else {
return bp(cmdArg);
}
break;
case "bl":
return bl();
break;
case "bc":
if (cmdArg == undefined) {
return "error: bc command requires an argument \"number of breakpoint\".\n";
} else {
return bc(cmdArg);
}
break;
case "help":
return help();
break;
default: return "error: command \"" + cmdName + "\" not found, you can get information by \"help\" command.\n";
break;
}
}
}
//-----------------------------------------------------------------------------//
// 主過程
//-----------------------------------------------------------------------------//
/*try {
debugger;
} catch (e) {}*/
var id = new InlineDebugger();
var console = new Console(document.body, function(s, printProc){printProc(id.exeCmd(s));});