XSS Front-end Firewall (4): Seamless protection

Source: Internet
Author: User
Tags types of functions

For example, our attribute hooks only consider setAttribute, but ignore similar setattributenode. Although this method has never been used, it does not mean that others cannot use it.

For example, creating an element is usually a createelement, in fact Createelementns is also possible. You can even use ready-made elements to cloneNode and achieve your goals. Therefore, these are all marginal approaches that are worth considering.

Here we review the monitoring points discussed previously.

Inline Event Execution Eval

At the end of the first article, it's best to monitor eval,settimeout (' ... ') when performing callbacks, which can parse the code to prevent the execution of XSS code stored elsewhere.

Let's start by enumerating these types of functions:

    • Eval
    • SetTimeout (String)/SetInterval (String)
    • Function
    • Execscript/setimmediate (String)

In fact, using the previous hook technique, it is perfectly possible to monitor all of them. But the reality is not as simple as we thought.

Is there a problem with eval rewriting?

Eval is not just a function, why can't it be rewritten?

12345678 var raw_fn = window.eval;window.eval = function(exp) {    alert(‘执行eval: ‘ + exp);    return raw_fn.apply(this, arguments);}; console.log(eval(‘1+1‘));

No problem at all. That's because the code is too simple, the following Demo can see the flaw of the Shanzhai version of Eval:

12345 (function() {    eval(‘var a=1‘);})();alert(typeof a);

Run

It should be undefined to be right, but the result is number. The local variables all went to the global. What's the situation? In fact, Eval is not really a function, but a keyword! If you want to know more details, please poke here.

Does Function rewriting make sense?

Function is a global variable that overrides window. Function theory is perfectly feasible.

