這個存在漏洞的url是http://bbs.demo.com//forum.php?mod=ajax&action=downremoteimg&message=
攻擊者把非法檔案傳入到參數進行SSRF攻擊:
http://bbs.demo.com//forum.php?mod=ajax&action=downremoteimg&message=[img]http://tv.phpinfo.me/exp.php?s=ftp%26ip=127.0.0.1%26port=6379%26data=helo.jpg[/img]
這裡message參數傳的是使用者在論壇發布的圖片地址,正常情況下是圖片格式尾碼,雖然程式有對尾碼進行了判斷,但是判斷不嚴格,只需要通過在url加圖片尾碼就可以矇混過去。
解決辦法是修改對url的合法性判斷,尾碼即使合法,也可能通過url rewrite方式偽造,所以進一步通過curl擷取檔案頭資訊,根據返回的報文Content-Type參數判斷檔案格式是否合法。
於是,在檔案/source/module/forum/forum_ajax.php檔案新增以下幾個函數:
PHP
//擷取上傳圖片url列表
function getImageList($temp)
{
$urlList = array();
foreach ($temp as $item) {
$urlList[] = $item[1];
}
return $urlList;
}
/**
* 檢查content-type是否合法
* @param $imageList array 圖片url列表
* @return bool true合法 false非法
*/
function checkContentType($imageList)
{
$allowExtensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
$allowTypes = array('image/png', 'image/x-png', 'image/gif', 'image/jpeg', 'image/pjpeg');
foreach ($imageList as $url) {
$extension = getUrlExtension($url);
if(!in_array(strtolower($extension), $allowExtensions)){
return false;
}
$contentType = getContentType($url);
if (!in_array($contentType, $allowTypes)) {
return false;
}
}
return true;
}
//擷取content-type
function getContentType($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
return $contentType;
}
//擷取url尾碼
function getUrlExtension($url)
{
$parseurl = parse_url($url);
$extension = pathinfo($parseurl['path'], PATHINFO_EXTENSION);
return $extension;
}
在具體介面處理的地方新增:
//檢測圖片是否合法 Added by tanteng<tanteng@xunlei.com> 2016.07.07
if(is_array($temp) && !empty($temp)){
$imageList = getImageList($temp);
$check = checkContentType($imageList);
if ($check === false) {
die('file upload error!');
}
}
首先判斷檔案尾碼是否合法,再通過curl請求判斷header的Content-Type是否合法,因為後者不容易偽造。其中curl判斷檔案Content-Type方法:
PHP
//擷取content-type
function getContentType($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
return $contentType;
}
再通過烏雲公開的漏洞地址,url傳入非法格式的檔案,程式不再繼續執行。
不過,這樣做有一個問題,有的圖片地址並不是真實的靜態檔案,如:http://image.demo.com/avatar/100/150*150,這個路徑就是一個圖片,儘管不是圖片格式的靜態路徑,那麼這樣判斷就會誤判,不過這種情況是很少數,暫且不管。