Mass Assignment: How Over-Posting Rewrites Fields Your Form Never Showed — and How Explicit Field Lists Stop It
Django Security Series — Post 10 | Series II: Broken Access Control
OWASP A08:2025 — Software or Data Integrity Failures | Reading time: ~16 min
🧪 Run it yourself. This attack ships as a runnable lab in django-security-lab: a customer order API built on a DRF
ModelSerializer. Thefields = '__all__'view lets aPATCHover-postprice,paid, andstatus— forging a free-and-paid order and capturing a flag the legitimate flow can never reach; the explicitfields+read_only_fieldsview silently drops the same over-posts and still returns200. Reproduce both withcurl— and see the detection twist: an earlier draft of this post claimedsemgrep --config p/djangoflagsfields='__all__'on serializers. It does not, in the community packs or the registry's Python rules — so the lab ships the custom rule that actually fires.
(Mapping note: Mass assignment is CWE-915, which OWASP officially files under A08 (Software or Data Integrity Failures). This post closes Series II — Broken Access Control — because the impact is almost always an access-control failure: the client writes a field it was never authorised to touch. Post 7 was the mirror image — it categorised under A01 for the same reason. Same bug, two OWASP homes, depending on whether you name it by mechanism or by consequence.)
Post 7 looked at one specific version of this bug: a form that exposed is_staff and let a user promote themselves. That post owned the permission dimension. This one takes the same mechanism and removes the word "permission" from it entirely.
Because here is the thing I under-appreciated until I audited my own models for this post: the dangerous field is rarely is_superuser. Most Django apps don't hand out admin over a profile form. What they do hand out, if the form binds every column, is the ability to set price to zero, flip paid to true, reassign owner to yourself, or change an order's status from pending to shipped. None of those are permission flags. None of them would show up if you only grepped for is_staff. They are ordinary business fields, and mass assignment turns every one of them into an attacker-controlled input.
Mass assignment (also called over-posting, or in the OWASP API Top 10, Broken Object Property Level Authorization) is what happens when an application binds a request payload to a model without deciding, field by field, which columns the client is actually allowed to write. Django's ModelForm and DRF's ModelSerializer both make this the path of least resistance: fields = '__all__' is shorter to type than an explicit list, it "just works" in development, and it silently exposes every editable column the model will ever have — including the ones you add six months later.
While researching this post I went back through Petição Brasil looking for the classic is_staff hole from Post 7. I didn't find one. What I found was the column that matters more: a signature's verification_status, which decides whether a citizen's signature counts. The submission form lists five fields and not that one, the view sets it to pending after binding, and the verification task re-decides it on every submission. Bind it from the request instead, with neither of those behind it, and one extra key in the POST would mark a signature approved before its ICP-Brasil certificate was ever checked. That is not a privilege escalation in the is_staff sense. It is a data-integrity failure on a legally binding record, which is why this bug lives under A08.
The Attack: What It Is and How It Works
Picture an order-editing endpoint. The page lets the customer change one thing before checkout, quantity, and sends it to the API as a PATCH. Behind it sits an Order model with more columns than that — quantity, price, paid, status, owner, discount_code. The developer wrote fields = '__all__' on the serializer because listing them felt redundant when the page only sends one.
The page is a suggestion. The serializer is the contract. When the customer sends {"quantity": 1}, nothing stops them from also sending "price": "0.00", "paid": true, "status": "shipped" in the same body. '__all__' makes each of those a writable field, DRF validates each value against its type, and save() writes the lot; a PATCH is partial, so the columns the request leaves out keep their values. The customer just bought a free, pre-paid, already-shipped order. No injection, no stolen credential, no exploit toolkit. They added keys to a request body. (A ModelForm with '__all__' would instead demand every required field on each submit and break the page, which is why the form version of this bug is usually a list that names one field too many.)
That is the whole attack. The root cause is the one that has run through this entire series since Post 1: the application treats structure that should be fixed in code as data that comes from the user. In SQL injection the user-controlled data became query syntax. In path traversal it became filesystem navigation. Here it becomes the set of columns the write touches. The developer meant to define that set — "the customer may write quantity" — but by writing '__all__' they delegated the decision to whoever sends the request.
The reason it survives code review is that the vulnerable line looks like configuration, not logic. fields = '__all__' reads as "this serializer is about the whole object," which sounds reasonable. It does not read as "the client may write every editable column, forever, including columns that don't exist yet." And it is invisible in manual testing, because the developer using the page only ever sends the fields the page sends. The extra keys are something you have to think to send.
From there, exploitation is mechanical. The attacker starts by learning the model's shape. They don't need your source: a GET request to the same endpoint (or a DRF browsable API, or an error message, or the JSON a detail view returns) usually leaks the field names. owner, status, is_published, price, balance, verified — the interesting fields tend to be guessable from the domain. Then they replay the write with the extra keys attached.
For a Django ModelForm the payload is a normal form POST with additional fields the template never rendered: status=approved, is_active=on. For a DRF ModelSerializer it is extra JSON keys — {"quantity": 1, "price": "0.00", "paid": true} — which DRF deserializes straight into validated_data and serializer.save() persists. Either way the server, not the browser, is the security boundary, and the server accepted fields it should have refused.
The same over-post has a second target: ownership. A foreign key the client can write, such as owner, creator or user, lets an attacker hand a record to another account or plant one in a victim's name, the write-side twin of the IDOR read from Post 6. That is the attack behind the best-known mass-assignment incident: in 2012 an over-posted user_id on GitHub's SSH-key form attached Egor Homakov's key to the rails organization's account, and Django's ModelForm documentation still cites GitHub when it warns against binding every field.
Real-World Incidents
Spree — CVE-2008-7310 (2008)
In September 2008, Eric Chapweske of the Rails blog Rail Spikes checked five popular open-source Rails applications for mass assignment and found four of them open to it. One was Spree, an e-commerce platform then gaining users. Its Order model did not declare attr_accessible, the Rails 2 allowlist, so every order attribute a request carried was written, including state, the column the checkout was supposed to advance. "Spree's public exposure of the 'state' attribute," he wrote, "allowed me to make my order appear as though it was paid for when I hadn't even entered my payment information." He had reported it first: on September 16 Spree announced that its order model had been missing attr_accessible and that the fix was in its source for the next release, and credited him. The CVE record, CVE-2008-7310, published in 2012, describes the flaw as letting remote attackers change the order state and skip the payment step.
The forged column was not a permission flag but a state the payment step should own, the lab's paid under another name, and the generic request his post opened with is the lab's attack in Rails: curl -X PUT -d "order[price_in_cents]=0" example.com/orders/225, sent to a controller that called @order.update_attributes(params[:order]), the equivalent of a DRF '__all__' serializer and save(). Rails later moved the allowlist into the controller and made it mandatory (strong parameters, Rails 4). Django refuses a ModelForm or ModelSerializer with no field list, but '__all__' is still one string away. In ATT&CK terms, rewriting a stored record's fields outside the request's authority is T1565.001 — Data Manipulation: Stored Data Manipulation.
Sources: Eric Chapweske, Rail Spikes — Is your Rails application safe? (2008, archived); Spree — Security Vulnerability: Mass Assignment of Order Params (2008, archived); GitHub Advisory Database — CVE-2008-7310
Django's Default Protections
The honest answer is close to the one Post 7 gave: Django refuses to guess, and then trusts you. A ModelForm whose Meta sets neither fields nor exclude raises ImproperlyConfigured, and DRF's ModelSerializer fails an assertion in the same case, so fields = '__all__' is always a value someone typed. Once it is typed there is no warning and no system check: both bind every editable field. The auto-generated primary key and fields marked editable=False, such as auto_now timestamps, stay out of a ModelForm regardless, and DRF makes them read-only.
What Django does give you is a clearly documented safe path and a loud warning in the docs. The ModelForm documentation says plainly that failing to list the fields explicitly "can easily lead to security problems when a form unexpectedly allows a user to set certain fields, especially when new fields are added to a model." DRF's serializer guide makes the same recommendation: name your fields. The framework's position is that field selection is a security decision the developer must make explicitly — it will not guess for you, and it will not stop you from choosing '__all__'.
There is one interface where the field list is curated for you: the admin. ModelAdmin.fields, fieldsets, readonly_fields, and exclude all constrain what the admin form binds. Even there the form underneath can be '__all__': UserAdmin is built on UserChangeForm, which declares fields = '__all__', and the admin narrows it with fieldsets and the auth.change_user permission. But the admin is a staff-only interface with its own forms. Your customer-facing views use your forms, and if those bind '__all__', the admin's fieldsets protect nothing.
What Django does NOT protect automatically:
- Any
ModelFormorModelSerializerusingfields = '__all__'or a broadexclude. - Any view that splats
**request.data/**request.POSTinto a model constructor,create(), orupdate(). - Writable nested serializers, which carry their own independent field rules.
- Direct
setattr(instance, key, value)loops over request data (the hand-rolled version of the same bug).
The Vulnerable Pattern and the Fix
Pattern 1 — A DRF Serializer That Binds Every Column
The lab's order API is the shape DRF tutorials reach for: a ModelViewSet over a ModelSerializer with '__all__'. The fix is in the serializer:
-class OrderSerializer(serializers.ModelSerializer):
+class CustomerOrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
- fields = "__all__" # DANGER: price, paid, status, owner are all writable
+ fields = ["id", "quantity", "price", "paid", "status", "owner"]
+ read_only_fields = ["id", "price", "paid", "status", "owner"]
On the vulnerable view, PATCH {"quantity": 2, "price": "0.00", "paid": true, "status": "shipped"} writes every key, and the order is free, paid and shipped, the state the lab's receipt view rewards with the flag. On the secure view DRF leaves read-only keys out of validated_data, so the same PATCH returns 200, writes quantity, and drops the rest: the request succeeds, the tampered values do not land. fields decides what the serializer knows about; read_only_fields decides what it will write. That option covers only the fields DRF generates from the model: a field declared on the serializer class ignores it (Post 7). Both views are in the lab: views_vulnerable.py and views_secure.py.
Pattern 2 — The Hand-Rolled Splat, Where commit=False Gives False Comfort
Developers who have been burned by '__all__' sometimes reach for save(commit=False) and believe it makes them safe. It does not: commit=False only delays the database write so you can set extra attributes, and by the time you have an obj, the attacker's price=0 is already on it. (An all-fields form validates only when the page posts every required column, which here it does as hidden inputs; the attacker edits those.) The raw splat is worse still, because it skips the form layer altogether:
def update_order(request, pk):
order = get_object_or_404(Order, pk=pk, owner=request.user)
- form = OrderForm(request.POST, instance=order) # Meta.fields = '__all__'
+ form = OrderQuantityForm(request.POST, instance=order) # Meta.fields = ['quantity']
if form.is_valid():
obj = form.save(commit=False) # with '__all__', price and paid are already on obj
obj.updated_by = request.user
obj.save()
def create_order(request):
- Order.objects.create(**json.loads(request.body)) # every posted key becomes a column
+ form = OrderQuantityForm(json.loads(request.body))
+ if form.is_valid():
+ Order.objects.create(owner=request.user, quantity=form.cleaned_data['quantity'])
The vulnerability lives at the moment of binding, not the moment of saving. commit=False is downstream of the problem.
Two rules apply to both patterns rather than one. First, give each audience its own serializer or form instead of one as broad as the most privileged caller: a customer serializer with fields = ['id', 'quantity'] beside a staff serializer that adds status and paid, chosen in the viewset's get_serializer_class(). The customer endpoint then physically cannot write paid, because the class handling its request has no such field. Second, prefer fields to exclude. exclude = ['owner', 'price', 'paid', 'status'] is equivalent to fields = ['quantity'] for today's model; add a commission_rate column next quarter and the exclude form silently starts accepting it, because a denylist fails open, while fields fails closed. That asymmetry is why Django's own docs steer you toward fields.
I'll be honest that I don't consider exclude indefensible — a team with a strict "every model change gets a security review" process can use it safely, and some codebases find it more readable. But it moves the safety from the code to the process, and processes lapse.
The Analyst's View
For a CySA+ analyst, mass assignment is a reminder that the most dangerous line in a codebase can be the one that looks like configuration. fields = '__all__' is not a dangerous call — there is no eval, no shell=True, no sink a pattern-matcher recognises — so the SAST tools this series standardises on report nothing on it. As the detection section below shows, even the Django ruleset the class's reputation suggests should catch it does not. A clean Bandit or Semgrep run over a serializer layer is therefore evidence of nothing: the control that matters — an explicit, per-audience field allowlist — is a property the scanner cannot confirm: a rule can flag '__all__', as the lab's does, but an explicit list that names one field too many looks exactly like a correct one.
That pushes detection onto review and the threat-modelling vocabulary an analyst already owns. Every fields / read_only_fields list is an authorization boundary written in framework syntax; read it as one, and ask of each column whether the client on the other end of this endpoint is authorized to write it. The high-value columns are the ones that decide money or state — price, paid, verification_status — which makes this the same broken-access-control question as the rest of Series II, moved from the row a request may read to the fields it may write.
Catching It Automatically
Testing Your Defence
One test proves the fix against this payload: over-post fields the page never sends, then read the record back. This is the one the lab uses:
def test_over_post_is_dropped_on_secure(self):
# read_only_fields strips the over-posts; the request still returns 200.
resp = self.client.patch(
f"/mass-assignment/secure/orders/{self.order.pk}/",
{"quantity": 2, "price": "0.00", "paid": True, "status": "shipped"},
format="json",
)
self.assertEqual(resp.status_code, 200)
self.order.refresh_from_db()
self.assertEqual(self.order.quantity, 2) # the allowed field WAS written
self.assertEqual(self.order.price, Decimal("49.90")) # over-post dropped
self.assertFalse(self.order.paid) # over-post dropped
self.assertEqual(self.order.status, "pending") # over-post dropped
setUp creates alice's order at 49.90, unpaid and pending. Point the test at /mass-assignment/vulnerable/ and it fails: the price is now 0.00. The quantity assertion keeps the fix honest: a serializer that made every field read-only would drop the over-posts too, and fail it. The lab's tests.py adds the forged order on the vulnerable view, which the receipt view rewards with the flag; its two owner-reassignment tests stay as regression checks.
Scanning It
I assumed this one would scan cleanly in the good sense — mass assignment is a textbook class, and an earlier draft of this very post asserted that semgrep --config p/django flags fields='__all__' on serializers. When I actually pointed the tools at the lab's two views, that turned out to be wrong, and the correction is the useful part of this section.
Bandit reports nothing on the serializer. Its checks target dangerous constructs (eval, subprocess … shell=True, yaml.load, hardcoded passwords); a serializer's field list is not one, so no plugin looks at '__all__', though nothing stops a syntax check from matching it, as the custom rule below does. The only things it flags in the lab are two B106 hardcoded passwords in the test file — noise, and a reminder that a clean report on vulnerable code is a miss, not a pass.
Semgrep community (p/django, p/python, p/owasp-top-ten) reports zero on the fields='__all__' serializer — and, checked directly before concluding "miss," so does the registry tier (r/python.django, r/python). No shipped Semgrep rule catches this pattern in any tier I could point at it. The tools that do catch it are dedicated Django linters — Ruff DJ007 (django-all-with-model-form) and flake8-django DJ07 — and even those are scoped to ModelForm, so on the DRF ModelSerializer side the off-the-shelf coverage thins to nothing. That gap is why the lab ships a small custom rule. It keys on fields = "__all__" inside a class Meta, fires on the vulnerable serializer, and stays silent on the explicit-allowlist fix:
# Fires on the vulnerable view, silent on the secure one — the assert no
# shipped tier gives on this class.
semgrep scan --config rules/mass_assignment.yaml labs/post_10_mass_assignment/views_vulnerable.py # 1 finding
semgrep scan --config rules/mass_assignment.yaml labs/post_10_mass_assignment/views_secure.py # 0 findings
That is the same rule Post 7 uses on its ModelForm: one sink, two labs, distinguished only by which field is exposed (a permission flag there, a business column here). It also catches the other spellings of "every field": Django's ALL_FIELDS constant, an empty exclude, and modelform_factory(..., fields="__all__"). Its fixture documents two limits: a non-empty exclude denylist, which fails open as the model grows, is not caught, and it flags a django-filter FilterSet Meta with fields = '__all__', which lists filters rather than writable fields. It also cannot see a list that names one field too many, or Pattern 2's splat, since neither says "all". And, like any syntax rule, it cannot tell when '__all__' is harmless, as on a serializer whose fields are all read-only. I reproduced every run above and captured them in the lab's scans/ directory.
The practical review takeaways are the ones grep and a running endpoint give you faster than a SAST run that reports nothing. Sweep the serializer and form layer directly:
# Every ModelForm / ModelSerializer that binds all columns (either quote style)
grep -rnE "fields = ['\"]__all__['\"]" --include="*.py" apps/ | grep -v migrations
# Broad exclude denylists (fail-open risk)
grep -rn "exclude = " --include="*.py" apps/ | grep -v migrations
# The hand-rolled splat
grep -rn "objects.create(\*\*\|(\*\*request\." --include="*.py" apps/
And prove the fix dynamically — over-post fields the form never rendered, then read the record back:
# Over-post against the secure endpoint; the tampered fields must not land.
curl -s -X PATCH http://127.0.0.1:8000/mass-assignment/secure/orders/1/ \
-H "Content-Type: application/json" \
-d '{"quantity": 2, "price": "0.00", "paid": true, "status": "shipped"}'
# 200 OK — quantity=2 written, price/paid/status unchanged
The habit this post left me with: every fields list is a permission grant, so I read it as one, and a column that decides money or state is set by the server, from the catalogue or the workflow, never bound from the request.
That closes Series II. Post 11 opens Series III — Authentication and Session — with Brute Force and Credential Stuffing, where the attack moves from what you're allowed to write to proving who you are in the first place, and Django's decision to ship no rate limiting at all becomes the gap you have to close yourself.
Further Reading
- django-security-lab — Mass Assignment lab (runnable DRF vulnerable/secure views, captured scans, and the custom Semgrep rule shared with Post 7)
- Django Docs — ModelForm: Selecting the Fields to Use
- DRF Docs — Specifying Which Fields to Include
- OWASP API Security Top 10 — Broken Object Property Level Authorization
- OWASP Cheat Sheet — Mass Assignment
- OWASP A08:2025 — Software or Data Integrity Failures
- MITRE CWE-915 — Improperly Controlled Modification of Dynamically-Determined Object Attributes
- MITRE ATT&CK — T1565.001: Stored Data Manipulation
- Eric Chapweske, Rail Spikes — Is your Rails application safe? (2008, archived; the Spree order-state case)
- Web Security for Developers: Real Threats, Practical Defense (Malcolm McDonald) — Chapter 11: Permissions