conducting-api-security-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Conducting API Security Testing

开展API安全测试

When to Use

适用场景

  • Testing API endpoints for authorization flaws, injection vulnerabilities, and business logic bypasses
  • Assessing the security of microservices architecture where APIs are the primary communication method
  • Validating that API gateway protections (rate limiting, authentication, input validation) are properly enforced
  • Testing third-party API integrations for data exposure and insecure configurations
  • Evaluating GraphQL APIs for introspection disclosure, query complexity attacks, and authorization bypasses
Do not use against APIs without written authorization, for load testing or denial-of-service testing unless explicitly scoped, or for testing production APIs that process real financial transactions without safeguards.
  • 测试API端点的授权缺陷、注入漏洞及业务逻辑绕过问题
  • 评估以API为主要通信方式的微服务架构安全性
  • 验证API网关防护措施(速率限制、认证、输入验证)是否正确生效
  • 测试第三方API集成的数据暴露风险与不安全配置
  • 评估GraphQL API的自省信息泄露、查询复杂度攻击及授权绕过问题
禁止场景: 未经书面授权测试API;除非明确界定范围,否则不得用于负载测试或拒绝服务测试;不得在无防护措施的情况下测试处理真实金融交易的生产环境API。

Prerequisites

前置条件

  • API documentation (OpenAPI/Swagger, GraphQL schema, Postman collection) or application access to reverse-engineer the API
  • Burp Suite Professional configured to intercept API traffic with JSON/XML content type handling
  • Postman or Insomnia for organizing and replaying API requests across different authentication contexts
  • Valid API tokens or credentials at multiple privilege levels (unauthenticated, standard user, admin)
  • Target API base URL and version information
  • API文档(OpenAPI/Swagger、GraphQL schema、Postman集合)或可逆向工程API的应用访问权限
  • 已配置好的Burp Suite Professional,可拦截处理JSON/XML内容类型的API流量
  • Postman或Insomnia工具,用于在不同认证上下文下组织和重放API请求
  • 多权限级别的有效API令牌或凭据(未认证、标准用户、管理员)
  • 目标API的基础URL及版本信息

Workflow

工作流程

Step 1: API Discovery and Documentation

步骤1:API发现与文档化

Map the complete API attack surface:
  • Import API documentation: Load OpenAPI/Swagger specs into Postman or Burp Suite to catalog all endpoints, methods, parameters, and authentication requirements
  • Reverse-engineer undocumented APIs: Proxy the mobile app or web frontend through Burp Suite and exercise all features to capture API calls. Export the Burp sitemap as the baseline endpoint inventory.
  • GraphQL introspection: Send an introspection query to discover the full schema:
    json
    {"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"}
  • Endpoint enumeration: Fuzz for hidden API versions (
    /api/v1/
    ,
    /api/v2/
    ,
    /api/internal/
    ), debug endpoints (
    /api/debug
    ,
    /api/health
    ,
    /api/metrics
    ), and administrative endpoints
  • Document authentication mechanisms: Identify if the API uses API keys, OAuth 2.0 Bearer tokens, JWT, session cookies, or mutual TLS
绘制完整的API攻击面:
  • 导入API文档:将OpenAPI/Swagger规范加载到Postman或Burp Suite中,编录所有端点、方法、参数及认证要求
  • 逆向工程未文档化API:通过Burp Suite代理移动端应用或Web前端,执行所有功能以捕获API调用。导出Burp站点地图作为基线端点清单。
  • GraphQL自省查询:发送自省查询以发现完整schema:
    json
    {"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"}
  • 端点枚举:模糊测试隐藏的API版本(
    /api/v1/
    /api/v2/
    /api/internal/
    )、调试端点(
    /api/debug
    /api/health
    /api/metrics
    )及管理端点
  • 记录认证机制:识别API是否使用API密钥、OAuth 2.0 Bearer令牌、JWT、会话Cookie或双向TLS

Step 2: Authentication and Token Testing

步骤2:认证与令牌测试

Test authentication mechanisms for weaknesses:
  • JWT analysis: Decode the JWT and inspect claims (sub, exp, iss, aud, role). Test:
    • Algorithm confusion: Change
      alg
      to
      none
      and remove the signature
    • Key confusion: Change
      alg
      from RS256 to HS256 and sign with the public key
    • Weak secret: Brute-force the HMAC secret with
      hashcat -m 16500 jwt.txt wordlist.txt
    • Token expiration: Verify tokens expire and cannot be used after expiration
    • Claim tampering: Modify role, userId, or permission claims and re-sign
  • OAuth 2.0 testing: Check for redirect_uri manipulation, authorization code reuse, token leakage in Referer headers, and missing state parameter (CSRF)
  • API key security: Test if API keys are validated per-endpoint, if revoked keys are immediately rejected, and if keys in query strings appear in access logs or analytics
