保护 Javascript 同源 postMessage 调用和消息侦听器,这就足够了吗?

Securing Javascript same-origin postMessage call and message listener, is this enough?

这是我第一次尝试使用 postMessage。想要确保子 iframe 和父 iframe 之间的通信是安全的。

每页:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

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

家长的消息监听功能如下:

uri = 'https://www.somedomain.com/';
window.addEventListener("message", function(event) {
    if (event.origin !== uri.base.slice(0, -1)) return;
    if (event.source.location.origin !== uri.base.slice(0, -1)) return;
    if (event.source.location.origin !== window.location.origin) return;

    console.log(event.data);
});

子 iframe 的 postMessage 调用:

uri = 'https://www.somedomain.com/';
eventData = {'type':'sometype','action':'someaction','id':'q12wucxdfgbvgfcvt'};
parent.postMessage(eventData, uri.slice(0, -1));

监听函数中的检查是否足够?还是太多了?

谢谢

太多了。如果同步检查,event.source.location.origin == event.origin 将始终为真。这意味着前两个条件是骗人的。对于第三个条件,它实际上是说“我只处理同源消息,并且源必须是 'https://www.somedomain.com'”。

因此可以简化为: event.origin == window.location.origin && event.origin == "https://www.somedomain.com"

现在我有点不明白你的真实意图了。

如果你事先知道你的页面确实托管在 "https://www.somedomain.com" 那么你根本不需要检查它,你只需要检查 event.origin == window.location.origin.

如果你事先知道来源不是,那么检查将永远不会通过。

逐字检查 "https://www.somedomain.com" 唯一有意义的情况是,当您将同一脚本部署到两个不同的来源时,并且您希望条件在一侧为真而在另一侧为假。但我怀疑这是你真正想要的。