satto1237’s diary

s4tt01237’s diary

ラーメンとかCTFとかセキュリティとか

2019年の振り返りと2020年の目標

はじめに

2019年の振り返りと2020年の目標について書きます.

2019年の振り返り

1月

1月は国内学会で発表したり,Webカメラで遊んだり,SecHack365のあれこれをやっていました.

学会の開催地は滋賀県の大津だったのでしっかり京都二郎を食べてきました(?)

f:id:satto1237:20191231221422j:plain
京都二郎(九条ネギトッピング)

2月

2月はSecHack365@沖縄回に参加しました.
SecHack365を通じてとても良い経験ができたと思うのですが,少し思い残すところがあります. と言うのも,自分が担当したIoT機器のトラフィックの異常検知と脆弱性スキャン機能を納得がいくところまで作り込めず,チームメンバに対して申し訳ないなという気持ちがあるからです. 次にこういった機会があるときは後悔を残さないように頑張りたいと思います.

satto.hatenadiary.com

3月,4月

3,4月は主に就活をしていました.
結果的には5社にエントリーして,2社から内定を頂き,3社は選考の途中で辞退させていただきました.
内定を承諾した企業でもセキュリティに関わることになったので引き続きセキュリティ関連のあれこれを頑張っていきたいと思います.

5月 ,6月,7月

5~7月はCTFをして遊んだり,就活の現実逃避で買って積んでいた本を消化していました(院生は研究をしろ)
CTFに関しては土日の予定が空いていたらほぼ毎回出ていた気がします(問題が解けるようになったとは言っていない)

↓SECCON4B CTF でCrypto全完できたのは結構嬉しかったです.

satto.hatenadiary.com

8月,9月

8,9月は評価実験をしたり,論文を書いたりしてました.
締め切りに追われながらコードや英語を書くのは結構キツかったです(計画性がないので)

10月

10月はSECCON予選があったのですが,何故かIPAの資格試験に申し込んでしまっており,ほとんど参加できませんでした…(チームメンバのみなさん本当に申し訳ないです)

ギリギリ合格したNW

f:id:satto1237:20191231231307j:plain

11月

11月はNetWarsに参加したり,国際学会で発表したりしてました.

NetWarsは学びが多く,満足度の高いイベントでした(来年度参加できないのが本当に悲しい).
ただ,結果が微妙だったのが少し残念でした (21位/94人中)
ペンテスト,本当に何もわからないのでHack The Boxで勉強します💪

www.nri-secure.co.jp

国際学会での発表は質疑応答で色々とやらかしてしまったのですが,なんとか無事に終わって良かったです.
英会話が本当にできない

f:id:satto1237:20191231233321j:plain
Palace of the National Military Circle

12月

12月はポケモンをやったり,修論を書いたりしてました.
堕落の限りを尽くしてしまった

2019年の目標

satto.hatenadiary.com

上記によると2019年の目標は

  • 国際学会での発表
  • SECCON 本戦(国内)に出場
  • 就活
  • 健康
  • セキュリティ

でしたが,達成率は40%程度だと思います(国際学会での発表,就活のみ達成).
評価しにくいので定量的な目標にすればよかった

2020年の目標

最後に2020年の目標についてです.

修了

それはそう(修了しないと働けないので)

CTFをがんばる

具体的には,以下の3つです.

  • 現在所属しているチーム(NekochanNano!)でCTF Timeの国内ランク1桁を目指す
  • SECCON 本戦(国内)に出場
  • Cryptoは中級者レベル, RevとWebは初級者レベルを目指す(曖昧)

社会人生活に慣れる

プライベートでどれだけの勉強時間を確保できるのか分からないのでかなり不安ですが, 早めに社会人生活に慣れて,土日や平日の帰宅後の時間を有効活用していきたいです.

具体的には土日は3時間,平日は1時間,時間を確保して勉強を続けていけたらいいなと思います.

CVEがほしい

CVEがほしい(願望)

健康

具体的には,以下の2つです.

  • ラーメンは週に1杯まで
  • 早寝早起き朝ごはん

アウトプット

2019年はインプット中心だったので2020年はアウトプットを増やしていけたらいいなと思います(具体的なアウトプットは未定)

CSAW CTF 2019 Write-up

はじめに

2019/09/15 ~ 2019/09/16に開催されたCSAW CTF 2019 にチーム(NekochanNano!)で参加しました.

成績

チームとしては4問解いて222位でした (1301チーム中).
今回は自分が解いた2問のWrite-upを書きます.

beleaf [Rev, 50pts, 397solves]

tree sounds are best listened to by https://binary.ninja/demo or ghidra

beleaf

> file beleaf
beleaf: ELF 64-bit LSB shared object x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=6d305eed7c9bebbaa60b67403a6c6f2b36de3ca4, stripped
> ./beleaf 
Enter the flag
>>> meow    
Incorrect!

アプローチ:Ghidraでデコンパイル

問題文にも書いてある通りにGhidraデコンパイルします.

undefined8 FUN_001008a1(void)
{
  size_t sVar1;
  long lVar2;
  long in_FS_OFFSET;
  ulong local_b0;
  char local_98 [136];
  long local_10;
  
  local_10 = *(long *)(in_FS_OFFSET + 0x28);
  printf("Enter the flag\n>>> ");
  __isoc99_scanf(&DAT_00100a78,local_98);
  sVar1 = strlen(local_98);
  if (sVar1 < 0x21) {
    puts("Incorrect!");
                    /* WARNING: Subroutine does not return */
    exit(1);
  }
  local_b0 = 0;
  while (local_b0 < sVar1) {
    lVar2 = FUN_001007fa((ulong)(uint)(int)local_98[local_b0]);
    if (lVar2 != *(long *)(&DAT_003014e0 + local_b0 * 8)) {
      puts("Incorrect!");
                    /* WARNING: Subroutine does not return */
      exit(1);
    }
    local_b0 = local_b0 + 1;
  }
  puts("Correct!");
  if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
                    /* WARNING: Subroutine does not return */
    __stack_chk_fail();
  }
  return 0;
}


long FUN_001007fa(char cParm1)
{
  long local_10;
  
  local_10 = 0;
  while ((local_10 != -1 && ((int)cParm1 != *(int *)(&DAT_00301020 + local_10 * 4)))) {
    if ((int)cParm1 < *(int *)(&DAT_00301020 + local_10 * 4)) {
      local_10 = local_10 * 2 + 1;
    }
    else {
      if (*(int *)(&DAT_00301020 + local_10 * 4) < (int)cParm1) {
        local_10 = (local_10 + 1) * 2;
      }
    }
  }
  return local_10;
}

デコンパイル結果からFUN_001008a1, FUN_001007faではそれぞれ次のような処理を行っていることが分かります.
FUN_001008a1

  • 入力文字列長のチェック (0x21文字未満はIncorrect)
  • 配列DAT_003014e0の要素と関数FUN_001007faの返り値の比較 (異なればIncorrect)

FUN_001007fa

  • 配列DAT_00301020の要素と引数を比較
  • long local_10をindexとしてreturn

あとはこれらの処理を再現し,候補となる文字を総当たりすれば解けます.
以下ソルバです.

import string

DAT_003014e0 = [0x01,0x09,0x11,0x27,0x02,0x00,0x12,0x03,0x08,0x12,0x09,0x12,0x11,0x01,0x03,0x13,0x04,0x03,0x05,0x15,0x2E,0x0A,0x03,0x0A,0x12,0x03,0x01,0x2E,0x16,0x2E,0x0A,0x12,0x06]
DAT_00301020 = [0x00000077, 0x00000066, 0x0000007b, 0x0000005f, 0x0000006e, 0x00000079, 0x0000007d, 0xffffffff, 0x00000062, 0x0000006c, 0x00000072, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000061, 0x00000065, 0x00000069, 0xffffffff, 0x0000006f, 0x00000074, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000067, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000075, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000]

def FUN_001007fa(c):
    count = 0
    while count < len(DAT_00301020):
        if ord(c) == DAT_00301020[count]:
            break
        elif ord(c) < DAT_00301020[count]:
            count = count * 2 + 1
        else:
            if DAT_00301020[count] < ord(c):
                count = (count + 1) * 2
    return count

flag = ''
for i in range(0x21):
    for c in string.printable:
        if DAT_003014e0[i] == FUN_001007fa(c):
            flag += c
            break
print(flag)
> python solve.py
flag{we_beleaf_in_your_re_future}

flag{we_beleaf_in_your_re_future}

SuperCurve [Crypto, 300pts, 171solves]

We are a super legitimate crypto company asking you to complete an audit on our new elliptic curve, SuperCurve, in order to show those hecklers at WhiteHat how legit we are!
nc crypto.chal.csaw.io 1000

server.py

#!/usr/bin/env python3

import random
from supercurve import SuperCurve, curve

def main():
    curve = SuperCurve(
        field = 14753, order = 7919,
        a = 1, b = -1, g = (1, 1),
    )
    # print curve parameters generically
    print(curve)

    # xP = Q
    secret_scalar = random.randrange(curve.order)
    base = curve.g
    pub = curve.mult(secret_scalar, base)
    print("Public key: {}".format(pub))
    #print("Secret scalar: {}".format(secret_scalar))

    while True:
        print("What is the secret?")
        user_input = input("Asking for secret")
        user_input = int(user_input)

        if curve.mult(user_input, base) == pub:
            with open("flag.txt", "r") as f:
                print(f.read())
            break
        else:
            print("WRONGGG!")
            continue

    return 0

if __name__ == "__main__":
    exit(main())

supercurve.py

"""
supercurve.py

    An implementation of a weak elliptic curve over a prime field in standard Weirstrauss form:
        y^2 = x^3 + ax + b

    Derived from: https://github.com/andreacorbellini/ecc/blob/master/logs/common.py
"""

class SuperCurve:

    def __init__(self, field, order, a, b, g):
        """
        a, b = coefficients
        g = base point
        """
        self.field = field
        self.order = order

        self.a = a
        self.b = b
        self.g = g

        assert pow(2, field - 1, field) == 1
        assert (4 * a * a * a + 27 * b * b) % field != 0

    def __str__(self):
        return "a = {}\nb = {}\np = {}\nn = {}".format(self.a, self.b, self.field, self.order)

    def is_on_curve(self, point):
        if point is None:
            return True

        (x, y) = point
        return (y * y - x * x * x - self.a * x - self.b) % self.field == 0

    def add(self, p1, p2):
        assert self.is_on_curve(p1)
        assert self.is_on_curve(p2)

        if p1 is None:
            return p2
        if p2 is None:
            return p1

        (x1, y1) = p1
        (x2, y2) = p2

        if x1 == x2 and y1 != y2:
            return None

        if x1 == x2:
            m = (3 * x1 * x1 + self.a) * SuperCurve.inv_mod(2 * y1, self.field)
        else:
            m = (y1 - y2) * SuperCurve.inv_mod(x1 - x2, self.field)

        x3 = m * m - x1 - x2
        y3 = y1 + m * (x3 - x1)
        result = (x3 % self.field, -y3 % self.field)
        assert self.is_on_curve(result)
        return result

    def double(self, p):
        return self.add(p, p)

    def neg(self, p):
        if p is None:
            return None

        (x, y) = p
        res = x, -y % self.field
        assert self.is_on_curve(res)
        return res

    def mult(self, scal, point):
        if scal % self.order == 0 or point is None:
            return None
        if scal < 0:
            return self.neg(self.mult(-scal, point))

        result = None
        addend = point

        while scal:
            if scal & 1:
                result = self.add(result, addend)
            addend = self.double(addend)
            scal >>= 1

        return result

    @staticmethod
    def inv_mod(n, p):
        if n == 0:
            raise Exception
        if n < 0:
            return p - SuperCurve.inv_mod(-n, p)

        s, old_s = 0, 1
        t, old_t = 1, 0
        r, old_r = p, n

        while r != 0:
            quotient = old_r // r
            old_r, r = r, old_r - quotient * r
            old_s, s = s, old_s - quotient * s
            old_t, t = t, old_s - quotient * t

        gcd, x, y = old_r, old_s, old_t

        assert gcd == 1
        assert (n * x) % p == 1
        return x % p


curve = SuperCurve(
    field = 14753, order = 14660,
    a = 1, b = -1, g = (1, 1),
)
> nc crypto.chal.csaw.io 1000
a = 1
b = -1
p = 14753
n = 7919
Public key: (1719, 13842)
What is the secret?
1127
WRONGGG!

アプローチ:愚直にブルートフォース

まずserver.pyから正しいsecretを入力すればflagが読み取れることが分かります.
ここでのsecretbase point楕円曲線上で何倍すればPublic keyと一致するかというものです.

楕円曲線上で P=xGを満たす xを見つけるのは離散対数問題であるため,通常であれば総当たりで解くことは困難です. しかし,今回の問題に限ればfieldorderが小さいため愚直に総当たりしても一瞬で解けてしまいます.

以下ソルバです.

import re
from supercurve import SuperCurve
from socket import *

def recvuntil(msg):
    rec = ''
    while msg not in rec:
        rec = s.recv(1024).decode('utf-8')

    return rec

s = socket(AF_INET, SOCK_STREAM)
s.connect(('crypto.chal.csaw.io', 1000))

curve = SuperCurve(
    field = 14753, order = 7919,
    a = 1, b = -1, g = (1, 1),
)
base = curve.g

rec = recvuntil('Public key:')
match = re.search(r"\((.+)\)",rec)
target = tuple(map(int,match.group(1).split(', ')))
print('Public key: {}'.format(target))

for scale in range(curve.order):
    pub =  curve.mult(scale, base)
    if pub == target:
        print('secret: {}'.format(scale))
        s.send(str(scale).encode('utf-8') + b'\n')
        rec = s.recv(1024).decode('utf-8')
        break

print(rec)
> python solve.py
Public key: (7031, 11777)
secret: 5829
flag{use_good_params}

flag{use_good_params}

まとめ

  • beleafSuperCurveは簡単だったのですんなりと解けた
  • byte_me, count_on_me, Fault Boxは10時間くらい取り組んだけど解けなかった(つらスギィ)
  • count_on_me, Fault Boxは良問だと思うのでWrite-up読んで勉強したい (byte_meエスパーが必要なのでダメ)
  • 今回のCTFはCryptoが他ジャンルよりも簡単だったのでもう少しチームに貢献したかった(完)

TokyoWesterns CTF 5th 2019 Write-up

はじめに

2019/08/31 ~ 2019/09/02に開催されたTokyoWesterns CTF 5th 2019にチーム(NekochanNano!)で参加しました.

成績

チームとしては6問解いて107位でした (1005チーム中).
今回は自分が解いた2問のWrite-upを書きます.

f:id:satto1237:20190902160154p:plain

Easy Crack Me [Rev, 88pts, 185solved]

Cracking is easy for you.

> file easy_crack_me
easy_crack_me: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=7e80b79602fcfd8121e9f4d9d26bb01a81f4afe5, stripped
> ./easy_crack_me 
./bin flag_is_here
> ./easy_crack_me flag
incorrect

アプローチ:Ghidraでデコンパイル + 気合で解読 + 制約条件に基づいて全探索

とりあえずidaで開いてみますが,これを静的解析するのはしんどいなという気持ちになり,すぐに方針をangrに切り替えました.

f:id:satto1237:20190902164721p:plain

しかし,上手くいきませんでした…(終)

f:id:satto1237:20190902193835p:plain

以下が上手く行かなかったangrソルバです.
問題点があれば教えてほしいです.
(strchrのせいなのか?)

import angr

length = 0x27

p = angr.Project('./easy_crack_me')
flag = claripy.BVS('flag', length*8)
state = p.factory.entry_state(args=[p.filename, flag])

for i, x in enumerate(flag.chop(8)):
    if i < 6:
        state.add_constraints(x == b'TWCTF{'[i])
    elif i == 0x25:
        state.add_constraints(x == b'5')
    elif i == 7:
        state.add_constraints(x == b'f')
    elif i == 0xb:
        state.add_constraints(x == b'8')
    elif i == 0xc:
        state.add_constraints(x == b'7')
    elif i == 0x17:
        state.add_constraints(x == b'2')
    elif i == 0x1f:
        state.add_constraints(x == b'4')
    elif i == 0x26:
        state.add_constraints(x == b'}')
    else:
        state.add_constraints(x >= b' ')
        state.add_constraints(x <= b'~')

simgr = p.factory.simulation_manager(state)

simgr.explore(find=0x400e10, avoid=[0x400777,0x400dfc])

try:
    simstate = simgr.found[0]
    print(simstate.posix.dumps(1))
    print(simstate.solver.eval(flag, cast_to=bytes))
except Exception as e:
    print(e)

angrで解けなかったので再度方針を静的解析に切り替えました.

まずはmain関数をGhidraデコンパイルしてソースコードを解析していきます.

undefined8 FUN_00400747(int iParm1,long lParm2)

{
  char cVar1;
  char *__s;
  int iVar2;
  undefined8 uVar3;
  size_t sVar4;
  char *pcVar5;
  long lVar6;
  undefined8 *puVar7;
  long in_FS_OFFSET;
  byte bVar8;
  int local_1b8;
  int local_1b4;
  int local_1b0;
  uint local_1ac;
  int local_1a8;
  int local_1a4;
  int local_1a0;
  uint local_19c;
  int local_198;
  int local_194;
  int local_190;
  int local_18c;
  char *local_188;
  undefined8 local_168;
  undefined8 local_160;
  undefined8 local_158;
  undefined8 local_150;
  undefined8 local_148;
  undefined8 local_140;
  undefined8 local_138;
  undefined8 local_130;
  undefined8 local_128;
  undefined8 local_120;
  undefined8 local_118;
  undefined8 local_110;
  undefined8 local_108;
  undefined8 local_100;
  undefined8 local_f8;
  undefined8 local_f0;
  undefined8 local_e8;
  undefined8 local_e0;
  undefined8 local_d8;
  undefined8 local_d0;
  undefined8 local_c8;
  undefined8 local_c0;
  undefined8 local_b8;
  undefined8 local_b0;
  undefined8 local_a8 [16];
  undefined8 local_28;
  undefined8 local_20;
  long local_10;

  bVar8 = 0;
  local_10 = *(long *)(in_FS_OFFSET + 0x28);
  if (iParm1 == 2) {
    __s = *(char **)(lParm2 + 8);
    sVar4 = strlen(__s);
    if (sVar4 != 0x27) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    iVar2 = memcmp(__s,"TWCTF{",6);
    if ((iVar2 != 0) || (__s[0x26] != '}')) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    local_e8 = 0;
    local_e0 = 0;
    local_d8 = 0;
    local_d0 = 0;
    local_c8 = 0;
    local_c0 = 0;
    local_b8 = 0;
    local_b0 = 0;
    local_28 = 0x3736353433323130;
    local_20 = 0x6665646362613938;
    local_1b8 = 0;
    while (local_188 = __s, local_1b8 < 0x10) {
      while (pcVar5 = strchr(local_188,(int)*(char *)((long)&local_28 + (long)local_1b8)),
            pcVar5 != (char *)0x0) {
        *(int *)((long)&local_e8 + (long)local_1b8 * 4) =
             *(int *)((long)&local_e8 + (long)local_1b8 * 4) + 1;
        local_188 = pcVar5 + 1;
      }
      local_1b8 = local_1b8 + 1;
    }
    iVar2 = memcmp(&local_e8,&DAT_00400f00,0x40);
    if (iVar2 != 0) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    local_168 = 0;
    local_160 = 0;
    local_158 = 0;
    local_150 = 0;
    local_148 = 0;
    local_140 = 0;
    local_138 = 0;
    local_130 = 0;
    local_1b4 = 0;
    while (local_1b4 < 8) {
      local_1b0 = 0;
      local_1ac = 0;
      local_1a8 = 0;
      while (local_1a8 < 4) {
        local_1b0 = local_1b0 + (int)__s[(long)local_1a8 + (long)(local_1b4 << 2) + 6];
        local_1ac = local_1ac ^ (int)__s[(long)local_1a8 + (long)(local_1b4 << 2) + 6];
        local_1a8 = local_1a8 + 1;
      }
      *(int *)((long)&local_168 + (long)local_1b4 * 4) = local_1b0;
      *(uint *)((long)&local_148 + (long)local_1b4 * 4) = local_1ac;
      local_1b4 = local_1b4 + 1;
    }
    local_128 = 0;
    local_120 = 0;
    local_118 = 0;
    local_110 = 0;
    local_108 = 0;
    local_100 = 0;
    local_f8 = 0;
    local_f0 = 0;
    local_1a4 = 0;
    while (local_1a4 < 8) {
      local_1a0 = 0;
      local_19c = 0;
      local_198 = 0;
      while (local_198 < 4) {
        local_1a0 = local_1a0 + (int)__s[(long)(local_198 << 3) + (long)local_1a4 + 6];
        local_19c = local_19c ^ (int)__s[(long)(local_198 << 3) + (long)local_1a4 + 6];
        local_198 = local_198 + 1;
      }
      *(int *)((long)&local_128 + (long)local_1a4 * 4) = local_1a0;
      *(uint *)((long)&local_108 + (long)local_1a4 * 4) = local_19c;
      local_1a4 = local_1a4 + 1;
    }
    iVar2 = memcmp(&local_168,&DAT_00400f40,0x20);
    if ((iVar2 != 0) || (iVar2 = memcmp(&local_148,&DAT_00400f60,0x20), iVar2 != 0)) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    iVar2 = memcmp(&local_128,&DAT_00400fa0,0x20);
    if ((iVar2 != 0) || (iVar2 = memcmp(&local_108,&DAT_00400f80,0x20), iVar2 != 0)) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    lVar6 = 0x10;
    puVar7 = local_a8;
    while (lVar6 != 0) {
      lVar6 = lVar6 + -1;
      *puVar7 = 0;
      puVar7 = puVar7 + (ulong)bVar8 * 0x1ffffffffffffffe + 1;
    }
    local_194 = 0;
    while (local_194 < 0x20) {
      cVar1 = __s[(long)local_194 + 6];
      if ((cVar1 < '0') || ('9' < cVar1)) {
        if ((cVar1 < 'a') || ('f' < cVar1)) {
          *(undefined4 *)((long)local_a8 + (long)local_194 * 4) = 0;
        }
        else {
          *(undefined4 *)((long)local_a8 + (long)local_194 * 4) = 0x80;
        }
      }
      else {
        *(undefined4 *)((long)local_a8 + (long)local_194 * 4) = 0xff;
      }
      local_194 = local_194 + 1;
    }
    iVar2 = memcmp(local_a8,&DAT_00400fc0,0x80);
    if (iVar2 != 0) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    local_190 = 0;
    local_18c = 0;
    while (local_18c < 0x10) {
      local_190 = local_190 + (int)__s[(long)((local_18c + 3) * 2)];
      local_18c = local_18c + 1;
    }
    if (local_190 != 0x488) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    if ((((__s[0x25] != '5') || (__s[7] != 'f')) || (__s[0xb] != '8')) ||
       (((__s[0xc] != '7' || (__s[0x17] != '2')) || (__s[0x1f] != '4')))) {
      puts("incorrect");
                    /* WARNING: Subroutine does not return */
      exit(0);
    }
    printf("Correct: %s\n",__s);
    uVar3 = 0;
  }
  else {
    fwrite("./bin flag_is_here",1,0x12,stderr);
    uVar3 = 1;
  }
  if (local_10 == *(long *)(in_FS_OFFSET + 0x28)) {
    return uVar3;
  }
                    /* WARNING: Subroutine does not return */
  __stack_chk_fail();
}

