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 463 464 465 466 467 468 469 470 471 472 473 474 475 476
|
""" ezov (Balanced OV) exploit: 1) parse pub.txt (64 public quadratic forms, n=128, GF(65537)) 2) recover oil subspace W using annihilator polynomial of M = P0^{-1} P1 3) build change-of-basis S = [U|W] so oil becomes last 64 coords 4) forge signature for msg="admin" 5) connect remote and submit choice=2 + signature WITHOUT waiting for prompts """
import argparse import ast import hashlib import os import random import re import socket import time from typing import List, Optional, Tuple
import numpy as np import sympy as sp
P = 0x10001 O = 64 V = 64 N = 128
def modinv(a: int, p: int = P) -> int: a %= p if a == 0: raise ZeroDivisionError("inv(0)") return pow(a, p - 2, p)
def mat_inv_mod(A: np.ndarray, p: int = P) -> np.ndarray: """Gauss-Jordan inversion over GF(p).""" A = (A % p).astype(np.int64) n = A.shape[0] I = np.eye(n, dtype=np.int64) aug = np.concatenate([A, I], axis=1) % p
for col in range(n): pivot = None for r in range(col, n): if aug[r, col] % p != 0: pivot = r break if pivot is None: raise ValueError("singular matrix")
if pivot != col: aug[[col, pivot]] = aug[[pivot, col]]
inv_piv = modinv(int(aug[col, col]), p) aug[col, :] = (aug[col, :] * inv_piv) % p
for r in range(n): if r == col: continue f = int(aug[r, col] % p) if f: aug[r, :] = (aug[r, :] - f * aug[col, :]) % p
return aug[:, n:] % p
def rref_mod(A: np.ndarray, p: int = P) -> Tuple[np.ndarray, List[int]]: """RREF over GF(p). Return (RREF, pivot_cols).""" A = (A % p).astype(np.int64) m, n = A.shape pivots: List[int] = [] row = 0
for col in range(n): if row >= m: break
pivot = None for r in range(row, m): if A[r, col] % p != 0: pivot = r break if pivot is None: continue
if pivot != row: A[[row, pivot]] = A[[pivot, row]]
inv_piv = modinv(int(A[row, col]), p) A[row, :] = (A[row, :] * inv_piv) % p
for r in range(m): if r == row: continue f = int(A[r, col] % p) if f: A[r, :] = (A[r, :] - f * A[row, :]) % p
pivots.append(col) row += 1
return A, pivots
def nullspace_basis_mod(A: np.ndarray, p: int = P) -> np.ndarray: """ Right nullspace basis of A over GF(p). Return basis vectors as rows: shape (nullity, ncols). """ R, piv = rref_mod(A, p) m, n = R.shape piv_set = set(piv) free_cols = [c for c in range(n) if c not in piv_set]
basis = [] for fc in free_cols: x = np.zeros(n, dtype=np.int64) x[fc] = 1 for r, pc in enumerate(piv): x[pc] = (-R[r, fc]) % p basis.append(x)
return np.array(basis, dtype=np.int64)
def solve_linear_mod(A: np.ndarray, b: np.ndarray, p: int = P) -> Optional[np.ndarray]: """ Solve A x = b over GF(p) with Gauss-Jordan (A must be square). Return x or None if singular. """ A = (A % p).astype(np.int64) b = (b % p).astype(np.int64).reshape(-1, 1) n = A.shape[0] aug = np.concatenate([A, b], axis=1) % p
row = 0 for col in range(n): pivot = None for r in range(row, n): if aug[r, col] % p != 0: pivot = r break if pivot is None: return None
if pivot != row: aug[[row, pivot]] = aug[[pivot, row]]
inv_piv = modinv(int(aug[row, col]), p) aug[row, :] = (aug[row, :] * inv_piv) % p
for r in range(n): if r == row: continue f = int(aug[r, col] % p) if f: aug[r, :] = (aug[r, :] - f * aug[row, :]) % p
row += 1
return aug[:, n].reshape(-1) % p
def load_pub(path: str) -> List[np.ndarray]: pub = [] with open(path, "r", encoding="utf-8", errors="ignore") as f: for _ in range(O): f.readline() s = "".join(f.readline().strip() for __ in range(N)) mat = np.array(ast.literal_eval(s), dtype=np.int64) % P pub.append(mat) return pub
def hash_vec(msg: str) -> np.ndarray: h = hashlib.shake_128(msg.encode()).hexdigest(128) arr = [int(h[i:i + 4], 16) % P for i in range(0, len(h), 4)] assert len(arr) == O return np.array(arr, dtype=np.int64)
def krylov_annihilator_poly(M: np.ndarray, v: np.ndarray) -> sp.Poly: """ Find non-zero poly a(x)=a0+...+ad x^d s.t. a(M)v=0 by solving K*c=0 for K=[v, Mv, ..., M^N v], K in GF(p)^{N x (N+1)}. """ cols = [] w = v.copy() % P for _ in range(N + 1): cols.append(w.copy()) w = (M @ w) % P K = np.stack(cols, axis=1) % P
ns = nullspace_basis_mod(K, P) if ns.shape[0] == 0: raise RuntimeError("unexpected: nullspace empty") c = ns[0] % P
nz = np.nonzero(c)[0] d = int(nz.max()) c = c[:d + 1] % P
inv_lead = modinv(int(c[-1]), P) c = (c * inv_lead) % P
x = sp.Symbol("x") return sp.Poly([int(t) for t in c[::-1]], x, modulus=P)
def poly_eval_matrix(poly: sp.Poly, M: np.ndarray) -> np.ndarray: """Compute poly(M) mod P with Horner.""" coeffs = [int(c) % P for c in poly.all_coeffs()] I = np.eye(N, dtype=np.int64) R = (coeffs[0] * I) % P for a in coeffs[1:]: R = (R @ M + (a % P) * I) % P return R % P
def recover_oil_space(pub: List[np.ndarray], max_tries: int = 30) -> np.ndarray: """ Recover W (128x64) oil subspace columns. Strategy: M = P0^{-1} P1 get annihilator poly f(x) for random v g = squarefree(f) = f / gcd(f, f') W = ker(g(M)) ; then verify W^T P_i W = 0 for all i """ inv0 = mat_inv_mod(pub[0], P) M = (inv0 @ pub[1]) % P x = sp.Symbol("x")
for t in range(1, max_tries + 1): v = np.random.randint(0, P, size=N, dtype=np.int64) f = krylov_annihilator_poly(M, v)
g = f.quo(sp.gcd(f, f.diff())) if g.degree() != O: continue
GM = poly_eval_matrix(g, M) ns = nullspace_basis_mod(GM, P) if ns.shape[0] != O: continue W = (ns.T) % P
ok = True for i in range(O): K = (W.T @ pub[i] @ W) % P if not np.all(K == 0): ok = False break if ok: return W
raise RuntimeError("failed to recover oil space; try rerun / increase max_tries")
def extend_to_full_basis(W: np.ndarray) -> np.ndarray: """ Build invertible S = [U|W] where W is last 64 columns. Method: start with columns=W, add standard basis vectors that increase rank. """ cols = [W[:, i].copy() for i in range(W.shape[1])] cur = np.column_stack(cols) % P _, piv = rref_mod(cur.copy(), P) cur_rank = len(piv)
for i in range(N): if len(cols) >= N: break e = np.zeros(N, dtype=np.int64) e[i] = 1 cand = np.column_stack([cur, e]) % P _, piv2 = rref_mod(cand.copy(), P) if len(piv2) == cur_rank + 1: cols.append(e) cur = cand cur_rank += 1
while len(cols) < N: e = np.random.randint(0, P, size=N, dtype=np.int64) cand = np.column_stack([cur, e]) % P _, piv2 = rref_mod(cand.copy(), P) if len(piv2) == cur_rank + 1: cols.append(e) cur = cand cur_rank += 1
B = np.column_stack(cols) % P U = B[:, O:] % P S = np.column_stack([U, W]) % P return S
def transform_pub(pub: List[np.ndarray], S: np.ndarray) -> List[np.ndarray]: St = S.T % P return [((St @ Pm @ S) % P) for Pm in pub]
def verify(pub: List[np.ndarray], sig: np.ndarray, h: np.ndarray) -> bool: sig = sig % P for i in range(O): if int((sig @ pub[i] @ sig) % P) != int(h[i]) % P: return False return True
def forge_admin_signature(pub: List[np.ndarray]) -> np.ndarray: h = hash_vec("admin") print("[*] Recovering oil space ...") W = recover_oil_space(pub) print("[+] Oil space recovered!")
print("[*] Building basis transform ...") S = extend_to_full_basis(W) pub_t = transform_pub(pub, S)
inv2 = modinv(2, P)
print("[*] Forging signature for 'admin' ...") tries = 0 while True: tries += 1 x = np.random.randint(0, P, size=V, dtype=np.int64) L = np.zeros((O, O), dtype=np.int64) rhs = np.zeros(O, dtype=np.int64)
for i in range(O): Pi = pub_t[i] A = Pi[:V, :V] B = Pi[:V, V:] const = int((x @ A @ x) % P) row = (x @ B) % P L[i, :] = row rhs[i] = ((int(h[i]) - const) % P) * inv2 % P
y = solve_linear_mod(L, rhs, P) if y is None: continue
z = np.concatenate([x, y]) % P sig = (S @ z) % P if verify(pub, sig, h): print(f"[+] Signature forged! (tries={tries})") return sig
def fmt_signature(sig: np.ndarray) -> str: sig = sig % P return "(" + ",".join(str(int(t)) for t in sig.tolist()) + ")"
def recv_some(sock: socket.socket, total_timeout: float = 1.0) -> bytes: """ Try to read as much as possible within total_timeout. """ end = time.time() + total_timeout data = b"" while time.time() < end: sock.settimeout(0.2) try: chunk = sock.recv(4096) except socket.timeout: continue if not chunk: break data += chunk end = max(end, time.time() + 0.2) return data
def submit_and_get_flag(host: str, port: int, sig_str: str, verbose: bool = True) -> Optional[str]: """ The server script does: menu(); choice=int(input('>')) if choice==2: sig=input('your signature:') if verify('admin',sig): print(flag) Some deployments may buffer stdout, so we send inputs without waiting: "2\n" + "<sig>\n" Then read output and regex VNCTF{...}. """ s = socket.create_connection((host, port), timeout=8.0) try: if verbose: b0 = recv_some(s, total_timeout=0.8) if b0: print(b0.decode(errors="ignore"), end="")
payload = f"2\n{sig_str}\n".encode() s.sendall(payload)
out = b"" deadline = time.time() + 12.0 while time.time() < deadline: out += recv_some(s, total_timeout=0.8) m = re.search(rb"VNCTF\{.*?\}", out) if m: flag = m.group(0).decode(errors="ignore") if verbose: print(out.decode(errors="ignore"), end="") print("\n[FLAG] " + flag) return flag
if verbose: if out: print(out.decode(errors="ignore"), end="") print("\n[!] No VNCTF{...} found in output.") return None finally: s.close()
def main(): ap = argparse.ArgumentParser(description="ezov auto exploit (forge admin sig + fetch flag)") ap.add_argument("--host", default="114.66.24.228") ap.add_argument("--port", default=34122, type=int) ap.add_argument("--pub", default="pub.txt") ap.add_argument("--no-remote", action="store_true", help="only forge signature, don't connect") ap.add_argument("--verbose", action="store_true", help="print remote outputs") args = ap.parse_args()
if not os.path.exists(args.pub): raise FileNotFoundError(f"pub file not found: {args.pub}")
print("[*] Loading pubkey ...") pub = load_pub(args.pub) print("[+] pub loaded.")
sig = forge_admin_signature(pub) sig_str = fmt_signature(sig) print("[*] admin signature:") print(sig_str)
if args.no_remote: return
print(f"[*] Connecting to {args.host}:{args.port} and submitting ...") submit_and_get_flag(args.host, args.port, sig_str, verbose=True or args.verbose)
if __name__ == "__main__": main()
|