测试认证机制的弱点:
  • JWT分析:解码JWT并检查声明(sub、exp、iss、aud、role)。测试:
    • 算法混淆:将
      alg
      改为
      none
      并移除签名
    • 密钥混淆:将
      alg
      从RS256改为HS256并使用公钥签名
    • 弱密钥:使用
      hashcat -m 16500 jwt.txt wordlist.txt
      暴力破解HMAC密钥
    • 令牌过期:验证令牌过期后无法继续使用
    • 声明篡改:修改role、userId或权限声明并重新签名
  • OAuth 2.0测试:检查redirect_uri操纵、授权码重用、Referer头中的令牌泄露及缺失state参数(CSRF)问题
  • API密钥安全性:测试API密钥是否按端点验证、吊销的密钥是否被立即拒绝、查询字符串中的密钥是否出现在访问日志或分析数据中

Step 3: Authorization Testing (BOLA/BFLA)

步骤3:授权测试(BOLA/BFLA)

Test for Broken Object Level Authorization (BOLA) and Broken Function Level Authorization (BFLA):
  • BOLA (IDOR) testing: For every endpoint that returns user-specific data, replace the object identifier with another user's identifier:
    • GET /api/users/123/orders
      ->
      GET /api/users/456/orders
    • Test with numeric IDs, UUIDs, usernames, and email addresses
    • Automate with Burp Autorize extension: configure it with two sessions (attacker and victim) and replay all requests
  • BFLA testing: Using a low-privilege token, attempt to access administrative endpoints:
    • DELETE /api/users/456
      (admin-only delete)
    • PUT /api/users/456/role
      (role modification)
    • GET /api/admin/dashboard
      (admin panel data)
  • Mass assignment: Send additional JSON properties not shown in the documentation:
    json
    PUT /api/users/123
    {"name": "Test", "role": "admin", "isVerified": true, "balance": 99999}
  • HTTP method testing: If GET works on an endpoint, try PUT, PATCH, DELETE, and OPTIONS to discover unprotected methods
测试对象级授权失效(BOLA)与功能级授权失效(BFLA):
  • BOLA(IDOR)测试:对于每个返回用户特定数据的端点,将对象标识符替换为其他用户的标识符:
    • GET /api/users/123/orders
      ->
      GET /api/users/456/orders
    • 测试数值ID、UUID、用户名及电子邮件地址
    • 使用Burp Autorize扩展自动化测试:配置两个会话(攻击者与受害者)并重放所有请求
  • BFLA测试:使用低权限令牌尝试访问管理端点:
    • DELETE /api/users/456
      (仅管理员可执行的删除操作)
    • PUT /api/users/456/role
      (角色修改)
    • GET /api/admin/dashboard
      (管理面板数据)
  • 批量赋值:发送文档中未列出的额外JSON属性:
    json
    PUT /api/users/123
    {"name": "Test", "role": "admin", "isVerified": true, "balance": 99999}
  • HTTP方法测试:如果某个端点支持GET方法,尝试PUT、PATCH、DELETE及OPTIONS方法,发现未受保护的方法

Step 4: Input Validation and Injection Testing

步骤4:输入验证与注入测试

Test API inputs for injection and validation flaws:
  • SQL injection in API parameters: Test all parameters (path, query, body, headers) with SQL injection payloads. JSON APIs are often overlooked:
    {"username": "admin' OR 1=1--", "password": "test"}
  • NoSQL injection: For MongoDB backends, test with operator injection:
    {"username": {"$gt": ""}, "password": {"$gt": ""}}
  • SSRF via API: Test any parameter that accepts URLs (webhook URLs, avatar URLs, import endpoints) with internal addresses and cloud metadata endpoints
  • GraphQL-specific injection: Test for query depth attacks, alias-based batching for brute force, and field suggestion enumeration
  • XXE in XML APIs: Submit XML content with external entity declarations to API endpoints that accept XML
  • Rate limiting validation: Send 100+ rapid requests to authentication endpoints, password reset, and OTP verification to test for brute force protection
测试API输入的注入与验证缺陷:
  • API参数中的SQL注入:使用SQL注入 payload测试所有参数(路径、查询、请求体、头信息)。JSON API常被忽略:
    {"username": "admin' OR 1=1--", "password": "test"}
  • NoSQL注入:针对MongoDB后端,测试运算符注入:
    {"username": {"$gt": ""}, "password": {"$gt": ""}}
  • API中的SSRF:测试任何接受URL的参数(Webhook URL、头像URL、导入端点),使用内部地址及云元数据端点
  • GraphQL特定注入:测试查询深度攻击、基于别名的批量暴力破解及字段建议枚举
  • XML API中的XXE:向接受XML内容的API端点提交包含外部实体声明的XML
  • 速率限制验证:向认证端点、密码重置及OTP验证端点发送100+次快速请求,测试暴力破解防护措施