これを気合で解読すると以下の処理を行っていることが分かります.

  • 文字列長の確認 (0x27文字)
  • flagフォーマットの確認 (TWCTF{*f***87**********2*******4*****5})
  • 0123456789abcdefの出現回数の確認 ([3, 2, 2, 0, 3, 2, 1, 3, 3, 1, 1, 3, 1, 2, 2, 3])
  • 7文字目以降から4文字区切りで総和をとって確認 ([0x15e, 0xda, 0x12f, 0x131, 0x100, 0x131, 0xfb, 0x102])
  • 7文字目以降から4文字区切りで総XORをとって確認 ([0x52, 0x0c, 0x01, 0x0f, 0x5c, 0x05, 0x53, 0x58])
  • 7文字目以降から8文字飛ばしで4文字毎に総和をとって確認 ([0x129, 0x103, 0x12b, 0x131, 0x135, 0x10b, 0xff, 0xff])
  • 7文字目以降から8文字飛ばしで4文字毎に総XORをとって確認 ([0x01, 0x57, 0x07, 0x0d, 0x0d, 0x53, 0x51, 0x51])
  • 7文字目以降から1文字飛ばしで総和をとって確認 (0x488)
  • 7文字目以降が[a-f]または[0-9]のどちらに含まれるか確認 ([a-f] -> 0x80, [0-9] -> 0xff, [0x80, 0x80, 0xff, 0x80, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0x80, 0x80, 0xff, 0xff, 0x80, 0xff, 0xff, 0x80, 0xff, 0x80, 0x80, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0xff, 0x80, 0xff])

あとはこれらの制約条件に基づいて全探索すれば解けます.

# flag = 'TWCTF{*f***87**********2*******4*****5}'
flag = '*f***87**********2*******4*****5'

appearance = [3, 2, 2, 0, 3, 2, 1, 3, 3, 1, 1, 3, 1, 2, 2, 3]
main_constraint =[0x80, 0x80, 0xff, 0x80, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0x80, 0x80, 0xff, 0xff, 0x80, 0xff, 0xff, 0x80, 0xff, 0x80, 0x80, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0xff, 0x80, 0xff]
plus_constraint1 = [0x15e, 0xda, 0x12f, 0x131, 0x100, 0x131, 0xfb, 0x102]
xor_constraint1 = [0x52, 0x0c, 0x01, 0x0f, 0x5c, 0x05, 0x53, 0x58]
plus_constraint2 = [0x129, 0x103, 0x12b, 0x131, 0x135, 0x10b, 0xff, 0xff]
xor_constraint2 = [0x01, 0x57, 0x07, 0x0d, 0x0d, 0x53, 0x51, 0x51]

def flag_check(flag):
    total = 0
    for i in range(0x10):
        total += ord(flag[i * 2])
    if total != 0x488:
        return False

    for i in range(8):
        plus_check = 0
        xor_check = 0
        for j in range(i,32,8):
            plus_check += ord(flag[j])
            xor_check ^= ord(flag[j])
        if plus_constraint2[i] != plus_check or xor_constraint2[i] != xor_check:
            return False
    return True

def appearance_check(flag):
    for i,c in enumerate('0123456789abcdef'):
        if flag.count(c) > appearance[i]:
            return False
    return True

def candidates_search(s, d, base):
    if d == 4:
        plus_check = 0
        xor_check = 0
        for c in s:
            plus_check += ord(c)
            xor_check ^= ord(c)
        if plus_constraint1[base // 4] == plus_check and xor_constraint1[base // 4] == xor_check:
            yield s
    else:
        if flag[base + d] != '*':
            yield from candidates_search(s + flag[base + d], d + 1, base)
        else:
            if main_constraint[base + d] == 0x80:
                for c in 'abcdef':
                    yield from candidates_search(s + c, d + 1, base)
            else:
                for c in '012456789':
                    yield from candidates_search(s + c, d + 1, base)

def flag_search(s, d, candidates_list):
    if d == 8:
        if flag_check(s):
            yield s
    else:
        for h in candidates_list[d]:
            if appearance_check(s + h):
                yield from flag_search(s + h, d + 1, candidates_list)

candidates_list = []
for base in range(0,32,4):
    x = []
    for candidate in candidates_search('', 0, base):
        x.append(candidate)
    candidates_list.append(x)

print('TWCTF{{{}}}'.format(next(flag_search('', 0, candidates_list))))
> python solve.py
TWCTF{df2b4877e71bd91c02f8ef6004b584a5}

TWCTF{df2b4877e71bd91c02f8ef6004b584a5}

動けばいいやと思って書いてるので必然的にクソコードになる

Simple Logic [Crypto, 95pts, 167solved]

Simple cipher is always strong.

encrypt.rb

require 'securerandom'
require 'openssl'

ROUNDS = 765
BITS = 128
PAIRS = 6

def encrypt(msg, key)
    enc = msg
    mask = (1 << BITS) - 1
    ROUNDS.times do
        enc = (enc + key) & mask
        enc = enc ^ key
    end
    enc
end

def decrypt(msg, key)
    enc = msg
    mask = (1 << BITS) - 1
    ROUNDS.times do
        enc = enc ^ key
        enc = (enc - key) & mask
    end
    enc
end

fail unless BITS % 8 == 0

flag = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16)
key = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16)

STDERR.puts "The flag: TWCTF{%x}" % flag
STDERR.puts "Key=%x" % key
STDOUT.puts "Encrypted flag: %x" % encrypt(flag, key)
fail unless decrypt(encrypt(flag, key), key) == flag # Decryption Check

PAIRS.times do |i|
    plain = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16)
    enc = encrypt(plain, key)
    STDOUT.puts "Pair %d: plain=%x enc=%x" % [-~i, plain, enc]
end

output

Encrypted flag: 43713622de24d04b9c05395bb753d437
Pair 1: plain=29abc13947b5373b86a1dc1d423807a enc=b36b6b62a7e685bd1158744662c5d04a
Pair 2: plain=eeb83b72d3336a80a853bf9c61d6f254 enc=614d86b5b6653cdc8f33368c41e99254
Pair 3: plain=7a0e5ffc7208f978b81475201fbeb3a0 enc=292a7ff7f12b4e21db00e593246be5a0
Pair 4: plain=c464714f5cdce458f32608f8b5e2002e enc=64f930da37d494c634fa22a609342ffe
Pair 5: plain=f944aaccf6779a65e8ba74795da3c41d enc=aa3825e62d053fb0eb8e7e2621dabfe7
Pair 6: plain=552682756304d662fa18e624b09b2ac5 enc=f2ffdf4beb933681844c70190ecf60bf

アプローチ:keyを下位bitから求めていく

encrypt.rbの本質的な暗号化処理は以下のようになります.

enc = (enc + key) & mask
enc = enc ^ key

一見シンプルな暗号化処理ですが,enc + keyの際に発生する繰り上がりがその後のenc ^ keyに影響を与えてしまうため,keyの特定が難しくなっているように見て取れます.
しかし,ネックになっているのが繰り上がりなのであれば繰り上がりが発生しない最下位bitからkeyを徐々に確定していくことでkeyの特定が可能になると考えられます.
そこで,outputとして与えられたPair1~6plainの下位1byteを暗号化した際にencの下位1byteと一致するようなkeyを求め,そこから徐々にkeyを確定させていくソルバを書きました.

ROUNDS = 765

def encrypt(msg, key, mask):
    enc = msg
    for _ in range(ROUNDS):
        enc = (enc + key) & mask
        enc = enc ^ key

    return enc

def decrypt(msg, key):
    enc = msg
    mask = (1 << 128) - 1
    for _ in range(ROUNDS):
        enc = enc ^ key
        enc = (enc - key) & mask

    return enc

enc_flag = 0x43713622de24d04b9c05395bb753d437
msgs = [0x29abc13947b5373b86a1dc1d423807a ,0xeeb83b72d3336a80a853bf9c61d6f254,0x7a0e5ffc7208f978b81475201fbeb3a0,0xc464714f5cdce458f32608f8b5e2002e,0xf944aaccf6779a65e8ba74795da3c41d,0x552682756304d662fa18e624b09b2ac5]
encs = [0xb36b6b62a7e685bd1158744662c5d04a,0x614d86b5b6653cdc8f33368c41e99254,0x292a7ff7f12b4e21db00e593246be5a0,0x64f930da37d494c634fa22a609342ffe,0xaa3825e62d053fb0eb8e7e2621dabfe7,0xf2ffdf4beb933681844c70190ecf60bf]

fixed_keys = [0x09] # Brute-force search in advance
for bits in range(16,136,8):
    print('BITS: {}'.format(bits))
    fixed_bits = bits - 8
    mask = (1 << bits) - 1
    keys = []
    print('fixed_keys: {}'.format(list(map(hex,fixed_keys))))
    for fixed_key in fixed_keys:
        for x in range(0,256):
            check = True
            for i in range(6):
                enc = encrypt(msgs[i] & mask, (x << fixed_bits) + fixed_key, mask)
                if  enc != (encs[i] & mask):
                    check = False
            if check:
                keys.append((x << fixed_bits) + fixed_key)
    fixed_keys = keys

for key in fixed_keys:
    dec = decrypt(enc_flag, key)
    print('TWCTF{{{}}}'.format(hex(dec)[2:]))
> python solve.py
BITS: 16
fixed_keys: ['0x9']
BITS: 24
fixed_keys: ['0x5509', '0xd509']
BITS: 32
fixed_keys: ['0x73d509', '0xf3d509']
BITS: 40
fixed_keys: ['0x7773d509', '0xf773d509']
BITS: 48
fixed_keys: ['0x3e7773d509', '0xbe7773d509']
BITS: 56
fixed_keys: ['0x153e7773d509', '0x953e7773d509']
BITS: 64
fixed_keys: ['0x3a153e7773d509', '0xba153e7773d509']
BITS: 72
fixed_keys: ['0x29ba153e7773d509', '0xa9ba153e7773d509']
BITS: 80
fixed_keys: ['0x57a9ba153e7773d509', '0xd7a9ba153e7773d509']
BITS: 88
fixed_keys: ['0x4957a9ba153e7773d509', '0xc957a9ba153e7773d509']
BITS: 96
fixed_keys: ['0x494957a9ba153e7773d509', '0xc94957a9ba153e7773d509']
BITS: 104
fixed_keys: ['0x5c494957a9ba153e7773d509', '0xdc494957a9ba153e7773d509']
BITS: 112
fixed_keys: ['0x6bdc494957a9ba153e7773d509', '0xebdc494957a9ba153e7773d509']
BITS: 120
fixed_keys: ['0x1aebdc494957a9ba153e7773d509', '0x9aebdc494957a9ba153e7773d509']
BITS: 128
fixed_keys: ['0x521aebdc494957a9ba153e7773d509', '0xd21aebdc494957a9ba153e7773d509']
TWCTF{ade4850ad48b8d21fa7dae86b842466d}

TWCTF{ade4850ad48b8d21fa7dae86b842466d}

まとめ

  • Crypto, Revの簡単な問題は徐々に解けるようになってきた気がする
  • Web, Pwnはチームメイトに任せっぱなしで問題すら見てないのでwrite-up読んで勉強します
  • Happy!meow を解きたかった…

InterKosenCTF Write-up

はじめに

2019/08/11 ~ 2019/08/12に開催されたInterKosenCTFに個人で参加しました.

成績

チーム単位だと18位(91チーム中)でした.

個人だと9位だったみたいです .

f:id:satto1237:20190813170159p:plain

Welcome

Welcome [warmup, 200pts, 77solved]

Join in our slack and get the flag!

アプローチ:Slackにjoinする

KosenCTF{g3t_r34dy_f0r_InterKosenCTF_2019}

Web

uploader [warmup, 227pts, 34solved]

UPLOADER

f:id:satto1237:20190813170948p:plain

アプローチ:searchでSQLi

Webサイトの特徴をまとめると以下のようになります.

  • ファイルアップロード機能を有する
  • ファイルアップロード時にはダウンロード用パスワードの入力が必須
  • キーワードによるアップロード済みファイルの検索機能を有する
  • 既にsecret_fileがアップロード済み

これらの特徴からsecret_fileのダウンロードパスワードを入手すればflagを獲得できると考えられます.

次に検索関連の処理を行っているコードを見てみます.

$files = [];
// search
if (isset($_GET['search'])) {
    $rows = $db->query("SELECT name FROM files WHERE instr(name, '{$_GET['search']}') ORDER BY id DESC");
    foreach ($rows as $row) {
        $files []= $row[0];
    }
}

instr(name, '{$_GET['search']}')SQLiできそうですね.

') UNION SELECT passcode FROM files -- を検索キーワードとして入力することで以下のようなクエリが生成されます.
SELECT name FROM files WHERE instr(name, '') UNION SELECT passcode FROM files -- ORDER BY id DESC
このクエリでファイル名と共にダウンロードパスワードを表示させます.

f:id:satto1237:20190813172913p:plain

the_longer_the_stronger_than_more_complicatedsecret_file のダウンロードパスワードのようです.

secret_fileを開くとflagが書かれていました.

KosenCTF{y0u_sh0u1d_us3_th3_p1ac3h01d3r}

Forensics

Hugtto! [easy, 238pts, 32solved]

Wow! It's random!

steg.py

from PIL import Image
from secret import flag
from datetime import datetime
import tarfile
import sys

import random

random.seed(int(datetime.now().timestamp()))

bin_flag = []
for c in flag:
    for i in range(8):
        bin_flag.append((ord(c) >> i) & 1)

img = Image.open("./emiru.png")
new_img = Image.new("RGB", img.size)

w, h = img.size

i = 0
for x in range(w):
    for y in range(h):
        r, g, b = img.getpixel((x, y))
        rnd = random.randint(0, 2)
        if rnd == 0:
            r = (r & 0xFE) | bin_flag[i % len(bin_flag)]
            new_img.putpixel((x, y), (r, g, b))
        elif rnd == 1:
            g = (g & 0xFE) | bin_flag[i % len(bin_flag)]
            new_img.putpixel((x, y), (r, g, b))
        elif rnd == 2:
            b = (b & 0xFE) | bin_flag[i % len(bin_flag)]
            new_img.putpixel((x, y), (r, g, b))
        i += 1

new_img.save("./steg_emiru.png")
with tarfile.open("stegano.tar.gz", "w:gz") as tar:
    tar.add("./steg_emiru.png")
    tar.add(sys.argv[0])

steg_emiru.png

> file steg_emiru.png
steg_emiru.png: PNG image data, 766 x 1021, 8-bit/color RGB, non-interlaced

アプローチ:seed + exif

steg.pyではflagを1bitずつemiry.pngに埋め込む処理を行っており,この際,乱数によって埋め込み先を決定しています(R, G, Bのいずれかの最下位ビット)
そのため,全探索でflagを得るにはpow(3, len(flag))回の試行が必要になり,現実的な時間での探索は難しいと考えられます(そもそもflag長が分からないので無理).
そこで,全探索は諦めて乱数生成のシードに注目します. コードを確認するとシード値としてint(datetime.now().timestamp())が与えられていることが分かります.
シード値を得ることができれば生成される乱数を再現することができるので関連ファイルのexif情報を確認してみます.

> exiftool steg_emiru.png
ExifTool Version Number         : 11.29
File Name                       : steg_emiru.png
Directory                       : .
File Size                       : 1315 kB
File Modification Date/Time     : 2019:08:06 11:44:18+09:00
File Access Date/Time           : 2019:08:13 18:40:48+09:00
File Inode Change Date/Time     : 2019:08:11 17:32:37+09:00
File Permissions                : rw-r--r--
File Type                       : PNG
File Type Extension             : png
MIME Type                       : image/png
Image Width                     : 766
Image Height                    : 1021
Bit Depth                       : 8
Color Type                      : RGB
Compression                     : Deflate/Inflate
Filter                          : Adaptive
Interlace                       : Noninterlaced
Image Size                      : 766x1021
Megapixels                      : 0.782

2019:08:06 11:44:18+09:00にファイルが編集されたことが確認できます.つまり,2019:08:06 11:44:18+09:00周辺のDate/Timetimestamp()によって乱数生成を再現できます.

ソルバは以下のようになります.

from PIL import Image
from datetime import datetime
import random
from Crypto.Util.number import *

# datetime(2019, 8, 6, 11, 44, 18)
random.seed(int(datetime(2019, 8, 6, 11, 44, 15).timestamp()))

img = Image.open("./steg_emiru.png")
new_img = Image.new("RGB", img.size)

w, h = img.size
msg = ''

for x in range(w):
    for y in range(h):
        r, g, b = img.getpixel((x, y))
        rnd = random.randint(0, 2)
        if rnd == 0:
            msg += str(r & 0x1)
        elif rnd == 1:
            msg += str(g & 0x1)
        elif rnd == 2:
            msg += str(b & 0x1)

flag = long_to_bytes(int(msg[::-1],2)).decode('utf-8')
print(flag[::-1][:68])
> python solve.py
KosenCTF{Her_name_is_EMIRU_AISAKI_who_is_appeared_in_Hugtto!PreCure}

KosenCTF{Her_name_is_EMIRU_AISAKI_who_is_appeared_in_Hugtto!PreCure}

Temple of Time [medium, 285pts, 25solved]

We released our voting system and it's under attack. Can you investigate if the admin credential is stolen?

40142c592afd88a78682234e2d5cada9.pcapng

> file 40142c592afd88a78682234e2d5cada9.pcapng
40142c592afd88a78682234e2d5cada9.pcapng: pcap-ng capture file - version 1.0

アプローチ:Blind SQLiのログをいい感じに処理する

pcapngなのでWireSharkで開きます.

f:id:satto1237:20190813211953p:plain

怪しいリクエストが流れてますね.

GETリクエストをデコードすると以下のようになります.

GET /index.php?portal='OR(SELECT(IF(ORD(SUBSTR((SELECT password FROM Users WHERE username='admin'),1,1))=48,SLEEP(1),'')))

Time-Based Blind SQLiですね.

1つずつリクエストを見ていけばflagを復元できると思いますが,面倒くさいのでPythonにやらせます.

> strings 40142c592afd88a78682234e2d5cada9.pcapng | grep GET > grep_get.txt
> head -n 3 grep_get.txt
x<nGET /index.php?portal=%27OR%28SELECT%28IF%28ORD%28SUBSTR%28%28SELECT+password+FROM+Users+WHERE+username%3D%27admin%27%29%2C1%2C1%29%29%3D48%2CSLEEP%281%29%2C%27%27%29%29%29%23 HTTP/1.1
GET /index.php?portal=%27OR%28SELECT%28IF%28ORD%28SUBSTR%28%28SELECT+password+FROM+Users+WHERE+username%3D%27admin%27%29%2C1%2C1%29%29%3D49%2CSLEEP%281%29%2C%27%27%29%29%29%23 HTTP/1.1
GET /index.php?portal=%27OR%28SELECT%28IF%28ORD%28SUBSTR%28%28SELECT+password+FROM+Users+WHERE+username%3D%27admin%27%29%2C1%2C1%29%29%3D50%2CSLEEP%281%29%2C%27%27%29%29%29%23 HTTP/1.1
import urllib.parse

# EXAMPLE
# GET /index.php?portal='OR(SELECT(IF(ORD(SUBSTR((SELECT+password+FROM+Users+WHERE+username='admin'),37,1))=126,SLEEP(1),'')))# HTTP/1.1

# ASCII
# lines[i].split('=')[3].split(',')[0]
# 126

# COUNT
# lines[i].split('=')[2].split(',')[1]
# 37

with open('grep_get.txt') as f:
    lines = [urllib.parse.unquote(line.strip()) for line in f.readlines()]

attack_query = []
flag = ''

for line in lines:
    if len(line.split('=')) == 4:
        count = line.split('=')[2].split(',')[1]
        ascii = line.split('=')[3].split(',')[0]
        attack_query.append([count,ascii])

prev_query = attack_query[0]
for current_query in attack_query:
    if prev_query[0] != current_query[0]:
        flag += chr(int(prev_query[1],10))
    prev_query = current_query

print(flag)

countが増えたら攻撃が成功したということなのでcountが増える直前のクエリのasciiを集めています.

> python solve.py
KosenCTF{t1m3_b4s3d_4tt4ck_v31ls_1t}

KosenCTF{t1m3_b4s3d_4tt4ck_v31ls_1t}

Reversing

basic crackme [easy, 227pts, 34solved]

Crackme is a challenge to get the input which satisfies the constraints.

> file crackme 
crackme: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, BuildID[sha1]=3dca344245681e2c75d9588284830d858770c1e0, for GNU/Linux 3.2.0, not stripped
> ./crackme 
<usage> ./crackme: <flag>
> ./crackme CawaYui
Try harder!

アプローチ:Ghidraでデコンパイル

main関数をGhidraでデコンパイルすると以下のようになります.

undefined8 main(int iParm1,undefined8 *puParm2)

