Skip to content
Repos

TOSV

Python 17.5 KB426 lines Opens in site

Directory Raw Download

#!/usr/bin/env python3
# Raw SFTP/SSH probes for Gate 2: behaviors stock sftp cannot express.
# Run with the project .venv python (asyncssh). Self-asserting: prints
# PASS:/FAIL:/SKIP: lines; exit 1 on any FAIL.
import asyncio, asyncssh, socket, struct, sys

fails = 0
skips = 0

def ok(n): print(f"PASS: {n}", flush=True)
def bad(n, e=""):
    global fails; fails += 1; print(f"FAIL: {n} {e}".rstrip(), flush=True)
def skip(n, why):
    global skips; skips += 1; print(f"SKIP: {n} ({why})", flush=True)

async def a_main(port, gid, gp, keyfile):
    base = f"/{gid}/{gp}"
    try:
        conn = await asyncssh.connect('127.0.0.1', port, username='u',
            client_keys=[keyfile], known_hosts=None,
            kex_algs=['curve25519-sha256'],
            encryption_algs=['chacha20-poly1305@openssh.com'],
            signature_algs=['ssh-ed25519'])
    except Exception as e:
        bad("raw connect", f"{type(e).__name__}: {e}"[:120]); return
    ok("raw connect subset")
    try:
        async with conn.start_sftp_client() as sftp:
            await sftp.put('/dev/null', f"{base}/raw1.bin")
            try:
                await conn.run('true', check=False)
                bad("second channel refused", "accepted")
            except asyncssh.ChannelOpenError:
                ok("second channel refused")
            except Exception as e:
                bad("second channel refused", f"wrong error {type(e).__name__}")
            try:
                f = await sftp.open(f"{base}/raw1.bin", 'xb')
                await f.close()
                bad("EXCL on existing refused", "accepted")
            except ValueError:
                skip("EXCL on existing refused", "client lacks x mode")
            except (OSError, asyncssh.Error):
                ok("EXCL on existing refused")
            try:
                f = await sftp.open(f"{base}/raw1.bin", 'ab')
                await f.close()
                bad("APPEND unsupported", "accepted")
            except (OSError, asyncssh.Error):
                ok("APPEND unsupported")
            try:
                f = await sftp.open(f"{base}/raw2.bin", 'wb')
                await f.write(b'0123456789')
                try:
                    await f.seek(100)
                    await f.write(b'nope')
                except (OSError, asyncssh.Error):
                    pass
                await f.close()
                st = await sftp.stat(f"{base}/raw2.bin")
                if st.size == 10:
                    ok("non-sequential WRITE rejected")
                else:
                    bad("non-sequential WRITE rejected", f"size={st.size}")
            except Exception as e:
                bad("non-sequential WRITE rejected", f"{type(e).__name__}"[:80])
            try:
                s1 = await sftp.stat(f"{base}/raw1.bin")
                s2 = await sftp.lstat(f"{base}/raw1.bin")
                if s1.size == s2.size and s1.mtime == s2.mtime:
                    ok("STAT equals LSTAT")
                else:
                    bad("STAT equals LSTAT", "differ")
            except Exception as e:
                bad("STAT equals LSTAT", f"{type(e).__name__}"[:80])
            try:
                await sftp.symlink(f"{base}/raw1.bin", f"{base}/lnk")
                bad("SYMLINK unsupported", "accepted")
            except (OSError, asyncssh.Error):
                ok("SYMLINK unsupported")
            try:
                from asyncssh import SFTPAttrs
                try:
                    await sftp.setstat(f"{base}/raw1.bin",
                        SFTPAttrs(permissions=0o600, extended={'x': b'y'}))
                    skip("FSETSTAT extended unsupported", "client dropped extended (unverifiable)")
                except (OSError, asyncssh.Error):
                    ok("FSETSTAT extended unsupported")
            except (TypeError, AttributeError, ValueError):
                skip("FSETSTAT extended unsupported", "client cannot express")
    except Exception as e:
        bad("raw session", f"{type(e).__name__}: {e}"[:120])
        return
    try:
        conn2 = await asyncssh.connect('127.0.0.1', port, username='u',
            client_keys=[keyfile], known_hosts=None)
        try:
            await conn2.run('true', check=False)
            bad("exec refused", "ran")
        except Exception:
            ok("exec refused")
        conn2.close()
    except Exception as e:
        bad("exec probe connect", f"{type(e).__name__}"[:80])
    conn.close()

