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
| import socket, sys, itertools, random, re, time, select from hashlib import sha256 from contextlib import closing from multiprocessing import Process, Event, Queue, cpu_count
HOST = "8.147.135.168" PORT = 30736 N_QUERIES = 17 ROUNDS = 25 SEED_BASE = 42
READ_TIMEOUT = 7.0 WRITE_TIMEOUT = 7.0 PROMPT_TIMEOUT = 2.5 PER_Q_TIMEOUT = 3.5 LINE_MAXLEN = 32768 RECV_SOFT_LIMIT_LINES = 60 MAX_ERROR_BITS = 3 RETRY_PER_ROUND = 2 POW_WAIT_MAX = 200 VERBOSE = False
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
class LineIO: def __init__(self, sock: socket.socket): self.sock = sock self.buf = b"" try: self.sock.settimeout(None) except Exception: pass
def writeln(self, s: str): data = (s.rstrip("\r\n") + "\n").encode() end = time.time() + WRITE_TIMEOUT mv = memoryview(data) sent = 0 while sent < len(data): remain = end - time.time() if remain <= 0: raise TimeoutError("write timed out") _, w, _ = select.select([], [self.sock], [], remain) if not w: continue n = self.sock.send(mv[sent:]) if n <= 0: raise OSError("socket closed while writing") sent += n
def _recv_some(self, timeout: float): if timeout is not None and timeout < 0: timeout = 0 r, _, _ = select.select([self.sock], [], [], timeout) if not r: return b"" try: return self.sock.recv(4096) except BlockingIOError: return b""
def readline(self, timeout: float = READ_TIMEOUT) -> str: end = time.time() + (timeout if timeout is not None else 1e9) while True: pos = self.buf.find(b"\n") if pos != -1: line = self.buf[:pos+1]; self.buf = self.buf[pos+1:] return line.decode(errors="ignore") if time.time() >= end: return "" chunk = self._recv_some(end - time.time()) if chunk == b"": if self.buf: line = self.buf; self.buf = b"" return line.decode(errors="ignore") return "" self.buf += chunk if len(self.buf) > LINE_MAXLEN: line = self.buf[:LINE_MAXLEN]; self.buf = self.buf[LINE_MAXLEN:] return line.decode(errors="ignore")
def read_until_any(self, patterns, timeout=READ_TIMEOUT, max_lines=RECV_SOFT_LIMIT_LINES): compiled = [re.compile(p, re.I) for p in patterns] end = time.time() + (timeout if timeout is not None else 1e9) lines, midx = [], -1 while len(lines) < max_lines and time.time() < end: line = self.readline(timeout=end - time.time()) if not line: break lines.append(line) for i, pr in enumerate(compiled): if pr.search(line): return "".join(lines), i return "".join(lines), midx
def read_some_lines(self, n=1, timeout=READ_TIMEOUT): end = time.time() + (timeout if timeout is not None else 1e9) out = [] for _ in range(n): if time.time() >= end: break line = self.readline(timeout=end - time.time()) if not line: break out.append(line) return "".join(out)
def tcp_tune(sock: socket.socket): try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if hasattr(socket, "TCP_KEEPIDLE"): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) if hasattr(socket, "TCP_KEEPINTVL"): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10) if hasattr(socket, "TCP_KEEPCNT"): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4) except Exception: pass try: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except Exception: pass
def xor_two(a, b): return "( ( {} and ( {} == 0 ) ) or ( ( {} == 0 ) and {} ) )".format(a, b, a, b)
def xor_expr_for_indices(indices): if not indices: return "0" expr = f"S{indices[0]}" for idx in indices[1:]: expr = xor_two(expr, f"S{idx}") return expr
def rank_gf2(A): A = [row[:] for row in A] m = len(A); n = len(A[0]) if m else 0 r = 0 for c in range(n): piv = None for i in range(r, m): if A[i][c]: piv = i; break if piv is None: continue A[r], A[piv] = A[piv], A[r] for i in range(m): if i != r and A[i][c]: for j in range(c, n): A[i][j] ^= A[r][j] r += 1 if r == m: break return r
def build_queries(n_queries, seed=None): rnd = random.Random(seed) rows = [] while True: rows = [] for _ in range(8): mask = [i for i in range(8) if rnd.choice([0,1])] if not mask: mask = [rnd.randrange(8)] rows.append(mask) A = [[1 if j in row else 0 for j in range(8)] for row in rows] if rank_gf2(A) == 8: break while len(rows) < n_queries: mask = [i for i in range(8) if rnd.choice([0,1])] if not mask: mask = [rnd.randrange(8)] rows.append(mask) queries = [f"( {xor_expr_for_indices(mask)} ) == 1" for mask in rows] return rows, queries
def solve_gf2(A, b): m = len(A) if m == 0: return [0]* (0 if len(A)==0 else len(A[0])) n = len(A[0]) M = [row[:] + [bit] for row, bit in zip(A, b)] r = 0; pivs = [] for c in range(n): sel = None for i in range(r, m): if M[i][c] == 1: sel = i; break if sel is None: continue M[r], M[sel] = M[sel], M[r] pivs.append(c) for i in range(m): if i != r and M[i][c] == 1: for j in range(c, n+1): M[i][j] ^= M[r][j] r += 1 if r == m: break for i in range(r, m): if all(M[i][j]==0 for j in range(n)) and M[i][n]==1: return None x = [0]*n for i, c in enumerate(pivs): x[c] = M[i][n] return x
def rows_to_bitmasks(rows): masks = [] for mask_list in rows: v = 0 for j in mask_list: v |= (1 << j) masks.append(v) return masks
def predict_all(bitmasks, sol_bits): sv = 0 for i, b in enumerate(sol_bits): if b: sv |= (1 << i) return [ (m & sv).bit_count() & 1 for m in bitmasks ]
def decode_from_responses(rows, responses, max_err=3): n = len(rows) assert len(responses) == n A_full = [[1 if j in rows[i] else 0 for j in range(8)] for i in range(n)] b_full = responses bitmasks = rows_to_bitmasks(rows) idxs = range(n) for ecount in range(0, max_err+1): for errs in itertools.combinations(idxs, ecount): good = [i for i in idxs if i not in errs] A = [A_full[i] for i in good] b = [b_full[i] for i in good] sol = solve_gf2(A, b) if sol is None: continue pred = predict_all(bitmasks, sol) diff = [i for i in idxs if pred[i] != b_full[i]] if set(diff) == set(errs): return sol, errs return None, None
def _pow_worker(prefixes, suffix, target, found_evt: Event, outq: Queue): for a in prefixes: if found_evt.is_set(): return for b in ALPHABET: for c in ALPHABET: for d in ALPHABET: if found_evt.is_set(): return xxxx = f"{a}{b}{c}{d}" if sha256((xxxx + suffix).encode()).hexdigest() == target: outq.put(xxxx); found_evt.set(); return
def solve_pow_parallel(suffix, target): nprocs = min(max(4, cpu_count()), 32) chunk = (len(ALPHABET) + nprocs - 1) // nprocs found_evt = Event(); outq = Queue(); procs = [] for i in range(nprocs): seg = ALPHABET[i*chunk:(i+1)*chunk] if not seg: continue p = Process(target=_pow_worker, args=(seg, suffix, target, found_evt, outq)) p.daemon = True; p.start(); procs.append(p) xxxx = None deadline = time.time() + POW_WAIT_MAX try: while time.time() < deadline and not found_evt.is_set(): time.sleep(0.01) if found_evt.is_set(): xxxx = outq.get_nowait() except Exception: pass finally: for p in procs: p.terminate() for p in procs: try: p.join(timeout=0.1) except Exception: pass return xxxx
RE_PR_LINE = re.compile(r"Prisoner'?s?\s+response:\s*([A-Za-z0-9_!]+)", re.I) RE_TRUE = re.compile(r"\btrue\b", re.I) RE_FALSE = re.compile(r"\bfalse\b", re.I) RE_YES = re.compile(r"\byes\b|\bon\b|\b1\b", re.I) RE_NO = re.compile(r"\bno\b|\boff\b|\b0\b", re.I)
def parse_bool(text: str) -> int: m = RE_PR_LINE.search(text) if m: tok = m.group(1).lower() if tok in ("true","t","1","yes","y","on"): return 1 if tok in ("false","f","0","no","n","off"): return 0 if tok.startswith("t"): return 1 if tok.startswith("f"): return 0 if RE_TRUE.search(text): return 1 if RE_FALSE.search(text): return 0 if RE_YES.search(text): return 1 if RE_NO.search(text): return 0 return 0
PROMPT_PATTERNS = [ r"Ask your question", r"\byou may ask\b", r"\bquestion\b", r"\bquery\b", r"\bstart\b", r"\bS0\b", ]
SUBMIT_PATTERNS = [r"\banswer\b", r"\bsubmit\b", r"\benter\b", r"\binput\b"] RESULT_PATTERNS = [r"correct", r"scowls", r"\bnext\b", r"\bround\b", r"gift", r"congrat", r"success"]
def complete_round(io: LineIO, round_idx: int) -> bool: rows, queries = build_queries(N_QUERIES, seed=SEED_BASE + round_idx)
io.read_until_any(PROMPT_PATTERNS, timeout=READ_TIMEOUT, max_lines=40)
responses = [] for idx, q in enumerate(queries): io.read_until_any(PROMPT_PATTERNS, timeout=PROMPT_TIMEOUT, max_lines=4)
io.writeln(q)
ans_blob, _ = io.read_until_any( patterns=[r"Prisoner'?s?\s+response", r"\btrue\b", r"\bfalse\b", r"\b(?:yes|no)\b", r"\b[01]\b"], timeout=PER_Q_TIMEOUT, max_lines=8 ) if not ans_blob: ans_blob = io.read_some_lines(3, timeout=PER_Q_TIMEOUT)
bit = parse_bool(ans_blob) responses.append(bit) if VERBOSE: print(f"[A{idx:02d}] bit={bit} | raw={ans_blob.strip()[:120]}")
sol, errs = decode_from_responses(rows, responses, max_err=MAX_ERROR_BITS) if sol is None: return False
io.read_until_any(SUBMIT_PATTERNS, timeout=READ_TIMEOUT, max_lines=20) io.writeln(" ".join(str(x) for x in sol))
res, _ = io.read_until_any(RESULT_PATTERNS, timeout=READ_TIMEOUT, max_lines=40) low = (res or "").lower() ok = any(k in low for k in ["scowls","correct","next","round","gift","success","congrat"]) return ok
def do_pow(io: LineIO, banner: str): m = re.search(r"sha256\(XXXX\+([^\)]+)\)\s*==\s*([0-9a-fA-F]{64})", banner) if not m: extra, _ = io.read_until_any([r"sha256\(XXXX\+"], timeout=READ_TIMEOUT, max_lines=40) banner += extra m = re.search(r"sha256\(XXXX\+([^\)]+)\)\s*==\s*([0-9a-fA-F]{64})", banner) if not m: return suffix, target = m.group(1), m.group(2) print(f"[POW] suffix={suffix} target={target}") xxxx = solve_pow_parallel(suffix, target) if not xxxx: print("[POW] 并行未找到;建议提高 POW_WAIT_MAX 或换更快的机器。") sys.exit(2) print(f"[POW] solved: {xxxx}") io.writeln(xxxx) ack, _ = io.read_until_any([r"OK", r"pass", r"correct", r"success", r"failed", r"invalid"], timeout=READ_TIMEOUT, max_lines=20) if re.search(r"failed|invalid", ack or "", re.I): print("[POW] 校验失败"); sys.exit(3)
def interact(host, port): try: socket.getaddrinfo(host, port) except Exception: pass with closing(socket.create_connection((host, port), timeout=8)) as s: try: s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if hasattr(socket, "TCP_KEEPIDLE"): s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) if hasattr(socket, "TCP_KEEPINTVL"): s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10) if hasattr(socket, "TCP_KEEPCNT"): s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4) except Exception: pass try: s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except Exception: pass
io = LineIO(s)
banner = io.read_some_lines(40, timeout=READ_TIMEOUT) if banner: print("== banner ==\n" + banner)
do_pow(io, banner)
for r in range(ROUNDS): attempts = 0 while True: attempts += 1 ok = complete_round(io, r) if ok: if r == 9: gift = io.read_some_lines(20, timeout=READ_TIMEOUT) if gift.strip(): print("[Gift] " + gift.strip()[:200]) break if attempts > (1 + RETRY_PER_ROUND): print(f"[!] 第 {r+1} 轮失败过多,退出。") sys.exit(4) io.read_some_lines(40, timeout=READ_TIMEOUT)
final = io.read_some_lines(80, timeout=READ_TIMEOUT) if final: print("== Final ==\n" + final)
if __name__ == "__main__": try: interact(HOST, PORT) except KeyboardInterrupt: print("\n[!] 中断") sys.exit(130) except Exception as e: print(f"[!] 异常:{e}") sys.exit(1)
|