{
  size_t sVar1;
  long in_FS_OFFSET;
  uint local_d0;
  int local_cc;
  int local_c8 [4];
  undefined4 local_b8;
  undefined4 local_b4;
  undefined4 local_b0;
  undefined4 local_ac;
  undefined4 local_a8;
  undefined4 local_a4;
  undefined4 local_a0;
  undefined4 local_9c;
  undefined4 local_98;
  undefined4 local_94;
  undefined4 local_90;
  undefined4 local_8c;
  undefined4 local_88;
  undefined4 local_84;
  undefined4 local_80;
  undefined4 local_7c;
  undefined4 local_78;
  undefined4 local_74;
  undefined4 local_70;
  undefined4 local_6c;
  undefined4 local_68;
  undefined4 local_64;
  undefined4 local_60;
  undefined4 local_5c;
  undefined4 local_58;
  undefined4 local_54;
  undefined4 local_50;
  undefined4 local_4c;
  undefined4 local_48;
  undefined4 local_44;
  undefined4 local_40;
  undefined4 local_3c;
  undefined4 local_38;
  undefined4 local_34;
  undefined4 local_30;
  long local_20;
  
  local_20 = *(long *)(in_FS_OFFSET + 0x28);
  if (iParm1 < 2) {
    printf("<usage> %s: <flag>\n",*puParm2);
  }
  else {
    local_c8[0] = 0xb4;
    local_c8[1] = 0xf7;
    local_c8[2] = 0x39;
    local_c8[3] = 0x59;
    local_b8 = 0xea;
    local_b4 = 0x39;
    local_b0 = 0x4b;
    local_ac = 0x6b;
    local_a8 = 0xbf;
    local_a4 = 0x80;
    local_a0 = 0x3d;
    local_9c = 0xd1;
    local_98 = 0x42;
    local_94 = 0x10;
    local_90 = 0xe4;
    local_8c = 0x42;
    local_88 = 0x105;
    local_84 = 0x58;
    local_80 = 0x15;
    local_7c = 0x108;
    local_78 = 0xab;
    local_74 = 0x18;
    local_70 = 0xe8;
    local_6c = 0xcd;
    local_68 = 0x1b;
    local_64 = 0xeb;
    local_60 = 0x51;
    local_5c = 0x1e;
    local_58 = 0x111;
    local_54 = 0x44;
    local_50 = 0x51;
    local_4c = 0x86;
    local_48 = 0x53;
    local_44 = 0x48;
    local_40 = 0x59;
    local_3c = 0x36;
    local_38 = 0x10a;
    local_34 = 0x9b;
    local_30 = 0xfd;
    local_d0 = 0;
    local_cc = 0;
    while (sVar1 = strlen((char *)puParm2[1]), (ulong)(long)local_cc < sVar1) {
      local_d0 = local_d0 |
                 ((((int)*(char *)((long)local_cc + puParm2[1]) & 0xfU) << 4 |
                  (int)(*(char *)((long)local_cc + puParm2[1]) >> 4)) + local_cc) -
                 local_c8[(long)local_cc];
      local_cc = local_cc + 1;
    }
    if (local_d0 == 0) {
      puts("Yes. This is the your flag :)");
    }
    else {
      printf("Try harder!");
    }
  }
  if (local_20 == *(long *)(in_FS_OFFSET + 0x28)) {
    return 0;
  }
                    /* WARNING: Subroutine does not return */
  __stack_chk_fail();
}

ざっくりまとめると

((((int)*(char *)((long)local_cc + puParm2[1]) & 0xfU) << 4 | (int)(*(char *)((long)local_cc + puParm2[1]) >> 4)) + local_cc) - local_c8[(long)local_cc];

が0になれば条件を満たすようです.

そのため,条件を満たす文字列を全探索することでflagを得ることができます.
ソルバは以下のようになります.

import string

xs = [0xb4,0xf7,0x39,0x59,0xea,0x39,0x4b,0x6b,0xbf,0x80,0x3d,0xd1,0x42,0x10,0xe4,0x42,0x105,0x58,0x15,0x108,0xab,0x18,0xe8,0xcd,0x1b,0xeb,0x51,0x1e,0x111,0x44,0x51,0x86,0x53,0x48,0x59,0x36,0x10a,0x9b,0xfd]
flag = ''
for i,x in enumerate(xs):
    for s in string.ascii_letters + string.digits + '_-!?#{}':
        check = (((ord(s) & 0xf) << 4) | (ord(s) >> 4)) + i - x
        if check == 0:
            flag += s
            break
print(flag)
> python solve.py
KosenCTF{w3lc0m3_t0_y0-k0-s0_r3v3rs1ng}

KosenCTF{w3lc0m3_t0_y0-k0-s0_r3v3rs1ng}

magic function[easy, 263pts, 28solved]

Rumor has it that three simple functions may generate the flag.

> file chall 
chall: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=7f3589666f4eca86aca6d787459c5ae93987bb59, not stripped
> ./chall CawaYui
NG

アプローチ:Ghidraでデコンパイル

main関数をGhidraでデコンパイルすると以下のようになります.

undefined8 main(int iParm1,long lParm2)

{
  char cVar1;
  char cVar2;
  char *local_28;
  int local_1c;
  
  if (1 < iParm1) {
    local_1c = 0;
    local_28 = *(char **)(lParm2 + 8);
    while (*local_28 != 0) {
      if (local_1c < 8) {
        cVar1 = *local_28;
        cVar2 = f1();
        if (cVar1 != cVar2) goto LAB_0040087d;
      }
      else {
        if (local_1c < 0x10) {
          cVar1 = *local_28;
          cVar2 = f2();
          if (cVar1 != cVar2) goto LAB_0040087d;
        }
        else {
          cVar1 = *local_28;
          cVar2 = f3((ulong)(local_1c - 0x10));
          if (cVar1 != cVar2) goto LAB_0040087d;
        }
      }
      local_28 = local_28 + 1;
      local_1c = local_1c + 1;
    }
    if (local_1c == 0x18) {
      puts("OK");
      return 0;
    }
  }
LAB_0040087d:
  puts("NG");
  return 1;
}

次にf1()を見ていきます.

undefined8 f1(uint uParm1)

{
  undefined4 extraout_var;
  double __x;
  undefined8 local_48;
  undefined8 local_40;
  undefined8 local_38;
  undefined8 local_30;
  undefined8 local_28;
  undefined8 local_20;
  undefined8 local_18;
  undefined8 local_10;
  
  local_48 = 0x4052c00000000000;
  local_40 = 0xc06af763f572de44;
  local_38 = 0x40834ab05af6c69b;
  local_30 = 0xc0814416c15d2d02;
  local_28 = 0x406cf98e38a7e73a;
  local_20 = 0xc0490416c10ca52a;
  local_18 = 0x4015760b60dc38d1;
  local_10 = 0xbfcced4ed3decb0d;
  __x = (double)f((ulong)uParm1,&local_48,&local_48);
  __x = round(__x);
  return CONCAT44(extraout_var,(int)__x);
}

f1()内のlocal_48 - local_10浮動小数点数の内部表現だと考えられます.

次にf()の処理を確認します.

undefined  [16] f(int iParm1,long lParm2)

{
  double dVar1;
  double dVar2;
  double local_18;
  int local_c;
  
  local_18 = 0.00000000;
  local_c = 0;
  while (local_c < 8) {
    dVar1 = *(double *)(lParm2 + (long)local_c * 8);
    dVar2 = pow((double)iParm1,(double)local_c);
    local_18 = dVar2 * dVar1 + local_18;
    local_c = local_c + 1;
  }
  return ZEXT816((ulong)local_18);
}

どうやらf()はASCIIを返しているようです.
また,f2(), f3()も同様の処理を行っているのでソルバを書いて出力結果を確認してみます.

from Crypto.Util.number import *
import binascii
import struct

def f(p1, p2):
    ret = 0
    count = 0

    while count < 8:
        v1 = struct.unpack('>d', binascii.unhexlify(hex(p2[count])[2:]))[0]
        v2 = pow(p1, count)
        ret += v1 * v2
        count += 1

    return ret

def f1(p1):
    magic = [0x4052c00000000000,0xc06af763f572de44,0x40834ab05af6c69b,0xc0814416c15d2d02,0x406cf98e38a7e73a,0xc0490416c10ca52a,0x4015760b60dc38d1,0xbfcced4ed3decb0d]
    x = f(p1,magic)
    return chr(round(x))

def f2(p1):
      magic = [0x405ec00000000000,0xc086c40000000000,0x40988d360bf5d788,0xc093cb182d38476f,0x407ed11c714fce74,0xc058f471c6ecb8fb,0x4024416c17804f46,0xbfda0b60b59135b7]
      x = f(p1,magic)
      return chr(round(x))
def f3(p1):
      magic = [0x405c000000000000,0xc081178af89c5e70,0x408e8cddddb1209f,0xc0867196c15d2d02,0x40712d5554fbdad7,0xc04c8d27d2ace09e,0x40183bbbbb827794,0xbfd05e45e4187677]
      x = f(p1,magic)
      return chr(round(x))

print(''.join(list(map(f1,range(8)))))
print(''.join(list(map(f2,range(8)))))
print(''.join(list(map(f3,range(8)))))
> python solve.py
KosenCTF
{fl4ggy_
p0lyn0m}

KosenCTF{fl4ggy_p0lyn0m}

favorites[hard, 357pts, 18solved]

What is your favorite? My favorite is ...

 file favorites 
favorites: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, BuildID[sha1]=04682a5ac5fd6fb11c8f04408891974576f47ce1, for GNU/Linux 3.2.0, not stripped
./favorites 
Do you know
 --- the FLAG of this challenge?
 --- my favorite anime?
 --- my favorite character?

Input your guess: CawaYui
No! You are not interested in me, are you?

Ghidraでデコンパイル

flagよりも好きなアニメとキャラクターが気になりますね.

ltraceでライブラリ関数の呼び出しをトレースしてみます.

> ltrace -s 100 ./favorites 
puts("Do you know"Do you know
)                                                  = 12
puts(" --- the FLAG of this challenge?" --- the FLAG of this challenge?
)                             = 33
puts(" --- my favorite anime?" --- my favorite anime?
)                                      = 24
puts(" --- my favorite character?" --- my favorite character?
)                                  = 28
putchar(10, 0x56435dfff260, 0x7fd756e058c0, 0x7fd756b28154
)          = 10
printf("Input your guess: ")                                         = 18
__isoc99_scanf(0x56435c904138, 0x7fffddea1531, 0, 0Input your guess: CawaYui
)                 = 1
sprintf("62c5", "%04x", 0x62c5)                                      = 4
sprintf("7af7", "%04x", 0x7af7)                                      = 4
sprintf("d8a8", "%04x", 0xd8a8)                                      = 4
sprintf("07d7", "%04x", 0x7d7)                                       = 4
sprintf("0d26", "%04x", 0xd26)                                       = 4
sprintf("b2f8", "%04x", 0xb2f8)                                      = 4
sprintf("a407", "%04x", 0xa407)                                      = 4
sprintf("3a81", "%04x", 0x3a81)                                      = 4
sprintf("bb1c", "%04x", 0xbb1c)                                      = 4
sprintf("7a6f", "%04x", 0x7a6f)                                      = 4
sprintf("5136", "%04x", 0x5136)                                      = 4
sprintf("763e", "%04x", 0x763e)                                      = 4
sprintf("84c8", "%04x", 0x84c8)                                      = 4
sprintf("c421", "%04x", 0xc421)                                      = 4
strcmp("62c57af7d8a807d70d26b2f8a4073a81bb1c7a6f5136763e84c8c421", "62d57b27c5d411c45d67a3565f84bd67ad049a64efa694d624340178") = -1
strcmp("62c57af7d8a807d70d26b2f8a4073a81bb1c7a6f5136763e84c8c421", "62b64d65828570c33b25e1e54065524571a54d7583556d76b1767c759036") = 1
strcmp("62c57af7d8a807d70d26b2f8a4073a81bb1c7a6f5136763e84c8c421", "62c64af7db4839d7eeb3d5363e85bb35e826ec56abd5e7d523956bb5") = -1
puts("No! You are not interested in me, are you?"No! You are not interested in me, are you?
)                   = 43
+++ exited (status 0) +++

入力文字列に対して何らかの変換処理を行い,flag, anime, characterの変換結果と比較しています.
次に変換処理の内容を知るためにmain関数をGhidraでデコンパイルします.

undefined8 main(void)

{
  int iVar1;
  long in_FS_OFFSET;
  ushort local_92;
  uint local_90;
  int local_8c;
  ushort auStack136 [16];
  byte local_67 [14];
  undefined local_59;
  undefined8 local_58;
  undefined8 local_50;
  undefined8 local_48;
  undefined8 local_40;
  undefined8 local_38;
  undefined8 local_30;
  undefined8 local_28;
  undefined local_20;
  long local_10;
  
  local_10 = *(long *)(in_FS_OFFSET + 0x28);
  local_92 = 0x1234;
  puts("Do you know");
  puts(" --- the FLAG of this challenge?");
  puts(" --- my favorite anime?");
  puts(" --- my favorite character?");
  putchar(10);
  printf("Input your guess: ");
  __isoc99_scanf(&DAT_00102138,local_67);
  local_59 = 0;
  local_90 = 0;
  while ((int)local_90 < 0xe) {
    local_92 = f((ulong)local_67[(long)(int)local_90],(ulong)local_90,(ulong)local_92,
                 (ulong)local_90);
    auStack136[(long)(int)local_90] = local_92;
    local_90 = local_90 + 1;
  }
  local_58 = 0;
  local_50 = 0;
  local_48 = 0;
  local_40 = 0;
  local_38 = 0;
  local_30 = 0;
  local_28 = 0;
  local_20 = 0;
  local_8c = 0;
  while (local_8c < 0xe) {
    sprintf((char *)((long)&local_58 + (long)(local_8c << 2)),"%04x",
            (ulong)auStack136[(long)local_8c]);
    local_8c = local_8c + 1;
  }
  iVar1 = strcmp((char *)&local_58,first);
  if (iVar1 == 0) {
    printf("Congrats! The flag is KosenCTF{%s}!\n",local_67);
  }
  else {
    iVar1 = strcmp((char *)&local_58,second);
    if (iVar1 == 0) {
      puts("Wow! Let\'s see it together now!");
    }
    else {
      iVar1 = strcmp((char *)&local_58,third);
      if (iVar1 == 0) {
        puts("Yes! Do you like too this?");
      }
      else {
        puts("No! You are not interested in me, are you?");
      }
    }
  }
  if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
                    /* WARNING: Subroutine does not return */
    __stack_chk_fail();
  }
  return 0;
}

main関数では変換処理を行っているf()に文字,index, stateを引数として渡しています.

ulong f(byte bParm1,uint uParm2,ushort uParm3)

{
  return (ulong)(ushort)(((ushort)(bParm1 >> 4) | (ushort)(((ulong)bParm1 & 0xf) << 4)) + 1 ^
                         ((ushort)(uParm2 >> 4) | (ushort)(~uParm2 << 4)) & 0xff |
                        (uParm3 >> 4) << 8 ^
                        (ushort)(((uint)(uParm3 >> 0xc) | (uint)uParm3 << 4) << 8));
}

変換処理の内容が分かったのでflagを全探索します.
以下がソルバです.

#include <stdio.h>

int f(char bParm1, unsigned int uParm2, unsigned short uParm3) {
  return (long)(unsigned short)(((unsigned short)(bParm1 >> 4) | (unsigned short)(((long)bParm1 & 0xf) << 4)) + 1 ^ ((unsigned short)(uParm2 >> 4) | (unsigned short)(~uParm2 << 4)) & 0xff | (uParm3 >> 4) << 8 ^ (unsigned short)(((unsigned int)(uParm3 >> 0xc) | (unsigned int)uParm3 << 4) << 8));
}

int main() {
    int count = 0;
    int state = 0x1234, temp_state;
    int i;
    //flag
    int flag[14] = {0x62d5,0x7b27,0xc5d4,0x11c4,0x5d67,0xa356,0x5f84,0xbd67,0xad04,0x9a64,0xefa6,0x94d6,0x2434,0x0178};
    // anime
    // int flag[15] = {0x62b6,0x4d65,0x8285,0x70c3,0x3b25,0xe1e5,0x4065,0x5245,0x71a5,0x4d75,0x8355,0x6d76,0xb176,0x7c75,0x9036};
    // character
    // int flag[14] = {0x62c6,0x4af7,0xdb48,0x39d7,0xeeb3,0xd536,0x3e85,0xbb35,0xe826,0xec56,0xabd5,0xe7d5,0x2395,0x6bb5};

    while (count < 0xe) {
        for (i = 32; i < 128; i++) {
            temp_state = f(i, count, state);
            if (temp_state == flag[count]) {
                printf("%c", i);
                count++;
                state = temp_state;
            }
        }
    }

    return 0;
}
> ./solve
Bl00m_1n70_Y0u
> ./favorites 
Do you know
 --- the FLAG of this challenge?
 --- my favorite anime?
 --- my favorite character?

Input your guess: Bl00m_1n70_Y0u
Congrats! The flag is KosenCTF{Bl00m_1n70_Y0u}!

KosenCTF{Bl00m_1n70_Y0u}

やがて君になる」,まだ見ていないので今度見てみます.

因みにanimeはTHE IDOLMA@STER, characterはSaya YAKUSHIJIでした.

自分は620646760388b857fe468b25ea07dea86767005885472c38412766d6624572331425132563d30b3833c8bf187a282558d7d700d77d87afb7が好きです.

Crypto

Kurukuru Shuffle [easy, 200pts, 53solved]

Please! My...

shuffle.py

from secret import flag
from random import randrange


def is_prime(N):
    if N % 2 == 0:
        return False
    i = 3
    while i * i < N:
        if N % i == 0:
            return False
        i += 2
    return True


L = len(flag)
assert is_prime(L)

encrypted = list(flag)
k = randrange(1, L)
while True:
    a = randrange(0, L)
    b = randrange(0, L)

    if a != b:
        break

i = k
for _ in range(L):
    s = (i + a) % L
    t = (i + b) % L
    encrypted[s], encrypted[t] = encrypted[t], encrypted[s]
    i = (i + k) % L

encrypted = "".join(encrypted)
print(encrypted)

encrypted

1m__s4sk_s3np41m1r_836lly_cut3_34799u14}1osenCTF{5sKm

アプローチ:全探索

shuffle.pyでは3つのパラメータk, a, bを決定してswap処理を行っています.
3つのパラメータの組み合わせは多く見積もっても533なので全探索が可能です.

以下がソルバになります.

enc = '1m__s4sk_s3np41m1r_836lly_cut3_34799u14}1osenCTF{5sKm'

for k in range(1,53):
    for a in range(53):
        for b in range(53):
            if a == b:
                continue
            encrypted = list(enc)
            i = k
            for _ in range(53):
                s = (i - a) % 53
                t = (i - b) % 53
                encrypted[s], encrypted[t] = encrypted[t], encrypted[s]
                i = (i - k) % 53

            encrypted = "".join(encrypted)

            if encrypted[:9] == 'KosenCTF{' and encrypted[-1] == '}':
                print(encrypted)
                print(k,a,b)
> python solve.py
KosenCTF{5s4m1m1_m4rk_s3np41_1s_s38l9y_cut3_34769l1u}
17 2 15
KosenCTF{5s4m1m1_m4rk_s3np41_1s_s38l9y_cut3_34769l1u}
17 15 2
KosenCTF{us4m1m1_m4sk_s3np41_1s_r34lly_cut3_38769915}
17 21 34
KosenCTF{us4m1m1_m4sk_s3np41_1s_r34lly_cut3_38769915}
17 34 21
KosenCTF{5s4m1m1_m4sk_s3np41_1s_r34l9y_cut3_38769l1u}
17 38 51
KosenCTF{5s4m1m1_m4sk_s3np41_1s_r34l9y_cut3_38769l1u}
17 51 38

grepするとKosenCTF{us4m1m1_m4sk_s3np41_1s_r34lly_cut3_38769915}がそれっぽいことが分かります.

KosenCTF{us4m1m1_m4sk_s3np41_1s_r34lly_cut3_38769915}

Flag Ticket [medium, 400pts, 15solved]

My ticket number for getting the flag is 765876346283. Please check if I can get the flag here.

f:id:satto1237:20190814004019p:plain

f:id:satto1237:20190814003951p:plain

アプローチ:Cookieの改ざん

チケットナンバーを入力してもNot available. I'm sorry.と言われます.

そこで,コードを確認してみます.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Flag Ticket</title>
    <link rel="stylesheet" href="{{ api.static_url('style.css') }}">
  </head>
  <body>
    <div id="app">
      <h1>Your ticket:</h1>
      <div>
        <div style="display: inline-block; width: 100px;">Number: </div>
        <div style="display: inline-block;">{{ data.number }}</div>
      </div>
      <div>
        <div style="display: inline-block; width: 100px;">Flag: </div>
        {% if data.is_hit %}
        <div style="display: inline-block; width: 100px;">{{ flag }}</div>
        {% else %}
        <div style="display: inline-block;">Not available. I'm sorry.</div>
        {% endif %}
      </div>

      <p><a href="/exit">exit</a></p>
    </div>
  </body>
</html>
@api.route("/check")
class Check:
    def on_get(self, req, resp):
        resp.html = api.template("check.html")

    async def on_post(self, req, resp):
        form = await req.media("form")
        number = form.get("number", None)
        try:
            _ = int(number)
        except ValueError:
            resp.text = "ERROR: please input your ticket number"
            return

        data = json.dumps({"is_hit": False, "number": number}).encode()
        data = Padding.pad(data, AES.block_size)
        iv = Random.get_random_bytes(AES.block_size)
        aes = AES.new(key, AES.MODE_CBC, iv)
        resp.cookies["result"] = hexlify(iv + aes.encrypt(data)).decode()

        api.redirect(resp, api.url_for(result))

f:id:satto1237:20190814005715p:plain

is_hittrueになるようにCookieを書き換えてあげればいいことが分かります.

CookieCBCモードを利用したAESで暗号化されているので改ざんは比較的簡単に行なえます.

以下がCookie改ざんスクリプトです.

from Crypto.Util import Padding
from Crypto.Cipher import AES
from Crypto import Random
from binascii import hexlify, unhexlify
import json

# sample_json = '{"is_hit": false, "number": 765876346283}'
# attack_json = '{"is_hit":  true, "number": 765876346283}'
result = 'cef97abbed1b1aea90e9a7826d16e63106617ab01c078b2afa6898f1f0661894f30f6f309f6833dd8e167c66facd6c739f3f219899b4225fe9f1ee729b08daf9'
offset = 11
ba = bytearray(unhexlify(result))
ba[offset] =  ba[offset] ^ ord('f') ^ ord(' ')
ba[offset + 1] =  ba[offset + 1] ^ ord('a') ^ ord('t')
ba[offset + 2] =  ba[offset + 2] ^ ord('l') ^ ord('r')
ba[offset + 3] =  ba[offset + 3] ^ ord('s') ^ ord('u')
# ba[offset + 4] =  ba[offset + 4] ^ ord('e') ^ ord('e')

print(hexlify(ba))
> python solve.py
b'cef97abbed1b1aea90e9a7c47808e03106617ab01c078b2afa6898f1f0661894f30f6f309f6833dd8e167c66facd6c739f3f219899b4225fe9f1ee729b08daf9'

あとはCookieをセットしてページをリロードすればflagを取得できます.

f:id:satto1237:20190814010100p:plain

KosenCTF{padding_orca1e_is_common_sense}

E_S_P [hard, 526pts, 9solved]

ESP stands for Erai-Sugoi-Power.

esp.py

from Crypto.Util.number import *
from secret import flag, yukko
import re

assert re.match(r"^KosenCTF{.+}$", flag)

Nbits = 1024
p = getPrime(Nbits)
q = getPrime(Nbits)
n = p * q
e = 5
c = pow(bytes_to_long((yukko + flag).encode()), e, n)

print("N = {}".format(n))
print("e = {}".format(e))

print("Wow Yukko the ESPer helps you!")
print(yukko + "the length of the flag = {}".format(len(flag)))
print("c = {}".format(c))

out.txt

N = 11854673881335985163635072085250462726008700043680492953159905880499045049107244300920837378010293967634187346804588819510452454716310449345364124188546434429828696164683059829613371961906369413632824692460386596396440796094037982036847106649198539914928384344336740248673132551761630930934635177708846275801812766262866211038764067901005598991645254669383536667044207899696798812651232711727007656913524974796752223388636251060509176811628992340395409667867485276506854748446486284884567941298744325375140225629065871881284670017042580911891049944582878712176067643299536863795670582466013430445062571854275812914317
e = 5
Wow Yukko the ESPer helps you!
Yukko the ESPer: My amazing ESP can help you to get the flag! -----> the length of the flag = 39
c = 4463634440284027456262787412050107955746015405738173339169842084094411947848024686618605435207920428398544523395749856128886621999609050969517923590260498735658605434612437570340238503179473934990935761387562516430309061482070214173153260521746487974982738771243619694317033056927553253615957773428298050465636465111581387005937843088303377810901324355859871291148445415087062981636966504953157489531400811741347386262410364012023870718810153108997879632008454853198551879739602978644245278315624539189505388294856981934616914835545783613517326663771942178964492093094767168721842335827464550361019195804098479315147

アプローチ:Coppersmith's Attack (Stereotyped Messages)

超能力アイドルが平文の上位bitと文字列長を教えてくれました.
そのため,Coppersmith's Attack (Stereotyped Messages)が使えます.

# partial_msg.sage

def long_to_bytes(data):
    data = str(hex(long(data)))[2:-1]
    return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])