123456789 var raw_fn = window. Function;  window. function = function () {      alert (      return raw_fn.apply ( this };  var add = Function ( ' a ' ' B ' ' return a+b ' ); console. log (Add (1, 2));

Rewriting is really doable. But the reality is vulnerable: because all functions are instances of the function class, accessing the constructor of any function can get the original function.

For example Alert.constructor, you can bypass our hooks. You can even use anonymous functions:

1 (function(){}).constructor

So, Function is never hooked.

Additional methods of execution

Even without such functions, there are still quite a few ways to execute strings, such as:

    • Create script, InnerHTML = code
    • Create script, Path = data: Code
    • Create frame, Path = javascript: Code
    • ......

It seems unrealistic to want to completely monitor the behavior of the eval-like. But as an early warning, we can only monitor eval,settimeout/interval enough.

Suspicious module interception

The second chapter discusses the interception of the outside of the station module. The "module" rather than the "script" is not the only script element that has the ability to execute. The frames page, the plug-in all can run the code.

Executable element

We enumerate the elements that can execute the remote module:

    • Script
1 <scriptsrc="..."/>
    • Framework
12 <iframe src="..."><frame src="...">
    • Plug-in (Flash)
123 <embed src="..."><object data="..."><object><param name="moive|src"value="..."></object>
    • Plugins (Others)
1 <applet codebase="...">

The path properties of these elements should be used as objects for troubleshooting.

However, the existence of such an element may cause our path detection to fail, which is:

1 <base href="...">

It can redefine the relative path of the page, which is obviously not negligible.

In fact, in addition to using elements to execute off-site modules, you can also use network traffic to get out-of-station scripting code and then call eval execution:

Ajax

Currently, mainstream browsers support cross-domain requests as long as the server is allowed. Therefore, we need to monitor the Xmlhttprequest::open method. If you are requesting an off-site address, you have to do a policy match. Do not pass up the call, or throw an exception, or give XHR a 400 state.

WebSocket

WebSocket and XHR are similar and can be monitored by means of hooks.

However, it is worth noting that WebSocket is not a function, but a class. Therefore, when returning an instance, do not forget to change the constructor to its own hook, otherwise it will reveal the original interface :

123456789101112 var raw_class = window.WebSocket;window.WebSocket = function WebSocket(url, arg) {    alert(‘WebSocket 请求:‘ + url);    var ins = new raw_class(url, arg);    // 切记    ins.constructor = WebSocket;    return ins;};var ws = new WebSocket(‘ws://127.0.0.1:1000‘);

Also, because it is a class, do not ignore static methods or properties:

    • Websocket.connecting
    • Websocket.open
    • ...

Therefore, they must also be copied to the hooks.

Frames page Messages

HTML5 gives the framework the ability to communicate across domains. If no whitelist is created for the frame element, the attacker can embed his own frame page and then postMessage the XSS code to the main page, which is performed through Eval.

For security reasons, however, HTML5 stores the source address in the message event to identify which page the message was sent from.

Because it is an event, we can use the method mentioned in the first article to capture it. Whenever a message is received, depending on the policy, you can decide whether to block the delivery of the event.

12345678910111213 // 我们的防御系统(function() {    window.addEventListener(‘message‘, function(e) {        if (confirm(‘发现来自[‘ + e.origin + ‘]的消息:\n\n‘ + e.data + ‘\n\n是否拦截?‘)) {            e.stopImmediatePropagation();        }    }, true);})();window.addEventListener(‘message‘, function(e) {    alert(‘收到:‘ + e.data)})postMessage(‘hello‘, ‘*‘);

Run

Of course, if you configure the whitelist of the frames page, you can completely avoid this. So this defense can be selectively turned on.

Event Source

HTML5 has added an interface called EventSource. However, the usage is very similar to WebSocket, so you can use similar hooks for defense.

In this way, we have listed a variety of ways to execute remote modules. In fact, the defense is not difficult, the difficulty is to collect these monitoring points, to be watertight.

API Hooks

For dynamically created executable modules, we use property hooks to monitor their remote paths.

Methods for creating elements

This section is for Chrome because it does not support the native accessors.

    • Createelement/createelementns nothing.
    • CloneNode Cloning existing
    • Innerhtml/outerhtml Factory Creation

The first two, through the hook program is easy to achieve.

Third, because inner/outerhtml is the property of the element, not the attribute. Because Chrome cannot get native accessors, using hooks can result in the inability to invoke the ancestor interface.

Furthermore, the inner/outerhtml comes in as a string. tags and attributes are a mixed bag, parsing a string is certainly not reliable. So you have to call the native InnerHTML to build the node in batches and then scan the elements. In this process, the node Mount event has been triggered.

Therefore, there is no need to consider a third case.

You may have doubts, since the node mount event can be done, why the previous hooks? In fact, in the second article has been discussed in detail, the dynamic creation of the script can not be intercepted by the event, so only use hooks.

And the script produced by InnerHTML will not be executed! Everyone has heard about it.

Modifying an accessor for a property

By using the accessor hooks of the prototype chain, you can directly monitor the specific property of a particular element without affecting others at all, so it is very efficient. Just now the elements that can execute the remote module are enumerated, and the path properties of those elements have to be rewritten accessors.

Of course, Chrome can ignore this section.

Methods for modifying properties

Also mentioned in the beginning, in addition to SetAttribute, using Setattributenode can also set properties, and even setattributens version of the.

Since SetAttribute is a frequently invoked method, the hook program must be optimized enough to minimize additional detection consumption.

New page Environment

In addition to using the simplest framework, there are other ways to get new pages.

Pop-up window

The new page environment can also be obtained through the pop-up window, as we all know. But when the window is closed and destroyed, can it still be used? You might want to test it:

123456789101112131415 <style> .aa { color: red }</style><button id="btn">POPUP</button><script>    btn.onclick = function() {        var win = window.open();        var raw_fn = win.Element.prototype.setAttribute;        win.close();        setTimeout(function() {            console.log(raw_fn);            raw_fn.call(btn, ‘class‘, ‘aa‘);        }, 1000);    };</script>

Run

Although there will be flashes in a flash, the variables obtained from the new window are actually preserved and still work. Because we refer to it, even if the window is closed, it will still not be reclaimed for its memory.

In reality, click events can be tied to the document, so that users can easily trigger anywhere, so as to obtain a pure environment.

Therefore, we also have to protect the window function, also through the hook.

In addition to the most commonly used window.open, in fact, there are:

    • ShowModalDialog
    • showModelessDialog
Opener

If the current page is clicked from another page, whether it is a popup or a hyperlink, Window.opener records the environment of the source page.

If it is a source page and you are also a homologous site, you can even access the variables in the source page.

This situation is quite common. For example, from the Posts list page, click on a Post Details page, then the details page can be completely manipulated list page.

To solve this problem is not difficult, directly to the Window.opener inject the protection program is not possible, just like the new frame page.

However, Window.opener may also have their own opener, a layer of recursion may be a lot. Each page may have its own frames page, so protection Window.opener may execute very much code. If you do it at initialization time, there may be performance issues.

In fact, this unpopular attribute is hardly used. So instead of a time-lapse strategy: Only the first time to visit the opener, it is to protect.

We'll rewrite the Window.opener and turn it into a getter accessor:

12345678910 var raw_opener = window.opener;var scanned; window.__defineGetter__(‘opener‘, function() {    if (!scanned) {        installHook(raw_opener);        scanned = true;    }    return raw_opener;});

This way, as long as you do not access the opener, it will not trigger the protection of it, so that real on-demand execution.

Postscript

Regarding the protection monitoring point, also did not have a complete answer, can think how many calculate how many, later can add slowly.

However, with so many hooks and events, how much does it affect the performance of the page?

So, we have to develop a test console to track this system. See how much impact the page will have when the monitor is fully open.

XSS Front-end Firewall (4): Seamless protection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.