def pkt(payload):
    pad = 8 - ((4 + 1 + len(payload)) % 8)
    if pad < 4: pad += 8
    import os
    body = bytes([pad]) + payload + os.urandom(pad)
    return struct.pack('>I', len(body)) + body

def nl(s): return struct.pack('>I', len(s)) + s.encode()

def kexinit(kex='curve25519-sha256,kex-strict-c-v00@openssh.com',
            ciphers='chacha20-poly1305@openssh.com'):
    import os
    p = b'\x14' + os.urandom(16)
    p += nl(kex) + nl('ssh-ed25519') + nl(ciphers) + nl(ciphers)
    p += nl('hmac-sha2-256') + nl('hmac-sha2-256') + nl('none') + nl('none')
    p += nl('') + nl('') + b'\x00' + struct.pack('>I', 0)
    return p

def read_frame(s):
    hdr = b''
    while len(hdr) < 4:
        b = s.recv(4 - len(hdr))
        if not b: return None
        hdr += b
    (ln,) = struct.unpack('>I', hdr)
    if ln > 300000: return None
    body = b''
    while len(body) < ln:
        b = s.recv(ln - len(body))
        if not b: return None
        body += b
    return body[1:]

def k_probe(name, sendfn, want_code):
    try:
        s = socket.create_connection(('127.0.0.1', KPORT), timeout=10)
        s.settimeout(10)
        line = b''
        while not line.endswith(b'\n'):
            b = s.recv(1)
            if not b: raise OSError('no banner')
            line += b
        s.sendall(b'SSH-2.0-rawprobe\r\n')
        got = read_frame(s)
        if not got or got[0:1] != b'\x14':
            raise OSError('no server kexinit')
        for msg in sendfn():
            s.sendall(pkt(msg))
        rep = read_frame(s)
        s.close()
        if rep and rep[0:1] == b'\x01' and len(rep) >= 5 and struct.unpack('>I', rep[1:5])[0] == want_code:
            ok(name)
        else:
            detail = 'none' if not rep else f"type={rep[0]}"
            bad(name, f"want disconnect {want_code} got {detail}")
    except Exception as e:
        bad(name, f"{type(e).__name__}: {e}"[:100])

def k_main(port):
    global KPORT; KPORT = port
    k_probe("kex no-strict refused code 2",
        lambda: [kexinit(kex='curve25519-sha256')], 2)
    k_probe("kex short key refused code 3",
        lambda: [kexinit(), b'\x1e' + struct.pack('>I', 31) + b'Q' * 31], 3)
    k_probe("kex zero key refused code 3",
        lambda: [kexinit(), b'\x1e' + struct.pack('>I', 32) + b'\x00' * 32], 3)
    k_probe("kex unknown kex refused code 3",
        lambda: [kexinit(kex='diffie-hellman-group14-sha256,kex-strict-c-v00@openssh.com')], 3)
    k_probe("kex aes-only refused code 3",
        lambda: [kexinit(ciphers='aes128-ctr')], 3)