def bytes_to_long(data):
    return int(data.encode('hex'), 16)

N = 11854673881335985163635072085250462726008700043680492953159905880499045049107244300920837378010293967634187346804588819510452454716310449345364124188546434429828696164683059829613371961906369413632824692460386596396440796094037982036847106649198539914928384344336740248673132551761630930934635177708846275801812766262866211038764067901005598991645254669383536667044207899696798812651232711727007656913524974796752223388636251060509176811628992340395409667867485276506854748446486284884567941298744325375140225629065871881284670017042580911891049944582878712176067643299536863795670582466013430445062571854275812914317
e = 5
c = 4463634440284027456262787412050107955746015405738173339169842084094411947848024686618605435207920428398544523395749856128886621999609050969517923590260498735658605434612437570340238503179473934990935761387562516430309061482070214173153260521746487974982738771243619694317033056927553253615957773428298050465636465111581387005937843088303377810901324355859871291148445415087062981636966504953157489531400811741347386262410364012023870718810153108997879632008454853198551879739602978644245278315624539189505388294856981934616914835545783613517326663771942178964492093094767168721842335827464550361019195804098479315147

m = bytes_to_long("Yukko the ESPer: My amazing ESP can help you to get the flag! -----> KosenCTF{\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
P.<x> = PolynomialRing(Zmod(N), implementation='NTL')
f = (m + x)^e - c
roots = f.small_roots(epsilon=1/30)
print(long_to_bytes(m+roots[0]))
> sage partial_msg.sage
Yukko the ESPer: My amazing ESP can help you to get the flag! -----> KosenCTF{H0R1_Yukk0_1s_th3_ESP3r_QUEEN}

KosenCTF{H0R1_Yukk0_1s_th3_ESP3r_QUEEN}

このもんだいすき

pascal homomorphicity [hard, 333pts, 20solved]

nc pwn.kosenctf.com 8002

service.py

from secrets import flag
from Crypto.Util.number import getStrongPrime

p = getStrongPrime(512)
q = getStrongPrime(512)
n = p * q

key = int.from_bytes(flag, "big")
c = pow(1 + n, key, n * n)

print("I encrypted my secret!!!", flush=True)
print(c, flush=True)

# receive plaintext
print(
    "I encrypt your message ;)",
    flush=True,
)

while True:
    plaintext = input("> ")
    m = int(plaintext)
    
    # check plaintext
    if m.bit_length() < key.bit_length():
        print(
            "[!]Your plaintext is too weak. At least {} bits long plaintext is required.".format(
                key.bit_length()
            ),
            flush=True,
        )
        continue
        
    # encrypt
    c = pow(1 + n, m, n * n)

    # output
    print("Thanks. This is your secret message.", flush=True)
    print(c, flush=True)
> nc pwn.kosenctf.com 8002
I encrypted my secret!!!
1262857578229849625592543029547547796770030710051239261336994523314619001742667541252815623550770135660912680908941505783985012435631082810136219805264693165701250029504073696358672069220281716653558838458149022732337356864441375498164600804134428326880233128927480019870218798012927966462425363014820830186607030485735872606434690678775788458188765641673812991171735274337232827979297766034220993137996691251201406709068956
I encrypt your message ;)
> 1127
[!]Your plaintext is too weak. At least 383 bits long plaintext is required.

アプローチ:Paillier暗号の性質を利用する

pascal + 準同型 ということはPaillier暗号ですね.
Paillier暗号は次の性質が成り立つことを利用しています.


{(1+N)}^{M} \equiv 1 + MN \bmod {N}^{2}

つまり M, Nのどちらかが不明な場合でも,右辺から1を引いて Mで割れば N Nで割れば Mが分かります.

ここでもう一度service.pyを確認してみると

Secret \equiv {(1 + N)}^{KEY} \bmod {N}^{2}

Encrypt\_Msg \equiv {(1 + N)}^{INPUT} \bmod {N}^{2}

となっています.

したがって, Encrypt\_Msg INPUTから N求めることで Secret Nから KEYを求めることができます.

以下がソルバになります.

from Crypto.Util.number import getPrime, long_to_bytes

secret = 1761936486623756335852108882692115588477115971162337998137481347057121324806922005277706292815229546031033439042215524499713873642542521729509682838646308703023063479677737439256444162084598201363736124334661404002715959496797879169656117447146787541229250196232968651612605305211318384064862196982673609075930605769729339062400348479556886544573256607504296732785505715594857057058398721137526234772018747830391939883909096
my_msg = 2519069992930202561931503452746462101247553844641202040232365459465067044913573911051697429207935426241669305018380744147
encrypt_msg = 382276127748490868856542238238127120947422793888757155446115331235234982574827621504562354440004831537501251577850463534093807405851598384642100935207529193338262632938489660750686993321476287085442753652605547721366210308666016137479036099160497741071321817122420507113954954995393919509472485719868161572146380050490941445127612251774032766887253059165999633506354414961263521106621530076380278080560215657614094585185611450634

N = (encrypt_msg - 1) // my_msg
key = (secret - 1) // N

print(long_to_bytes(key))
> python solve.py
b'KosenCTF{Th15_15_t00_we4k_p41ll1er_crypt05y5tem}'

KosenCTF{Th15_15_t00_we4k_p41ll1er_crypt05y5tem}

Survey

Survey [warmup, 212pts, 77solved]

Please give us your feedback here.

アプローチ:アンケートに答える

KosenCTF{th4nk_y0u_f0r_pl4y1ng_InterKosenCTF_2019}

まとめ

  • 全体的に面白い問題が多くて楽しめました
  • 初心者になれるようにがんばります
  • Pwn, Web ナ〜

f:id:satto1237:20190814021339p:plain

peaCTF 2019 Round 1 Write-up

はじめに

2019/07/22 ~ 2019/07/28に開催されたpeaCTF Round 1に個人で参加しました.

成績

150位(540チーム中)でした.

f:id:satto1237:20190801022045p:plain

General Skills

Worth - Points: 50

This problem is worth 0o1454 points.

アプローチ:Octal to Decimal

flag{peactf_812}

Hide and Seek - Points: 100

Try to find to the flag file located somewhere in the folders located in: /problems/hide-and-seek_28_e5e549870631c4a82efc93c0630570bf

アプローチ:grep

指定されたフォルダを覗いてみると多数のフォルダが存在していることが分かるのでgrepflagを探します.

satto1237@peactf-2019-shell-1:/problems/hide-and-seek_28_e5e549870631c4a82efc93c0630570bf$ ls
00ef4680df9a09b9377b8bc4911f023c  6a607e806de3a71f198d0a5289777b1f  c9fe31d8b0acfd94ed33171a0a5dc2ff
0256e6db0ed0c52181d2b5aebb926ca4  72fa69a14478147c0e7072f0da6022aa  cccdf9025e805f3dc4c142d6381703f9
0406278c5efdb169c5ee6039fbf4d5ae  75a736c898dfe0b64f72d3559473020a  d029da976887fa3ac47aea412b6a77f4
0bf553aaf44527d74074ed7231f5244b  78e6723e7dbbf03ce74d54191827f72a  d16cafd2033bc29c22b941ed82a1143d
0c016d7eaf9b7308492db63bfb1abc31  7a801ff27ab8e667746dc0179f4a1ce2  d6705198476c85fdc0c7685ac7a2f80e
0dd0453f32c0ebf7daf98e2359788af8  7c4e713381579bd9903ebd94a2ec1581  d7a373b7b05197d349c623d43da627ca
0e9ef8e2015ed4c9f53fa1780408e44e  7d45526b8fba594307a8a2e5b4464b2b  d7ca477c142000738976440516230a0e
0fd396bf5aab7dcb688b5484629f6ba8  83a25df132f835cb7ef3e384229655a6  dad3db94141109304b14c74e6171f7ab
15960169b784e48392d75587d87c2d63  83fee6b9c2fda47a050575071648f80b  dc30b7b52bc225d4b5273b4003a94e06
254ab5d75a8f09eaaaef016e0e583114  90b3b954693a878d1b1bc94dc4fd6a91  dd306d2db6d7854d4b7bf7be8a8f1d9e
2909a9c58d591e93021cd92a2d45c474  91443f0e7a5138cd0615e52ae4d89eb9  dd83aa9de84b5c8c8f0c0154dd8f18d5
2b25601046d1933091792dbff4236c42  9852f47d4c8f59c449f634c2de28976a  dd86f67181f61d14a7b43df0dc6f9229
2ed1d0e8640b9ed69d7fe0147068336e  9b625797a48b1deb8c2c2c7900c7e408  df19ef43cb627647ba062a4595b2a02b
35b3e6a103a2f515e189a29a2b227dea  a59cd36eb28c32e3fcdb509a90a6cceb  e1cccc142e54daa1b9c944e5b2a880c2
39c2946318f9884d714e74b6d64d450b  ac61d7f5e1c299c3b66053b52edb809e  e37372a1c26223c1a6d18cf5a1c9f8fe
415610d493e787945ad043eed69d3465  ac97be330db79788553b0e2b8cc3fbdc  ec9645d1bd751b57060f898b17257f96
43160c0249b4c011c15c1672562f58fc  af5f662b9069469491f2debb2d1b61bf  edd55758a50a426d9475e44b2a978987
44e49f811c02977719558b1503ce14d7  b0a0feb496e970cce94a254ed92444e0  ee7550d9294ac336eee66dd7f56d93df
4724ab2b151532286824d17166538e9f  b3c3c9f7659fe6341b9ba444bda6bcc9  ef5a0bb515d66c33481769dac6a42b7a
536a4861fb7801ee2b607fdbfe84bf5d  baacfcb9759ff86d548c70882bbb3fc8  f1bcf77f7d06c3acfc816ef7532010f8
5b03c379589439356689e18a5b4c6ce7  c2646431e0c6f5bbb0d9f99ad97467b9  f28f001ac87becef906218f6fcd3c6bc
6036e1656c0b0b36adc414f7f4367235  c47187be680f4e3347ca2c87cc97f0a9  f3ed13c57a1903313d8f29efb678fcc5
61d1e7d000523d81101d745ac04c6e4a  c5a46882b4620e5f9139b0209779908f  f9836b210710ed0525abb626e99da3a2

satto1237@peactf-2019-shell-1:/problems/hide-and-seek_28_e5e549870631c4a82efc93c0630570bf$ grep -r flag ./      
./c9fe31d8b0acfd94ed33171a0a5dc2ff/3361b9c2b222aa9f81186d5b36f82032/7ebd790c6e8eb1dbd1dcf1b244c589bf/5b073431762e613fe1a80b7fa479106a/31f3e448c58e17f225e21591b6170f88/flag.txt:flag{peactf_linux_is_fun_21e61d463e005e9bbc6aa1a208f74ed7}

flag{peactf_linux_is_fun_21e61d463e005e9bbc6aa1a208f74ed7}

Cryptography

Breakfast - Points: 50

Mmm I ate some nice bacon and eggs this morning. Find out what else I had for an easy flag. Don’t forget to capitalize CTF!

011100010000000000101001000101{00100001100011010100000000010100101010100010010001}

アプローチ:Baconian Cipher

www.dcode.fr

011100010000000000101001000101 -> PEACTF
00100001100011010100000000010100101010100010010001 -> EGGWAFFLES

Don’t forget to capitalize CTF!

peaCTF{eggwaffles}

Broken Keyboard - Points: 50

Help! My keyboard only types numbers!

112 101 97 67 84 70 123 52 115 99 49 49 105 115 99 48 48 108 125

アプローチ:Decimal to ASCII

#!/usr/bin/env python
# -*- coding: utf-8 -*-

enc = [112, 101, 97, 67, 84, 70, 123, 52, 115, 99, 49, 49, 105, 115, 99, 48, 48, 108, 125]
flag = ''.join(list(map(chr, enc)))
print(flag)

peaCTF{4sc11isc00l}

School - Points: 100

My regular teacher was out sick so we had a substitute today.

Alphabet: WCGPSUHRAQYKFDLZOJNXMVEBTI
zswGXU{ljwdhsqmags}

アプローチ:換字式暗号

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string

upp = string.ascii_uppercase
low = string.ascii_lowercase
sub = 'WCGPSUHRAQYKFDLZOJNXMVEBTI'
enc = 'zswGXU{ljwdhsqmags}'
flag = ''

for x in enc:
    if x in upp:
        flag += upp[sub.find(x)]
    elif x in low:
        flag += low[sub.find(chr(ord(x) - 32))]
    else:
        flag += x

print(flag)

peaCTF{orangejuice}

Crack the Key - Points: 450

On one of my frequent walks through the woods, I stumbled upon this old French scroll with the title "le chiffre indéchiffrable." Remember to submit as peaCTF{plaintext_key}.

DVMDVRWOUISIERRRGNNVMWPOPGTOHSBUIHTCSSMJIVUWEXHTCTKZKFXIENWTDDOVMEOWDZRQEBQPVLFWKJBGL
EEDALGCIVLQGLTWTCMFXSIAQTLTUGZQZZWOPVGIRCSLRUZRJUZBQSXSPXGJMGTPRPUGRSIVRGUDAFXHTNLVVBMF
ZMQSFUWTWTFSWHIGXHTQLGCUSRGLEIWWXXWWCJDAIFXGAPDWGWFHTZSVOBISITRVUTTVRTWTDGMCPHGGNRDB
POIZZWZPGHTTDQPHOYIUTUEWJDCPWORWDAZREDNHYSJZRJPAFSOCPDXZVPLVPGMNIWPFWUVRDUJINIDFXLYIUTE
NWAHITVJZRJPVQEFAJEXWIMQVIYPTWGZYYYXKTNNVMQJTPVZRJHEBVDWPOKGEIUDCAHDJGTRYKLHSILXHPIZPVDE
MDZGLEEGTDWDMGSTRAHXIPFGRVKPLUEDPHEVSEKHSZREMDCELWGVHKQBYSCXRLLRRGLQFLESIZGGDQXCQPETT
XEXGKLHDBUIRPCTQSCWLIPNHBTTYEYIIHSBUETIWPCKYSXALNPLBTPXAEXKTJVKBPGYEKJSRCIFQRYDYIKNEVHISILN
DFXGWXKTENCOASXEBFVVDPRAAHPWASPWFPTYIDIWZYYYXKTVNQEJCOIJNLLRPUIHPSMIWEIAWQOMTTSHEKNMOAQ
AKDDCMISLXBLIFWOWXRLDPVHVIEHESDYXZVJDGUGLAITGIJPSQTENWQJXEIJVEGNBBPOHTLRZFYUHAYIEEXYSJUIUI
WUIAGLSELYIKPLGSSPNLXGEIHCLBJTWTMMYSEUCWAESDGESXIELHMQTLPIQSJDQDYWEAAHPWVWRHBTVFGOCRPH
GELLHJRHOUHEVSNYQSMEELPCEIJEAKXKULUCVQVGDEETIZLELPDXOVPYTGRERHDWHSEHKPLYETTAJKJFAQGIGLEG
HESMKFXIPRAAHHEMDCEPPRRWTXRWSGBMQVXVKWXISEOZWHPVQFECTGSDVRWPXCIAGPYGWZRVEQGIOUISIXRG
WIPNXHXHEYKYIVWIQREKTCFWVRFJBOIFDGPPGEKWWMBXHTGLRADEOHJRKACIZEJIMYTIAHMPZPXZVQVTTIISRDXJGI
XDQTREFITCXZVMUSQSJEGTYXXRWKXWAWFXGDXURQHIPRXHGTPHGXWEACRFEAAUIKJMHPVQTICRSIJRRGIPRRTWT
AMYJAKDARXTATOHGNRLCBUISIGLAADQHSQNXEANTRXISQIWSXHTEWELWSUBBUIHTCDTWIGKTLGLEBHPPNVWRCBU
IWXCOSOJMOAAGLEEXRIGEWIACGXEGTOYHKSWWMEEFITCWLYIVWMRTACSNSOJPDNLBANQTSMFUXKTXVKSPCOFW
XEQIWPLELISIULHWWMGAORPCXZFVVTAOSXTGLRVTPRKMEGABTTRLFKHIPRVWPAVMFXZHGGFPOLAJEFUWHIBVRGS
DHRLYILGDNWTWPTVQYSRUAJMTWVCISKGDGMYISIISIJVWKDCYHBTHZQWJQDATNRIBPWGGEGHPTRHICISIKKVDLKYS
VTGHEKRWWDCGQOIWPVDPQDGMNTPGDLGZZRJBQQHLTATJWNLRWIQREKTCUMZXHVWGLEGUTKMIIEPKXEFITCLWIJ
RJZGLFDPWFGOIULIFENTCZVEFYVQMNWTCTLVDPILVPGIECWLRVJLLVPNRDPHDXJFRJPANRYILZSJUMQPZLLOGHPWH
LXWDORXHTGLAZZXHHBEMPTSZAFYMVCWFIGPKPLADEVDURAHPIDXMGMGPXCIAGPYGWRRGXVSECIWPASJRRIWSJI
GHEVSKILCBRPLXVPRUVFXIPRAAHJYMNVVVPTYCRTHAIUKIGUWELIHHEISUMQTAFSFRWLVSTXHGIAHTGTXIFUSXHXBA
EGHZJOFVNPNGIRIWPLGIWHHKNQEBJCMWCXKTEUMTTVZELRRGQMANABXYXZVHRCSRCBTCUEEZRZPAGLEDAOIKKE
QXUNPOCISIXRVPPVQXHTLZVKKXHBXRVESWPWWCHRBBNPKTSLRVNLHCPRHISXEASJYVJIYPYIDXECVWRBMPCNXRL
PJVQDGSSSRXCDXSEGHWMJSUASDEQKLDIOBHHPSRMNVRKXUNXAXAESCVISIPRJLXTDSXWFXIBUETWTHSMCHVDWA
IRWPGIZRHQDBNMLPCORGWPLTANPOCTLQGEKWWMNRIBPWWGEXKTNNVMWTYINVVOPCTLESXQEKBIGLPLLELDFPVJ
EBIPNXHTHLAFFXKXVTXOAPFKZRXQTDRVTWTWIKJALIPBYTDEPRDPEGBQGXICVTXZVADHLRZOITOXGSSATZGLEILZSX
KLHBCFYAAAJWHVRWIPRMRHJYHSPWWDORXHTGTRLYIVBIYPPPSOSUBFHNWAHTWTZVUYEUSOEEZXCRWAUIENAVH
EPCORWMIUHXREKXCR

アプローチ:Vigenere Cipher

Vigenere Solverを使ってkeyを探索します.

f:id:satto1237:20190801025146p:plain

peaCTF{redpineapples}

RSA - Points: 500

Can you help Bob retrieve the two messages for a flag?

Encrypted channel:
n = 165481207658568424313022356820498512502867488746572300093793
e = 65537
c = 150635433712900935381157860417761227624682377134647578768653
Authenticated (unhashed) channel:
n = 59883006898206291499785811163190956754007806709157091648869
e = 65537
c = 23731413167627600089782741107678182917228038671345300608183

アプローチ:公開鍵による暗号化 + 秘密鍵による暗号化

enc_channelは公開鍵による暗号化を行っており(通常のRSA暗号),auth_channel秘密鍵による暗号化を行っています(電子署名). そのため,enc_channel秘密鍵による復号を行い,auth_channelは公開鍵による復号を行います.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Crypto.Util.number import *

e = 0x10001

# enc_channel
p_1 = 404796306518120759733507156677
q_1 = 408801179738927870766525808109
n_1 = p_1 * q_1
c_1 = 150635433712900935381157860417761227624682377134647578768653
phi_1 = (p_1 - 1) * (q_1 - 1)
d_1 = inverse(e, phi_1)
m_1 = pow(c_1, d_1, n_1)
print(long_to_bytes(m_1))


# auth_channel
n_2 = 59883006898206291499785811163190956754007806709157091648869
c_2 = 23731413167627600089782741107678182917228038671345300608183
m_2 = pow(c_2, e, n_2)
print(long_to_bytes(m_2))

# flag
print(long_to_bytes(m_1) + long_to_bytes(m_2))
> python solve.py
b'peaCTF{f4ct0r'
b'1ng1sfun}'
b'peaCTF{f4ct0r1ng1sfun}'

peaCTF{f4ct0r1ng1sfun}

Forensics

Choose your Pokemon - Points: 150

Just a simple type of recursive function.

アプローチ:rar -> zip -> pdf -> rtf

> file master-ball
master-ball: RAR archive data, v5
> file roshambo
roshambo: Zip archive data, at least v2.0 to extract

f:id:satto1237:20190801032653p:plain

pastebin.com

f:id:satto1237:20190801032758p:plain

{wild_type}

We are E.xtr - Points: 350

E.xtr

アプローチ:ファイルシグネチャを書き換える

> file E.xtr
E.xtr: data
89 58 54 52 -> 89 50 4E 47

f:id:satto1237:20190801034053p:plain

f:id:satto1237:20190801034107p:plain

f:id:satto1237:20190801034324p:plain

{read_banned_it}

The Wonderful Wizard - Points: 750

TheWonderfulWizard.png

f:id:satto1237:20190801034626p:plain

アプローチ:stegsolve

f:id:satto1237:20190801034901p:plain

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Crypto.Util.number import *

msg = 0x666c61677b7065616374665f77686572655f7468655f77696e645f626c6f77737d
print(long_to_bytes(msg))
> python solve.py
b'flag{peactf_where_the_wind_blows}'

Reversing

Coffee Time - Points: 250

Run this jar executable in a virtual machine and see what happens.

> file coffeetime.jar
coffeetime.jar: Java archive data (JAR)

アプローチ:decompile

JD-GUIでdecompileします.

