rompetroll
rompetroll

Reputation: 4799

protecting websockets from external scripts

On many webpages, we include external scripts. Be it facebook like buttons, client code for analytics or ad systems, an external comment provider or other stuff.

Those scripts have no access to my Ajax resources, because there is a check for the origin header all the time.

But, I'm a bit worried about what those scripts can do with websocket connections that I have on my page. Here, the origin header is only checked during the handshake as far as I understand.

Let's say I open a connection and define an onmessage handler like this

var ws = new WebSocket("ws://host/resource");
ws.onmessage = function(evt) { my stuff ... }

Would an external script not be able to reassign the onmessage handler, and thus gain access to everything my server sends to the browser through the websocket? Like

var oldHandler = ws.onmessage;
ws.onmessage = function(evt) { 
   externalscript.readMystuffAndDoEvilThings(evt); 
   oldHandler(evt); 
}

I don't see why it would not be possible. Neither wss:// nor session cookies or other stuff would prevent it. but maybe I am missing something?

Upvotes: 3

Views: 180

Answers (1)

Ivan Zuzak
Ivan Zuzak

Reputation: 18782

You are not missing anything. If you have loaded an external (cross-origin) script into your browsing context, then that script has the same privileges as "local" (same-origin) scripts. The external script could in the same way replace your XHR callbacks, console.log-s, and everything else.

The problem for such malicious external scripts is that a) you have to be willing to load them into your app, and b) the scripts would have to know what to replace (function/variable names).

The way to prevent such attacks is to use what is called the JavaScript module pattern -- you wrap all your code within an anonymous function and execute that function immediately. This way, your code is shielded from external scripts since it executes within the closure (local scope). See this for more info and variations of the pattern: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

Upvotes: 1

Related Questions