143 lines
4.4 KiB
Python
143 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Small raw sondib protocol client used by the local PoCs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import socket
|
|
import struct
|
|
|
|
|
|
PORT = 7777
|
|
TIMEOUT = 10.0
|
|
MAX_FRAME = 0x100200
|
|
|
|
|
|
class ProtocolError(RuntimeError):
|
|
"""The target returned a malformed sondib frame."""
|
|
|
|
|
|
def encode_sdz(data: bytes) -> bytes:
|
|
"""Encode a literal-only SDZ block.
|
|
|
|
Literal-only blocks are sufficient for the short control frames used by
|
|
these PoCs. The format supports extended literal lengths as well.
|
|
"""
|
|
|
|
if len(data) > 0x40000:
|
|
raise ValueError("control frame is too large")
|
|
encoded = bytearray(b"SDZ1")
|
|
encoded.extend(len(data).to_bytes(3, "little"))
|
|
encoded.append(0)
|
|
if len(data) <= 14:
|
|
encoded.append(len(data) << 4)
|
|
else:
|
|
encoded.append(0xF0)
|
|
remaining = len(data) - 15
|
|
while remaining >= 0xFF:
|
|
encoded.append(0xFF)
|
|
remaining -= 0xFF
|
|
encoded.append(remaining)
|
|
encoded.extend(data)
|
|
return bytes(encoded)
|
|
|
|
|
|
def _read_exact(sock: socket.socket, size: int) -> bytes:
|
|
chunks: list[bytes] = []
|
|
while size:
|
|
chunk = sock.recv(size)
|
|
if not chunk:
|
|
raise ProtocolError("connection closed in a frame")
|
|
chunks.append(chunk)
|
|
size -= len(chunk)
|
|
return b"".join(chunks)
|
|
|
|
|
|
def decode_sdz(blob: bytes) -> bytes:
|
|
if len(blob) < 8 or blob[:4] != b"SDZ1":
|
|
raise ProtocolError("invalid SDZ header")
|
|
expected = int.from_bytes(blob[4:7], "little")
|
|
pos = 8
|
|
output = bytearray()
|
|
while pos < len(blob):
|
|
control = blob[pos]
|
|
pos += 1
|
|
literal_length = control >> 4
|
|
match_code = control & 0x0F
|
|
if literal_length == 0x0F:
|
|
literal_length = 15
|
|
while True:
|
|
if pos >= len(blob):
|
|
raise ProtocolError("truncated literal length")
|
|
extra = blob[pos]
|
|
pos += 1
|
|
literal_length += extra
|
|
if extra != 0xFF:
|
|
break
|
|
end = pos + literal_length
|
|
if end > len(blob):
|
|
raise ProtocolError("truncated literal data")
|
|
output.extend(blob[pos:end])
|
|
pos = end
|
|
if pos == len(blob):
|
|
break
|
|
if pos + 3 > len(blob):
|
|
raise ProtocolError("truncated match descriptor")
|
|
distance = int.from_bytes(blob[pos : pos + 3], "little")
|
|
pos += 3
|
|
match_length = match_code + 4
|
|
if match_code == 0x0F:
|
|
while True:
|
|
if pos >= len(blob):
|
|
raise ProtocolError("truncated match length")
|
|
extra = blob[pos]
|
|
pos += 1
|
|
match_length += extra
|
|
if extra != 0xFF:
|
|
break
|
|
if distance == 0 or distance > len(output):
|
|
raise ProtocolError("invalid match distance")
|
|
for _ in range(match_length):
|
|
output.append(output[-distance])
|
|
if len(output) != expected:
|
|
raise ProtocolError(
|
|
f"decoded length mismatch: expected {expected}, got {len(output)}"
|
|
)
|
|
return bytes(output)
|
|
|
|
|
|
class SondibClient:
|
|
def __init__(self, target: str, timeout: float = TIMEOUT) -> None:
|
|
self.sock = socket.create_connection((target, PORT), timeout=timeout)
|
|
self.sock.settimeout(timeout)
|
|
self.receive() # protocol hello
|
|
|
|
def close(self) -> None:
|
|
self.sock.close()
|
|
|
|
def send(self, payload: bytes) -> None:
|
|
encoded = encode_sdz(payload)
|
|
self.sock.sendall(struct.pack("<I", len(encoded)))
|
|
self.sock.sendall(encoded)
|
|
|
|
def receive(self) -> bytes:
|
|
size = struct.unpack("<I", _read_exact(self.sock, 4))[0]
|
|
if size > MAX_FRAME:
|
|
raise ProtocolError(f"frame exceeds {MAX_FRAME} bytes")
|
|
return decode_sdz(_read_exact(self.sock, size))
|
|
|
|
def request(self, payload: bytes) -> bytes:
|
|
self.send(payload)
|
|
return self.receive()
|
|
|
|
|
|
def credentials_frame(opcode: int, username: str, password: str) -> bytes:
|
|
name = username.encode()
|
|
secret = password.encode()
|
|
if not 0 < len(name) <= 15:
|
|
raise ValueError("username must be 1..15 bytes")
|
|
if not 0 < len(secret) <= 31:
|
|
raise ValueError("password must be 1..31 bytes")
|
|
return bytes((opcode,)) + struct.pack("<H", len(name)) + name + struct.pack(
|
|
"<H", len(secret)
|
|
) + secret
|