f:id:satto1237:20190801035500p:plain

peaCTF{nice_cup_of_coffee}

まとめ

  • 全完してるチームが結構いたのに3問解けず辛くなった…
  • Web解けなかったので勉強します (毎回言っている)
  • 難しすぎず簡単すぎないCrypto問が解きたいナ〜〜

ISITDTU CTF 2019 Write-up

はじめに

2019/06/29 ~ 2019/06/30に開催されたISITDTU CTFに個人で参加しました.

成績

69位(327チーム中)でした.

f:id:satto1237:20190701224224p:plain

Welcome

Welcome [10pts, 263solves]

Welcome to our Discord

アプローチ:Discordに参加する

f:id:satto1237:20190701224431p:plain

ISITDTU{Welcome_everyone_to_ISITDTUCTF}

Rev

Recovery [100pts, 79solves]

Could you help me recovery my number?
Note: The flag is not in flag format, please wrap it in format when you submit. ISITDTU{x, y, z, ...}
File: recovery

> file recovery.jar
recovery.jar: Java archive data (JAR)

アプローチ:デコンパイル + Pre-order

ダウンロードしたjarファイルをデコンパイルします (JD-GUIを使いました).

// [snip]
  private void btnSubmitActionPerformed(ActionEvent evt)
  {
    try
    {
      String txtInputS = this.txtInput.getText().trim();
      String[] str = txtInputS.split(",");
      int[] input = new int[str.length];
      for (int i = 0; i < str.length; i++) {
        input[i] = Integer.parseInt(str[i].trim());
      }
      int[] s = { 9, 11, 33, 35, 38, 40, 44, 48, 61, 85, 89, 101, 106, 110, 135, 150, 159, 180, 188, 200, 201, 214, 241, 253, 268, 269, 275, 278, 285, 301, 301, 327, 356, 358, 363, 381, 396, 399, 413, 428, 434, 445, 449, 462, 471, 476, 481, 492, 496, 497, 509, 520, 526, 534, 540, 589, 599, 613, 621, 621, 623, 628, 634, 650, 652, 653, 658, 665, 679, 691, 708, 711, 716, 722, 752, 756, 764, 771, 773, 786, 807, 808, 826, 827, 836, 842, 856, 867, 875, 877, 879, 889, 892, 922, 946, 951, 965, 980, 993, 996 };
      int[] l = { 35, 33, 44, 40, 38, 48, 11, 85, 89, 61, 110, 150, 159, 135, 188, 200, 180, 106, 101, 214, 268, 275, 269, 253, 241, 201, 9, 301, 301, 285, 327, 356, 363, 396, 413, 399, 445, 434, 462, 449, 428, 471, 481, 492, 496, 497, 476, 381, 358, 278, 534, 526, 520, 613, 599, 623, 621, 621, 589, 540, 628, 650, 653, 652, 665, 691, 679, 711, 756, 752, 722, 716, 807, 786, 773, 771, 826, 808, 827, 764, 856, 875, 867, 842, 836, 708, 879, 892, 889, 922, 877, 951, 946, 658, 980, 996, 993, 965, 634, 509 };
      if (check(s, new CTF_Problem().getResultA(input)))
      {
        if (check(l, new CTF_Problem().getResultB(input))) {
          JOptionPane.showMessageDialog(this.rootPane, "Recovery successfull\nFlag is your solution");
        } else {
          JOptionPane.showMessageDialog(this.rootPane, "Wrong answer! Try angain...");
        }
      }
      else {
        JOptionPane.showMessageDialog(this.rootPane, "Wrong answer! Try angain...");
      }
    }
    catch (Exception ex)
    {
      JOptionPane.showMessageDialog(this.rootPane, "Wrong answer! Try angain...");
    }
  }
// [snip]

コードを読むと入力値に対して何らかの処理(getResultA(), getResultB())をした後,s, lと比較を行っていることが分かります.
次にgetResultA(), getResultB()について確認します.

// [snip]
  public int[] getResultA(int[] a)
  {
    CTF_Problem b = new CTF_Problem();
    l = m = 0;
    for (int i = 0; i < arr1.length; i++) {
      b.insert(a[i]);
    }
    b.inOrder(root);
    return arr1;
  }
  
  public int[] getResultB(int[] a)
  {
    CTF_Problem b = new CTF_Problem();
    l = m = 0;
    for (int i = 0; i < arr2.length; i++) {
      b.insert(a[i]);
    }
    b.postOrder(root);
    return arr2;
  }
// [snip]

getResultA()ではPre-orderからIn-orderへの変換,getResultB()ではPre-orderからPost-orderへの変換を行っています.
したがって,s, lはそれぞれIn-order, Post-orderであり,入力値としてPre-orderを与えればflagを取得できることが分かります.

en.wikipedia.org

以下のページを参考にIn-order, Post-orderからPre-orderを生成しました.

stackoverflow.com

f:id:satto1237:20190701231111p:plain

ISITDTU{509, 278, 9, 201, 101, 61, 11, 48, 38, 33, 35, 40, 44, 89, 85, 106, 180, 135, 110, 159, 150, 200, 188, 241, 214, 253, 269, 268, 275, 358, 356, 327, 285, 301, 301, 381, 363, 476, 471, 428, 399, 396, 413, 449, 434, 445, 462, 497, 496, 492, 481, 634, 628, 540, 520, 526, 534, 589, 621, 599, 613, 621, 623, 965, 658, 652, 650, 653, 946, 877, 708, 679, 665, 691, 836, 764, 716, 711, 722, 752, 756, 827, 808, 771, 773, 786, 807, 826, 842, 867, 856, 875, 922, 889, 879, 892, 951, 993, 980, 996}

Pytecode [100pts, 74solves]

File: Pytecode

> file pytecode
pytecode: ASCII text
C0rr3ct func:
  6           0 LOAD_CONST               1 ('Wow!!!You so best^_^')
              3 PRINT_ITEM          
              4 PRINT_NEWLINE       
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE        

Ch3cking func:
  8           0 LOAD_CONST               1 (0)
              3 STORE_FAST               1 (check)

  9           6 LOAD_GLOBAL              0 (ord)
              9 LOAD_FAST                0 (flag)
             12 LOAD_CONST               1 (0)
             15 BINARY_SUBSCR       
             16 CALL_FUNCTION            1
             19 LOAD_CONST               2 (52)
             22 BINARY_ADD          
             23 LOAD_GLOBAL              0 (ord)
             26 LOAD_FAST                0 (flag)
             29 LOAD_CONST               3 (-1)
             32 BINARY_SUBSCR       
             33 CALL_FUNCTION            1
             36 COMPARE_OP               3 (!=)
             39 POP_JUMP_IF_TRUE        78
[snip]

アプローチ:dis (Python バイトコードの逆アセンブラ)のドキュメントを読む

docs.python.org

flagに関する処理をPythonっぽく書き換えると以下のようになります.

flag[:7] == 'ISITDTU'
flag[9] == flag[14]
flag[14] == flag[19]
flag[19] == flag[24]

flag[8] == '1'
flag[8] == flag[16] (flag[16] == '1')

flag[10:14] == 'd0nT'

int(flag[18]) + int(flag[23]) + int(flag[28]) == 9
flag[18] == flag[28]

flag[15] == 'L'

ord(flag[17]) ^ -10 == -99 (flag[17] == 'k')

ord(flag[20]) + 2 == ord(flag[27]) 
ord(flag[27]) < 123
ord(flag[20]) > 97

ord(flag[27]) % 100 == 0 (flag[27] == 'd', flag[20] == 'b')

flag[25] == 'C'

ord(flag[26]) % 2 == 0
ord(flag[26]) % 3 == 0
ord(flag[26]) % 4 == 0
(flag[26] == '0')

int(flag[23]) == 3 (flag[23] == '3')

flag[22] == lower(flag[13]) (flag[22] == 't')

temp = 0
for i in flag:
  temp += ord(i)
temp == 2441

この情報を元にflagを復元するとISITDTU{1*d0nT*L1k3*b*t3*C0d3} (*は不明な文字) になります.
不明な文字を以下の情報(制約)を使って全探索します.

flag[9] == flag[14]
flag[14] == flag[19]
flag[19] == flag[24]

temp = 0
for i in flag:
  temp += ord(i)
temp == 2441

ISITDTU{1_d0nT_L1k3_b:t3_C0d3}

Programming

Do you like math? [100pts, 106solves]

nc 104.154.120.223 8083

>  nc 104.154.120.223 8083

 #####  #######          #####    #
#     # #        #   #  #     #  ##
      # #         # #         # # #      #####
 #####  ######  #######  #####    #
#             #   # #   #         #      #####
#       #     #  #   #  #         #
#######  #####          ####### #####

>>> 1127
Wrong!

アプローチ:頑張ってパースしてシグネチャで判定

何度かncすると次のことが分かります.

  • 一桁または二桁の演算を行っている
  • 演算は加算,減算,乗算のみ (除算はなし)
  • 表示される文字は0~9, +, -, *, =のみ

めちゃくちゃ面倒くさい

以下のようにして演算を行います.

  1. 表示される文字を空白(スペース)で分割
  2. #カウントベースのシグネチャを生成
  3. シグネチャに対応する文字で演算文字列を生成
  4. evalで演算

ex.

表示される文字

 #                #####
#    #   #   #  #     #
#    #    # #   #     #    #####
#    #  #######  ######
#######   # #         #    #####
     #   #   #  #     #
     #           #####

スペースで分割

#      
#    # 
#    # 
#    # 
#######
     # 
     # 
       
 #   # 
  # #  
#######
  # #  
 #   # 
       
 #####
#     #
#     #
 ######
      #
#     #
 #####


#####
#####

1行分の#を数え,文字として連結させる (これをシグネチャとした)
#のカウントだけだと6,9が同値だったりして面倒くさい

4: 12227110
*: 02272200
9: 52261250
=: 00505000

以下ソルバです.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.connect(('104.154.120.223', 8083))


def parse(lines):
    index = [0]
    for i in range(len(lines[0])):
        space_check = True
        for j in range(8):
            if lines[j][i] == '#':
                space_check = False
                break
        if space_check:
            index.append(i)

    f = ''
    for i in range(len(index) - 1):
        if index[i] + 1 == index[i+1]:
            continue
        signature = ''
        for j in range(8):
            signature += str(lines[j][index[i]:index[i+1]].count('#'))

        print('signature: {}'.format(signature))
        if signature == '32222230':
            f += '0'
        elif signature == '12211150':
            f += '1'
        elif signature == '52151170':
            f += '2'
        elif signature == '52151250':
            f += '3'
        elif signature == '12227110':
            f += '4'
        elif signature == '71161250':
            f += '5'
        elif signature == '52162250':
            f += '6'
        elif signature == '72111110':
            f += '7'
        elif signature == '52252250':
            f += '8'
        elif signature == '52261250':
            f += '9'
        elif signature == '00505000':
            f += '='
        elif signature == '02272200':
            f += '*'
        elif signature == '00050000':
            f += '-'
        elif signature == '01151100':
            f += '+'

    return f

for i in range(200):
    print(i)
    rec = s.recv(1024).decode('utf-8')
    temp = s.recv(1024).decode('utf-8')
    if 'ISI' in rec:
        print(rec)
        break

    lines = rec.split('\n')[1:-1]
    prob = parse(lines)
    print(rec)
    print(prob)
    result = str(eval(prob[:-1])).encode('utf_8') + b'\n'
    print(result)
    s.send(result)
    print('-'*50)
> python solve.py
0
signature: 52151170
signature: 52151250
signature: 02272200
signature: 12211150
signature: 71161250
signature: 00505000

 #####   #####            #   #######
#     # #     #  #   #   ##   #
      #       #   # #   # #   #          #####
 #####   #####  #######   #   ######
#             #   # #     #         #    #####
#       #     #  #   #    #   #     #
#######  #####          #####  #####


23*15=
b'345\n'
--------------------------------------------------
[snip]
--------------------------------------------------
99
signature: 52151250
signature: 32222230
signature: 02272200
signature: 12211150
signature: 52261250
signature: 00505000

 #####    ###             #    #####
#     #  #   #   #   #   ##   #     #
      # #     #   # #   # #   #     #    #####
 #####  #     # #######   #    ######
      # #     #   # #     #         #    #####
#     #  #   #   #   #    #   #     #
 #####    ###           #####  #####


30*19=
b'570\n'
--------------------------------------------------
100

Good job, this is your flag:   ISITDTU{sub5cr1b3_b4_t4n_vl0g_4nd_p3wd13p13}

100問解くとflagが降ってきます.

ISITDTU{sub5cr1b3_b4_t4n_vl0g_4nd_p3wd13p13}

balls [100pts, 76solves]

There are 12 balls, all of equal size, but only 11 are of equal weight, one fake ball is either lighter or heavier. Can you find the fake ball by using a balance scale only 3 times?

nc 34.68.81.63 6666

> nc 34.68.81.63 6666

                    ≡≡≡≡≡≡/\≡≡≡≡≡≡
                   /\     ││     /\
                  /  \    ││    /  \
                 ╚════╝   ││   ╚════╝
 _   _   _   _   _   _    ││    _   _   _   _   _   _
(_) (_) (_) (_) (_) (_)  ████  (_) (_) (_) (_) (_) (_)
There are 12 balls, all of equal size, but only 11 are of equal weight, one fake ball is either lighter or heavier. Can you find the fake ball by using a balance scale only 3 times?
Example weigh balls at position 1,2,3 vs 4,5,6: 1,2,3 4,5,6
Round 1 :
Weighting 1: 1,2,3,4 5,6,7,8
The left is lighter than the right
Weighting 2: 1,2,3,4 5,6,7,8
The left is lighter than the right
Weighting 3: 1,2,3,4 5,6,7,8
The left is lighter than the right
The fake ball is :
12
WRONG!!!!!!
The fake ball is : 3

アプローチ:12 balls problemとかでググる

12個あるボールの中に1つだけ重さが異なるボールが混ざっているのではかりを3回だけ使ってどのボールがfakeなのか判定しましょうという問題.
いや、3回だけじゃ無理でしょと思ったので自力で考えずにググりました.

www.mytechinterviews.com

本当に3回で判定できてすごいな〜となりました.

以下めっちゃ汚いソルバです.

#!/usr/bin/env python3
# -*- coding: utf_8 -*-

from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.connect(('34.68.81.63', 6666))

def balls_round():
    rec = s.recv(2048).decode('utf_8')
    fake = ''
    s.send('1,2,3,4 5,6,7,8\n'.encode('utf_8'))
    rec = s.recv(2048).decode('utf_8')
    print(rec)
    if 'equally' in rec:
        print('equally')
        rec = s.recv(2048).decode('utf_8')
        s.send('8,9 10,11\n'.encode('utf_8'))
        print(rec)
        rec = s.recv(2048).decode('utf_8')
        print(rec)
        if 'equally' in rec:
            print('equally')
            fake = '12'
            s.send('11 12\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
        elif 'heavier' in rec:
            print('heavier')
            s.send('10 11\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '9'
            elif 'heavier' in rec:
                print('heavier')
                fake = '11'
            elif 'lighter' in rec :
                print('lighter')
                fake = '10'
        elif 'lighter' in rec :
            print('lighter')
            s.send('10 11\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '9'
            elif 'heavier' in rec:
                print('heavier')
                fake = '10'
            elif 'lighter' in rec :
                print('lighter')
                fake = '11'
    elif 'heavier' in rec:
        print('heavier')
        rec = s.recv(2048).decode('utf_8')
        s.send('1,2,5 3,6,9\n'.encode('utf_8'))
        print(rec)
        rec = s.recv(2048).decode('utf_8')
        print(rec)
        if 'equally' in rec:
            print('equally')
            s.send('7 8\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '4'
            elif 'heavier' in rec:
                print('heavier')
                fake = '8'
            elif 'lighter' in rec :
                print('lighter')
                fake = '7'
        elif 'heavier' in rec:
            print('heavier')
            s.send('1 2\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '6'
            elif 'heavier' in rec:
                print('heavier')
                fake = '1'
            elif 'lighter' in rec :
                print('lighter')
                fake = '2'
        elif 'lighter' in rec :
          print('lighter')
          s.send('5 9\n'.encode('utf_8'))
          rec = s.recv(2048).decode('utf_8')
          print(rec)
          rec = s.recv(2048).decode('utf_8')
          print(rec)
          if 'equally' in rec:
              print('equally')
              fake = '3'
          elif 'lighter' in rec :
              print('lighter')
              fake = '5'
    elif 'lighter' in rec :
        print('lighter')
        rec = s.recv(2048).decode('utf_8')
        s.send('5,6,1 7,2,9\n'.encode('utf_8'))
        print(rec)
        rec = s.recv(2048).decode('utf_8')
        print(rec)
        if 'equally' in rec:
            print('equally')
            s.send('3 4\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '8'
            elif 'heavier' in rec:
                print('heavier')
                fake = '4'
            elif 'lighter' in rec :
                print('lighter')
                fake = '3'
        elif 'heavier' in rec:
            print('heavier')
            s.send('5 6\n'.encode('utf_8'))
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            rec = s.recv(2048).decode('utf_8')
            print(rec)
            if 'equally' in rec:
                print('equally')
                fake = '2'
            elif 'heavier' in rec:
                print('heavier')
                fake = '5'
            elif 'lighter' in rec :
                print('lighter')
                fake = '6'
        elif 'lighter' in rec :
          print('lighter')
          s.send('1 9\n'.encode('utf_8'))
          rec = s.recv(2048).decode('utf_8')
          print(rec)
          rec = s.recv(2048).decode('utf_8')
          print(rec)
          if 'equally' in rec:
              print('equally')
              fake = '7'
          elif 'lighter' in rec :
              print('lighter')
              fake = '1'

    print(fake)
    s.send(fake.encode('utf_8') + b'\n')
    rec = s.recv(2048).decode('utf_8')
    print(rec)
    print('-----')

rec = s.recv(2048).decode('utf_8')
for i in range(51):
    print('Round: {}'.format(i))
    if i == 50:
        rec = s.recv(2048).decode('utf_8')
        print(rec)
        break
    balls_round()
> python solve.py
Round: 0
Both are equally heavy

equally
Weighting 2:
The left is lighter than the right

lighter
Weighting 3:
The left is heavier than the right
The fake ball is :

heavier
10
EXACTLY, The fake ball is 10

-----
[snip]
-----
Round: 49
The left is heavier than the right

heavier
Weighting 2:
Both are equally heavy

equally
Weighting 3:
Both are equally heavy
The fake ball is :

equally
4
EXACTLY, The fake ball is 4

-----
Round: 50
ISITDTU{y0u_hav3_200iq!!!!}

50問解くとflagが降ってきます.
ISITDTU{y0u_hav3_200iq!!!!}

Cryptography

Old story [239pts, 47solves]

This is an old story about wheat and chessboard, and it's easy, right?
File: Old_story (cipher.txt)

file cipher.txt cipher.txt: ASCII text, with very long lines, with no line terminators

[524288, 4194304, 16384, 1024, 4194304, 32, 262144, 2097152, 4194304, 16777216, 70368744177664, 2251799813685248, 8192, 8388608, 8192, 4503599627370496, 16777216, 36028797018963968, 16384, 2199023255552, 67108864, 1048576, 2097152, 18014398509481984, 33554432, 68719476736, 4, 17179869184, 536870912, 549755813888, 262144, 4294967296, 16384, 128, 288230376151711744, 137438953472, 16777216, 36028797018963968, 1024, 4503599627370496, 16384, 68719476736, 262144, 4611686018427387904]

アプローチ:エスパー + base64

cipher.txtを見ても何も分からないのでwheat and chessboardとかでググります.

en.wikipedia.org

2の累乗とチェスボードが関係する問題だということが推測できます.
チェスボードは64マスなのでこれはbase64だとエスパーできます(???).

以下ソルバです.

import math
import string
import base64

enc = [524288, 4194304, 16384, 1024, 4194304, 32, 262144, 2097152, 4194304, 16777216, 70368744177664, 2251799813685248, 8192, 8388608, 8192, 4503599627370496, 16777216, 36028797018963968, 16384, 2199023255552, 67108864, 1048576, 2097152, 18014398509481984, 33554432, 68719476736, 4, 17179869184, 536870912, 549755813888, 262144, 4294967296, 16384, 128, 288230376151711744, 137438953472, 16777216, 36028797018963968, 1024, 4503599627370496, 16384, 68719476736, 262144, 4611686018427387904]
dec = [int(math.log(x,2)) for x in enc]

b64 = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'

flag = ''.join([b64[x - 1] for x in dec])
print(base64.b64decode(flag))

ISITDTU{r1c3_che55b0ard_4nd_bs64}

シフトが1つずれているせいで時間を浪費した

Chaos [304pts, 45solves]

Could you help me solve this case? I have a tool but do not understand how it works.

nc 104.154.120.223 8085

> nc 104.154.120.223 8085
Your cipher key: Here is your cipher: 66/99/uu 22/ww/LL/TT 55/11/nn 66/44/zz 55/rr/AA/GG 77/kk/$$/hh 00/ff/<</hh 11/11/dd 55/ll/FF/LL 44/pp/~~/yy 66/jj/++/bb 88/vv/DD/==/)) 99/pp/**/tt 44/ii/BB/ZZ 66/ss/HH/&&/,, 11/pp/??/yy 22/zz/!!/tt 77/xx/KK/MM 99/kk/$$/hh 11/kk/VV/AA 33/oo/HH/__/^^ 44/uu/%%/ll 11/mm/FF/++/`` 44/ii/OO/KK 22/tt/@@/rr 55/dd/<</bb 44/ee/HH/QQ 00/yy/WW/TT 44/uu/CC/VV 55/qq/UU/DD 33/gg/$$/bb 11/mm/II/GG 44/tt/BB/II 99/kk/GG/))/~~ 11/uu/CC/??/?? 00/aa/^^/ee 33/bb/TT/JJ 11/hh/==/ll 44/ww/||/zz 00/vv/!!/yy 44/cc/YY/DD 55/dd/KK/YY 44/tt/HH/AA 99/mm/RR/CC 77/bb/XX/QQ 55/oo/>>/qq 66/ll/../aa 77/qq/==/zz 55/ii/II/&&/@@ 66/dd/JJ/EE 44/hh/||/ww 88/bb/EE/$$/** 11/rr/GG/LL 00/tt/**/rr 88/ee/OO/@@/-- 00/kk/MM/ZZ 77/cc/QQ/CC 99/xx/RR/PP 99/dd/&&/dd 88/ss/II/||/,, 88/dd/??/pp 77/uu/LL/HH 77/ff/OO/<</.. 99/kk/KK/))/++
WELCOME TO CHAOS TOOL:
Description: This is a tool which helps you hide the content of the message
Notes:
- Message cannot contain whitespace characters
- Message can use all characters including punctuation marks and number
- Decrypt the above key to get the flag, len(key) = 64
- All punctuation marks use in plain key: ~`!@#$%^&*()_-+=<,>.?|
- Key is not a meaningful sentence
- Find the rule in this tool
**FEATURES**
<1> Encrypt message
<2> Get the flag
Your choice: 1
Enter your message: abc
Here is your cipher: 33/aa/||/jj 22/bb/../bb 77/cc/^^/xx
**FEATURES**
<1> Encrypt message
<2> Get the flag
Your choice: 1
Enter your message: ABC
Here is your cipher: 99/mm/AA/UU 22/kk/BB/HH 33/xx/CC/VV
**FEATURES**
<1> Encrypt message
<2> Get the flag
Your choice: 1
Enter your message: 0123
Here is your cipher: 00/99/uu 11/55/hh 22/88/qq 33/88/bb
**FEATURES**
<1> Encrypt message
<2> Get the flag
Your choice: 1
Enter your message: <>?
Here is your cipher: 66/jj/HH/**/<< 00/zz/JJ/%%/>> 99/ff/OO/%%/??

アプローチ:変換ルールを見つけてGet the flag

以下が変換ルールです.

[a-z]
a -> 33/aa/||/jj (スラッシュで区切った2つめ)

[A-Z]
A -> 99/mm/AA/UU (スラッシュで区切った3つめ)

[0-9]
0 -> 00/99/uu (スラッシュで区切った1つめ)

[記号]
? -> 99/ff/OO/%%/??  (スラッシュで区切った5つめ)

以下がソルバです.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string
from socket import *

s = socket(AF_INET, SOCK_STREAM)
s.connect(('104.154.120.223', 8085))

rec = s.recv(1024).decode('utf_8')
rec = s.recv(2048).decode('utf_8')
my_cipher = rec.split('\n')[0].split(' ')[4:]
msg = ''

for x in my_cipher:
    enc = x.split('/')
    if len(enc) == 4 and enc[-1][0] in string.ascii_lowercase:
        msg += enc[1][0]
    elif len(enc) == 4 and enc[-1][0] in string.ascii_uppercase:
        msg += enc[2][0]
    elif len(enc) == 3:
        msg += enc[0][0]
    else:
        msg += enc[-1][0]

print(msg)
s.send(b'2\n')
rec = s.recv(2048).decode('utf_8')
s.send(msg.encode('utf_8') + b'\n')
rec = s.recv(2048).decode('utf_8')
print(rec)
> python solve.py
wz+3tUV8)KqORqV*JzPI|d4XjM0%|#GO+<hVB|,MSr?TOzZ`z$gmUcAGpRaMon^_
Good job! Here is your flag: ISITDTU{Hav3_y0u_had_a_h3adach3??_Forgive_me!^^}

