[Hack] Directory Traversal
2009/03/15
來講一下Directory Traversal , 會想講的原因是因為有意外看到相關的資訊是藉由 DT 而跑出來的..
Live Demo(index.php):
<?php //初始化參數 if(!$path) { $path="test"; $xpath =""; }
define("PATHFIELD",0); define("FILEFIELD",1); define("EXTFIELD",2); $class="xxxxxx"; //類別,在每個目錄的class.conf.php中有紀錄,若無則保持空白 $filecount=0; //Count file(not directory) num $dircount=0; //Count dir num $dir=@opendir($path);
//讀取目錄資料並至於陣列當中 while($file=@readdir($dir)) { if(is_dir("$path/$file")) { if($file=="."||$file=="..") continue; $examdir[$dircount++]="$file"; } else if(is_file("$path/$file")) { if($file=="class.conf.php") require("$path/$file"); //取得目錄提示資料 $exten=substr($file,-3,3); //Get file extention if(!strcasecmp($exten,"pdf")||!strcasecmp($exten,"gif")||!strcasecmp($exten,"zip")) { $examfile["$filecount"][PATHFIELD]="$path/$file"; $examfile["$filecount"][FILEFIELD]="$file"; $examfile["$filecount"][EXTFIELD]="$exten"; $filecount++; } } }
討論:
從最前面就可以看到 , Programmer 在設計這個頁面的時候 , 並沒有考慮到 DT 的問題 , 所以就沒有對一些具有攻擊性的字做filter or 白名單過濾 , 所以當 $path 來個 “../” 就掰囉~從父目錄一直到根目錄都一覽無遺…
Demo PHP Code 1(index.php):
<?php readfile('/home/xx/file/'.$_GET['file']); ?>
Exploit:
http://target/index.php?file=../../etc/passwd
討論:
結果Unix Like的passwd的檔案就會被顯示出來 = =”…
Demo PHP Code 2(index.php):
<?php readfile('/home/xx/file/'.$_GET['file'].'.dat'); ?>
Exploit:
http://target/index.php?file=../../etc/passwd
討論:
利用 NULL character 來把後面的.dat給無用化 , 這樣就可以讀到passwd的內容了..
防範:
利用basename()把後面的東西做filter , 像是在$path那邊可以改成這樣 ,
$path = str_replace('.','',$path); $true_path = "/www/".basename($path);
則所有的’.’都會被換成’ ‘,這樣就可以再依個人需求做變化 , 大致上應該是不會有太多問題了