def e_main(port, gid, gp, keyfile):
    # Full raw SSH handshake (cryptography lib) plus truncated SFTP
    # packets: each malformed request must yield EXACTLY ONE reply
    # (single status 5), and the channel must stay alive after.
    try:
        from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
        from cryptography.hazmat.primitives import hashes, serialization
        from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
        from cryptography.hazmat.primitives.poly1305 import Poly1305
    except Exception as e:
        skip("single-reply truncated", f"no cryptography lib: {e}"[:60]); return
    try:
        priv = serialization.load_ssh_private_key(open(keyfile, 'rb').read(), password=None)
        pub = priv.public_key()
    except Exception as e:
        bad("single-reply truncated", f"key load: {e}"[:80]); return

    def u32(i): return struct.pack('>I', i)
    def ns(b):
        if isinstance(b, str): b = b.encode()
        return u32(len(b)) + b
    def mpint(b):
        b = b.lstrip(b'\x00')
        if not b: return u32(0)
        if b[0] & 0x80: b = b'\x00' + b
        return u32(len(b)) + b
    def chacha(key, nonce12, counter, data):
        nonce16 = struct.pack('<I', counter) + nonce12
        c = Cipher(algorithms.ChaCha20(key, nonce16), None).encryptor()
        return c.update(data) + c.finalize()
    def nonce12(seq): return b'\x00' * 4 + struct.pack('>Q', seq)

    st = {"rseq": 0, "wseq": 0, "rxh": None, "rxm": None, "txh": None, "txm": None}

    def send_pkt(s, payload):
        enc = st["txm"] is not None
        abase = (1 + len(payload)) if enc else (4 + 1 + len(payload))
        pad = 8 - (abase % 8)
        if pad < 4: pad += 8
        import os
        body = bytes([pad]) + payload + os.urandom(pad)
        plen = len(body)
        if st["txm"] is None:
            s.sendall(u32(plen) + body)
        else:
            n12 = nonce12(st["wseq"])
            pkey = chacha(st["txm"], n12, 0, b'\x00' * 32)
            enc_len = chacha(st["txh"], n12, 0, u32(plen))
            enc_body = chacha(st["txm"], n12, 1, body)
            tag = Poly1305.generate_tag(pkey, enc_len + enc_body)
            s.sendall(enc_len + enc_body + tag)
        st["wseq"] += 1

    def recv_pkt(s):
        if st["rxm"] is None:
            hdr = _recvn(s, 4)
            (plen,) = struct.unpack('>I', hdr)
            if plen < 6 or plen > 35000: raise OSError('bad plen')
            body = _recvn(s, plen)
            pad = body[0]
            st["rseq"] += 1
            return body[1:len(body) - pad]
        n12 = nonce12(st["rseq"])
        enc_len = _recvn(s, 4)
        plen = struct.unpack('>I', chacha(st["rxh"], n12, 0, enc_len))[0]
        if plen < 6 or plen > 300000 or plen % 8: raise OSError('bad eplen')
        rest = _recvn(s, plen + 16)
        pkey = chacha(st["rxm"], n12, 0, b'\x00' * 32)
        Poly1305.verify_tag(pkey, enc_len + rest[:plen], rest[plen:])
        body = chacha(st["rxm"], n12, 1, rest[:plen])
        pad = body[0]
        st["rseq"] += 1
        return body[1:len(body) - pad]

    def _recvn(s, n):
        b = b''
        while len(b) < n:
            c = s.recv(n - len(b))
            if not c: raise OSError('eof')
            b += c
        return b

    def kdf(K, H, sid, x):
        h = hashes.Hash(hashes.SHA256())
        h.update(mpint(K) + H + bytes([x]) + sid)
        k1 = h.finalize()
        h = hashes.Hash(hashes.SHA256())
        h.update(mpint(K) + H + k1)
        return k1 + h.finalize()

    try:
        s = socket.create_connection(('127.0.0.1', port), timeout=10)
        s.settimeout(10)
        banner = b''
        while not banner.endswith(b'\n'):
            banner += s.recv(1)
        vc = b'SSH-2.0-rawprobe'
        s.sendall(vc + b'\r\n')
        vs = banner.strip()
        import os
        my_init = b'\x14' + os.urandom(16) + ns('curve25519-sha256,kex-strict-c-v00@openssh.com')
        my_init += ns('ssh-ed25519') + ns('chacha20-poly1305@openssh.com') * 2
        my_init += ns('hmac-sha2-256') * 2 + ns('none') * 2 + ns('') + ns('') + b'\x00' + u32(0)
        send_pkt(s, my_init)
        si = recv_pkt(s)
        if si[0:1] != b'\x14': raise OSError('no kexinit')
        eph = X25519PrivateKey.generate()
        qpub = eph.public_key().public_bytes(serialization.Encoding.Raw,
                                               serialization.PublicFormat.Raw)
        send_pkt(s, b'\x1e' + ns(qpub))
        rp = recv_pkt(s)
        if rp[0:1] != b'\x1f': raise OSError('no kexreply')
        o = 1
        def take(b, off):
            (ln,) = struct.unpack('>I', b[off:off + 4])
            return b[off + 4:off + 4 + ln], off + 4 + ln
        ks, o = take(rp, o)
        qs, o = take(rp, o)
        K = eph.exchange(X25519PublicKey.from_public_bytes(qs))
        H = hashes.Hash(hashes.SHA256())
        H.update(ns(vc) + ns(vs) + ns(my_init) + ns(si) + ns(ks) + ns(qpub) + ns(qs) + mpint(K))
        H = H.finalize()
        sigb, o = take(rp, o)
        send_pkt(s, b'\x15')
        nk = recv_pkt(s)
        if nk[0:1] != b'\x15': raise OSError('no newkeys')
        st["rxm"], st["rxh"] = kdf(K, H, H, ord('D'))[:32], kdf(K, H, H, ord('D'))[32:]
        st["txm"], st["txh"] = kdf(K, H, H, ord('C'))[:32], kdf(K, H, H, ord('C'))[32:]
        st["rseq"] = st["wseq"] = 0
        send_pkt(s, b'\x05' + ns('ssh-userauth'))
        if recv_pkt(s)[0:1] != b'\x06': raise OSError('no service ok')
        blob = ns('ssh-ed25519') + ns(pub.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
        send_pkt(s, b'\x32' + ns('u') + ns('ssh-connection') + ns('publickey') + b'\x00' + ns('ssh-ed25519') + ns(blob))
        if recv_pkt(s)[0:1] != b'\x3c': raise OSError('no pk ok')
        sd = ns(H) + b'\x32' + ns('u') + ns('ssh-connection') + ns('publickey') + b'\x01' + ns('ssh-ed25519') + ns(blob)
        sig = priv.sign(sd)
        send_pkt(s, b'\x32' + ns('u') + ns('ssh-connection') + ns('publickey') + b'\x01' + ns('ssh-ed25519') + ns(blob) + ns(ns('ssh-ed25519') + ns(sig)))
        if recv_pkt(s)[0:1] != b'\x34': raise OSError('auth failed')
        send_pkt(s, b'\x5a' + ns('session') + u32(0) + u32(2097152) + u32(32768))
        if recv_pkt(s)[0:1] != b'\x5b': raise OSError('no chan open')
        send_pkt(s, b'\x62' + u32(0) + ns('subsystem') + b'\x01' + ns('sftp'))
        if recv_pkt(s)[0:1] != b'\x63': raise OSError('no subsystem ok')

        def chan(data):
            send_pkt(s, b'\x5e' + u32(0) + ns(u32(len(data)) + data))

        def read_sftp(want_ids, secs=3):
            s.settimeout(0.5)
            got = {i: [] for i in want_ids}
            import time
            end = time.time() + secs
            buf = b''
            while time.time() < end:
                try:
                    m = recv_pkt(s)
                except socket.timeout:
                    continue
                except OSError:
                    break
                if not m or m[0:1] != b'\x5e' or len(m) < 9:
                    continue
                (ln,) = struct.unpack('>I', m[5:9])
                buf += m[9:9 + ln]
                while len(buf) >= 4:
                    (fl,) = struct.unpack('>I', buf[:4])
                    if len(buf) < 4 + fl:
                        break
                    pkt = buf[4:4 + fl]
                    buf = buf[4 + fl:]
                    if len(pkt) >= 5:
                        rid = struct.unpack('>I', pkt[1:5])[0]
                        if rid in got:
                            got[rid].append(pkt)
            return got

        chan(b'\x01' + u32(3))
        _ = read_sftp([], secs=2)
        chan(b'\x04' + u32(41) + u32(16) + b'abc')
        chan(b'\x05' + u32(42) + struct.pack('>Q', 0))
        got = read_sftp([41, 42], secs=3)
        s.close()
        n41, n42 = len(got[41]), len(got[42])
        if n41 == 1 and got[41][0][0] == 101 and struct.unpack('>I', got[41][0][5:9])[0] == 5:
            ok("single-reply truncated close")
        else:
            bad("single-reply truncated close", f"replies={n41}")
        if n42 == 1 and got[42][0][0] == 101 and struct.unpack('>I', got[42][0][5:9])[0] == 5:
            ok("single-reply truncated read")
        else:
            bad("single-reply truncated read", f"replies={n42}")
    except Exception as e:
        bad("single-reply truncated", f"{type(e).__name__}: {e}"[:100])


def r_main(port, gid, gp, keyfile, hostpub):
    import os, shutil, subprocess, tempfile
    if not hostpub:
        skip("rclone sftp roundtrip", "no host key arg"); return
    if shutil.which('rclone') is None:
        skip("rclone sftp roundtrip", "rclone not installed"); return
    try:
        hk = open(hostpub).read().split()
        hostkey = f"{hk[0]} {hk[1]}"
    except Exception:
        bad("rclone sftp roundtrip", "unreadable host key"); return
    td = tempfile.mkdtemp(prefix='tosv-rclone-')
    env = dict(os.environ)
    env.update({
        'RCLONE_CONFIG_TV_TYPE': 'sftp',
        'RCLONE_CONFIG_TV_HOST': '127.0.0.1',
        'RCLONE_CONFIG_TV_PORT': str(port),
        'RCLONE_CONFIG_TV_USER': 'u',
        'RCLONE_CONFIG_TV_KEY_FILE': os.path.abspath(keyfile),
        'RCLONE_CONFIG_TV_HOST_KEY': hostkey,
        'RCLONE_CONFIG_TV_SHELL_TYPE': 'none',
        'RCLONE_CONFIG_TV_MD5SUM_COMMAND': 'none',
        'RCLONE_CONFIG_TV_SHA1SUM_COMMAND': 'none',
        'HOME': td,
        'XDG_CONFIG_HOME': td,
    })
    up = os.path.join(td, 'up.bin'); down = os.path.join(td, 'down.bin')
    open(up, 'wb').write(os.urandom(262144))
    remote = f"tv:/{gid}/{gp}/rc-gate.bin"
    try:
        for args in (['copyto', up, remote], ['copyto', remote, down]):
            p = subprocess.run(['rclone'] + args, capture_output=True,
                               text=True, env=env, timeout=30)
            if p.returncode != 0:
                err = (p.stderr.strip().splitlines() or ['exit ' + str(p.returncode)])[-1]
                bad("rclone sftp roundtrip", err[:100]); return
        if open(up, 'rb').read() != open(down, 'rb').read():
            bad("rclone sftp roundtrip", "byte mismatch"); return
        ok("rclone sftp roundtrip")
    except subprocess.TimeoutExpired:
        bad("rclone sftp roundtrip", "stalled over 30s (EOF close regressed?)")
    except Exception as e:
        bad("rclone sftp roundtrip", f"{type(e).__name__}: {e}"[:100])
    finally:
        shutil.rmtree(td, ignore_errors=True)

if __name__ == '__main__':
    port, gid, gp, keyfile = int(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4]
    hostpub = sys.argv[5] if len(sys.argv) > 5 else None
    asyncio.run(a_main(port, gid, gp, keyfile))
    k_main(port)
    e_main(port, gid, gp, keyfile)
    r_main(port, gid, gp, keyfile, hostpub)
    print(f"== raw probe: {fails} fail, {skips} skip ==")
    sys.exit(1 if fails else 0)
30.1ms