ISITDTU{Hav3_y0u_had_a_h3adach3??_Forgive_me!^^}

これCryptoなのか?

decrypt to me [395pts, 42solves]

decrypt to me?????
File: decrypt_to_me

import binascii
def generate_prg_bit(n):
    state = n
    while True:
        last_bit = state & 1
        yield last_bit
        middle_bit = state >> len(bin(n)[2:])//2 & 1
        state = (state >> 1) | ((last_bit ^ middle_bit) << (len(bin(n)[2:])-1))
flag = '###########'
enc = "OKQI+f9R+tHEJJGcfko7Ahy2AuL9c8hgtYT2k9Ig0QyXUvsj1B9VIGUZVPAP2EVD8VmJBZbF9e17"
flag_bin_text = bin(int(binascii.hexlify(flag), 16))[2:]
prg =  generate_prg_bit(len(flag_bin_text))
ctext = []
flag_bits = [int(i) for i in flag_bin_text]
for i in range(len(flag_bits)):
    ctext.append(flag_bits[i] ^ next(prg))  
ciphertext = '0b' + ''.join(map(str, ctext))
n = int(ciphertext, 2)
print binascii.unhexlify('%x' % n).encode('base64')

アプローチ:全探索

適切なflagencryptするとOKQI+f9R+tHEJJGcfko7Ahy2AuL9c8hgtYT2k9Ig0QyXUvsj1B9VIGUZVPAP2EVD8VmJBZbF9e17になるっぽいです.
encrypt処理を読む限り,1つのbitencrypt全体に影響を与えるような処理はされていないことが分かります.
つまり,1文字ずつflagを探索していくことが可能です.

以下ソルバです.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import base64
import binascii
import string
from Crypto.Util.number import *


def generate_prg_bit(n):
    state = n
    while True:
        last_bit = state & 1
        yield last_bit
        middle_bit = state >> len(bin(n)[2:])//2 & 1
        state = (state >> 1) | ((last_bit ^ middle_bit) << (len(bin(n)[2:])-1))

def encrypt(flag):
    flag_bin_text = bin(bytes_to_long(flag.encode('utf_8')))[2:]
    prg =  generate_prg_bit(len(flag_bin_text))
    ctext = []
    flag_bits = [int(i) for i in flag_bin_text]
    for i in range(len(flag_bits)):
        ctext.append(flag_bits[i] ^ next(prg))

    ciphertext = '0b' + ''.join(map(str, ctext))
    n = int(ciphertext, 2)
    enc = base64.b64encode(long_to_bytes(n)).decode('utf_8')
    return enc

def char_match(target, enc):
    count = 0
    for t,e in zip(target, enc):
        if t == e:
            count += 1
        else:
            break
    return count

match_length = 10
flag = 'ISITDTU{' # length 57 (?)
target = 'OKQI+f9R+tHEJJGcfko7Ahy2AuL9c8hgtYT2k9Ig0QyXUvsj1B9VIGUZVPAP2EVD8VmJBZbF9e17'
search_range = string.ascii_letters + string.digits + '{}_!@'

for i in range(47):
    max_length = match_length
    max_a = ''
    max_b = ''
    for a in search_range:
        for b in search_range:
            enc_result = encrypt(flag + a + b  + '*' * (56-len(flag + a + b)) + '}')
            length = char_match(target, enc_result)
            if length > max_length:
                max_length = length
                max_a = a
                max_b = b
    flag += max_a
    match_length = max_length
    print(flag + max_b)
