#!/usr/bin/env python3
"""Player-side TLS relay for stealmygift.iamwonderingif.com.

Run this on your machine, then point the exploit tools at 127.0.0.1:8080.
It just forwards raw TCP to the HTTPS frontend (nginx on 443) - the exploit
chain passes through unchanged (verified end-to-end 2026-10-31).

  python3 ctf-tls-relay.py 8080
"""
import socket, ssl, sys, threading

LISTEN_PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
TARGET_HOST = "stealmygift.iamwonderingif.com"
TARGET_PORT = 443

def pump(a, b):
    try:
        while True:
            d = a.recv(65536)
            if not d:
                break
            b.sendall(d)
    except Exception:
        pass
    finally:
        for s in (a, b):
            try: s.shutdown(socket.SHUT_RDWR)
            except Exception: pass

def handle(c):
    try:
        ctx = ssl.create_default_context()
        s = ctx.wrap_socket(socket.create_connection((TARGET_HOST, TARGET_PORT), timeout=120),
                            server_hostname=TARGET_HOST)
        s.settimeout(300); c.settimeout(300)
        threading.Thread(target=pump, args=(c, s), daemon=True).start()
        pump(s, c)
    except Exception as e:
        print("relay error: %r" % (e,), file=sys.stderr)
        try: c.close()
        except Exception: pass

ls = socket.socket()
ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ls.bind(("127.0.0.1", LISTEN_PORT))
ls.listen(256)
print("relay listening on 127.0.0.1:%d -> %s:%d" % (LISTEN_PORT, TARGET_HOST, TARGET_PORT), flush=True)
while True:
    c, _ = ls.accept()
    threading.Thread(target=handle, args=(c,), daemon=True).start()
