Mass Assignment in APIs
What is Mass Assignment?
Mass Assignment is a vulnerability that occurs when an API endpoint blindly accepts and processes all properties sent in a request payload, including those the client should not be allowed to modify. This typically happens when developers use frameworks that automatically bind request parameters to object properties without proper filtering or validation.
The vulnerability arises from a mismatch between what data an API client is allowed to see versus what they're allowed to modify. While an API might properly restrict which fields are returned in responses (preventing data exposure), it may fail to restrict which fields can be modified through write operations.
For example, consider a user update endpoint that accepts a JSON payload. If the backend simply maps all incoming properties to a user object without validation, an attacker could potentially modify fields like is_admin, account_status, or subscription_tier that should only be modifiable by privileged users or internal systems.
How Mass Assignment Affects APIs
The impact of Mass Assignment vulnerabilities can be severe, ranging from privilege escalation to complete account takeover. Here are common attack scenarios:
- Privilege Escalation: An attacker modifies security-critical properties like
role,permissions, oris_adminto gain elevated access - Account Takeover: Changing
user_idorowner_idproperties to take control of other users' resources - Bypass Business Logic: Modifying
subscription_status,payment_status, orquota_usedto circumvent paywalls or usage limits - Data Integrity Corruption: Altering audit fields like
created_by,created_at, orversionto break application logic
A classic example is the CVE-2020-5398 vulnerability in Spring Boot, where applications using @RequestParam or @ModelAttribute without proper binding restrictions allowed attackers to modify any property of bound objects.
The attack typically involves crafting a request with additional properties that the API should not accept. For instance, a legitimate user update request might look like this:
PUT /api/users/123 HTTP/1.1
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]",
"is_admin": true
}If the API blindly accepts all properties, the attacker successfully escalates their privileges by setting is_admin to true.
How to Detect Mass Assignment
Detecting Mass Assignment vulnerabilities requires examining both the API's behavior and its implementation. Here are key detection methods:
- Property Enumeration: Test if the API accepts properties that shouldn't be user-modifiable by sending requests with unexpected fields
- Response Analysis: Check if the API returns sensitive properties in responses that users shouldn't see
- Schema Validation: Verify that the API enforces strict property whitelisting rather than blacklisting
- Authentication Context Testing: Attempt to modify properties that should only be changeable by different user roles
middleBrick's API security scanner includes specific checks for Mass Assignment vulnerabilities. The scanner tests unauthenticated endpoints by sending requests with common sensitive properties like is_admin, role, owner_id, and created_by. If the API accepts and processes these properties, middleBrick flags this as a critical finding.
The scanner also analyzes OpenAPI specifications to identify properties that should be restricted based on their names and context, then attempts to modify them during runtime testing. This combination of static analysis (spec review) and dynamic testing (runtime probing) provides comprehensive coverage for Mass Assignment detection.
For example, middleBrick would flag this vulnerable code pattern:
// VULNERABLE - accepts all properties
const user = await User.create(req.body);
// SECURE - explicitly whitelists allowed properties
const { name, email } = req.body;
const user = await User.create({ name, email });Prevention & Remediation
Preventing Mass Assignment requires a defense-in-depth approach with multiple layers of protection:
1. Explicit Property Whitelisting
Always explicitly define which properties can be modified rather than trying to blacklist sensitive ones. This is the most effective prevention method.
// SECURE - whitelist approach
const allowedProperties = ['name', 'email', 'phone'];
const userData = {};
for (const prop of allowedProperties) {
if (prop in req.body) {
userData[prop] = req.body[prop];
}
}
const user = await User.create(userData);
2. Use Framework Security Features
Leverage built-in security features of your framework. For example, in Django use ModelForm with fields attribute, in Rails use attr_accessible or strong parameters, in Spring Boot use @JsonIgnore and @JsonProperty(access = Access.WRITE_ONLY).
3. Implement Role-Based Property Access
Different user roles should have different property modification permissions. An admin updating a user should be able to modify different properties than the user themselves.
async function updateUser(userId, updateData, currentUser) {
const user = await User.findById(userId);
// Regular users can only update their own basic info
if (currentUser.id === userId) {
const allowed = ['name', 'email', 'phone'];
const filtered = pick(updateData, allowed);
return await user.update(filtered);
}
// Admins can update more properties
if (currentUser.isAdmin) {
const allowed = ['name', 'email', 'role', 'status'];
const filtered = pick(updateData, allowed);
return await user.update(filtered);
}
throw new Error('Unauthorized');
}4. Validate Property Types and Formats
Even with whitelisting, validate that properties have expected types and formats to prevent type confusion attacks.
const schema = {
name: joi.string().max(100).required(),
email: joi.string().email().required(),
age: joi.number().integer().min(0).max(150)
};
const { error, value } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}5. Audit and Monitor
Implement logging for property changes, especially for sensitive properties. Monitor for unusual modification patterns that might indicate exploitation attempts.
Real-World Impact
Mass Assignment vulnerabilities have caused significant real-world security incidents. In 2012, a vulnerability in Ruby on Rails' mass assignment feature led to multiple high-profile breaches, including the compromise of GitHub's Rails application. Attackers were able to set the administrator flag on their accounts by sending crafted POST requests.
The CVE-2020-5398 vulnerability in Spring Boot's data binding allowed attackers to modify any property of objects bound from HTTP requests, leading to privilege escalation in numerous applications. This vulnerability affected applications using @RequestParam and @ModelAttribute annotations without proper binding restrictions.
More recently, API security researchers have found Mass Assignment vulnerabilities in e-commerce platforms where attackers could modify price, discount, or quantity properties to get products at incorrect prices or bypass inventory controls.
The financial impact can be substantial. A single Mass Assignment vulnerability that allows price modification could lead to direct revenue loss, while privilege escalation vulnerabilities could result in data breaches with regulatory fines and reputational damage. According to OWASP, API security failures including Mass Assignment can cost organizations an average of $4.35 million per incident when including breach response, legal fees, and lost business.
middleBrick's scanner helps prevent these incidents by automatically detecting Mass Assignment vulnerabilities before they reach production. With its 12 security checks running in parallel, middleBrick can identify these issues in 5–15 seconds, providing immediate feedback to developers. The Pro plan's continuous monitoring feature ensures that new endpoints added to your API are automatically scanned for Mass Assignment and other vulnerabilities on a configurable schedule, with alerts sent via Slack or Teams when issues are detected.