douyinWEB/scripts/_probe_neko8_eval.py
2026-09-13 22:10:49 -05:00

209 lines
6.8 KiB
Python

# -*- coding: utf-8 -*-
"""Probe neko8 page title via CDP Runtime.evaluate (detect Aw Snap / SIGILL)."""
from __future__ import annotations
import base64
import json
import os
import socket
import struct
import sys
import paramiko
HOST = "108.174.50.68"
PASS = "Xiao4669805"
CID = "douyinweb-neko-8"
def ws_connect(url: str) -> socket.socket:
assert url.startswith("ws://"), url
hostport, path = url[5:].split("/", 1)
path = "/" + path
host, port_s = hostport.split(":")
port = int(port_s)
key = base64.b64encode(os.urandom(16)).decode()
sock = socket.create_connection((host, port), timeout=8)
req = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {hostport}\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n"
).encode()
sock.sendall(req)
buf = b""
while b"\r\n\r\n" not in buf:
chunk = sock.recv(4096)
if not chunk:
raise RuntimeError("ws handshake closed")
buf += chunk
return sock
def ws_send(sock: socket.socket, payload: dict) -> None:
data = json.dumps(payload).encode()
mask = os.urandom(4)
header = bytearray([0x81])
n = len(data)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header.extend(struct.pack("!H", n))
else:
header.append(0x80 | 127)
header.extend(struct.pack("!Q", n))
header.extend(mask)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
sock.sendall(bytes(header) + masked)
def ws_recv(sock: socket.socket):
def readexact(n: int) -> bytes:
out = b""
while len(out) < n:
chunk = sock.recv(n - len(out))
if not chunk:
raise RuntimeError("ws closed")
out += chunk
return out
hdr = readexact(2)
b1, b2 = hdr[0], hdr[1]
opcode = b1 & 0x0F
masked = (b2 & 0x80) != 0
ln = b2 & 0x7F
if ln == 126:
ln = struct.unpack("!H", readexact(2))[0]
elif ln == 127:
ln = struct.unpack("!Q", readexact(8))[0]
mask = readexact(4) if masked else b""
data = readexact(ln)
if masked:
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
if opcode == 0x8:
return None
if opcode != 0x1:
return ws_recv(sock)
return json.loads(data.decode())
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
# Port-forward CDP via docker exec python inside host using host network? Use SSH tunnel to container IP.
_, o, e = c.exec_command(
f"docker inspect -f '{{{{.NetworkSettings.IPAddress}}}}' {CID}", timeout=20
)
ip = (o.read() + e.read()).decode().strip()
print("ip", ip)
if not ip:
print("no ip")
return 1
# List tabs from inside container
_, o, e = c.exec_command(
f"""docker exec {CID} python3 -c 'import json,urllib.request; print(json.dumps(json.load(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=4))))'""",
timeout=30,
)
raw = (o.read() + e.read()).decode().strip()
tabs = json.loads(raw)
pages = [t for t in tabs if t.get("type") == "page"]
print("pages", len(pages))
for t in pages:
print("meta", t.get("title"), (t.get("url") or "")[:90])
# Open SSH local forward isn't trivial; evaluate INSIDE container with a tiny python ws client.
eval_script = r'''
import base64,json,os,socket,struct,urllib.request,sys
expr = r"""(() => ({
title: document.title || '',
href: location.href || '',
body: (document.body && (document.body.innerText || '')).slice(0, 400),
crash: !!(document.documentElement && /Aw,\s*Snap|SIGILL|STATUS_INVALID|Something went wrong/i.test(document.title + ' ' + (document.body && document.body.innerText || '')))
}))()"""
tabs=json.load(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4))
pages=[t for t in tabs if t.get('type')=='page']
if not pages:
print(json.dumps({'ok':False,'err':'no page'})); sys.exit(0)
def ws_connect(url):
hostport,path=url[5:].split('/',1); path='/'+path
host,port=hostport.split(':'); port=int(port)
key=base64.b64encode(os.urandom(16)).decode()
s=socket.create_connection((host,port),timeout=8)
s.sendall(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode())
buf=b''
while b'\r\n\r\n' not in buf:
c=s.recv(4096)
if not c: raise RuntimeError('hs')
buf+=c
return s
def ws_send(s,payload):
data=json.dumps(payload).encode(); mask=os.urandom(4)
h=bytearray([0x81]); n=len(data)
if n<126: h.append(0x80|n)
elif n<65536: h.append(0x80|126); h.extend(struct.pack('!H',n))
else: h.append(0x80|127); h.extend(struct.pack('!Q',n))
h.extend(mask); s.sendall(bytes(h)+bytes(b^mask[i%4] for i,b in enumerate(data)))
def ws_recv(s):
def ex(n):
o=b''
while len(o)<n:
c=s.recv(n-len(o))
if not c: raise RuntimeError('closed')
o+=c
return o
b1,b2=ex(2); opcode=b1&0x0f; masked=(b2&0x80)!=0; ln=b2&0x7f
if ln==126: ln=struct.unpack('!H',ex(2))[0]
elif ln==127: ln=struct.unpack('!Q',ex(8))[0]
mask=ex(4) if masked else b''; data=ex(ln)
if masked: data=bytes(b^mask[i%4] for i,b in enumerate(data))
if opcode==8: return None
if opcode!=1: return ws_recv(s)
return json.loads(data.decode())
t=pages[0]
ws=t.get('webSocketDebuggerUrl')
s=ws_connect(ws)
ws_send(s,{'id':1,'method':'Runtime.enable'})
ws_recv(s)
ws_send(s,{'id':2,'method':'Runtime.evaluate','params':{'expression':expr,'returnByValue':True,'awaitPromise':False}})
resp=None
for _ in range(20):
msg=ws_recv(s)
if not msg: break
if msg.get('id')==2:
resp=msg; break
s.close()
val=((resp or {}).get('result') or {}).get('result') or {}
print(json.dumps({'ok':True,'meta_title':t.get('title'),'meta_url':t.get('url'),'eval':val.get('value')}, ensure_ascii=False))
'''
# write script on remote and run
sftp = c.open_sftp()
with sftp.file("/tmp/_neko8_eval.py", "w") as f:
f.write(eval_script)
sftp.close()
_, o, e = c.exec_command(f"docker cp /tmp/_neko8_eval.py {CID}:/tmp/_neko8_eval.py && docker exec {CID} python3 /tmp/_neko8_eval.py", timeout=40)
print((o.read() + e.read()).decode())
_, o, e = c.exec_command(
f"docker exec {CID} bash -lc \"grep -aEi 'SIGILL|Illegal instruction|Aw, Snap|STATUS_INVALID' /var/log/neko/google-chrome.log 2>/dev/null | tail -20\"",
timeout=30,
)
print("=== log hits ===")
print((o.read() + e.read()).decode() or "(none)")
c.close()
return 0
if __name__ == "__main__":
sys.exit(main())