When do I need to check the origin
property on events that implement the MessageEvent
interface in order to avoid security vulnerabilities?
The origin attribute must return the value it was initialized to. It represents, in server-sent events and cross-document messaging, the origin of the document that sent the message (typically the scheme, hostname, and port of the document, but not its path or fragment).
This property is exposed by server-sent events, Web sockets, cross-document messaging, channel messaging, and broadcast channels.
What should I know? What do I need to beware of? What should I keep in mind?
What scenarios would it make sense to check the origin
property?
Do I even need to check origin
at all, or just the isTrusted
property?
var websocket = new WebSocket('ws://echo.websocket.org/');
websocket.onmessage = function(e) {
// Can I trust this event?
// Do I need to check e.origin?
};
When do I need to check the origin property?
Best practise: always.
What should I know? What do I need to beware of? What should I keep in mind?
Whenever you are communicating with some other party, that party might be hostile. Depending on what the communication is about, that can be a security issue, especially if you a) share data b) act on requests - which is pretty much always.
The point is that any party can try to initiate communication with you, and even if you initiated it, in the case of cross-document messaging (frames, tabs etc) and channels your counterpart may change (by navigation, by forwarding). You should explicitly check whom you are communicating with and whether you want that.
To cite MDN on postMessage
:
If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.
If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.
Do I even need to check origin at all, or just the isTrusted property?
No, the isTrusted
property does something entirely different. Also, the browser cannot know which domains you trust and which not, especially when you want to do cross-origin messaging.