1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
| from pwn import remote, context, log import re, itertools, hashlib, time, string, sys
context.log_level = 'info'
host = "8.147.132.101" port = 26651
ALPHANUM = string.ascii_letters + string.digits WHITE_TOKENS = set(['==','(',')','S0','S1','S2','S3','S4','S5','S6','S7','0','1','and','or']) POW_RE = re.compile(r"sha256\(XXXX\+([^\)]+)\)\s*==\s*([0-9a-f]{64})")
M = [ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1], [1,1,1,1,1,0,0,0], [1,0,1,0,1,1,0,0], [0,1,1,0,0,1,1,0], [1,1,0,0,1,1,1,0], [1,1,1,0,0,1,1,1], [0,1,1,1,1,0,0,1], [1,0,1,1,0,1,0,1], [1,1,0,1,0,0,1,1], [1,1,1,1,1,1,1,1], ] assert len(M) == 17 and all(len(r)==8 for r in M)
def token_wrap(toklist): if len(toklist) == 1: return toklist[:] return ['('] + toklist[:] + [')']
def xor_two_tokens(A, B): Aw = token_wrap(A); Bw = token_wrap(B) inner = ['('] + Aw + ['=='] + Bw + [')'] expr = ['('] + inner + ['==', '0'] + [')'] return expr
def xor_subset_tokens(indices): if not indices: return ['0'] toks = ['S' + str(indices[0])] for idx in indices[1:]: toks = xor_two_tokens(toks, ['S' + str(idx)]) return toks
def tokens_to_query(tokens): for t in tokens: if t == "": raise ValueError("Empty token produced") if not (t in WHITE_TOKENS or re.fullmatch(r"S[0-7]", t)): raise ValueError("Invalid token produced: " + repr(t)) return " ".join(tokens)
def eval_expression(expr, candidate): tokens = []; i = 0; s = expr while i < len(s): c = s[i] if c.isspace(): i += 1; continue if c in '()': tokens.append(c); i += 1; continue if c in '01': tokens.append(True if c == '1' else False); i += 1; continue j = i while j < len(s) and (s[j].isalnum() or s[j] in '_='): j += 1 word = s[i:j]; i = j if re.fullmatch(r"S[0-7]", word): tokens.append(bool(candidate[int(word[1])])) elif word in ('and','or','=='): tokens.append(word) elif word.lower() in ('true','false'): tokens.append(True if word.lower()=='true' else False) else: raise ValueError("Unknown token in eval: "+repr(word)) prec = {'==':3, 'and':2, 'or':1} output = []; ops = [] for t in tokens: if t is True or t is False: output.append(t) elif t == '(': ops.append(t) elif t == ')': while ops and ops[-1] != '(': output.append(ops.pop()) if not ops or ops[-1] != '(': raise ValueError("Mismatched parentheses") ops.pop() elif t in prec: while ops and ops[-1] != '(' and prec.get(ops[-1], -1) >= prec.get(t, -1): output.append(ops.pop()) ops.append(t) else: raise ValueError("Unknown token in shunting-yard eval: "+str(t)) while ops: if ops[-1] == '(': raise ValueError("Mismatched parentheses at end") output.append(ops.pop()) stack = [] for t in output: if t is True or t is False: stack.append(t) elif t == '==': b = stack.pop(); a = stack.pop(); stack.append(a == b) elif t == 'and': b = stack.pop(); a = stack.pop(); stack.append(a and b) elif t == 'or': b = stack.pop(); a = stack.pop(); stack.append(a or b) else: raise ValueError("Unknown RPN op: "+str(t)) if len(stack) != 1: raise ValueError("RPN ended with stack size !=1") return stack[0]
def solve_pow_from_text(text): m = POW_RE.search(text) if not m: raise ValueError("POW not found") suffix = m.group(1); target = m.group(2) log.info("POW found; trying numeric then alnum brute-force...") for i in range(10000): cand = f"{i:04}".encode() if hashlib.sha256(cand + suffix.encode()).hexdigest() == target: log.success("POW numeric found: " + cand.decode()); return cand.decode() total = len(ALPHANUM)**4; tried = 0 for comb in itertools.product(ALPHANUM, repeat=4): tried += 1 cand = ''.join(comb).encode() if hashlib.sha256(cand + suffix.encode()).hexdigest() == target: log.success("POW found: " + cand.decode()); return cand.decode() if tried % 2000000 == 0: log.info(f"POW progress: tried {tried}/{total}") raise RuntimeError("POW not found")
def parse_prisoner_response(text): if text is None: raise ValueError("Empty") s = text.replace("\n"," ").replace("!"," ").strip() if "refuse to answer" in s or "I refuse to answer" in s: raise RuntimeError("Server refused phrasing: " + s) m = re.search(r"Prisoner's response:\s*([A-Za-z0-9]+)", s, re.IGNORECASE) if m: tok = m.group(1) if tok.lower() == 'true' or tok == '1': return True if tok.lower() == 'false' or tok == '0': return False m2 = re.search(r"\b(True|False|1|0)\b", s, re.IGNORECASE) if m2: tok = m2.group(1).lower() return tok == 'true' or tok == '1' for ch in s: if ch == '1': return True if ch == '0': return False raise ValueError("Cannot parse prisoner response: "+repr(text))
def recover_from_observed(observed): n = 17 def encode(msg_bits): out = [] for row in M: s = 0 for j,b in enumerate(row): if b and msg_bits[j]: s ^= 1 out.append(bool(s)) return out for k in range(3): for flips in itertools.combinations(range(n), k): corr = observed[:] for idx in flips: corr[idx] = not corr[idx] for mask in range(256): msg = [bool((mask>>i)&1) for i in range(8)] if encode(msg) == corr: return [1 if x else 0 for x in msg] raise ValueError("No valid decoding under ≤2 flips assumption")
def wait_for_round_prompt_with_leftover(r, leftover, timeout=30): """ leftover: a string that may already contain previously-read-but-unprocessed data. Returns (accumulated_text, updated_leftover) where accumulated_text contains at least the prompt ('Ask your question:' or 'Now reveal the true secrets') or server end messages. updated_leftover contains any extra text beyond what caller needs to process now (so we don't lose it). If timeout and no data -> returns (None, leftover). """ acc = leftover or "" start = time.time() if acc and ('Ask your question:' in acc or 'Now reveal the true secrets' in acc or 'fell for my deception' in acc or 'you win' in acc.lower() or 'confesses all his secrets' in acc.lower()): return acc, "" while True: try: chunk = r.recv(timeout=1) except Exception: chunk = b"" if chunk: try: s = chunk.decode(errors='ignore') except: s = str(chunk) acc += s if 'Ask your question:' in acc or 'Now reveal the true secrets' in acc or 'fell for my deception' in acc or 'you win' in acc.lower() or 'confesses all his secrets' in acc.lower(): return acc, "" else: if time.time() - start > timeout: if acc: return acc, "" else: return None, leftover
def recv_until_prompt_or_collect(r, leftover, timeout=8): """ Read from socket (appended to leftover) until we can parse a prisoner response or timeout. Returns (collected_text, updated_leftover). collected_text may contain the response and possibly extra. """ acc = leftover or "" start = time.time() while True: try: _ = parse_prisoner_response(acc) return acc, "" except Exception: pass try: chunk = r.recv(timeout=1) except Exception: chunk = b"" if chunk: try: s = chunk.decode(errors='ignore') except: s = str(chunk) acc += s if "The prisoner smirks" in acc or "I refuse to answer" in acc: return acc, "" else: if time.time() - start > timeout: return acc, ""
def run(): r = remote(host, port, timeout=10) log.info(f"Connected to {host}:{port}") data = b""; pow_line = None; t0 = time.time() while time.time() - t0 < 5: try: chunk = r.recv(timeout=1) except Exception: chunk = b"" if chunk: data += chunk txt = data.decode(errors='ignore') if 'sha256(' in txt: m = POW_RE.search(txt) if m: pow_line = m.group(0); break if not pow_line: try: more = r.recvrepeat(timeout=2) if more: data += more txt = data.decode(errors='ignore') m = POW_RE.search(txt) if m: pow_line = m.group(0) except Exception: pass if not pow_line: log.failure("POW not found; server banner:\n" + data.decode(errors='ignore')) r.close(); return log.info("POW challenge: " + pow_line) try: prefix = solve_pow_from_text(pow_line) except Exception as e: log.failure("POW failed: " + str(e)); r.close(); return r.sendline(prefix) log.info("Sent POW solution")
rounds = 0 leftover = "" try: while True: txt, leftover = wait_for_round_prompt_with_leftover(r, leftover, timeout=30) if txt is None: log.info("No prompt received and no data; assuming connection closed.") break log.debug("Pre-round text (accumulated): " + (txt.replace("\n"," | ")[:1000])) if 'fell for my deception' in txt or 'laughs triumphantly' in txt: log.failure("Server indicated failure: " + txt.replace("\n"," | ")) break if 'you win' in txt.lower() or 'confesses all his secrets' in txt.lower(): log.success("Server indicates success/flag: " + txt.replace("\n"," | "))
observed = [] queries_texts = []
for qi, row in enumerate(M): indices = [i for i,b in enumerate(row) if b] toklist = xor_subset_tokens(indices) qstr = tokens_to_query(toklist) queries_texts.append(qstr) if leftover and 'Ask your question:' in leftover: leftover = "" else: try: r.recvuntil(b"Ask your question:", timeout=6) except Exception: log.debug("Did not see per-question prompt before sending; proceeding.") log.info(f"Sending query [{qi+1}/17]: {qstr!r}") r.sendline(qstr)
acc = "" got = False t1 = time.time() while time.time() - t1 < 8: try: chunk = r.recv(timeout=1) except Exception: chunk = b"" if chunk: try: s = chunk.decode(errors='ignore') except: s = str(chunk) acc += s if "The prisoner smirks" in acc or "I refuse to answer" in acc: log.failure("Server refused phrasing: " + acc.replace("\n"," | ")) r.close(); return try: val = parse_prisoner_response(acc) observed.append(val) got = True break except RuntimeError as rexc: log.failure(str(rexc)); r.close(); return except Exception: pass else: pass if not got: try: tail = r.recvrepeat(timeout=1).decode(errors='ignore') acc += tail val = parse_prisoner_response(acc) observed.append(val) except Exception as e: log.failure("Failed to parse response for query %s collected=%r err=%s" % (qstr, acc, str(e))) r.close(); return log.info(f"Got [{qi+1}/17]: {observed[-1]}") time.sleep(0.02)
acc2 = "" t2 = time.time() while time.time() - t2 < 4: try: chunk = r.recv(timeout=1) except Exception: chunk = b"" if chunk: try: s = chunk.decode(errors='ignore') except: s = str(chunk) acc2 += s if 'Now reveal the true secrets' in acc2: leftover = acc2.split('Now reveal the true secrets',1)[1] break else: pass try: recovered = recover_from_observed(observed) except Exception as e: log.exception("Recovery failed: " + str(e)) r.close(); return
ans_line = " ".join(map(str, recovered)) log.success("Recovered secrets: " + ans_line) r.sendline(ans_line)
acc_after = "" t3 = time.time() while time.time() - t3 < 4: try: chunk = r.recv(timeout=0.8) except Exception: chunk = b"" if chunk: try: s = chunk.decode(errors='ignore') except: s = str(chunk) acc_after += s else: pass leftover = (leftover or "") + acc_after log.info("Server after submission (buffered):\n" + (acc_after.strip()[:1000] if acc_after else "<none>")) if acc_after and ('fell for my deception' in acc_after or 'laughs triumphantly' in acc_after): log.failure("Server indicated round failure; stopping. " + acc_after.replace("\n"," | ")) break if acc_after and ('you win' in acc_after.lower() or 'confesses all his secrets' in acc_after.lower()): log.success("Server indicates success/flag: " + acc_after.replace("\n"," | ")) rounds += 1 log.info("Completed round #%d" % rounds) time.sleep(0.05)
except Exception as e: log.exception("Exception: " + str(e)) finally: try: r.close() except: pass log.info("Connection closed. Rounds: %d" % rounds)
if __name__ == "__main__": run()
|