Step 5: Data Exposure and Response Analysis

步骤5:数据暴露与响应分析

Check for excessive data exposure in API responses:
  • Verbose responses: Compare the data returned in API responses with what the UI displays. APIs often return more fields than needed (internal IDs, creation timestamps, email addresses of other users, role information).
  • Error message analysis: Trigger errors by sending malformed input, invalid tokens, and non-existent resources. Check if error messages reveal stack traces, database queries, internal paths, or technology details.
  • Pagination and enumeration: Test if enumeration is possible by iterating through paginated responses (
    /api/users?page=1
    ,
    page=2
    , etc.) to extract all records
  • GraphQL data exposure: Query for fields not intended for the current user's role. Test nested queries that traverse relationships to access unauthorized data.
  • Debug endpoints: Check
    /api/debug
    ,
    /api/status
    ,
    /metrics
    ,
    /health
    ,
    /.env
    ,
    /api/swagger.json
    for exposed internal information
检查API响应中的过度数据暴露问题:
  • 详细响应:对比API返回的数据与UI展示的数据。API通常会返回超出需求的字段(内部ID、创建时间戳、其他用户的电子邮件地址、角色信息)。
  • 错误消息分析:通过发送格式错误的输入、无效令牌及不存在的资源触发错误。检查错误消息是否泄露堆栈跟踪、数据库查询、内部路径或技术细节。
  • 分页与枚举:通过遍历分页响应(
    /api/users?page=1
    page=2
    等)测试是否可枚举所有记录
  • GraphQL数据暴露:查询当前用户角色无权访问的字段。测试遍历关系的嵌套查询以获取未授权数据。
  • 调试端点:检查
    /api/debug
    /api/status
    /metrics
    /health
    /.env
    /api/swagger.json
    是否暴露内部信息

Key Concepts

核心概念

