QR puzzle Write-up

どうもみむらです。

冬だ!おこただ!CTFだ! ということで、
今年も SECCON CTF 2015 のオンライン予選に参加しました。

12月5日~12月6日ということで、
んじゃ泊まり込んでやってみますか・・ということで、
大学に泊まり込んでやっていました。

・・・論文作成で煮詰まっていたので、気分転換にもいいよね! ということで。

 

今回は出題された問題のうち、 “QR-Puzzle (Windows)” という問題について。

問題概要や想定解に関しては、出題者である山崎さんの記事を閲覧して頂ければとおもいます。

SECCON 2015オンライン予選に3問を出題しました! | ラック公式ブログ | 株式会社ラック
http://www.lac.co.jp/blog/category/security/201512072.html

 

さて。
CTF, Windows と来ると勝手に「やる気スイッチ」(古い?)が入る私です。

問題に関してこんな感じで解きました:


1. ファイルを見る。

image

.net !!
ドットネットですよ、おくさん!!

これはもう、この時点で やる気スイッチ が入ります。
びんびんに入ります。

 

ということで、まずは逆アセンブリ結果を見ていきます。

image

まずリソースを見て、”SmartAssembly なのかなぁ..” と思いを馳せ、

次に作者の名前をみて「ごめんなさい..」という懺悔の気持ちになり、
いったん気分転換の為にお風呂に行きました。

このとき、銭湯にて、風呂場にいた皆さんからもの凄く強い視線を感じて
「何か私ミスしてるかな・・」と思って振り返ったところ、
皆さん背中や腕に絵が描かれていたのはいい思い出です。
でもそのあと「怖い人じゃない・・!」と思う出来ごともありまして、
ルシウス技師の言葉を思い出した・・ということがありました。

 

その後、いったん自分のなかで「ごめんなさい」をしたうえで、
「んじゃ解くか!」ということで解析を始めました。

いえ、以前こういう形で取り上げられたことがありまして・・
http://www.slideshare.net/ymzkei5/xss-201412089

また、いろいろとお世話になっているかたでもありますので、申し訳ない気持ちがあったのですが、「これは CTF だ。今は競技に集中して、終わった後、お会いした時に謝ればいい」と気持ちを切り替えました。

 


2. プログラムを起動する

image

QRCode のパズルゲームになっていました。
手でかちゃかちゃやって、何か文字が得られる QR であるということも分かりました。


3. 難読化を解く

プログラムがどういうものか分かったところで、難読化を解きます。
なんとなく雰囲気から SmartAssembly 感がしていましたので、
その難読化解除ツールをインターネット上から適当に持ってきて適用します。

 

難読化解除前:

image

難読化解除後:

image

 

読めるようになりました。


4. Form_Load を読む

普通の .net なアプリケーションを読む場合、読み始める場所は多々あるのですが、
画面の初期化部分のコードを見ることで、何を叩いているのかを調べることにしました。

こんな感じのコードです。
スタックベースの処理系なので、引数を積んで、呼び出して、結果は積まれる。というような。

image

 

でもって、注目したいのはこのあたり。

image

 

引数(数字)を取って、返値は文字列になる。
なんとなく答えの文字列を読んでそうな雰囲気がしましたので、ここを読んでみます。

読み込んでいると思われる所は他にも幾つかありましたが、
読むのが面倒くさそうだったのでやめました・・。

たとえば、答えをメモリ上で MD5Hash にしている・・と思われる箇所など、
幾つか良さそうな場所もありました。

image

見た感じ、リソースファイルから何か読み出しているんだろう、という雰囲気が伝わってきます。

確認のためにコンストラクタも見てみますと、
自分自身を取得してその中のリソースファイルを抜き出した後、
処理を実行している事が読めますので、この中に何か答えに繋がるものがあるな、と判断できます。

(実際にはリソースデータをデータとして抜き出した後、難読化を解除し、そのあとそのデータをライブラリとして読み直して、中に書かれている命令を実行するコードが書かれているようです。)

image


5.内部リソースを展開

いちいち手で解いてもいいのですが、CTF は時間勝負ということで、
「どうせ一回解いたデータはメモリ上に持ってるだろ・・」ということでデータを抜き出します。

デバッガでちまちまーっとやって ( “.loadby sos clr” とか・・! ) 抜き出すとこんな感じ:

image

なんかこう、英単語帳みたいな Dictionary 型のデータが出てきました。

 

もしかして・・と思い、最初に手で解いた答えの文字列が入っていないかどうかを調べると、
この一覧に含まれていました。

どうやら使えそうです。


6.機械的に解く。

