Mass Assignment and ORM Injection
What you'll learn: How user-controlled input can overwrite internal model fields through ORM mass assignment and how attackers exploit ORM query builders for injection.
The Hidden Danger of Automatic Field Mapping
Modern ORMs make it easy to map HTTP request parameters directly to database models—just pass the entire request body to User.create(params) and the ORM handles the rest. But here's the trap: what if the user sends fields you didn't expect?
Mass assignment occurs when an ORM blindly copies all user-supplied fields to a model, allowing attackers to modify sensitive attributes like is_admin, account_balance, or role that should never be user-controlled.
Analogy: Imagine a hotel registration form where you fill in your name and room preferences. Mass assignment is like the receptionist blindly copying every field you write—including if you scribbled "VIP status: YES" or "room rate: $0" in the margins.
ORM Injection Risks
Even with query builders, injection is possible when you concatenate user input into method names, column names, or use raw fragments:
order_by(user_input)with input like"id; DROP TABLE users--"- Dynamic
where()clauses built from unvalidated field names - Raw SQL fragments mixed into otherwise-safe ORM calls
Defensive Strategies
Against mass assignment:
- Use allowlists (e.g., Django's
fields, Rails'permit()) to explicitly declare which fields are user-assignable - Never pass raw request data directly to model constructors
- Keep sensitive fields in a protected/readonly list
Against ORM injection:
- Never use user input for column names, table names, or method selectors
- Validate field names against a strict allowlist
- Avoid raw SQL fragments; use ORM abstractions
Key Takeaway:
ORM convenience can bypass your input validation—always use explicit field allowlists for mass assignment and never trust user input in query structure, even with an ORM.