註:以下文章非本人撰寫為中國大陸網路轉載文章,並經本人整理。
來源:Xfocus Team 浅谈javascript函数劫持
作者:hkluoluo http://www.ph4nt0m.org
##CONTINUE##
一、概述
javascript函數劫持,也就是老外提到的javascript hijacking技術。最早還是和劍心同學討論問題時偶然看到的一段代碼,大概這樣寫的:
window.alert = function(s) {};
覺得這種用法很巧妙新穎,和API Hook異曲同工,索性稱之為javascript function hook,也就是函數劫持。通過替換js函數的實現來達到劫持這個函式呼叫的目的,一個完整的hook alert函數例子如下:
<!--1.htm-->
<script type="text/javascript">
<!--
var _alert = alert;
window.alert = function(s) {
if (confirm("是否要彈框框,內容是\"" + s + "\"?")) {
_alert(s);
}
}
//-->
</script>
<html>
<body>
<input type="button" onclick="javascript: alert('Hello World!')" value="test" />
</body>
</html>
搞過API Hook的同學們看到這個代碼一定會心的一笑,先保存原函數實現,然後替換為我們自己的函數實現,添加我們自己的處理邏輯後最終再調用原來的函數實現,這樣這個alert函數就被我們劫持了。原理非常簡單,下面舉些典型的應用來看看我們能利用它來做些什麼。
二、應用舉例
1. 實現一個簡易的javascript debugger,這裡說是debugger比較標題党,其實只是有點類似於debugger的功能,主要利用js函數劫持來實現函數的break point,來看看個簡單的例子:
<script type="text/javascript">
<!--
var _eval = eval;
eval = function(s) {
if (confirm("eval被調用\n\n調用函數\n" + eval.caller + "\n\n調用參數\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函數劫持中斷函數執行,並顯示參數和函式呼叫者代碼,來看一個完整例子的效果:
>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.
這裡演示設置中斷點,察看中斷點和刪除中斷點,完整代碼在本文附錄[1]給出。
2. 設置陷阱即時捕捉跨站測試者,搞跨站的人總習慣用alert來確認是否存在跨站,如果你要監控是否有人在測試你的網站xss的話,可以在你要監控的頁面裡hook alert函數,記錄alert調用情況:
<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>
當然,你這個函數要加到頁面的最開始,而且還要比較隱蔽一些,赫赫,你甚至可以使alert不彈框或者彈個警告框,讓測試者抓狂一把。
3. 實現DOM XSS自動化掃描,目前一般的XSS自動化掃描的方法是從http返回結果中搜索特徵來確定是否存在漏洞,但是這種方法不適用於掃描DOM XSS,因為DOM XSS是由用戶端指令碼造成的,原理如下:
document.write(document.location.hash);
這樣的跨站無法反映在http response裡,所以傳統掃描方法沒法掃描出來。但是如果你從上個例子裡受到啟發的話,一定會想到設置陷阱的辦法,DOM XSS最終導致alert被執行,所以我們hook alert函數設置陷阱,如果XSS成功則會去調用alert函數,觸發我們的陷阱記錄結果,這樣就可以實現DOM XSS的自動化掃描,陷阱代碼類似於上面。
4. 靈活的使用js劫持輔助你的頁面代碼分析工作,比如分析網頁木馬時,經常會有通過eval或者document.write來進行加密的情況,於是我們編寫段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);
當然你還能想到更多的靈活應用:)
三、反劫持
談到劫持也就必然要談談反劫持的話題,假設你要寫一個健壯的xss playload,就需要考慮反劫持,有兩個問題要解決:
如何判斷是否被劫持了?
如果發現被劫持了,如何反劫持?
1. 判斷某個函數是否被劫持,這個好辦,寫個小程式對比一下一個函數被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>
結果:
function eval() {
[native code]
}
function(s) {
alert(s);
_eval(s);
}
我們發現那些內置函數是[native code],而自訂的則是具體的函式定義,用這個特徵就可以簡單的檢測函數是否被劫持:
function checkHook(proc) {
if (proc.toString().indexOf("[native code]") > 0) {
return false;
} else {
return true;
}
}
2. 如何反劫持,第一個想法就是恢復被劫持的函數,如果劫持的人把原函數保存在某個變數裡那還好辦,直接調用原函數就可以了,但是劫持者自己也沒保存副本怎麼辦,只能自己創建個新的環境,然後用新環境裡的乾淨的函數來恢復我們這裡被hook了的,怎麼創建新環境?整個新的iframe好了,裡面就是個全新的環境。ok,動手吧:
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節,整個測試代碼如下:
<!--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. 不是上面兩個問題都解決了麼,為什麼要有第3節?因為那不是個最好的解決辦法,既然我們可以創建全新的iframe,何不把代碼直接放到全新iframe裡執行呢,這樣做的話綠色環保,既不用考慮當前context裡的hook問題,也不用改動當前context,不會影響本身的程式執行。給出兩個比較通用點的函數:
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封裝進一個函數,然後調用這兩個方法來在iframe裡執行:
function payload() {
// your code goes here
}
var f = createIframe(top);
injectScriptIntoIframe(f, payload);
四、最後(註:以下是該文章原始作者的朋友與描述。)
由於國內很少有見文章提及這個東西,所以才草成這篇,希望能夠抛磚引玉。由於本人水準有限,難免有錯誤或者疏漏之處請諒解,沒有說清楚的地方,歡迎和我交流。還有就是一些不得不感謝的人,感謝劍心一直以來毫無保留的交流,感謝黑鍋多次鼓勵我把自己的心得體會寫成文字,感謝幻影所有的朋友們、B.C.T的朋友們以及群裡那幫經常一起扯淡的朋友們。
五、附錄[1]
簡易的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.
*/
//--------------------------------------------------------------------------//
// 公用的函數
//--------------------------------------------------------------------------//
// 判斷是否是IE
function isIE() {
return document.all && window.external;
}
// 去除字串兩邊的空格
String.prototype.trim = function() {
var re = /(^\s*)|(\s*)$/g;
return this.replace(re, "");
}
// 刪除陣列中某個元素
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;
}
// 判斷一個陣列中是否存在相同的元素
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);
// 標題列
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);
// 標題列拖動視窗功能
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;
}
// 關閉視窗功能
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;
// 窗口關閉
closeButton.onclick = function(evt) {
isVisible = false;
panel.style.display = "none";
}
// 標題列文字
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;
// 輸出函數
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);
}
}
// 調用輸入處理回呼函數
cmdTextbox.onkeydown = function(evt) {
var event = evt || window.event;
if (event.keyCode == 0x0d) {
processInputProc(this.value, dbgPrint);
this.value = "";
}
}
}
// 座標類
function Position(x, y) {
this.x = x;
this.y = y;
}
//--------------------------------------------------------------------------//
// 內聯調試器類
//--------------------------------------------------------------------------//
function InlineDebugger() {
var bpList = new Array();
var id_eval;
// 設置中斷點
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";
}
}
// 枚舉所有的中斷點
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;
}
// 清除某個中斷點
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));});