我什么时候需要检查来源属性?

When do I need to check the origin property?

我什么时候需要检查实现 MessageEvent 接口的事件的 origin 属性 以避免安全漏洞?

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).

此 属性 由服务器发送的事件、Web 套接字、跨文档消息传递、通道消息传递和广播通道公开。

我应该知道什么?我需要注意什么?我应该记住什么?

在什么情况下检查 origin 属性 是有意义的?

我什至需要检查 origin,还是只检查 isTrusted 属性?

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?

最佳实践:总是

What should I know? What do I need to beware of? What should I keep in mind?

每当您与另一方交流时,该方可能是敌对的。根据通信的内容,这可能是一个安全问题,特别是如果您 a) 共享数据 b) 根据请求采取行动 - 这几乎总是如此。

重点是任何方都可以尝试发起与您的通信,即使是您发起的,在跨文档消息传递(框架、选项卡等)的情况下以及你的对手可能改变的渠道(通过导航,通过转发)。你应该明确地检查你正在与谁交流,以及你是否想要那样。

引用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?

不,isTrusted property 做了完全不同的事情。此外,浏览器无法知道您信任哪些域,哪些不信任,尤其是当您想要进行跨源消息传递时。