TermDefinition
BOLABroken Object Level Authorization (OWASP API #1); failure to verify that the requesting user is authorized to access a specific object, enabling IDOR attacks
BFLABroken Function Level Authorization (OWASP API #5); failure to restrict administrative or privileged API functions from being accessed by lower-privilege users
Mass AssignmentA vulnerability where the API binds client-provided data to internal object properties without filtering, allowing attackers to modify fields they should not have access to
GraphQL IntrospectionA built-in GraphQL feature that exposes the complete API schema including all types, fields, and relationships; should be disabled in production
JWTJSON Web Token; a self-contained token format used for API authentication containing claims signed with a secret or key pair
Rate LimitingControls that restrict the number of API requests a client can make within a time window, preventing brute force, enumeration, and abuse
术语定义
BOLA对象级授权失效(OWASP API #1);未验证请求用户是否有权访问特定对象,导致IDOR攻击
BFLA功能级授权失效(OWASP API #5);未限制低权限用户访问管理或特权API功能
批量赋值一种漏洞,API将客户端提供的数据绑定到内部对象属性而未做过滤,允许攻击者修改其无权访问的字段
GraphQL自省GraphQL内置功能,暴露完整的API schema包括所有类型、字段及关系;生产环境应禁用
JWTJSON Web令牌;用于API认证的自包含令牌格式,包含经密钥或密钥对签名的声明
速率限制控制客户端在时间窗口内可发起的API请求数量,防止暴力破解、枚举及滥用

Tools & Systems

工具与系统

  • Burp Suite Professional: HTTP proxy for intercepting, modifying, and replaying API requests with extensions like Autorize for automated authorization testing
  • Postman: API development platform used for organizing endpoint collections, scripting tests, and comparing responses across authentication contexts
  • GraphQL Voyager: Visual tool for exploring GraphQL schemas obtained through introspection queries
  • jwt.io / jwt_tool: Tools for decoding, analyzing, and tampering with JWT tokens to test authentication bypasses
  • Nuclei: Template-based scanner with API-specific templates for detecting common misconfigurations and known vulnerabilities
  • Burp Suite Professional:HTTP代理工具,用于拦截、修改及重放API请求,搭配Autorize扩展可实现自动化授权测试
  • Postman:API开发平台,用于组织端点集合、编写测试脚本及对比不同认证上下文下的响应
  • GraphQL Voyager:可视化工具,用于探索通过自省查询获取的GraphQL schema
  • jwt.io / jwt_tool:用于解码、分析及篡改JWT令牌以测试认证绕过的工具
  • Nuclei:基于模板的扫描器,带有API特定模板,可检测常见配置错误及已知漏洞

Common Scenarios

常见场景

Scenario: API Security Assessment for a Fintech Mobile Application

场景:金融科技移动应用的API安全评估

Context: A fintech startup has a mobile banking application with a REST API backend. The API handles account management, fund transfers, bill payments, and transaction history. The tester has Swagger documentation and accounts at user and admin levels.
Approach:
  1. Import Swagger spec into Postman, generating 87 endpoint collections across 12 controllers
  2. Discover BOLA on
    /api/v1/accounts/{accountId}/transactions
    allowing any authenticated user to view any account's transaction history
  3. Find mass assignment on the user update endpoint where adding
    "dailyTransferLimit": 999999
    bypasses the configured transfer limit
  4. Identify that the fund transfer endpoint lacks rate limiting, allowing unlimited transfer attempts without throttling
  5. Discover that JWT tokens have a 30-day expiration with no refresh token rotation, enabling long-lived session hijacking
  6. Find that the admin endpoint
    /api/v1/admin/users
    is accessible with a standard user token (BFLA)
  7. Report all findings with CVSS scores and specific API code-level remediation guidance
Pitfalls:
  • Testing only the endpoints documented in Swagger and missing undocumented or deprecated API versions
  • Not testing the same endpoint with tokens from every privilege level to detect authorization bypasses
  • Ignoring response body analysis for excessive data exposure when the UI only shows a subset of returned fields
  • Failing to test for mass assignment by only sending fields shown in the documentation
背景:某金融科技初创公司拥有一款移动银行应用,后端采用REST API。该API处理账户管理、资金转账、账单支付及交易记录。测试人员拥有Swagger文档及用户、管理员级别的账户。
测试方法
  1. 将Swagger规范导入Postman,生成12个控制器下的87个端点集合
  2. 发现
    /api/v1/accounts/{accountId}/transactions
    存在BOLA漏洞,任何已认证用户均可查看任意账户的交易记录
  3. 发现用户更新端点存在批量赋值漏洞,添加
    "dailyTransferLimit": 999999
    可绕过配置的转账限额
  4. 发现资金转账端点缺乏速率限制,允许无限制的转账尝试而不触发限流
  5. 发现JWT令牌有效期为30天且无刷新令牌轮换机制,导致会话劫持风险长期存在
  6. 发现管理端点
    /api/v1/admin/users
    可通过标准用户令牌访问(BFLA)
  7. 报告所有发现并附上CVSS评分及具体的API代码级修复指导
常见陷阱
  • 仅测试Swagger文档中记录的端点,忽略未文档化或已废弃的API版本
  • 未使用所有权限级别的令牌测试同一端点,导致遗漏授权绕过漏洞
  • 忽略响应体分析,未发现API返回的数据超出UI展示范围的过度暴露问题
  • 仅发送文档中列出的字段,未测试批量赋值漏洞

Output Format

输出格式

undefined
undefined

Finding: Broken Object Level Authorization in Transaction History API

发现:交易记录API中的对象级授权失效

ID: API-001 Severity: Critical (CVSS 9.1) Affected Endpoint: GET /api/v1/accounts/{accountId}/transactions OWASP API Category: API1:2023 - Broken Object Level Authorization
Description: The transaction history endpoint returns all transactions for the specified account without verifying that the authenticated user owns the account. Any authenticated user can view the complete transaction history of any account by substituting the accountId path parameter.
Proof of Concept:
  1. Authenticate as User A (account ID: ACC-10045)
  2. Request: GET /api/v1/accounts/ACC-10046/transactions Authorization: Bearer <User_A_token>
  3. Response: 200 OK with User B's full transaction history
Impact: Any authenticated user can view the complete financial transaction history of all 45,000 customer accounts, including amounts, dates, recipients, and transaction descriptions.
Remediation: Implement server-side authorization check that verifies the authenticated user owns the requested account before returning data: const account = await Account.findById(accountId); if (account.userId !== req.user.id) return res.status(403).json({error: "Forbidden"});
undefined
ID:API-001 严重程度:关键(CVSS 9.1) 受影响端点:GET /api/v1/accounts/{accountId}/transactions OWASP API分类:API1:2023 - 对象级授权失效
描述: 交易记录端点返回指定账户的所有交易记录,但未验证已认证用户是否拥有该账户。任何已认证用户均可通过替换accountId路径参数查看任意账户的完整交易记录。
验证步骤
  1. 以用户A身份认证(账户ID:ACC-10045)
  2. 请求:GET /api/v1/accounts/ACC-10046/transactions Authorization: Bearer <User_A_token>
  3. 响应:200 OK,返回用户B的完整交易记录
影响: 任何已认证用户均可查看全部45000个客户账户的完整金融交易记录,包括交易金额、日期、收款方及交易描述。
修复建议: 实现服务器端授权检查,在返回数据前验证已认证用户是否拥有请求的账户: const account = await Account.findById(accountId); if (account.userId !== req.user.id) return res.status(403).json({error: "Forbidden"});
undefined