> python solve.py
ISITDTU{El
ISITDTU{Ena
ISITDTU{Encr
ISITDTU{Encrx
ISITDTU{Encryp
ISITDTU{Encrypt
ISITDTU{Encrypt_
ISITDTU{Encrypt_X
ISITDTU{Encrypt_X0
ISITDTU{Encrypt_X0p
ISITDTU{Encrypt_X0rP
ISITDTU{Encrypt_X0r_N
ISITDTU{Encrypt_X0r_N0
ISITDTU{Encrypt_X0r_N0p
ISITDTU{Encrypt_X0r_N0t_
ISITDTU{Encrypt_X0r_N0t_T
ISITDTU{Encrypt_X0r_N0t_Us
ISITDTU{Encrypt_X0r_N0t_Us3
ISITDTU{Encrypt_X0r_N0t_Us3_
ISITDTU{Encrypt_X0r_N0t_Us3_P
ISITDTU{Encrypt_X0r_N0t_Us3_Ps
ISITDTU{Encrypt_X0r_N0t_Us3_Psd
ISITDTU{Encrypt_X0r_N0t_Us3_Psep
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0P
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_R
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Ra
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Raa
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0a
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_D
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Ga
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Gen
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Gend
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Genep
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Genera
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!!
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!!!
ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!!!!

ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!!!!}

多分想定解法とは違うと思います.
もっとスマートに解きたかった…

Thank you

Survey [10pts, 263solves]

Thank you for join with us, hope to see you next year, and so sorry about the server issue.
Survey

アプローチ:wgetでサクッと終わらせる (アンケートに答えない)

> wget https://forms.gle/v3eqi162QLeeBuse6
> grep 'ISITDTU{' ./v3eqi162QLeeBuse6
,["ISITDTU{thank_you_for_your_feedback}",1,0,0,0]

ISITDTU{thank_you_for_your_feedback}

まとめ

  • 最近チームで参加できていない
  • Web, Pwn... (勉強します)
  • BabyなのでEasy RSAが解けない (Boneh Durfee Attackとか初めて聞いた(Wiener's Attackしか知らなかった)し,近似してからフェルマー法かけるのは思いつかなかった…)

f:id:satto1237:20190702011350p:plain

BCACTF 2019 Write-up

はじめに

2019/06/09 ~ 2019/06/16に開催されたBCACTFに個人で参加しました.

成績

115位(902チーム中)でした.

f:id:satto1237:20190616190048p:plain

Welcome

hello-world [50pts, 858solves]

Input your first ever flag! The flag is bcactf{hello!}

アプローチ:問題文を読む

bcactf{hello!}

net-cat [50pts, 700solves]

Some problems in this CTF will require you to use netcat to access server-side problems.

For this problem netcat in to our server by using
nc challenges.ctfd.io 30126

アプローチ:問題文を読む

> nc challenges.ctfd.io 30126
bcactf{5urf1n_7h3_n37c47_c2VydmVyc2lkZQ}

bcactf{5urf1n_7h3_n37c47_c2VydmVyc2lkZQ}

wuphf [50pts, 563solves]

Social media is so fractured today. I mean, there's Discord, Twitter, Instagram... Don't you wish there was just one platform that could send things to every platform? Sadly that's not the case, so to find the flag you will have to collect flag-ments from all of our platforms.

アプローチ:問題文を読む

f:id:satto1237:20190616191024p:plain

www.instagram.com

Discord: bcactf{h17
Twitter: _u5_uP_d3
Instagram: VwaGYuY29t}

bcactf{h17_u5_uP_d3VwaGYuY29t}

Binary-exploitation

executable [150pts, 217solves]

It's in there somewhere. Good luck!

> file executable-ubuntu
executable-ubuntu: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=2d69b145cafba5b1850ed1677373b4058b19a78e, not stripped

アプローチ:strings

stringsするとBrainf*ckっぽいのが出てきます.

> strings executable-ubuntu
[snip]
Welcome to the lottery!
So now we're going to pick a ginormous number!
If it's 1, you win!
Your number is %d!
Congratulations, you're our lucky winner!
Try again next time!
--[----->+<]>----.+.--.++.-[--->+<]>--.+++[->+++<]>+.+[----->+<]>.>-[----->+<]>.+[--->++<]>.[++>---<]>-.-[->++<]>-.-[--->+<]>-.-.>-[----->+<]>+.---[->++<]>.++++++++++.[-->+<]>---.--[--->++<]>---.++[->+++<]>.[--->+<]>---.+++[->+++<]>.+++++++.-[--->+<]>--.-------.---------------.+[-->+<]>+.+.++.+[->++<]>.--.---.+++++++++++++.--[->+++++<]>.++++++++.+.-------.++.+.>--[-->+++<]>.
;*3$"
GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
[snip]

適当なインタプリタで実行すればflagが出てきます.

bcactf{3x3cut4bl3s_r_fun_124jher089245}

これのどこにPwn要素があるんだろう?

Crypto

basic-numbers [50pts, 698solves]

We have a raw flag here, but what do we do with it?

01100010 00110001 01101110 01100001 01110010 01111001 01011111 01110011
00110000 01101100 01110110 00110011 01100100 01011111 01100111 00110000
00110000 01100100 01011111 01110111 00110000 01110010 01101011

アプローチ:bin to ascii

bins = '01100010 00110001 01101110 01100001 01110010 01111001 01011111 01110011 00110000 01101100 01110110 00110011 01100100 01011111 01100111 00110000 00110000 01100100 01011111 01110111 00110000 01110010 01101011'
flag = ''
for b in bins.split(' '):
    flag += chr(int(b, 2))
print('bcactf{{{0}}}'.format(flag))

bcactf{b1nary_s0lv3d_g00d_w0rk}

cracking-the-cipher [50pts, 627solves]

Hackers work in the most unlikely of places. We have recently discovered one working in a grocery store (weird), and he was able to print out receipts to pass on information to certain customers. We have obtained one of the receipts, but we cannot tell what it says.
vjg rcuuyqtf ku ngctpkpi_ecguct_ekrjgtu_ku_hwp!

アプローチ:rot24

the password is learning_caesar_ciphers_is_fun! bcactf{learning_caesar_ciphers_is_fun!}

three-step-program [125pts, 300solves]

We found this strange file with a bunch of stuff in it... Can you help us decode it?

MzIgLSAgfDMgVGltZXMgQSBDaGFybXwgLSAzMg==

JJGTEVSLKNBVISSGINCU2VCTGJFVETCWKNGVGTKLKJEEKQ2VJNEUSNC2KZKVCS2OJFNE4RKPKNFUUSKSJNKTITSDKJFEERKUI5GTETKJLJGVMQ2RJNLEWUSLIZAVES2DJRFE2RKDK5JU2SKKJBCTEVKLJBDUSWSUI5KTETSLKZEVKS2TLJKEWUSFIU2FKU2WJRBEIVCFKFJVASKWIFKU2USLIRDUUR2FGJJEWQ2LKJGFMR2TJNCUYSSIIRFU2U2UJFCTEVKJKZJUMSKKJNKU6VK2KRFVES2VGZKEWUSKIJCVIR2XKNBEUNKGIZDVMMSEJRFEERKDKRJVOR2SJJKUGV2TJVFDKR2VGRLVGSKLJUZEKSKWJNHEWWSKKVDVCSSUJFJEERJUK5JVKTCCIZKEKVCDIVFFUQKWKFITEQSJJZEVKV2SGJDEYQSCKVBVMSSTJFFEMRSFKMZEISKFLJCVSTKTIZEUUTCGJ5JVUV2KJJAVKNSVKNMUWTSBKZKU2MSUJJLEYRCFKEZEETCKJNDECVCSKZFU4QSVI5ITEU2LJZCEMU2VJNDEYRSOIVKVCS2OJRFE4RKPKFNFIS2SINCTEUSTKZGEERCVKNJEGRKKGVDEISKXINBEOVSDIVGVES2DJM2UIVKXKNFUKSS2I5LE2VSLLBGEKWSVJFJFGUCLLJHEKQ2QJI2UQVJWKE6T2PJ5

lhlm oad lamaew eyhmgs. lg i sxsro rgu ntee qhj a qesg? dbfcp rgu stne xtve tm lhtl xac, b’dl rh wadr gn jhm ayw zayw at zowr. 
mvscey{bu57_j0n_o4i7_kgbhmffhlqe} bfm, te htjnpw, feim lixx at hhf’t mx ko dbepwx…

アプローチ:Vigenere cipher

first-stepのbase64をデコードします.

> echo 'MzIgLSAgfDMgVGltZXMgQSBDaGFybXwgLSAzMg==' | base64 -D
32 -  |3 Times A Charm| - 32

???
何も分からないのでthird-stepの暗号化方式をエスパーしてVigenere Solverで無理やり解きます.

www.guballa.de

that was simple enough. so i heard you came for a flag? since you have made it this far, i’ll go easy on you and hand it over. 
bcactf{ju57_y0u_w4i7_znjhbmnhaxm} but, be warned, next time it won’t be so simple…

bcactf{ju57_y0u_w4i7_znjhbmnhaxm}

keysaltらしいです.

a-major-problem [200pts, 313solves]

A mysterious figure named Major Mnemonic has sent you the following set of words. Figure out what they mean!

"Pave Pop Poke Pop Dutch Dozen Denim Deism Loot Thatch Pal Atheism Rough Ditch Tonal"

アプローチ:Mnemonic major system

オンラインツールを使ってデコードするとメッセージは98, 99, 97, 99, 116, 102, 123, 103, 51, 116, 95, 103, 47, 116, 125に対応していることがわかります.

major-system.info

asciiに変換すると以下のようになります.

num_words = [98, 99, 97, 99, 116, 102, 123, 103, 51, 116, 95, 103, 47, 116, 125]
flag = [chr(x) for x in num_words]
print(''.join(flag))

bcactf{g3t_g/t}

これで終わりかと思いきやこのflagsubmitしてもincorrectと言われます.

色々と試してみても上手く行かなかったので最終的にエスパーで通しました (/に違和感があったので0に置き換えてsubmitするとcorrectになりました).

bcactf{g3t_g0t}

Forensics

split-the-red-sea [100pts, 551solves]

Moses used a staff to split the Red Sea. What will you use?

f:id:satto1237:20190616200035p:plain

アプローチ:Exif

> exiftool redsea.png | grep bcactf
Text Layer Name                 : bcactf{7w0_r3d5_sdf3wqa}
Text Layer Text                 : bcactf{7w0_r3d5_sdf3wqa}

bcactf{7w0_r3d5_sdf3wqa}

bca-craft [125pts, 460solves]

Yo I made a sic Minecraft adventure MAP! Try it out it's kewler than ur Fortnite gamez!

アプローチ:grep

> grep -r 'flag' ./BCACraft
./BCACraft/datapacks/bcacraft/data/bca/functions/flag.mcfunction:tellraw @a ["Hello ", {"selector": "@p", "color": "yellow"}, "! The flag is: ", "b", "c", "a", "c", "t", "f", "{", {"text": "m1n3cr4f7_b347s_f0rtn1t3", "color": "blue", "bold": true, "obfuscated": true, "hoverEvent": {"action": "show_text", "value": {"text": "Good luck! ", "extra": [{"text": "Hint: Where does Minecraft store its worlds?", "color": "dark_gray", "italic": true}]}}}, "}"]

bcactf{m1n3cr4f7_b347s_f0rtn1t3}

file-head [125pts, 457solves]

It looks like the PNG file that holds our flag has been corrupted. My computer isn't able to recognize the file type, maybe it has something to do with how the file type is recognized...

> file flag.png
flag.png: 5View capture file

アプローチ:マジックナンバー

バイナリエディタflag.pngを開くとヘッダが0xAAで潰されていることが分かります.

f:id:satto1237:20190616201126p:plain

89 50 4E 47 0D 0A 1A 0Aに修正します.

f:id:satto1237:20190616201425p:plain

bcactf{f1l3_h3ad3rs_r_c001}

of-course-rachel [150pts, 219solves]

Ugh, I had a really important file with the flag, but sadly it broke. My friend Rachel said that snapshots are good for backing up, and luckily I listened so here is my screenshot. Do you think you could help me put it back together?

> tree snapshot
snapshot
├── part1.png
├── part2.png
├── part3.png
├── part4.png
└── part5.png

0 directories, 5 files

f:id:satto1237:20190616202007p:plain

part*.pngにはそれぞれhex dataっぽいものが描画されているのでOCRを使ってテキストデータに変換します.

www.onlineocr.net

テキストデータを1つのファイルにまとめます

from Crypto.Util.number import long_to_bytes

with open('./snapshot/memo.txt') as f:
    hex_lines = [line.strip() for line in f.readlines()]

flag = b''

for line in hex_lines:
    for msg in line.split(' '):
        flag += long_to_bytes(int(msg,16))

with open('flag.py', 'wb') as f:
    f.write(flag)

出力結果はPythonスクリプトになります.

import binascii
import random


class Vector(object):
    """
        This class represents a vector of arbitray size.
        You need to give the vector components. 

        Overview about the methods:

        constructor(components : list) : init the vector
        set(components : list) : changes the vector components.
        __str__() : toString method
        component(i : int): gets the i-th component (start by 0)
        __len__() : gets the size of the vector (number of components)
        euclidLength() : returns the eulidean length of the vector.
        operator + : vector addition
        operator - : vector subtraction
        operator * : scalar multiplication and dot product
        copy() : copies this vector and returns it.
        changeComponent(pos,value) : changes the specified component.
        TODO: compare-operator
    """

    def __init__(self, components=[]):
        """
            input: components or nothing
            simple constructor for init the vector
        """
        self.__components = list(components)

    def set(self, components):
        """
            input: new components
            changes the components of the vector.
            replace the components with newer one.
        """
        if len(components) > 0:
            self.__components = list(components)
        else:
            raise Exception("please give any vector")

    def __str__(self):
        """
            returns a string representation of the vector
        """
        return "(" + ",".join(map(str, self.__components)) + ")"

    def component(self, i):
        """
            input: index (start at 0)
            output: the i-th component of the vector.
        """
        if type(i) is int and -len(self.__components) <= i < len(self.__components):
            return self.__components[i]
        else:
            raise Exception("index out of range")

    def __len__(self):
        """
            returns the size of the vector
        """
        return len(self.__components)

    def eulidLength(self):
        """
            returns the eulidean length of the vector
        """
        summe = 0
        for c in self.__components:
            summe += c**2
        return math.sqrt(summe)

    def __add__(self, other):
        """
            input: other vector
            assumes: other vector has the same size
            returns a new vector that represents the sum.
        """
        size = len(self)
        if size == len(other):
            result = [self.__components[i] +
                      other.component(i) for i in range(size)]
            return Vector(result)
        else:
            raise Exception("must have the same size")

    def __sub__(self, other):
        """
            input: other vector
            assumes: other vector has the same size
            returns a new vector that represents the differenz.
        """
        size = len(self)
        if size == len(other):
            result = [self.__components[i] -
                      other.component(i) for i in range(size)]
            return result
        else:  # error case
            raise Exception("must have the same size")

    def __mul__(self, other):
        """
            mul implements the scalar multiplication 
            and the dot-product
        """
        if isinstance(other, float) or isinstance(other, int):
            ans = [c*other for c in self.__components]
            return ans
        elif (isinstance(other, Vector) and (len(self) == len(other))):
            size = len(self)
            summe = 0
            for i in range(size):
                summe += self.__components[i] * other.component(i)
            return summe
        else:  # error case
            raise Exception("invalide operand!")

    def copy(self):
        """
            copies this vector and returns it.
        """
        return Vector(self.__components)

    def changeComponent(self, pos, value):
        """
            input: an index (pos) and a value
            changes the specified component (pos) with the
            'value'
        """
        # precondition
        assert (-len(self.__components) <= pos < len(self.__components))
        self.__components[pos] = value


flag = 820921601166721424573282546345206805820898697321521913920196691573868657577500743744203737234698


def zeroVector(dimension):
    """
        returns a zero-vector of size 'dimension'
    """
    # precondition
    assert(isinstance(dimension, int))
    return Vector([0]*dimension)


def main():
    print(int_to_text(flag))


def unitBasisVector(dimension, pos):
    """
        returns a unit basis vector with a One 
        at index 'pos' (indexing at 0)
    """
    # precondition
    assert(isinstance(dimension, int) and (isinstance(pos, int)))
    ans = [0]*dimension
    ans[pos] = 1
    return Vector(ans)


def axpy(scalar, x, y):
    """
        input: a 'scalar' and two vectors 'x' and 'y'
        output: a vector
        computes the axpy operation
    """
    # precondition
    assert(isinstance(x, Vector) and (isinstance(y, Vector))
           and (isinstance(scalar, int) or isinstance(scalar, float)))
    return (x*scalar + y)


def randomVector(N, a, b):
    """
        input: size (N) of the vector.
               random range (a,b)
        output: returns a random vector of size N, with 
                random integer components between 'a' and 'b'.
    """
    random.seed(None)
    ans = [random.randint(a, b) for i in range(N)]
    return Vector(ans)


def text_to_int(inp):
    hexed = binascii.hexlify(inp)
    return int(hexed, 16)


def int_to_text(inp):
    hexed = hex(inp)
    return bytearray.fromhex(hexed[2:]).decode()


class Matrix(object):
    """
    class: Matrix
    This class represents a arbitrary matrix.

    Overview about the methods:

           __str__() : returns a string representation 
           operator * : implements the matrix vector multiplication
                        implements the matrix-scalar multiplication.
           changeComponent(x,y,value) : changes the specified component.
           component(x,y) : returns the specified component.
           width() : returns the width of the matrix
           height() : returns the height of the matrix
           operator + : implements the matrix-addition.
           operator - _ implements the matrix-subtraction
    """

    def __init__(self, matrix, w, h):
        """
            simple constructor for initialzes 
            the matrix with components.
        """
        self.__matrix = matrix
        self.__width = w
        self.__height = h

    def __str__(self):
        """
            returns a string representation of this
            matrix.
        """
        ans = ""
        for i in range(self.__height):
            ans += "|"
            for j in range(self.__width):
                if j < self.__width - 1:
                    ans += str(self.__matrix[i][j]) + ","
                else:
                    ans += str(self.__matrix[i][j]) + "|\n"
        return ans

    def changeComponent(self, x, y, value):
        """
            changes the x-y component of this matrix
        """
        if x >= 0 and x < self.__height and y >= 0 and y < self.__width:
            self.__matrix[x][y] = value
        else:
            raise Exception("changeComponent: indices out of bounds")

    def component(self, x, y):
        """
            returns the specified (x,y) component
        """
        if x >= 0 and x < self.__height and y >= 0 and y < self.__width:
            return self.__matrix[x][y]
        else:
            raise Exception("changeComponent: indices out of bounds")

    def width(self):
        """
            getter for the width
        """
        return self.__width

    def height(self):
        """
            getter for the height
        """
        return self.__height

    def __mul__(self, other):
        """
            implements the matrix-vector multiplication.
            implements the matrix-scalar multiplication
        """
        if isinstance(other, Vector):  # vector-matrix
            if (len(other) == self.__width):
                ans = zeroVector(self.__height)
                for i in range(self.__height):
                    summe = 0
                    for j in range(self.__width):
                        summe += other.component(j) * self.__matrix[i][j]
                    ans.changeComponent(i, summe)
                    summe = 0
                return ans
            else:
                raise Exception(
                    "vector must have the same size as the " + "number of columns of the matrix!")
        elif isinstance(other, int) or isinstance(other, float):  # matrix-scalar
            matrix = [[self.__matrix[i][j] *
                       other for j in range(self.__width)] for i in range(self.__height)]
            return Matrix(matrix, self.__width, self.__height)

    def __add__(self, other):
        """
            implements the matrix-addition.
        """
        if (self.__width == other.width() and self.__height == other.height()):
            matrix = []
            for i in range(self.__height):
                row = []
                for j in range(self.__width):
                    row.append(self.__matrix[i][j] + other.component(i, j))
                matrix.append(row)
            return Matrix(matrix, self.__width, self.__height)
        else:
            raise Exception("matrix must have the same dimension!")

    def __sub__(self, other):
        """
            implements the matrix-subtraction.
        """
        if (self.__width == other.width() and self.__height == other.height()):
            matrix = []
            for i in range(self.__height):
                row = []
                for j in range(self.__width):
                    row.append(self.__matrix[i][j] - other.component(i, j))
                matrix.append(row)
            return Matrix(matrix, self.__width, self.__height)
        else:
            raise Exception("matrix must have the same dimension!")


def squareZeroMatrix(N):
    """
        returns a square zero-matrix of dimension NxN
    """
    ans = [[0]*N for i in range(N)]
    return Matrix(ans, N, N)


def randomMatrix(W, H, a, b):
    """
        returns a random matrix WxH with integer components
        between 'a' and 'b'
    """
    random.seed(None)
    matrix = [[random.randint(a, b) for j in range(W)] for i in range(H)]
    return Matrix(matrix, W, H)


main()
> python flag.py
bcactf{0p71c4lly_r3c0gn1z3d_ch4r4c73rs}

open-docs [150pts, 420solves]

Yay! I really enjoy using these free and open file standards. I love them so much, that I made a file expressing how much I like using them. Let's enjoy open standards together!

f:id:satto1237:20190616203408p:plain

アプローチ:unzip

docxファイルをunzipして中身詳しく見ていきます.

> tree open
open
├── [Content_Types].xml
├── _rels
├── docProps
│   ├── app.xml
│   └── core.xml
└── word
    ├── _rels
    │   └── document2.xml.rels
    ├── document2.xml
    ├── fontTable.xml
    ├── secrets.xml
    ├── settings.xml
    ├── styles.xml
    ├── theme
    │   └── theme1.xml
    └── webSettings.xml

5 directories, 11 files

secret.xmlに怪しいbase64テキストがあります.

<?xml version="1.0" encoding="utf-8"?>
PHNlY3JldCBmbGFnPSJiY2FjdGZ7ME94TWxfMXNfNG00ejFOZ30iIC8+
> echo 'PHNlY3JldCBmbGFnPSJiY2FjdGZ7ME94TWxfMXNfNG00ejFOZ30iIC8+' | base64 -D
<secret flag="bcactf{0OxMl_1s_4m4z1Ng}" />

bcactf{0OxMl_1s_4m4z1Ng}

study-of-roofs [150pts, 294solves]

My friend has always gotten in to weird things, and his recent obsession is with roofs. He sent me this picture recently, and said he hid something special in it. Do you think you could help me find it?

f:id:satto1237:20190616203918j:plain

アプローチ:ファイル抽出

binwalkすると別のjpgが埋め込まれていることがわかります.

> binwalk dem_shingles.jpg

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
0             0x0             JPEG image data, EXIF standard
12            0xC             TIFF image data, big-endian, offset of first image directory: 8
14689         0x3961          Unix path: /www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stEvt=
1562983       0x17D967        JPEG image data, EXIF standard
1562995       0x17D973        TIFF image data, big-endian, offset of first image directory: 8
1568937       0x17F0A9        Unix path: /www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:xmpMM="http
1573688       0x180338        Copyright string: "Copyright (c) 1998 Hewlett-Packard Company"

f:id:satto1237:20190616204345j:plain

bcactf{r4i53_7h3_r00f_liz4rd}

wavey [150pts, 347solves]

My friend sent me his new mixtape, but honestly I don't think it's that good. Can you take a look at it and figure out what's going on?

> file straightfire.wav
straightfire.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 22050 Hz

アプローチ:スペクトログラム

f:id:satto1237:20190616204732p:plain

bcactf{f331in_7h3_vib3z}

corrupt-psd [200pts, 343solves]

I wanted to use Photoshop to embiggen my head, but er... something happened. It looks like Photoshop isn't the signature image editing program it used to be.

> file flag.psd
flag.psd: data

アプローチ:マジックナンバー

f:id:satto1237:20190616205229p:plain

バイナリエディタflag.psdを開くとヘッダがOOPSになっていることが分かります.

本来のpsdファイルのヘッダは0x38425053なのでヘッダを修正します.

f:id:satto1237:20190616205611p:plain

bcactf{corrupt3d_ph0705sh0p?_n0_pr0b5_1af4efb890}

the-flag-is [200pts, 377solves]

I have a flag! The flag is... wait... did my PDF editor not save the flag? OH NO! I remember typing it in, can you help me find it?

> file flag.pdf
flag.pdf: PDF document, version 1.3

f:id:satto1237:20190616205815p:plain

アプローチ:foremost

f:id:satto1237:20190616205858p:plain

bcactf{d0n7_4g3t_4b0u7_1nCr3Men74l_uPd473s}

Programming

1+1=window [75pts, 307solves]

hex+hex=hex

> file one.txt two.txt
one.txt: ASCII text
two.txt: ASCII text

one.txt

0x23 0x49 0x16 0x46 0x45 0x16 0x3c 0x3c 0x45 0x64 0x16 0x37 0x3c 0x3c 0x3c 0x16 0x46 0x45 0x37 0x1e 0x49 0x16 0x46 0x49 0x16 0x1e 0x16 0x32 0x32 0x3c 0x32 0x49 0x3c 0x64 0x1e 0x32 0x3c 0x18 0x64 0x32 0x32 0x50 0x14 0x64 0x32 0x5a 0x45 0x32 0x32 0x55 0x50 0x49 0x3c 0x14 0x3c 0x5f

two.txt

0x26 0x2b 0x0a 0x23 0x2e 0x0a 0x29 0x25 0x2e 0x15 0x0a 0x37 0x25 0x25 0x2c 0x0a 0x23 0x2e 0x37 0x09 0x2b 0x0a 0x23 0x2b 0x0a 0x21 0x0a 0x30 0x31 0x25 0x31 0x2b 0x2a 0x17 0x13 0x2d 0x2c 0x18 0x0c 0x01 0x2d 0x29 0x1c 0x11 0x2d 0x1b 0x2e 0x01 0x2d 0x1b 0x29 0x2b 0x2c 0x1c 0x32 0x1e

アプローチ:足す

with open('./one.txt') as f:
    one = f.readline().strip().split(' ')

with open('./two.txt') as f:
    two = f.readline().strip().split(' ')

flag = [chr(int(o[2:], 16) + int(t[2:], 16)) for o, t in zip(one, two)]
print(''.join(flag))

It is easy naah isn't it ? bcactf{1_h0p3_y0u_us3_pyth0n}

bcactf{1_h0p3_y0u_us3_pyth0n}

bca-store [75pts, 247solves]

You are a cashier for a small store that sells a few items. Coming up is the annual sale, and you really don't want to do that much math. So, being you, you decide to automate it.

You are a cashier for a small store that sells a few items. Coming up is the annual sale, and you really don't want to do that much math. So, being you, you decide to automate it.

Items:

A: $45, no sale
B: $52, buy one get one 10% off
C: $67, buy one get one half off
D: $75, buy two get one free
Input:

What the customer ordered, separated by spaces.
The amount the customer paid.
For example, C B B C A 250.

The input file is attached. If we had the above twice, then you can use the following to test on your local machine:

C B B C A 250
D A B B 250
D D D D D A B 390

5.70
31.20
-1

input.txt

C B B C A 250
A C D A 230
A B C D 240
D D D 225
A A A A 150
A A A A B B B B B C C C C C D D D D 1000
A A A A B B B B B C C C C C D D D D 900

アプローチ:普通に計算する

クソコードになってしまった

import fileinput

flag = ''

for line in fileinput.input():
    print('-' * 100)
    A_cnt = 0
    B_cnt = 0
    C_cnt = 0
    D_cnt = 0
    problem = line.strip().split(' ')
    paid = int(problem[-1])
    for x in problem[:-1]:
        if x == 'A':
            A_cnt += 1
        elif x == 'B':
            B_cnt += 1
        elif x == 'C':
            C_cnt += 1
        else:
            D_cnt += 1
    print(problem)
    print(A_cnt, B_cnt, C_cnt, D_cnt)
    ans = paid - (A_cnt * 45 + B_cnt//2*52*0.9 + (B_cnt - B_cnt//2)*52 + C_cnt//2*67*0.5 + (C_cnt - C_cnt//2)*67 + (D_cnt - D_cnt//3)*75)
    print('{:.2f}'.format(ans))
    if ans < 0:
        flag += '-1 '
    else:
        flag += '{:.2f}'.format(ans) + ' '

print(flag)

5.70 -1 1.00 75.00 -1 77.40 -1

instructions [175pts, 320solves]

We intercepted a message between two agents from a terrorist group known as 0x4556494c. We think it might contain some useful information, so we'd like you to crack it. Here is the message.

Dear Agent Reffef,

I have attached the super secret plans for operation 0x576f726b206f6e207468652070757a7a6c652c2073746f702072656164696e672068657821.
You will need to decode it first though.

The rules are simple:

A line is "viable" if the length of a line is divisible by 3, and the line does not contain the `&` character. 

For every viable line, you will grab the `n`th character, 
where `n` is the corresponding number at the top of the file (Counting from one!) 
The first viable line will use the first number, etc.

Put all the letters together to find the answer!  

- Agent Doposi
> wc -l flag.txt
    1656 flag.txt

flag.txt

20 30 8 14 17 24 44 19 17 29 20 34 35 27 42 34 7 25 7 21 8 38 13 25 14 13 42 14 20 23 3 27 38 9 18 41 3 11 35
X=yU|(}J=|%Std-RtJ)hWb^+)$F$Usne}u7UaTB50+Yn52#(Zj9(j[PW61|}c++%*I+a6O9li\89M;)
V6Em{hdTl#5nc:xb0zPj1KqhlrS;pIGTUtM&94BXY-r0x1#OTd6yD-
]t!xTzZg-Yz|#+Av*Ha[#Ps;l$d+;whUGx64C^n]Jt\XG)%eUoR4K{KZyTUFLY^xsuX}g%3W+
C0+FQdv\IZGkP8rk-|FirmeqgtPHpfp$OM_6hm=b9[:bV]
YHsM5*w43A]btgOX_(9FFfNv)\12IhwLf:-b0_9m
1cTwC]Sp%LUoRnDr}fzPvA]tQ9BgGhIT&i0kIr[60[kV7Lnh5#CUs\f}tuyP{-L7FvLXQCHHp}t)W6
\IPx6FXK7dNj%cyot*eGpAj4Mm7hKvs1-4-So5pwfwA1-gDZ=1Rj\vBxp9dtJOv[R@}ng])UjO}g
+\;XqU#{#u^x:i[SjqozO)vGQ9x&2Go:oGH49C#fU\vH+l1mMk]:w;W:@|P+svp
Xu2AcLyn*&c2$2+pZxe-bTcFCzmxhU;x}AOXBg8veQ}BzFrSD@RtKRN{hRqQptj-DEz$U3@rlRH
[snip]

アプローチ:ルールに従って実装する

文字列長が3の倍数であり,&を含んでいないテキストを抽出し,x文字目を参照します.

flag = ''

with open('./flag.txt') as f:
    msg = [line.strip() for line in f.readlines()]

secret_lines = []
for x in msg[1:]:
    if len(x) % 3 == 0 and '&' not in x:
        secret_lines.append(x)

for secret, secret_line in zip(msg[0].split(' '), secret_lines):
    flag += secret_line[int(secret,10) - 1]

print(flag)

bcactf{f0110w_tH3_r00lz_<3_l0ve_m3_pls}

public-library [200pts, 404solves]

Hidden in this mysterious public library is the flag. Can you get it?

> file PublicLibrary.class
PublicLibrary.class: compiled Java class data, version 52.0 (Java 1.8)

アプローチ:strings

> strings PublicLibrary.class | grep bcactf
,bcactf{t4k3_4_j4v4_c7a55_789208694209642475}

bcactf{t4k3_4_j4v4_c7a55_789208694209642475}
これ系(デコンパイルして系)の問題出すならflagを生で保持していてはダメなのでは…

manner-of-thpeaking [250pts, 191solves]

Tho, I came Acroth thith therieth of inthturcthins, and thomething that thaid "the key ith the attached litht of ATHCII printableth." Tho anywayth, here'th the inthtructhinth.

printableth.txt

(( !\"#$%&'\(\)*+,-./)(0123456789)(:;<=>?@)(ABCDEFGHIJKLMNOPQRSTUVWXYZ)(\[\\\]^_`)(abcdefghijklmnopqrstuvwxyz)(\{|\}~))

inthtructhins.txt

cadadddddr, caddadddddr, caadddddr, caddadddddr, cadddddddddddddddddddadddddr, cadddddadddddr, caaddddddr, cadddddddddddadddr, cadadr, cadddddadr, cadddddddadr, caddddaddddr, caddddddddadr, caddddadr, cadddddadr, cadddadr, cadddadddddr, caddddaddddr, cadddddddddddddddadddddr, cadddddddddddddddddadddr, caadr, caddddddadddddr, cadddddddddddddddddadddr, caddddadr, caddddddddddddadddr, caddddddddddddadddddr, cadadr, cadddddddddddddadddddr, caddddddadddr, caddddaddddr, cadadr, cadddddadr, caddddaddddr, caddddadr, caddddddddddddddddddddddadddddr, cadddadr, caddddddddddddddddddadddr, caadr, caddddddddddddadddr, caddddadddddr, cadar, caddaddddddr

アプローチ:CARとCDR

inthtructhins.txtのコマンドがlispCARCDR(リストを操作するための基本的な2つの関数)っぽく見えたのでそれっぽい処理を実装します.

yoshiiz.blog.fc2.com

printables = [' !\"#$%&\'()*+,-./', '0123456789', ':;<=>?@', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '[\\]^_`', 'abcdefghijklmnopqrstuvwxyz', '{|}~']
flag = ''
with open('./inthtructhins.txt') as f:
    cmds = f.readline().strip().split(' ')

for cmd in cmds:
    d_count = 0
    s = printables
    for x in cmd[1:-1][::-1]:
        if x == 'd':
            d_count += 1
        elif x == 'a':
            s = s[d_count:][0]
            d_count = 0
    flag += s

print(flag)

bcactf{L157_8453d_pR0gR4Mm1nG_15_4w3S0Me!}

Quest

for-the-night-is-dark-1 [150pts, 254solves]

Hello, traveler. Welcome to your quest. You must walk the Red Lord's shining path, guided by his shining stars. Here is a picture of those stars. A map if you will. May the Lord of Light give you wisdom.

> file starmap.bmp
starmap.bmp: PC bitmap, Windows 3.x format, 63 x 63 x 24

f:id:satto1237:20190616214502p:plain

アプローチ:R value to ascii

from PIL import Image

img = Image.open('./starmap.bmp')
size = img.size

msg = ''

for y in range(size[1]):
    for x in range(size[0]):
        rgb = img.getpixel((x,y))
        if rgb[0] > 0:
            msg += chr(rgb[0])

print(msg)
> python solve.py
http://rhllor.xyz/7h3fir31n0urh3ar75_d2VsY29tZSB0byBzdGVwIG9uZQ

ソルバを実行するとURLが出力されます.
飛ぶとflagがとれます.

f:id:satto1237:20190616215053p:plain

bcactf{gu1d3d_8y_574r5_QmVnaW5uaW5ncw}

for-the-night-is-dark-2 [150pts, 247solves]

The Lord of Light always knows the truth. A true hero of the light would always be able to tell the truth as well. Prove yourself a true hero here and you will recieve your second flag.

f:id:satto1237:20190616215559p:plain

アプローチ:md5

stage2.js

$("#target").submit(function( event ) {
  var hash = md5($("#secret").val())
  if (hash == "3758002ab24653af8d550c0c50473098") {
    var encode = "ÐßϽ榠ÐÞÙ֩û¤× ÃºªîÈ©¼×ÐÖËÕ§£¢Íç«ÖÉ̱ÈÕÒßÊÕÅ"
    var newstr = ""
    var key = $("#secret").val()
    for (var i = 0; i < encode.length; i++) {
        newstr += String.fromCharCode(encode.charCodeAt(i) - key.charCodeAt(i%key.length))
    }
    window.location = "/f" + newstr
  }

  $("#secret").val("")
  event.preventDefault();
});

入力値のmd53758002ab24653af8d550c0c50473098と一致すればflagがとれるようです.

hashtoolkit.com

上記のサイトによると3758002ab24653af8d550c0c50473098darknightハッシュ値らしいです(厨二病か?

f:id:satto1237:20190616220205p:plain

bcactf{7h37ru7h15411w3h4v3_dGhlIGxpZ2h0IGluIG91ciBleWVz}

Rev

basic-pass-1

Your company is testing out a new login software, and being one of the CompSec experts, they want you to test it. They say that they have hidden a key somewhere in the program, and want you to look for it. Find it, and they might even consider giving you a pay raise...

They have told you that there is a four digit pin on the program to unlock it.

> file basic-pass-1-linux
basic-pass-1-linux: ELF 64-bit LSB shared object x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=9cee815c93440268757240e6499bc622fbbed466, not stripped

アプローチ:strings

> strings basic-pass-1-linux | grep bcactf{
Congrats! The key is bcactf{hey_its_a_password}

scratch-that [150pts, 433solves]

I made a Guess the Flag game! It's in Scratch, what could be easier? Click here to access the game.

f:id:satto1237:20190616220938p:plain

アプローチ:ネコにflagを言わせる

generate flagをReversingするのはちょっと面倒なのでScratchのブロックの1つである***と***秒言う ブロックを使ってネコにflagを吐かせます.

f:id:satto1237:20190616221206p:plain

f:id:satto1237:20190616221513p:plain

bcactf{scr4tch3d_Pourquoi_empty_23412342463682}

another-pass [200pts, 174solves]

Alright. Your friend John found this cool binary file on the Interwebz. Against all best practices, he downloaded it. Strange, it doesn't appear to be a virus. Because of the password prompt, you feel like it will lead to something important. Figure this one out!

> file another-linux
another-linux: ELF 64-bit LSB shared object x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=d262a12229a4736c50637beb2133d07c1ea03c2c, not stripped

アプローチ:頑張って処理を追う

文字列の和が0x4bになるパスワードを入力するとCorrect.になるっぽいことが分かります.
f:id:satto1237:20190616222023p:plain

>  ./another-linux
Pass: 99999999111
Correct.

99999999111

これ何通りも正解があるし問題としてどうなの

basic-pass-2 [200pts, 449solves]

Your company is testing out its new employee portal. After your previous shot, they made the password a bit more secure, so you can't brute force it anymore. Rise up to the occasion and demonstrate why a local machine is a bad idea, and having the account credentials on a remote server is a better idea.

アプローチ:ltrace

ltraceしたらstrcmpを使って入力文字列のチェックをしていたので簡単にパスワードが分かります.

ltrace -s 100 ./basic-pass-2-linux "this is a much more secure password, i think"
strcmp("this is a much more secure password, i think", "this is a much more secure password, i think") = 0
puts("Congrats! The key is bcactf{its_another_password}"Congrats! The key is bcactf{its_another_password}
)                 = 50
+++ exited (status 0) +++

bcactf{its_another_password}

basic-pass-3 [200pts, 356solves]

Ok, the sysadmin finally admits that maybe authentication should happen on a server. Can you just check everything really quick to make sure there aren't any problems now? He put some readouts for people who forget their passwords.

nc challenges.ctfd.io 30133

>  nc challenges.ctfd.io 30133
welcome to the login portal.
Enter the password.
hoge
00000000000000000000000000000000000000
Enter the password.
bcactf{
11111110000000000000000000000000000000
Enter the password.

アプローチ:全探索

flagn番目の文字列が正しければn番目のbitが立つことが分かります.

from socket import *
import string

s = socket(AF_INET, SOCK_STREAM)
s.connect(('challenges.ctfd.io', 30133))

flag = 'bcactf{'
rec = s.recv(1024).decode('utf-8')

for _ in range(32):
    pre_x = ''
    for x in string.printable:

        s.send((flag + x).encode('utf-8') + b'\n')
        rec = s.recv(1024).decode('utf-8')
        msg  = rec.split('\n')[0][:(len(flag) + 1)]
        if '0' not in msg and '1' in msg:
            flag += pre_x
            print(flag)
            break
        pre_x = x
> python solve.py
bcactf{y
bcactf{y0
bcactf{y0u
bcactf{y0u_
bcactf{y0u_4
bcactf{y0u_4r
bcactf{y0u_4r3
bcactf{y0u_4r3_
bcactf{y0u_4r3_4
bcactf{y0u_4r3_4_
bcactf{y0u_4r3_4_m
bcactf{y0u_4r3_4_m4
bcactf{y0u_4r3_4_m45
bcactf{y0u_4r3_4_m457
bcactf{y0u_4r3_4_m4573
bcactf{y0u_4r3_4_m4573r
bcactf{y0u_4r3_4_m4573rm
bcactf{y0u_4r3_4_m4573rm1
bcactf{y0u_4r3_4_m4573rm1n
bcactf{y0u_4r3_4_m4573rm1nD
bcactf{y0u_4r3_4_m4573rm1nD!
bcactf{y0u_4r3_4_m4573rm1nD!_
bcactf{y0u_4r3_4_m4573rm1nD!_Y
bcactf{y0u_4r3_4_m4573rm1nD!_Ym
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9v
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vb
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbG
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbGl
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbGlu
bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbGlu}

bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbGlu}

compression [200pts, 301solves]

A stranger on the internet is giving away his passwords. They claim they are encrypted, but you quickly realize that it is only compressed. You have to get hold of their passwords so that you can prove them wrong.

> file 999
999: bzip2 compressed data, block size = 900k

アプローチ:bzip => gzip => bzip

999を解凍すると123ファイルが出現します.
123ファイルは何らかのファイルのhexdumpっぽいのでこれを復元します.

00000000: 1f8b 0808 348e 365c 0003 3531 3100 019d  ....4.6\..511...
00000010: 0762 f842 5a68 3931 4159 2653 59f7 ed65  .b.BZh91AY&SY..e
00000020: dd00 006d 7fff ffff ffff ffff ffff ffff  ...m............
00000030: ffff ffff 7fff ffff ffff ffff ffff 7fff  ................
00000040: ffff ffff ffff d004 1ef7 79a5 af7b 65d7  ..........y..{e.
00000050: b9ce 6578 6453 d264 0f50 6991 ea3c 88f2  ..exdS.d.Pi..<..
00000060: 9ea1 a0f4 8d34 c434 643c 93d4 d0d3 ca3d  .....4.4d<.....=
00000070: 468d 0327 a1a2 36a6 83d4 69a6 8c8d a9ea  F..'..6...i.....
00000080: 6341 0191 e90f 28f5 068c d1a9 a69e a794  cA....(.........
00000090: 6d46 8c81 b506 c206 936a 7a9b d354 f53c  mF.......jz..T.<
000000a0: a1e8 c90f d29a 69b5 10d1 a009 e826 9823  ......i......&.#
000000b0: d4d3 1320 6002 186a 3068 9813 6a69 9300  ... `..j0h..ji..
000000c0: 0001 3c84 c046 98d3 4980 1a0d 01a9 e826  ..<..F..I......&
000000d0: 0004 f47a 40d1 a4c3 4981 190c 9a69 9a98  ...z@...I....i..
000000e0: 0009 821a 24f2 261a 0460 1368 134c 04f4  ....$.&..`.h.L..
000000f0: 4c9a 6032 0119 3009 a7a3 4469 e9a3 44f4  L.`2..0...Di..D.
00000100: 098d 23d3 2989 b203 4041 a323 4601 0c98  ..#.)...@A.#F...
00000110: 0133 5193 d04f 200d 00d4 c10c 9a69 e9a9  .3Q..O ......i..
00000120: 91a6 130d 263a 9ea3 1a46 9e50 dea8 f518  ....&:...F.P....
00000130: 46d4 d8a6 86d4 7a64 d314 69a7 b532 834d  F.....zd..i..2.M
00000140: 313c 834d 4f14 f51e 9368 8d1a 7a41 8868  1<.MO....h..zA.h
00000150: c4c8 3d4f 51a3 d46d 2611 b534 7a4c 2794  ..=OQ..m&..4zL'.
00000160: c4f5 0f24 3d23 d468 3464 f49a 1934 3681  ...$=#.h4d...46.
00000170: 0f53 d468 d34d 1e44 c41d 1ea6 84f5 3d26  .S.h.M.D......=&
00000180: 344d 306a 7a13 d027 a341 a340 98d2 7a20  4M0jz..'.A.@..z 
00000190: c27a 04c0 689e 8000 11a6 9ea6 099a 9846  .z..h..........F
000001a0: d081 a0c4 da04 f531 327a 0119 a21b 499a  .......12z....I.
000001b0: 9a7a 0261 184c 8699 06d1 1930 3426 5722  .z.a.L.....04&W"
000001c0: 054b 04b9 6f83 285d e411 270c 9d3b 1727  .K..o.(]..'..;.'
000001d0: dbfc 8629 e02c da67 7450 5730 d011 a8d0  ...).,.gtPW0....
000001e0: 887a 84b4 093b f9bd 408e 1e60 a318 419d  .z...;..@..`..A.
000001f0: 99e8 b139 b31d b8c1 8310 8380 863d 737b  ...9.........=s{
00000200: fd2b f4df 3c6e 030e ea17 73f4 b0f5 73ef  .+..<n....s...s.
00000210: 382f 880d 7672 3b34 b9db b9c7 de29 c6aa  8/..vr;4.....)..
00000220: e5f4 df56 4968 8a62 9734 a614 cf46 8a6a  ...VIh.b.4...F.j
00000230: 1507 b984 8400 32cf d8e0 1f7c 324d eba8  ......2....|2M..
00000240: d360 4b80 d091 0e11 0c61 5a73 94db c820  .`K......aZs... 
00000250: d5a0 08df c32a 20d1 92dd de81 bc49 a54f  .....* ......I.O
00000260: ad98 51f2 6b51 3bae 165d 8e30 873e d8ef  ..Q.kQ;..].0.>..
00000270: 0280 7f49 ca02 3451 7e49 a407 c418 e3a8  ...I..4Q~I......
00000280: 4cc6 9b07 003d 4ac0 a963 c186 8df1 4a95  L....=J..c....J.
00000290: fd92 9903 75d3 16b2 1f60 f99c d118 e7c1  ....u....`......
000002a0: 23bf 452b 11e3 d096 f1c6 464a bbee 4893  #.E+......FJ..H.
000002b0: 28d6 e813 0c68 8088 004f ce0a 805d c5d7  (....h...O...]..
000002c0: c5a4 bb71 5289 9e9d 4cd4 071c 4831 339d  ...qR...L...H13.
000002d0: cdcc 8ec3 a823 a062 f450 b5c6 2415 abd3  .....#.b.P..$...
000002e0: faf8 ff82 46aa 9ec5 cf5f 38e5 ff71 9ed1  ....F...._8..q..
000002f0: 4bcf 8e8d a8c7 320a f5a8 375c c3f5 ef84  K.....2...7\....
00000300: 29fc 91b1 ac85 c677 d1fd e134 240f 0e8d  )......w...4$...
00000310: 93ee 7d80 ab73 5a9d cf4e 4b9e 60bc 5c41  ..}..sZ..NK.`.\A
00000320: 0ac9 687d 2d04 039c c382 f516 b54b 3d4c  ..h}-........K=L
00000330: 7e1a 3336 a410 985a e0e3 e25e 4e2a 9bfe  ~.36...Z...^N*..
00000340: 5f92 e1bd 5909 13e4 2049 4a45 871c ea07  _...Y... IJE....
00000350: 1705 b805 bfc7 20c1 6b2f 8b90 4e7d 7e50  ...... .k/..N}~P
00000360: 8c24 a043 d655 6a8d f32c 09ce f12d 26dc  .$.C.Uj..,...-&.
00000370: 23b4 98a4 d647 2383 0b72 7152 045a 8e80  #....G#..rqR.Z..
00000380: fa4e 8790 5480 7d5e 989c 41ea 158a 4e23  .N..T.}^..A...N#
00000390: 4518 d97a 6fef a53e c075 5a48 1813 de0c  E..zo..>.uZH....
000003a0: 7503 226c bb73 2ae6 d01e c44b 68ad 8767  u."l.s*....Kh..g
000003b0: 0532 5c0b 84cf 9e8a 3b8f b661 8b02 b748  .2\.....;..a...H
000003c0: 672a 4d4d 0702 2899 c021 76b7 3d6d 2a85  g*MM..(..!v.=m*.
000003d0: 2bcb 6014 3a6d ee03 2d7b 5e92 1211 e320  +.`.:m..-{^.... 
000003e0: 7725 aa83 57fa 9243 e877 c62a 73a2 f589  w%..W..C.w.*s...
000003f0: 10b0 e323 5203 a52c 504d c5b7 1170 e87d  ...#R..,PM...p.}
00000400: 8327 11fa e4ca d8be 03c2 cbe4 f16c cf75  .'...........l.u
00000410: b20b ac94 855a 485d 1dde e8dc 78a0 d116  .....ZH]....x...
00000420: c58f 1f69 e4ff bd9b e180 7c84 2048 e26d  ...i......|. H.m
00000430: 5fa1 5c2b 11b4 cf67 de67 2619 841a 71d4  _.\+...g.g&...q.
00000440: da3c 658d 2bca b130 ff83 7f4c a932 bc84  .<e.+..0...L.2..
00000450: 2565 fd66 8925 1d73 2904 5eb2 1ed2 4fb1  %e.f.%.s).^...O.
00000460: 2922 82a4 9f88 f0f4 e082 2774 9da2 a8c7  )"........'t....
00000470: 3649 d1e9 52ce 9814 8b9b 1430 b977 cfcd  6I..R......0.w..
00000480: 65fb 17e8 9b4a 68d2 c114 ca93 5856 f8f9  e....Jh.....XV..
00000490: 05a4 2709 4983 b7f3 8e13 72e4 b2fe b557  ..'.I.....r....W
000004a0: 748b 6bed ddbc d3a9 816a d750 0a92 b2fe  t.k......j.P....
000004b0: 4290 8c32 4b9e 7b27 2afe 83fc 9594 3c1d  B..2K.{'*.....<.
000004c0: 34b9 9092 1a0b 4857 13eb 9d25 eaf0 3562  4.....HW...%..5b
000004d0: cde8 cf39 9492 8952 cb53 1823 6909 0fef  ...9...R.S.#i...
000004e0: 34c1 8dac c38e 1d0e fd7a 4667 6edd 98d7  4........zFgn...
000004f0: f995 2f2e 2f8d 2c51 b81d 535e e047 f033  .././.,Q..S^.G.3
00000500: 84fb a724 c117 b45d fad9 6b26 87df f3c8  ...$...]..k&....
00000510: 9180 005f 6e7d 9c76 3173 61ee d89e 60d0  ..._n}.v1sa...`.
00000520: e83d d3a1 9865 298b 493a fd78 5d23 61c4  .=...e).I:.x]#a.
00000530: 0527 3d55 6f5b c9b9 fc83 aa8f 0cf6 ce7f  .'=Uo[..........
00000540: 2d27 c625 6882 a80b 7596 0563 4d29 a920  -'.%h...u..cM). 
00000550: 59af a871 8db1 768e a400 14c5 4e19 800c  Y..q..v.....N...
00000560: fa15 6c55 e041 bc98 6682 c601 8114 e994  ..lU.A..f.......
00000570: 3613 5c8e afc4 86cc 199b ec6c b7a9 0da6  6.\........l....
00000580: 4a89 4e0a 48eb 314c 0a80 7141 c53f d7db  J.N.H.1L..qA.?..
00000590: 40c2 343e 00b6 7573 758d b795 292f c2a5  @.4>..usu...)/..
000005a0: ab7a 85ab 26f1 cc96 7c05 7dd4 8661 6d68  .z..&...|.}..amh
000005b0: 2513 ee39 33a0 6fc6 b437 f070 4be8 fee2  %..93.o..7.pK...
000005c0: 3f3f 2d0c 3005 d554 743e e716 f3fb 59af  ??-.0..Tt>....Y.
000005d0: 9181 1715 c470 8269 fb36 da47 b97b 5a54  .....p.i.6.G.{ZT
000005e0: b434 f892 3dea d2b5 6fe0 02db b126 eb0a  .4..=...o....&..
000005f0: 4c81 417d 19d0 f77f 2ea2 d6ab 8dd5 1d2e  L.A}............
00000600: 2e97 0bec 8c09 1345 26ca 8abe d3cf e06e  .......E&......n
00000610: 3d84 3710 5023 e29d 8211 9508 4a6e e878  =.7.P#......Jn.x
00000620: ca43 fa05 9e52 a57f 2239 7c39 b6a2 98c7  .C...R.."9|9....
00000630: 6f4a 53af 708d 67af 2c2f c5e3 4577 dd9f  oJS.p.g.,/..Ew..
00000640: 244f 6460 5851 f703 54f2 0994 956c efbe  $Od`XQ..T....l..
00000650: 72c7 4ca3 0f98 2310 f0de 56f7 fa8a a6cf  r.L...#...V.....
00000660: 0d34 1a52 c1db 569d 17d8 c202 1d7a 7432  .4.R..V......zt2
00000670: 68f4 c57d c535 e3d3 aea4 9d2c 8a55 4456  h..}.5.....,.UDV
00000680: 106c 4d60 374a c41e 5500 5425 3975 1298  .lM`7J..U.T%9u..
00000690: d484 7125 9d2f 237a f054 7352 d72d 9a57  ..q%./#z.TsR.-.W
000006a0: 874b b8a7 f69e 6bac 1e54 7319 b45f 6f10  .K....k..Ts.._o.
000006b0: 66d1 6d24 f0d0 5808 58a0 acb3 a294 a823  f.m$..X.X......#
000006c0: 77fb 0e29 bb37 946a 6919 bd0a 9e5b 8b01  w..).7.ji....[..
000006d0: 1cc6 b86d 71d9 1ad1 6ee1 0344 d244 0086  ...mq...n..D.D..
000006e0: 95a0 30bd 0d42 e51c 56a9 a37a bafc 561f  ..0..B..V..z..V.
000006f0: 9d78 1db5 1f61 4778 f82a 2040 16c9 e6f1  .x...aGx.* @....
00000700: b309 e7c1 50d6 a645 c305 473d 7906 7404  ....P..E..G=y.t.
00000710: c807 ea26 a4cd 408d c1c9 0e05 e286 235d  ...&..@.......#]
00000720: 177e 0f68 a5b7 4d67 8d41 16be 8c57 e0ce  .~.h..Mg.A...W..
00000730: d637 c69a d7b0 68cd f71d 39b6 e954 993c  .7....h...9..T.<
00000740: 1ddc 097c f740 88c5 5c17 49bc bf38 97e5  ...|.@..\.I..8..
00000750: 77a9 9da5 61b9 711c 2d32 955a 8467 e1f5  w...a.q.-2.Z.g..
00000760: b6b1 794c 6d90 9eb4 522a 0711 86a7 7f38  ..yLm...R*.....8
00000770: c688 392a 8304 04ff c8a0 337e c2d7 49e0  ..9*......3~..I.
00000780: 594d 598d 9230 000d ef2f ba8e e1ce a6d2  YMY..0.../......
00000790: 20f3 4460 9a69 08ad 2833 8854 878c b81c   .D`.i..(3.T....
000007a0: f301 c582 0fbe 2ee4 8a70 a121 efda cbba  .........p.!....
000007b0: e0a3 c611 9d07 0000                      ........
> file output_from_123
output_from_123: gzip compressed data, was "511", last modified: Thu Jan 10 00:13:40 2019, from Unix, original size 1949

復元結果はgzipだったのでこれを解凍すると240ファイルが出現します.
240ファイルも何らかのファイルのhexdumpっぽいので再度復元します.

00000000: 425a 6839 3141 5926 5359 51cd bcbb 0000  BZh91AY&SYQ.....
00000010: 24ff ffff fde7 4eff cd5f ffab df7c ddff  $.....N.._...|..
00000020: ff6c 7bff ed5b e8ff f5fd 7fff ffde ffff  .l{..[..........
00000030: 97ff bfb0 0159 99a0 ca00 69a0 d00d 0006  .....Y....i.....
00000040: 8000 0068 0000 0000 0000 01a7 a83d 41a0  ...h.........=A.
00000050: 0320 6832 000d 3400 34d0 c206 9826 d350  . h2..4.4....&.P
00000060: 5526 9ea3 4c81 a346 8034 0000 00f5 0d01  U&..L..F.4......
00000070: 90f5 0000 0000 0190 1900 d00c 9a00 c8d0  ................
00000080: 34d0 0000 341a 0d00 000a a23d 41a0 d1a6  4...4......=A...
00000090: 8340 0f53 20d0 0064 1a00 0006 9a00 00c8  .@.S ..d........
000000a0: 3400 1a00 001a 340f 5000 01a0 0640 069a  4.....4.P....@..
000000b0: 6868 0032 8c25 0a13 4849 9562 ebc5 e593  hh.2.%..HI.b....
000000c0: 108f 58e6 3000 343a 9c36 870e 77db d52e  ..X.0.4:.6..w...
000000d0: 0001 ff2b 994e f837 b6da c385 3428 1c83  ...+.N.7....4(..
000000e0: 60cd 7e12 0010 3e1e 6204 5953 4636 3cb3  `.~...>.b.YSF6<.
000000f0: 9ac3 4936 11f3 694e dd4a 871b 0ce8 f659  ..I6..iN.J.....Y
00000100: 10e1 e006 f887 db92 4273 4a10 000c 3bed  ........BsJ...;.
00000110: a0b0 7300 8409 1040 6a8b 98f5 6b24 ea3b  ..s....@j...k$.;
00000120: b720 22f6 46db 75f0 12a1 fac0 afcf fcd5  . ".F.u.........
00000130: cf00 126d 0903 8636 8775 e869 434c e368  ...m...6.u.iCL.h
00000140: e95f 800a abcc 933a 4882 431b 3270 96a7  ._.....:H.C.2p..
00000150: be9d c773 8179 a851 4048 71d5 9620 f07c  ...s.y.Q@Hq.. .|
00000160: afbc 0504 129a f6a2 1e67 e584 39f2 c48d  .........g..9...
00000170: 2c10 5c00 6925 3f72 28f8 6f99 4fed 8454  ,.\.i%?r(.o.O..T
00000180: 5993 a5ca 707c 1c5d 4c44 3079 9d4a 9e3f  Y...p|.]LD0y.J.?
00000190: dfeb e05f 4400 25cb df6f 1941 ed15 d350  ..._D.%..o.A...P
000001a0: 16fd 4fd8 af92 1013 1c49 c044 1c70 14c8  ..O......I.D.p..
000001b0: 911e e7d2 61e7 a525 7f11 65a7 8e64 08f3  ....a..%..e..d..
000001c0: 1d1b c5cd 91dd 1642 03eb 8691 1401 1059  .......B.......Y
000001d0: 232e 970d c982 e4a4 caa9 7e3e 5448 f054  #.........~>TH.T
000001e0: 4f0c 29f2 bafa 63b4 a991 d7c2 4eef 1342  O.)...c.....N..B
000001f0: 6773 ded6 49fd 1989 3cb3 8001 ad52 2d21  gs..I...<....R-!
00000200: 441c e65c 2a96 d234 de02 690f dfb1 1257  D..\*..4..i....W
00000210: 6e98 86c3 3aea 9444 32fa efea 3188 3d03  n...:..D2...1.=.
00000220: 426c b227 2a6e d4c3 e330 9ee2 461d 83db  Bl.'*n...0..F...
00000230: 112a c222 c3dd a384 78bf 62d6 0d29 810d  .*."....x.b..)..
00000240: 1dac a81d c234 10ab 17e7 0a7a 1390 37fa  .....4.....z..7.
00000250: 73b0 6692 7933 fd6f 204f 61f1 838a 19ac  s.f.y3.o Oa.....
00000260: 0ef1 99e4 d36d 7009 fc1f f8bb 9229 c284  .....mp......)..
00000270: 828e 6de5 d8                             ..m..
> file output_from_240
output_from_240: bzip2 compressed data, block size = 900k

復元結果はbzipだったのでこれを解凍すると000ファイルが出現します.

000ファイルがflagでした

bcactf{A_l0t_0f_c0mPr3s510n}

Web

the-inspector [50pts, 568solves]

The Federal CTF Inspector dropped by today looking for some hidden flags. He clearly needs to pursue a different career because we hid the flag right in plain sight.

アプローチ:inspect

f:id:satto1237:20190616225231p:plain

bcactf{1nsp3ct_3l3m3nt}

wite-out [50pts, 559solves]

Wait, where's the flag?

アプローチ:inspect

f:id:satto1237:20190616225619p:plain

bcactf{17s_r1gh7_h3r3_1n_wh1t3_1397856}

dig-dug [100pts, 486solves]

I found this super sketchy website called hole.sketchy.dev. Can you help me dig up some of its secrets?

Oh, and someone told me that the secrets are TXT. I don't know what this means, so good luck!

アプローチ:dig

> dig -t TXT hole.sketchy.dev

; <<>> DiG 9.10.6 <<>> -t TXT hole.sketchy.dev
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20628
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 3

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;hole.sketchy.dev.      IN  TXT

;; ANSWER SECTION:
hole.sketchy.dev.   3600    IN  TXT "bcactf{d1g-f0r-h073s-w/-dns-8044323}"

;; AUTHORITY SECTION:
sketchy.dev.        10737   IN  NS  molly.ns.cloudflare.com.
sketchy.dev.        10737   IN  NS  greg.ns.cloudflare.com.

;; ADDITIONAL SECTION:
molly.ns.cloudflare.com. 154304 IN  A   173.245.58.205
molly.ns.cloudflare.com. 154304 IN  AAAA    2400:cb00:2049:1::adf5:3acd

;; Query time: 15 msec
;; SERVER: 192.168.2.1#53(192.168.2.1)
;; WHEN: Tue Jun 11 20:36:17 JST 2019
;; MSG SIZE  rcvd: 194

bcactf{d1g-f0r-h073s-w/-dns-8044323}

My friend built a cookie clicker. How do I beat it?

http://35.225.2.44:5001/

f:id:satto1237:20190616230103p:plain

アプローチ:クッキーの書き換え

f:id:satto1237:20190616230048p:plain

f:id:satto1237:20190616230238p:plain

どうやらクッキーがいっぱい必要らしいのでクッキーを書き換えてflaggetします.

> curl -b cookies=100000000000000000000000000000000000000000000000  http://35.225.2.44:5001/flag
bcaCTF{c00k13s_c71ck3d_34a2344d}%

まとめ

  • Crypto問のCrypto感がなくて悲しかった
  • 全体的にエスパー系だった