じゃ、総当たりすればいいんですかね?
ということで適当にプログラムを書いてみます。

(言語は HSP.

origdic="seccon|accept|achieve|acquire|add|advance|affect|agree|allow|appear|apply|approach|argue|assume|avoid|bear|beat|belong|bite|care|catch|claim|communicate|compare|consider|consume|contact|contain|continue|cost|count|cover|create|cross|decline|define|depend|describe|destroy|determine|develop|die|disappear|discover|draw|earn|encourage|enter|establish|excite|exist|expect|explain|express|face|fail|fear|feed|fire|fit|flow|follow|gain|gather|get|guess|hit|hold|hunt|hurt|imagine|improve|include|increase|indicate|influence|insist|introduce|invent|involve|lay|lead|lie|lose|maintain|manage|manufacture|marry|mean|mention|miss|observe|offer|perform|please|prefer|prepare|press|prevent|produce|program|protect|prove|provide|publish|raise|reach|realize|receive|recognize|reduce|refer|reflect|refuse|regard|remain|remember|reply|represent|require|reveal|rise|risk|rule|satisfy|save|search|seat|seek|seem|serve|share|solve|sound|spend|spread|stay|steal|stick|strike|struggle|suffer|suggest|support|suppose|surprise|survive|tend|treat|vary|waste|wear|win|wonder|worry|action|activity|advantage|aid|amount|area|arms|aspect|atmosphere|attempt|attitude|audience|basis|behavior|benefit|bill|birth|blood|brain|case|cause|challenge|chance|character|choice|civilization|class|clerk|communication|community|company|competition|content|control|crowd|culture|customer|damage|degree|demand|desire|detail|development|difference|difficulty|direction|disease|distance|doubt|economy|education|effect|environment|event|evidence|exchange|exercise|experience|experiment|expression|fact|factor|failure|feature|field|figure|force|form|freedom|generation|god|government|growth|habit|history|idea|industry|information|issue|kid|knowledge|labor|lack|language|law|level|life|limit|line|literature|loss|majority|mark|market|mass|material|meal|measure|method|million|mind|mistake|moment|most|movement|nation|nature|note|object|office|opinion|opportunity|order|paper|party|period|phone|place|plant|pleasure|policy|population|position|power|practice|president|price|principle|problem|process|product|production|progress|purpose|quality|range|rate|reality|reason|relation|relationship|research|respect|response|rest|result|science|sense|shape|side|sign|situation|skill|society|sort|species|speech|stage|standard|state|step|stranger|stress|structure|subject|success|supply|surface|system|task|taste|technology|temperature|term|theory|trade|traffic|truth|universe|university|value|variety|view|war|weather|weight|afraid|ancient|available|average|aware|basic|certain|close|common|complete|complex|concerned|correct|direct|dressed|due|economic|environmental|equal|essential|expensive|familiar|famous|foreign|free|full|general|healthy|heavy|huge|human|impossible|individual|industrial|international|likely|local|major|married|medical|mental|modern|national|native|natural|necessary|obvious|ordinary|original|own|particular|past|personal|physical|political|popular|possible|practical|present|private|professional|public|recent|related|right|round|scientific|separate|serious|similar|single|social|special|strange|sure|thick|traditional|useful|various|vast|whole|wrong|abroad|actually|badly|especially|eventually|exactly|extremely|forward|frequently|generally|highly|however|immediately|indeed|later|maybe|merely|naturally|otherwise|particularly|pretty|probably|quite|recently|simply|therefore|although|unless|while|except|toward|worth|behind|abandon|absorb|accomplish|accompany|accuse|adapt|admire|admit|adopt|advertise|afford|aim|alter|annoy|appeal|arise|arrange|associate|attach|attend|attract|behave|bind|block|blow|borrow|breathe|collect|combine|command|compete|complain|compose|concentrate|conclude|confuse|connect|considerable|consist|construct|contribute|convey|convince|cope|criticize|decision|declare|decrease|defeat|defend|deny|derive|devote|disappoint|discuss|dislike|display|distinguish|disturb|divide|educate|emerge|emphasize|employ|enable|encounter|entertain|estimate|examine|expand|explore|export|expose|extend|fix|frighten|govern|graduate|greet|handle|hang|hate|hesitate|hire|identify|ignore|imply|import|impress|inform|intend|interpret|isolate|judge|notice|obtain|occupy|oppose|organize|overcome|participate|pause|perceive|permit|persuade|possess|praise|predict|preserve|pretend|promote|propose|punish|purchase|pursue|quit|react|recommend|recover|reject|release|rely|remind|remove|repair|replace|reserve|respond|retire|roll|rush|select|settle|sink|smell|stare|stimulate|stretch|suit|surround|suspect|tear|threaten|transfer|transform|translate|transport|vote|warn|account|addition|address|advice|affair|agent|agreement|agriculture|alternative|ancestor|anger|anxiety|appearance|assumption|association|author|authority|automobile|background|capacity|capital|career|characteristic|charge|circumstance|citizen|climate|conclusion|condition|conduct|conference|confidence|conflict|consequence|consumption|continent|contrast|contribution|conversation|cooperation|copy|creation|crime|crisis|criticism|crop|curiosity|custom|debate|debt|decade|definition|delight|democracy|desert|destruction|device|diet|disaster|discipline|discussion|distinction|district|drug|element|employee|enemy|entertainment|error|evolution|excuse|expert|explanation|extent|faith|fate|fault|favor|flight|focus|fuel|function|genius|goal|grammar|grant|guide|harm|height|household|humanity|ideal|imagination|immigrant|impact|impression|income|independence|instruction|intelligence|item|journey|joy|judgement|laboratory|landscape|laughter|leisure|lesson|luck|manager|manner|master|match|matter|merchant|murder|necessity|neighborhood|notion|novel|observation|occasion|occupation|operation|organization|origin|pain|passage|passenger|personality|phenomenon|philosopher|philosophy|physics|plenty|politician|politics|popularity|presence|profit|project|proof|property|proportion|proverb|psychologist|quantity|reaction|region|religion|remark|reputation|revolution|reward|row|security|self|shift|shortage|sight|significance|skin|soil|soldier|solution|statement|status|stock|strength|substance|sum|survey|survival|talent|theme|thought|threat|tongue|tradition|treatment|tribe|trust|union|vehicle|victim|violence|virus|vision|vocabulary|wealth|wisdom|witness|youth|accurate|actual|alike|anxious|appropriate|asleep|attractive|awake|biological|bored|brief|capable|chemical|civilized|comfortable|complicated|conscious|constant|contemporary|contrary|convenient|creative|critical|curious|current|dependent|distant|domestic|dramatic|dull|eager|educational|effective|efficient|elderly|emotional|empty|engaged|enormous|entire|evil|extra|extraordinary|extreme|fair|FALSE|fat|favorite|female|financial|firm|former|friendly|fundamental|gentle|global|harmful|historical|honest|immediate|independent|intellectual|intelligent|internal|junior|latter|literary|medium|military|mysterious|narrow|nearby|negative|nervous|nuclear|opposite|patient|pleasant|polite|positive|potential|previous|primary|primitive|proper|proud|rare|reasonable|remarkable|responsible|rough|rural|senior|sensitive|severe|significant|silly|slight|smart|solid|specific|stupid|sudden|suitable|superior|technical|terrible|tiny|tough|typical|unique|universal|unknown|unusual|upset|urban|useless|valuable|visible|vital|wealthy|welcome|well-known|willing|absolutely|alive|apart|closely|constantly|directly|entirely|fairly|forever|fully|gradually|largely|necessarily|nevertheless|normally|obviously|occasionally|possibly|properly|rapidly|seldom|slightly|somehow|somewhat|surely|totally|unfortunately|virtually|widely|wherever|despite|unlike|acknowledge|adjust|advise|amuse|analyze|assure|astonish|beg|bend|blink|bow|broadcast|burst|bury|capture|cease|celebrate|characterize|cling|commit|confine|confirm|confront|constitute|convert|cultivate|cure|dare|delay|deliver|depress|devise|diminish|disagree|discourage|dominate|dwell|eliminate|embarrass|endure|ensure|equip|evolve|exhaust|exhibit|fascinate|float|fold|found|fulfill|gaze|generate|grasp|guarantee|guard|illustrate|imitate|impose|inclined|industrialize|inspire|interfere|interrupt|investigate|justify|leap|melt|misunderstand|neglect|nod|offend|originate|overlook|owe|pour|pray|proceed|protest|rank|relieve|request|resist|resolve|restrict|retain|review|ruin|scare|scatter|scream|secure|specialize|spoil|strengthen|substitute|suppress|swallow|sweep|trace|undergo|urge|wander|weigh|whisper|yell|absence|accent|acceptance|access|acquaintance|affection|aggression|alarm|ambition|appetite|application|appointment|arrangement|athlete|avenue|band|border|burden|campaign|candidate|cash|category|cave|cell|charm|colleague|colony|committee|companion|comparison|complaint|complexity|composition|confusion|construction|contract|convention|courage|crash|crew|critic|description|dialect|dignity|disadvantage|dispute|division|divorce|document|ecology|economics|editor|emotion|emperor|enterprise|enthusiasm|equality|era|exception|executive|expense|explosion|extinction|facility|fairy|flame|fortune|foundation|frontier|fund|funeral|fur|furniture|garbage|gene|globe|grave|ground|harmony|harvest|honor|hunger|immigration|impulse|incident|infant|inhabitant|injury|insect|insight|instinct|institution|instrument|insurance|introduction|investment|liberty|limitation|load|location|logic|lord|lung|luxury|mail|mammal|mineral|minority|mood|motive|myth|neighbor|nerve|obligation|orbit|output|owner|participant|passion|patience|perception|perspective|pile|pioneer|poison|portion|possession|preference|prejudice|privilege|profession|pronunciation|prospect|punishment|pursuit|ray|recognition|reference|reflection|relief|requirement|resident|ritual|root|sacrifice|scholar|seed|servant|shade|shame|shelter|shore|similarity|site|specialist|statistics|steam|strip|stuff|suburb|tale|telescope|tension|territory|text|tide|tip|tone|traffic jam|tragedy|trail|trait|transportation|trap|treasure|trial|trick|unemployment|version|virtue|volunteer|voyage|wage|weapon|Westerner|absolute|abstract|accustomed|additional|adequate|aggressive|amazing|annual|apparent|artificial|Atlantic|atomic|awful|based|brilliant|calm|casual|civil|classical|definite|delicate|democratic|desirable|dirty|distinct|elaborate|electrical|elementary|equivalent|evident|exact|excessive|external|frequent|generous|genuine|grand|guilty|identical|inevitable|inferior|initial|inner|intimate|invisible|keen|latest|legal|liberal|located|logical|long-term|massive|mature|mechanical|minor|mutual|numerous|odd|overwhelming|painful|passive|peculiar|permanent|plain|precious|precise|precisely|prime|principal|profound|racial|rational|raw|relative|reliable|remote|routine|rude|satisfactory|sensible|spare|spiritual|steady|strict|subtle|sufficient|tremendous|tropical|ultimate|uncomfortable|unexpected|unlikely|unpleasant|verbal|visual|widespread|aloud|altogether|barely|commonly|consequently|deliberately|effectively|essentially|firmly|increasingly|literally|practically|primarily|readily|regardless|regularly|roughly|socially|steadily|traditionally|undoubtedly|whereas|beneath"

TEXTBOXADDR = 0xA098E
PROGBARADDR = 0x110C6A

sysfont 17
split origdic,"|",dic
prog = 0
repeat
if prog > 299 : break
last = "HELLO SECCON"
sendmsg TEXTBOXADDR,0xC,0,last
await 0
repeat length(dic)
sendmsg TEXTBOXADDR,0xC,0,dic(cnt)
sendmsg PROGBARADDR,0x408
if  prog != stat: prog = stat: title "Q."+stat+" - HIT: "+dic(cnt): break
loop
loop
title "DONE."

 

使い方としては TEXTBOXADDR と PROGBARADDR にウィンドウハンドルの値を与えて実行すれば、

あとは3分程度ほったらかして置くだけで答えが表示されています。

仕掛けとしては、

1. テキストボックスに WM_SETTEXT (0xC) メッセージを送り、任意のメッセージで初期化する。

https://msdn.microsoft.com/ja-jp/library/windows/desktop/ms632644(v=vs.85).aspx

2. テキストボックスに取得した辞書の単語を一つ取り出して送る。

3. プログラムバーに PBM_GETPOS (0x408) メッセージを投げて現在の進捗を調べる。

https://msdn.microsoft.com/en-us/library/windows/desktop/bb760830(v=vs.85).aspx

4. 進捗が 299 を超えていればソルバを終了する。

というような流れです。

 


Appendix.

じゃ、どうやって守ればいいのというところですが・・。

私もプレイヤーですので詳しく書くと色々と対策されそうなのでボソボソッと。

(でももう、聞かれたら答えようかなとも思ってます。。

たとえば今回私が使用した SendMessage 系は

Windows の昔ながらのコンポーネントが問題で使用されていた為に使えたというところがあり、

そうでなければ防げたのかなとも。

あとは、メモリに展開したデータをそのままにしておくというのも、あんまり・・と思ってみたり。

それ以外にも気になった点はいくつかありました。

・・・時間が出来たら、私がもし作問者側ならどう対策しよう・・というのを実験してブログ記事を書いてみたいところです。


そんなこんなで、久しぶりに CTF でワイワイした、そんな2日間(?)でした。

(そんなわけで、 CTF Advent Calendar 2015 の記事にもしてみました。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です