浅谈javascript函数劫持

by luoluo
on 2007-11-30
luoluonet_at_yahoo.cn
http://www.ph4nt0m.org

一、概述

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是由客户端脚本造成的,比如前段时间剑心发现的google的跨站(见附录[2])原理如下:

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的朋友们以及群里那帮经常一起扯淡的朋友们。

广告一下,没法幻影blog的朋友,可以添加hosts来突破:
72.14.219.190 pstgroup.blogspot.com

五、附录

[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));});

[2] http://www.xfocus.net/articles/200711/957.html

相关日志

发表评论